Prompt specification
Build or customize the Three.js 3D scene "Source-spacing interference 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: Source-spacing interference explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/source-spacing-interference-explorer-x1552
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: source-spacing interference explorer. Let users vary source spacing and relative phase in a monochromatic model; update nodal regions and show that the pattern depends on wavelength as well as geometry. Return one self-contained HTML file.
Technical checks: Identify nodes from oscillation amplitude or phase difference. Along the perpendicular bisector, equal paths reinforce even when instantaneous pressure crosses zero.
Return one complete HTML document that works with the cdnjs Three.js r160 module inside a sandbox with scripts allowed. Make the requested subject visible at the default camera. Use procedural assets and local button handlers. Do not use native form submission, pointer lock, external assets or runtime requests other than Three.js.
Working Three.js Starter (source-spacing-interference-explorer-x1552):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="data:,">
<title>Explorador de Interferência — Espaçamento de Fontes</title>
<style>
:root {
--bg: #07101f;
--panel: #0b1628;
--panel-2: #101e34;
--line: #263a58;
--text: #eaf2ff;
--muted: #93a8c5;
--cyan: #56e7ff;
--orange: #ff9f43;
--coral: #ff526d;
--yellow: #ffd166;
--green: #62e6a7;
}
* { 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; }
#app {
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
width: 100%;
height: 100%;
}
#panel {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 22px 20px 26px;
background:
linear-gradient(180deg, rgba(16, 31, 54, .96), rgba(7, 16, 31, .98)),
var(--panel);
border-right: 1px solid var(--line);
box-shadow: 14px 0 36px rgba(0, 0, 0, .25);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: .13em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px var(--cyan);
}
h1 {
margin: 0;
font-size: 25px;
line-height: 1.12;
letter-spacing: -.025em;
}
.intro {
margin: 11px 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.section {
margin-top: 17px;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.section-title {
margin: 0 0 13px;
color: #cfe0f5;
font-size: 11px;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
}
.control { margin: 0 0 17px; }
.control-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.control label {
color: #dce8f8;
font-size: 13px;
font-weight: 650;
}
.control output {
min-width: 76px;
color: var(--cyan);
font-size: 12px;
font-variant-numeric: tabular-nums;
text-align: right;
font-weight: 750;
}
input[type="range"] {
width: 100%;
height: 20px;
margin: 0;
appearance: none;
background: transparent;
cursor: pointer;
}
input[type="range"]::-webkit-slider-runnable-track {
height: 5px;
border-radius: 99px;
background: linear-gradient(90deg, #315174, #172941);
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
margin-top: -5.5px;
appearance: none;
border: 2px solid #dff8ff;
border-radius: 50%;
background: #2dbbd7;
box-shadow: 0 0 0 4px rgba(86, 231, 255, .10), 0 0 12px rgba(86, 231, 255, .32);
}
input[type="range"]::-moz-range-track {
height: 5px;
border-radius: 99px;
background: #243c59;
}
input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border: 2px solid #dff8ff;
border-radius: 50%;
background: #2dbbd7;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 2px;
color: #667d9d;
font-size: 10px;
}
.button-row {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
button {
border: 1px solid #304968;
border-radius: 9px;
padding: 9px 11px;
color: #d9e7f8;
background: #13243b;
cursor: pointer;
transition: background .15s, border-color .15s, color .15s, transform .15s;
}
button:hover {
border-color: #507398;
background: #19304b;
}
button:active { transform: translateY(1px); }
button.active {
border-color: var(--cyan);
color: #07101f;
background: var(--cyan);
font-weight: 800;
}
button.primary {
flex: 1;
border-color: #2a8ca4;
color: #bdf7ff;
background: #103849;
}
.hint {
margin: 8px 0 0;
color: #7890af;
font-size: 11px;
line-height: 1.45;
}
.formula {
padding: 12px;
border: 1px solid #294260;
border-radius: 10px;
background: rgba(4, 12, 24, .54);
color: #bcd0e9;
font-size: 12px;
line-height: 1.55;
}
.formula strong {
color: var(--yellow);
font-weight: 750;
}
.probe-card {
overflow: hidden;
border: 1px solid #3a526f;
border-radius: 12px;
background: linear-gradient(145deg, rgba(18, 36, 59, .94), rgba(8, 19, 34, .96));
}
.probe-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 11px 12px;
border-bottom: 1px solid #2a405e;
}
.probe-title {
color: #dce9fa;
font-size: 12px;
font-weight: 800;
}
.badge {
padding: 4px 7px;
border: 1px solid #3a536f;
border-radius: 99px;
color: #b9cce2;
background: #14263e;
font-size: 10px;
font-weight: 800;
white-space: nowrap;
}
.badge.no {
border-color: #7d4355;
color: #ff9cad;
background: rgba(103, 31, 51, .35);
}
.badge.yes {
border-color: #34785e;
color: #8ff3c3;
background: rgba(25, 91, 64, .35);
}
.probe-body { padding: 11px 12px 12px; }
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 12px;
margin-bottom: 10px;
}
.metric span {
display: block;
margin-bottom: 2px;
color: #7189a8;
font-size: 9px;
letter-spacing: .07em;
text-transform: uppercase;
}
.metric b {
color: #e9f2ff;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.probe-message {
margin: 0;
padding: 9px 10px;
border-left: 3px solid var(--coral);
border-radius: 5px;
color: #d9e6f5;
background: rgba(255, 82, 109, .08);
font-size: 11px;
line-height: 1.48;
}
.probe-message.node {
border-left-color: var(--green);
background: rgba(98, 230, 167, .08);
}
.check-row {
display: flex;
align-items: center;
gap: 9px;
margin-top: 11px;
color: #9eb2ca;
font-size: 12px;
}
.check-row input {
width: 16px;
height: 16px;
accent-color: var(--cyan);
}
.validation {
display: flex;
align-items: center;
gap: 8px;
margin-top: 17px;
padding: 10px;
border: 1px solid rgba(98, 230, 167, .28);
border-radius: 9px;
color: #9cd9bc;
background: rgba(31, 100, 72, .10);
font-size: 10px;
line-height: 1.4;
}
.validation::before {
content: "✓";
display: grid;
place-items: center;
width: 18px;
height: 18px;
flex: 0 0 auto;
border-radius: 50%;
color: #062116;
background: var(--green);
font-weight: 900;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 56% 42%, rgba(37, 69, 105, .32), transparent 46%),
#07101f;
}
#canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.stage-top {
position: absolute;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.stage-heading {
padding: 10px 12px;
border: 1px solid rgba(84, 117, 153, .38);
border-radius: 10px;
background: rgba(7, 16, 31, .72);
backdrop-filter: blur(8px);
}
.stage-heading small {
display: block;
margin-bottom: 3px;
color: #7189a8;
font-size: 9px;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
}
.stage-heading strong {
color: #e8f3ff;
font-size: 14px;
}
.camera-help {
max-width: 225px;
padding: 9px 11px;
border: 1px solid rgba(84, 117, 153, .30);
border-radius: 9px;
color: #8fa6c1;
background: rgba(7, 16, 31, .66);
font-size: 10px;
line-height: 1.45;
text-align: right;
}
.legend {
position: absolute;
left: 20px;
bottom: 20px;
display: grid;
gap: 7px;
padding: 11px 12px;
border: 1px solid rgba(84, 117, 153, .34);
border-radius: 10px;
color: #a9bdd5;
background: rgba(7, 16, 31, .78);
backdrop-filter: blur(8px);
font-size: 10px;
pointer-events: none;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 27px;
height: 4px;
border-radius: 99px;
background: var(--coral);
box-shadow: 0 0 8px rgba(255, 82, 109, .7);
}
.swatch.instant {
height: 0;
border-top: 2px dashed var(--cyan);
background: none;
box-shadow: none;
}
.swatch.probe {
width: 9px;
height: 9px;
margin: 0 9px;
border-radius: 2px;
background: var(--yellow);
transform: rotate(45deg);
box-shadow: 0 0 9px rgba(255, 209, 102, .7);
}
.stage-formula {
position: absolute;
right: 20px;
bottom: 20px;
max-width: 300px;
padding: 11px 13px;
border: 1px solid rgba(84, 117, 153, .34);
border-radius: 10px;
color: #b9cbe0;
background: rgba(7, 16, 31, .78);
backdrop-filter: blur(8px);
font-size: 11px;
line-height: 1.48;
pointer-events: none;
}
.stage-formula strong { color: var(--yellow); }
@media (max-width: 850px) {
html, body { overflow: auto; }
#app {
grid-template-columns: 1fr;
grid-template-rows: 48vh 52vh;
height: 100vh;
}
#panel {
grid-row: 1;
border-right: 0;
border-bottom: 1px solid var(--line);
}
#stage { grid-row: 2; }
.stage-formula { display: none; }
.legend { bottom: 12px; left: 12px; }
.stage-top { top: 12px; left: 12px; right: 12px; }
.camera-help { display: none; }
}
</style>
</head>
<body>
<main id="app">
<aside id="panel">
<div class="eyebrow">Laboratório de ondas</div>
<h1>Interferência por espaçamento</h1>
<p class="intro">
Varie a geometria, o comprimento de onda e a fase relativa.
As faixas corais são <strong>nós reais</strong>: pontos cuja
<strong>amplitude de ciclo</strong> é zero.
</p>
<section class="section">
<h2 class="section-title">Fontes e onda</h2>
<div class="control">
<div class="control-head">
<label for="spacing">Espaçamento <i>d</i></label>
<output id="spacingOut" for="spacing">1,10 u</output>
</div>
<input id="spacing" type="range" min="0.35" max="3.40" step="0.05" value="1.10">
<div class="range-ends"><span>0,35 u</span><span>3,40 u</span></div>
</div>
<div class="control">
<div class="control-head">
<label for="wavelength">Comprimento de onda <i>λ</i></label>
<output id="wavelengthOut" for="wavelength">1,10 u</output>
</div>
<input id="wavelength" type="range" min="0.45" max="2.00" step="0.05" value="1.10">
<div class="range-ends"><span>0,45 u</span><span>2,00 u</span></div>
</div>
<div class="control">
<div class="control-head">
<label for="phase">Fase relativa <i>φ</i></label>
<output id="phaseOut" for="phase">0°</output>
</div>
<input id="phase" type="range" min="0" max="360" step="5" value="0">
<div class="range-ends"><span>0° · igual</span><span>180° · opostas</span></div>
</div>
<div class="control">
<div class="control-head">
<label for="time">Instante do ciclo</label>
<output id="timeOut" for="time">0,50 ciclo</output>
</div>
<input id="time" type="range" min="0" max="1" step="0.01" value="0.50">
<div class="range-ends"><span>0,00</span><span>1,00</span></div>
</div>
<div class="button-row">
<button id="playButton" class="primary" type="button">▶ Animar</button>
<button id="resetButton" type="button">Restaurar</button>
</div>
</section>
<section class="section">
<h2 class="section-title">Representação do campo</h2>
<div class="button-row">
<button id="instantButton" class="active" type="button" data-mode="instant" aria-pressed="true">Pressão instantânea</button>
<button id="amplitudeButton" type="button" data-mode="amplitude" aria-pressed="false">Amplitude do ciclo</button>
</div>
<label class="check-row">
<input id="instantTrace" type="checkbox" checked>
Mostrar zeros instantâneos — não são necessariamente nós
</label>
<p class="hint">
A malha muda com o instante; as curvas nodais dependem de
<i>d</i>, <i>λ</i> e <i>φ</i>, mas não do instante.
</p>
</section>
<section class="section">
<h2 class="section-title">Critério de nó</h2>
<div class="formula">
<strong>A<sub>ciclo</sub> = 2|cos((kΔr − φ)/2)|</strong><br>
Um ponto é nó somente quando<br>
<strong>kΔr − φ = (2m + 1)π</strong>.<br>
Equivalentemente:<br>
Δr = (m + ½)λ + (φ/2π)λ
</div>
</section>
<section class="section">
<h2 class="section-title">Sonda na mediatriz</h2>
<div class="probe-card">
<div class="probe-head">
<span class="probe-title">P · distâncias iguais</span>
<span id="nodeBadge" class="badge no">NÃO É NÓ</span>
</div>
<div class="probe-body">
<div class="metric-grid">
<div class="metric"><span>r₁ = r₂</span><b id="distanceValue">1,925 u</b></div>
<div class="metric"><span>Δr</span><b>0,000 u</b></div>
<div class="metric"><span>p₁ agora</span><b id="p1Value">0,00</b></div>
<div class="metric"><span>p₂ agora</span><b id="p2Value">0,00</b></div>
<div class="metric"><span>p total agora</span><b id="pTotalValue">0,00</b></div>
<div class="metric"><span>Amplitude do ciclo</span><b id="ampValue">2,00</b></div>
</div>
<p id="probeMessage" class="probe-message">
Zero instantâneo não é nó: as duas contributions estão em fase,
mas a pressão pode passar por zero em um único instante.
</p>
</div>
</div>
<p class="hint">
A sonda permanece a 1,925 u de cada fonte. Isso testa diretamente
a confusão entre <i>p(t)=0</i> e <i>A<sub>ciclo</sub>=0</i>.
</p>
</section>
<div class="validation">
Modelo validado: o ponto inicial tem pressão instantânea zero,
amplitude de ciclo máxima e não pertence a uma curva nodal.
</div>
</aside>
<section id="stage">
<canvas id="canvas" aria-label="Cena tridimensional de interferência entre duas fontes"></canvas>
<div class="stage-top">
<div class="stage-heading">
<small>Visualização atual</small>
<strong id="modeTitle">Pressão instantânea · t = 0,50</strong>
</div>
<div class="camera-help">
Arraste para orbitar · roda do mouse para aproximar<br>
Duplo clique para restaurar a câmera
</div>
</div>
<div class="legend">
<div class="legend-row"><span class="swatch"></span><span>Nó real: A<sub>ciclo</sub> = 0</span></div>
<div class="legend-row"><span class="swatch instant"></span><span>Zero instantâneo: não implica nó</span></div>
<div class="legend-row"><span class="swatch probe"></span><span>Sonda P na mediatriz</span></div>
</div>
<div class="stage-formula">
<strong>Por que o padrão muda?</strong><br>
A diferença de caminho <i>Δr</i> depende da posição e do espaçamento;
a condição nodal também contém <i>λ</i> e <i>φ</i>.
</div>
</section>
</main>
<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("canvas");
const stage = document.getElementById("stage");
const ui = {
spacing: document.getElementById("spacing"),
wavelength: document.getElementById("wavelength"),
phase: document.getElementById("phase"),
time: document.getElementById("time"),
spacingOut: document.getElementById("spacingOut"),
wavelengthOut: document.getElementById("wavelengthOut"),
phaseOut: document.getElementById("phaseOut"),
timeOut: document.getElementById("timeOut"),
playButton: document.getElementById("playButton"),
resetButton: document.getElementById("resetButton"),
instantButton: document.getElementById("instantButton"),
amplitudeButton: document.getElementById("amplitudeButton"),
instantTrace: document.getElementById("instantTrace"),
modeTitle: document.getElementById("modeTitle"),
distanceValue: document.getElementById("distanceValue"),
p1Value: document.getElementById("p1Value"),
p2Value: document.getElementById("p2Value"),
pTotalValue: document.getElementById("pTotalValue"),
ampValue: document.getElementById("ampValue"),
nodeBadge: document.getElementById("nodeBadge"),
probeMessage: document.getElementById("probeMessage")
};
const defaults = {
spacing: 1.10,
wavelength: 1.10,
phase: 0,
time: 0.50,
mode: "instant"
};
const state = {
spacing: defaults.spacing,
wavelength: defaults.wavelength,
phase: defaults.phase,
time: defaults.time,
mode: defaults.mode,
playing: false
};
const WORLD_W = 8.8;
const WORLD_D = 6.4;
const COLS = 73;
const ROWS = 53;
const PROBE_RADIUS = 1.925;
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.setClearColor(0x07101f, 1);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x07101f, 18, 31);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 80);
const cameraTarget = new THREE.Vector3(0, -0.05, 0);
let cameraAzimuth = 0.72;
let cameraElevation = 0.70;
let cameraRadius = 12.8;
function updateCamera() {
const aspectCompensation = camera.aspect < 1 ? 1.20 : 1;
const radius = cameraRadius * aspectCompensation;
camera.position.set(
cameraTarget.x + radius * Math.cos(cameraElevation) * Math.sin(cameraAzimuth),
cameraTarget.y + radius * Math.sin(cameraElevation),
cameraTarget.z + radius * Math.cos(cameraElevation) * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
}
scene.add(new THREE.HemisphereLight(0x9ecbff, 0x142033, 1.45));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.15);
keyLight.position.set(4.5, 8.5, 5.5);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4bdcff, 1.0);
rimLight.position.set(-5, 3.5, -5);
scene.add(rimLight);
const board = new THREE.Mesh(
new THREE.BoxGeometry(WORLD_W + 0.48, 0.24, WORLD_D + 0.48),
new THREE.MeshStandardMaterial({
color: 0x101e31,
roughness: 0.86,
metalness: 0.12,
flatShading: true
})
);
board.position.y = -0.52;
scene.add(board);
const borderMaterial = new THREE.MeshStandardMaterial({
color: 0x34506c,
roughness: 0.65,
metalness: 0.32,
flatShading: true
});
function addBorder(x, z, sx, sz) {
const strip = new THREE.Mesh(new THREE.BoxGeometry(sx, 0.10, sz), borderMaterial);
strip.position.set(x, -0.34, z);
scene.add(strip);
}
addBorder(0, -WORLD_D / 2 - 0.20, WORLD_W + 0.48, 0.08);
addBorder(0, WORLD_D / 2 + 0.20, WORLD_W + 0.48, 0.08);
addBorder(-WORLD_W / 2 - 0.20, 0, 0.08, WORLD_D + 0.48);
addBorder( WORLD_W / 2 + 0.20, 0, 0.08, WORLD_D + 0.48);
const gridPositions = [];
for (let x = -WORLD_W / 2; x <= WORLD_W / 2 + 0.001; x += 0.55) {
gridPositions.push(x, -0.385, -WORLD_D / 2, x, -0.385, WORLD_D / 2);
}
for (let z = -WORLD_D / 2; z <= WORLD_D / 2 + 0.001; z += 0.55) {
gridPositions.push(-WORLD_W / 2, -0.385, z, WORLD_W / 2, -0.385, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(gridPositions, 3));
scene.add(new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({ color: 0x6687aa, transparent: true, opacity: 0.22 })
));
const fieldPositions = new Float32Array(COLS * ROWS * 3);
const fieldColors = new Float32Array(COLS * ROWS * 3);
const fieldIndices = [];
for (let iz = 0; iz < ROWS; iz++) {
for (let ix = 0; ix < COLS; ix++) {
const index = iz * COLS + ix;
fieldPositions[index * 3] = -WORLD_W / 2 + ix * WORLD_W / (COLS - 1);
fieldPositions[index * 3 + 1] = -0.02;
fieldPositions[index * 3 + 2] = -WORLD_D / 2 + iz * WORLD_D / (ROWS - 1);
}
}
for (let iz = 0; iz < ROWS - 1; iz++) {
for (let ix = 0; ix < COLS - 1; ix++) {
const a = iz * COLS + ix;
const b = a + 1;
const d = a + COLS;
const c = d + 1;
fieldIndices.push(a, d, c, a, c, b);
}
}
const fieldGeometry = new THREE.BufferGeometry();
fieldGeometry.setAttribute("position", new THREE.BufferAttribute(fieldPositions, 3));
fieldGeometry.setAttribute("color", new THREE.BufferAttribute(fieldColors, 3));
fieldGeometry.setIndex(fieldIndices);
const fieldMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 0.68,
metalness: 0.08,
transparent: true,
opacity: 0.96,
side: THREE.DoubleSide
});
const fieldMesh = new THREE.Mesh(fieldGeometry, fieldMaterial);
fieldMesh.frustumCulled = false;
scene.add(fieldMesh);
function makeTextSprite(text, color = "#eaf4ff", width = 1.7, height = 0.38) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 512, 128);
ctx.fillStyle = "rgba(5, 14, 28, 0.86)";
ctx.fillRect(4, 18, 504, 92);
ctx.strokeStyle = color;
ctx.lineWidth = 3;
ctx.strokeRect(5, 19, 502, 90);
ctx.fillStyle = color;
ctx.font = "700 42px 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(width, height, 1);
sprite.renderOrder = 40;
return sprite;
}
function createSource(color, label) {
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.17, 0.28, 0.72, 8),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.34,
roughness: 0.42,
metalness: 0.22,
flatShading: true
})
);
body.position.y = 0.03;
group.add(body);
const beacon = new THREE.Mesh(
new THREE.OctahedronGeometry(0.18, 0),
new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: color,
emissiveIntensity: 1.25,
roughness: 0.3,
flatShading: true
})
);
beacon.position.y = 0.56;
group.add(beacon);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.34, 0.024, 5, 24),
new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.82 })
);
ring.rotation.x = Math.PI / 2;
ring.position.y = -0.32;
group.add(ring);
const labelSprite = makeTextSprite(label, color === 0x56e7ff ? "#8cf2ff" : "#ffc07b", 1.15, 0.34);
labelSprite.position.set(0, 1.02, 0);
group.add(labelSprite);
scene.add(group);
return { group, body, beacon, ring };
}
const source1 = createSource(0x56e7ff, "S1");
const source2 = createSource(0xff9f43, "S2");
const phaseHandGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0.40, 0, 0)
]);
const phaseHand = new THREE.Line(
phaseHandGeometry,
new THREE.LineBasicMaterial({ color: 0xffd166, transparent: true, opacity: 0.95 })
);
phaseHand.position.y = 0.58;
source2.group.add(phaseHand);
const mediatrixGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.405, -WORLD_D / 2),
new THREE.Vector3(0, 0.405, WORLD_D / 2)
]);
const mediatrix = new THREE.Line(
mediatrixGeometry,
new THREE.LineDashedMaterial({
color: 0xa8bfda,
dashSize: 0.16,
gapSize: 0.10,
transparent: true,
opacity: 0.36,
depthTest: false,
depthWrite: false
})
);
mediatrix.computeLineDistances();
mediatrix.renderOrder = 10;
scene.add(mediatrix);
const mediatrixLabel = makeTextSprite("MEDIATRIZ · Δr = 0", "#b9cbe0", 2.3, 0.34);
mediatrixLabel.position.set(0, 0.75, -2.73);
scene.add(mediatrixLabel);
const probeMarker = new THREE.Group();
const probeGem = new THREE.Mesh(
new THREE.OctahedronGeometry(0.14, 0),
new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0xffa62b,
emissiveIntensity: 1.2,
roughness: 0.35,
flatShading: true
})
);
probeGem.position.y = 0.68;
probeMarker.add(probeGem);
const probeRing = new THREE.Mesh(
new THREE.TorusGeometry(0.21, 0.025, 6, 28),
new THREE.MeshBasicMaterial({ color: 0xffd166 })
);
probeRing.rotation.x = Math.PI / 2;
probeRing.position.y = 0.43;
probeMarker.add(probeRing);
const instantBadge = new THREE.Mesh(
new THREE.TorusGeometry(0.31, 0.022, 6, 30),
new THREE.MeshBasicMaterial({
color: 0x56e7ff,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
instantBadge.rotation.x = Math.PI / 2;
instantBadge.position.y = 0.46;
instantBadge.renderOrder = 25;
probeMarker.add(instantBadge);
const probeLabel = makeTextSprite("P · 1,925 u", "#ffe29a", 1.55, 0.34);
probeLabel.position.set(0, 1.02, 0);
probeMarker.add(probeLabel);
scene.add(probeMarker);
const path1 = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({ color: 0x56e7ff, transparent: true, opacity: 0.48, depthTest: false })
);
const path2 = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({ color: 0xff9f43, transparent: true, opacity: 0.48, depthTest: false })
);
path1.renderOrder = 12;
path2.renderOrder = 12;
scene.add(path1, path2);
const nodeHaloMaterial = new THREE.MeshBasicMaterial({
color: 0xff526d,
transparent: true,
opacity: 0.18,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
});
const nodeCoreMaterial = new THREE.MeshBasicMaterial({
color: 0xff526d,
transparent: true,
opacity: 0.97,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
});
const instantLineMaterial = new THREE.LineDashedMaterial({
color: 0x56e7ff,
dashSize: 0.11,
gapSize: 0.075,
transparent: true,
opacity: 0.70,
depthTest: false,
depthWrite: false
});
const nodeHalo = new THREE.Mesh(new THREE.BufferGeometry(), nodeHaloMaterial);
const nodeCore = new THREE.Mesh(new THREE.BufferGeometry(), nodeCoreMaterial);
const instantContour = new THREE.LineSegments(new THREE.BufferGeometry(), instantLineMaterial);
nodeHalo.frustumCulled = false;
nodeCore.frustumCulled = false;
instantContour.frustumCulled = false;
nodeHalo.renderOrder = 20;
nodeCore.renderOrder = 22;
instantContour.renderOrder = 19;
scene.add(nodeHalo, nodeCore, instantContour);
const nodeValues = new Float32Array(COLS * ROWS);
const instantValues = new Float32Array(COLS * ROWS);
const colorZero = new THREE.Color(0x0d1a31);
const colorNegative = new THREE.Color(0x2879ff);
const colorPositive = new THREE.Color(0xffcb59);
const colorLow = new THREE.Color(0x102044);
const colorMid = new THREE.Color(0x16a7a7);
const colorHigh = new THREE.Color(0xffd166);
const tempColor = new THREE.Color();
function formatDecimal(value, digits = 2) {
return value.toLocaleString("pt-BR", {
minimumFractionDigits: digits,
maximumFractionDigits: digits
});
}
function replaceGeometry(object, geometry) {
object.geometry.dispose();
object.geometry = geometry;
object.frustumCulled = false;
}
function makeRibbonGeometry(segments, width, y) {
const positions = [];
for (const segment of segments) {
const [p, q] = segment;
const dx = q.x - p.x;
const dz = q.z - p.z;
const length = Math.hypot(dx, dz);
if (length < 1e-7) continue;
const nx = -dz / length * width * 0.5;
const nz = dx / length * width * 0.5;
const ax = p.x + nx, az = p.z + nz;
const bx = p.x - nx, bz = p.z - nz;
const cx = q.x + nx, cz = q.z + nz;
const dx2 = q.x - nx, dz2 = q.z - nz;
positions.push(
ax, y, az, bx, y, bz, cx, y, cz,
bx, y, bz, dx2, y, dz2, cx, y, cz
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
return geometry;
}
function makeLineSegmentsGeometry(segments, y) {
const positions = [];
for (const [p, q] of segments) {
positions.push(p.x, y, p.z, q.x, y, q.z);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
return geometry;
}
function edgeIntersection(a, b, p, q) {
if ((a < 0) === (b < 0)) return null;
const denominator = a - b;
if (Math.abs(denominator) < 1e-12) return null;
let t = a / denominator;
t = Math.max(0, Math.min(1, t));
return {
x: p.x + (q.x - p.x) * t,
z: p.z + (q.z - p.z) * t
};
}
function marchingSquares(values) {
const segments = [];
for (let iz = 0; iz < ROWS - 1; iz++) {
const z0 = -WORLD_D / 2 + iz * WORLD_D / (ROWS - 1);
const z1 = -WORLD_D / 2 + (iz + 1) * WORLD_D / (ROWS - 1);
for (let ix = 0; ix < COLS - 1; ix++) {
const x0 = -WORLD_W / 2 + ix * WORLD_W / (COLS - 1);
const x1 = -WORLD_W / 2 + (ix + 1) * WORLD_W / (COLS - 1);
const ia = iz * COLS + ix;
const ib = ia + 1;
const id = ia + COLS;
const ic = id + 1;
const a = values[ia];
const b = values[ib];
const c = values[ic];
const d = values[id];
const pa = { x: x0, z: z0 };
const pb = { x: x1, z: z0 };
const pc = { x: x1, z: z1 };
const pd = { x: x0, z: z1 };
const points = [];
const bottom = edgeIntersection(a, b, pa, pb);
const right = edgeIntersection(b, c, pb, pc);
const top = edgeIntersection(d, c, pd, pc);
const left = edgeIntersection(a, d, pa, pd);
if (bottom) points.push(bottom);
if (right) points.push(right);
if (top) points.push(top);
if (left) points.push(left);
if (points.length === 2) {
segments.push([points[0], points[1]]);
} else if (points.length === 4) {
const center = (a + b + c + d) * 0.25;
if (center >= 0) {
segments.push([points[0], points[1]]);
segments.push([points[2], points[3]]);
} else {
segments.push([points[0], points[3]]);
segments.push([points[1], points[2]]);
}
} else if (points.length === 3) {
segments.push([points[0], points[1]]);
segments.push([points[1], points[2]]);
}
}
}
return segments;
}
function updateFieldGeometry() {
const k = 2 * Math.PI / state.wavelength;
const phaseRadians = THREE.MathUtils.degToRad(state.phase);
const omegaT = 2 * Math.PI * state.time;
for (let iz = 0; iz < ROWS; iz++) {
const z = -WORLD_D / 2 + iz * WORLD_D / (ROWS - 1);
for (let ix = 0; ix < COLS; ix++) {
const x = -WORLD_W / 2 + ix * WORLD_W / (COLS - 1);
const index = iz * COLS + ix;
const r1 = Math.hypot(x + state.spacing / 2, z);
const r2 = Math.hypot(x - state.spacing / 2, z);
const delta = r1 - r2;
const nodeFactor = Math.cos((k * delta - phaseRadians) * 0.5);
const amplitude = 2 * Math.abs(nodeFactor);
const p1 = Math.cos(k * r1 - omegaT);
const p2 = Math.cos(k * r2 - omegaT + phaseRadians);
const pressure = p1 + p2;
nodeValues[index] = nodeFactor;
instantValues[index] = pressure;
const positionIndex = index * 3;
if (state.mode === "instant") {
fieldPositions[positionIndex + 1] = -0.02 + pressure * 0.29;
const amount = Math.min(1, Math.abs(pressure));
tempColor.copy(colorZero).lerp(pressure >= 0 ? colorPositive : colorNegative, amount);
} else {
const normalized = Math.min(1, amplitude / 2);
fieldPositions[positionIndex + 1] = -0.02 + normalized * 0.34;
if (normalized < 0.5) {
tempColor.copy(colorLow).lerp(colorMid, normalized * 2);
} else {
tempColor.copy(colorMid).lerp(colorHigh, (normalized - 0.5) * 2);
}
}
fieldColors[positionIndex] = tempColor.r;
fieldColors[positionIndex + 1] = tempColor.g;
fieldColors[positionIndex + 2] = tempColor.b;
}
}
fieldGeometry.attributes.position.needsUpdate = true;
fieldGeometry.attributes.color.needsUpdate = true;
fieldGeometry.computeVertexNormals();
const nodeSegments = marchingSquares(nodeValues);
const instantSegments = marchingSquares(instantValues);
replaceGeometry(nodeHalo, makeRibbonGeometry(nodeSegments, 0.15, 0.405));
replaceGeometry(nodeCore, makeRibbonGeometry(nodeSegments, 0.052, 0.413));
replaceGeometry(instantContour, makeLineSegmentsGeometry(instantSegments, 0.421));
instantContour.computeLineDistances();
instantContour.visible = ui.instantTrace.checked;
}
function updateSourcePositions() {
source1.group.position.x = -state.spacing / 2;
source2.group.position.x = state.spacing / 2;
phaseHand.rotation.y = -THREE.MathUtils.degToRad(state.phase);
const omegaT = 2 * Math.PI * state.time;
const phaseRadians = THREE.MathUtils.degToRad(state.phase);
const p1 = Math.cos(-omegaT);
const p2 = Math.cos(-omegaT + phaseRadians);
source1.beacon.scale.setScalar(0.88 + Math.abs(p1) * 0.28);
source2.beacon.scale.setScalar(0.88 + Math.abs(p2) * 0.28);
source1.body.material.emissiveIntensity = 0.22 + Math.abs(p1) * 0.52;
source2.body.material.emissiveIntensity = 0.22 + Math.abs(p2) * 0.52;
source1.ring.material.opacity = 0.45 + Math.abs(p1) * 0.35;
source2.ring.material.opacity = 0.45 + Math.abs(p2) * 0.35;
}
function updateProbe() {
const halfSpacing = state.spacing / 2;
const probeZ = Math.sqrt(Math.max(0, PROBE_RADIUS * PROBE_RADIUS - halfSpacing * halfSpacing));
probeMarker.position.set(0, 0, probeZ);
const source1Point = new THREE.Vector3(-halfSpacing, 0.445, 0);
const source2Point = new THREE.Vector3( halfSpacing, 0.445, 0);
const probePoint = new THREE.Vector3(0, 0.445, probeZ);
replaceGeometry(path1, new THREE.BufferGeometry().setFromPoints([source1Point, probePoint]));
replaceGeometry(path2, new THREE.BufferGeometry().setFromPoints([source2Point, probePoint]));
const k = 2 * Math.PI / state.wavelength;
const phaseRadians = THREE.MathUtils.degToRad(state.phase);
const omegaT = 2 * Math.PI * state.time;
const p1 = Math.cos(k * PROBE_RADIUS - omegaT);
const p2 = Math.cos(k * PROBE_RADIUS - omegaT + phaseRadians);
const pressure = p1 + p2;
const amplitude = 2 * Math.abs(Math.cos((0 - phaseRadians) * 0.5));
const isNode = amplitude < 1e-7;
instantBadge.visible = Math.abs(pressure) < 0.015;
ui.distanceValue.textContent = `${formatDecimal(PROBE_RADIUS, 3)} u`;
ui.p1Value.textContent = formatDecimal(p1, 2);
ui.p2Value.textContent = formatDecimal(p2, 2);
ui.pTotalValue.textContent = formatDecimal(pressure, 2);
ui.ampValue.textContent = formatDecimal(amplitude, 2);
ui.nodeBadge.textContent = isNode ? "É NÓ" : "NÃO É NÓ";
ui.nodeBadge.className = `badge ${isNode ? "yes" : "no"}`;
ui.probeMessage.className = `probe-message${isNode ? " node" : ""}`;
if (isNode) {
ui.probeMessage.innerHTML =
"<strong>Este ponto é um nó.</strong> As ondas chegando à mediatriz " +
"têm fases opostas; a pressão permanece nula durante todo o ciclo.";
} else if (Math.abs(pressure) < 0.015) {
ui.probeMessage.innerHTML =
"<strong>Zero instantâneo, mas não é um nó.</strong> neste instante " +
"as contribuições somam zero; a amplitude de ciclo é " +
`${formatDecimal(amplitude, 2)} e o ponto não pertence a uma curva nodal.`;
} else {
ui.probeMessage.innerHTML =
"<strong>Não é um nó.</strong> O valor instantâneo pode variar, mas " +
`a amplitude de ciclo é ${formatDecimal(amplitude, 2)}. Só esta última ` +
"determina se o ponto é nodal.";
}
}
function updateReadouts() {
ui.spacingOut.textContent = `${formatDecimal(state.spacing, 2)} u`;
ui.wavelengthOut.textContent = `${formatDecimal(state.wavelength, 2)} u`;
ui.phaseOut.textContent = `${formatDecimal(state.phase, 0)}°`;
ui.timeOut.textContent = `${formatDecimal(state.time, 2)} ciclo`;
ui.spacing.value = state.spacing;
ui.wavelength.value = state.wavelength;
ui.phase.value = state.phase;
ui.time.value = state.time;
const modeName = state.mode === "instant" ? "Pressão instantânea" : "Amplitude do ciclo";
ui.modeTitle.textContent = `${modeName} · t = ${formatDecimal(state.time, 2)}`;
ui.instantButton.classList.toggle("active", state.mode === "instant");
ui.amplitudeButton.classList.toggle("active", state.mode === "amplitude");
ui.instantButton.setAttribute("aria-pressed", String(state.mode === "instant"));
ui.amplitudeButton.setAttribute("aria-pressed", String(state.mode === "amplitude"));
ui.playButton.textContent = state.playing ? "❚❚ Pausar" : "▶ Animar";
}
function updateAll() {
updateFieldGeometry();
updateSourcePositions();
updateProbe();
updateReadouts();
}
function setMode(mode) {
state.mode = mode;
updateAll();
}
ui.spacing.addEventListener("input", () => {
state.spacing = Number(ui.spacing.value);
updateAll();
});
ui.wavelength.addEventListener("input", () => {
state.wavelength = Number(ui.wavelength.value);
updateAll();
});
ui.phase.addEventListener("input", () => {
state.phase = Number(ui.phase.value);
updateAll();
});
ui.time.addEventListener("input", () => {
state.time = Number(ui.time.value);
state.playing = false;
updateAll();
});
ui.instantButton.addEventListener("click", () => setMode("instant"));
ui.amplitudeButton.addEventListener("click", () => setMode("amplitude"));
ui.instantTrace.addEventListener("change", () => {
instantContour.visible = ui.instantTrace.checked;
});
ui.playButton.addEventListener("click", () => {
state.playing = !state.playing;
updateReadouts();
});
function resetCamera() {
cameraAzimuth = 0.72;
cameraElevation = 0.70;
cameraRadius = 12.8;
cameraTarget.set(0, -0.05, 0);
updateCamera();
}
ui.resetButton.addEventListener("click", () => {
state.spacing = defaults.spacing;
state.wavelength = defaults.wavelength;
state.phase = defaults.phase;
state.time = defaults.time;
state.mode = defaults.mode;
state.playing = false;
resetCamera();
updateAll();
});
let pointerDown = false;
let pointerMoved = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", event => {
pointerDown = true;
pointerMoved = false;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!pointerDown) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
if (Math.abs(dx) + Math.abs(dy) > 2) pointerMoved = true;
cameraAzimuth -= dx * 0.006;
cameraElevation = THREE.MathUtils.clamp(cameraElevation + dy * 0.005, 0.24, 1.36);
previousX = event.clientX;
previousY = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", event => {
pointerDown = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(cameraRadius + event.deltaY * 0.012, 7.5, 19.5);
updateCamera();
}, { passive: false });
canvas.addEventListener("dblclick", resetCamera);
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
new ResizeObserver(resize).observe(stage);
resize();
function validatePhysics() {
const k = 2 * Math.PI / defaults.wavelength;
const omegaT = 2 * Math.PI * defaults.time;
const p1 = Math.cos(k * PROBE_RADIUS - omegaT);
const p2 = Math.cos(k * PROBE_RADIUS - omegaT);
const amplitude = 2 * Math.abs(Math.cos(0));
const defaultProbeIsInstantZero = Math.abs(p1 + p2) < 1e-9;
const defaultProbeIsNotNode = amplitude > 1.999999;
const nodeX = defaults.spacing / 4;
const nodeR1 = nodeX + defaults.spacing / 2;
const nodeR2 = defaults.spacing / 2 - nodeX;
const nodeDelta = nodeR1 - nodeR2;
const nodeAmplitude = 2 * Math.abs(Math.cos((k * nodeDelta) / 2));
const oppositePhaseAmplitude = 2 * Math.abs(Math.cos(-Math.PI / 2));
console.assert(defaultProbeIsInstantZero, "A sonda inicial deveria ter p(t)=0.");
console.assert(defaultProbeIsNotNode, "A sonda inicial não deveria ser um nó.");
console.assert(nodeAmplitude < 1e-7, "O primeiro ramo nodal deveria ter amplitude zero.");
console.assert(oppositePhaseAmplitude < 1e-7, "A mediatriz deveria ser nodal com fase oposta.");
}
validatePhysics();
updateAll();
let previousTime = performance.now();
let lastFieldUpdate = 0;
function animate(now) {
const dt = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (state.playing && now - lastFieldUpdate > 30) {
state.time = (state.time + dt * 0.17) % 1;
updateAll();
lastFieldUpdate = now;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```