Prompt specification
Build or customize the Three.js 3D scene "Prism spectral separation model" 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: Prism spectral separation model
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/prism-spectral-separation-model-x1533
Scene Description Prompt:
Build a triangular prism with several colored ray paths representing different wavelengths; use stated illustrative refractive indices and clearly separate dispersion from simple reflection. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Technical checks: With dispersion enabled and mirror reflection disabled, show the white incident beam and all five spectral paths inside and exiting the prism. Match their colors to the displayed key.
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 (prism-spectral-separation-model-x1533):
```html
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Prisma triangular — dispersão e reflexão</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(12, 25, 42, 0.88);
--panel-strong: rgba(15, 31, 51, 0.96);
--line: rgba(128, 184, 220, 0.18);
--text: #e9f4ff;
--muted: #91a9bf;
--cyan: #48d7ff;
--green: #54e39a;
--amber: #ffd166;
--danger: #ff7387;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
overflow-x: hidden;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 16% 8%, rgba(34, 119, 160, 0.20), transparent 33rem),
radial-gradient(circle at 91% 82%, rgba(73, 53, 151, 0.18), transparent 30rem),
linear-gradient(145deg, #07111f 0%, #091525 54%, #07101b 100%);
}
button { font: inherit; }
.shell {
width: min(1580px, 100%);
margin: 0 auto;
padding: 18px;
}
header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 20px;
margin-bottom: 14px;
}
.eyebrow {
margin: 0 0 5px;
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.35rem, 2.4vw, 2.15rem);
line-height: 1.08;
letter-spacing: -0.035em;
}
.lead {
max-width: 760px;
margin: 7px 0 0;
color: var(--muted);
font-size: 0.91rem;
line-height: 1.48;
}
.formula-chip {
flex: 0 0 auto;
padding: 8px 12px;
border: 1px solid var(--line);
border-radius: 999px;
color: #b9d6ea;
background: rgba(13, 32, 52, 0.68);
font: 700 0.78rem/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
.layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
gap: 16px;
align-items: start;
}
.card {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(12px);
}
.stage {
position: relative;
height: calc(100vh - 144px);
min-height: 570px;
max-height: 790px;
background:
radial-gradient(circle at 50% 42%, rgba(30, 87, 120, 0.10), transparent 50%),
linear-gradient(180deg, rgba(6, 17, 30, 0.40), rgba(5, 12, 22, 0.74));
}
#mainCanvas,
#reflectionCanvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.stage-top {
position: absolute;
z-index: 3;
top: 14px;
left: 14px;
right: 14px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.module-tag {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border: 1px solid rgba(72, 215, 255, 0.30);
border-radius: 9px;
color: #c8f4ff;
background: rgba(5, 22, 37, 0.82);
font-size: 0.72rem;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.module-tag::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
content: "";
}
.stage-note {
max-width: 315px;
padding: 8px 10px;
border: 1px solid rgba(126, 173, 202, 0.18);
border-radius: 9px;
color: #a8bfd1;
background: rgba(6, 19, 32, 0.75);
font-size: 0.72rem;
line-height: 1.4;
text-align: right;
}
.legend {
position: absolute;
z-index: 3;
left: 14px;
right: 14px;
bottom: 14px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
padding: 10px 12px;
border: 1px solid rgba(125, 177, 208, 0.18);
border-radius: 11px;
color: #a9c0d2;
background: rgba(5, 17, 29, 0.82);
font-size: 0.72rem;
pointer-events: none;
}
.legend strong { color: #e7f5ff; }
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 18px;
height: 4px;
border-radius: 999px;
background: currentColor;
box-shadow: 0 0 7px currentColor;
}
.red { color: #ff4d57; }
.yellow { color: #ffd84a; }
.green { color: #38e889; }
.blue { color: #4a91ff; }
.violet { color: #c16bff; }
.diagnostics {
display: flex;
align-items: flex-start;
gap: 10px;
min-height: 60px;
padding: 11px 14px;
border-top: 1px solid var(--line);
background: rgba(7, 19, 32, 0.95);
}
.diagnostic-icon {
flex: 0 0 auto;
width: 22px;
height: 22px;
margin-top: 1px;
border: 1px solid rgba(84, 227, 154, 0.45);
border-radius: 50%;
color: var(--green);
font-size: 0.74rem;
font-weight: 900;
line-height: 20px;
text-align: center;
}
.diagnostics.error .diagnostic-icon {
border-color: rgba(255, 115, 135, 0.6);
color: var(--danger);
}
#diagnosticTitle {
margin: 0 0 2px;
color: #dff8e9;
font-size: 0.79rem;
font-weight: 800;
}
#diagnosticDetail {
margin: 0;
color: #91aabc;
font-size: 0.71rem;
line-height: 1.42;
}
aside {
display: grid;
gap: 12px;
}
.control-card,
.table-card,
.reflection-card {
padding: 14px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel-strong);
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
h2 {
margin: 0;
font-size: 0.86rem;
letter-spacing: 0.025em;
}
.micro {
color: var(--muted);
font-size: 0.68rem;
line-height: 1.4;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.control-button {
min-height: 41px;
padding: 9px 10px;
border: 1px solid rgba(120, 166, 195, 0.22);
border-radius: 10px;
color: #c6d8e7;
background: rgba(25, 48, 70, 0.58);
cursor: pointer;
font-size: 0.73rem;
font-weight: 760;
transition: border-color 140ms ease, background 140ms ease, transform 140ms ease;
}
.control-button:hover {
border-color: rgba(72, 215, 255, 0.55);
background: rgba(31, 65, 88, 0.76);
transform: translateY(-1px);
}
.control-button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.control-button.active {
border-color: rgba(72, 215, 255, 0.65);
color: #ecfbff;
background: rgba(27, 111, 143, 0.45);
box-shadow: inset 0 0 0 1px rgba(72, 215, 255, 0.08);
}
.control-button.reflection-active {
border-color: rgba(255, 209, 102, 0.65);
color: #fff4d1;
background: rgba(127, 91, 24, 0.38);
}
.camera-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 8px;
}
.camera-row .control-button {
min-height: 34px;
font-size: 0.68rem;
}
.separator {
height: 1px;
margin: 13px 0;
background: var(--line);
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.72rem;
}
th {
padding: 0 6px 7px;
color: #738ca2;
font-size: 0.61rem;
font-weight: 800;
letter-spacing: 0.08em;
text-align: left;
text-transform: uppercase;
}
td {
padding: 7px 6px;
border-top: 1px solid rgba(123, 170, 201, 0.10);
color: #bfd0df;
font-variant-numeric: tabular-nums;
}
td:last-child,
th:last-child { text-align: right; }
.color-cell {
display: flex;
align-items: center;
gap: 7px;
font-weight: 750;
color: #e5f1fa;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 8px currentColor;
}
.index-value {
color: #d9f3ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-weight: 800;
}
.index-note {
margin: 9px 0 0;
color: #7f98ad;
font-size: 0.66rem;
line-height: 1.45;
}
.reflection-head {
align-items: flex-start;
}
.reflection-label {
flex: 0 0 auto;
padding: 4px 7px;
border: 1px solid rgba(255, 209, 102, 0.28);
border-radius: 999px;
color: #ffe5a3;
background: rgba(111, 79, 19, 0.25);
font-size: 0.59rem;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#reflectionCanvas {
height: 172px;
margin: 9px -6px 2px;
border: 1px solid rgba(116, 162, 192, 0.12);
border-radius: 11px;
background:
radial-gradient(circle at 50% 52%, rgba(100, 76, 29, 0.12), transparent 48%),
rgba(4, 13, 24, 0.65);
}
.reflection-note {
margin: 8px 0 0;
color: #9cb0c1;
font-size: 0.68rem;
line-height: 1.45;
}
.reflection-note strong { color: #ffe4a1; }
.key {
display: inline-block;
margin: 0 2px;
padding: 1px 5px;
border: 1px solid rgba(112, 158, 188, 0.28);
border-radius: 4px;
color: #cfe5f5;
background: rgba(31, 58, 80, 0.48);
font: 700 0.65rem/1.35 ui-monospace, SFMono-Regular, Menlo, monospace;
}
@media (max-width: 1020px) {
.layout { grid-template-columns: 1fr; }
.stage { height: 62vh; min-height: 480px; }
aside { grid-template-columns: 1fr 1fr; }
.reflection-card { grid-column: 1 / -1; }
#reflectionCanvas { height: 205px; }
}
@media (max-width: 680px) {
.shell { padding: 10px; }
header { align-items: flex-start; flex-direction: column; }
.formula-chip { display: none; }
.layout { gap: 10px; }
aside { grid-template-columns: 1fr; }
.stage { height: 56vh; min-height: 430px; }
.stage-note { display: none; }
.legend { gap: 6px 9px; font-size: 0.65rem; }
}
</style>
</head>
<body>
<div class="shell">
<header>
<div>
<p class="eyebrow">Laboratório óptico interativo</p>
<h1>Prisma triangular: dispersão × reflexão</h1>
<p class="lead">
O módulo principal mostra a dispersão de um feixe branco nas cinco cores da tabela.
A reflexão simples fica em um módulo separado e usa somente um feixe branco.
</p>
</div>
<div class="formula-chip">n(λ) ↑ quando λ ↓</div>
</header>
<main class="layout">
<section class="card" aria-label="Cena principal do prisma">
<div class="stage">
<canvas id="mainCanvas" aria-label="Prisma triangular com trajetórias coloridas de dispersão"></canvas>
<div class="stage-top">
<div class="module-tag">Módulo A · Dispersão</div>
<div class="stage-note">
As cores são deslocadas em profundidade apenas para separar visualmente os cinco raios.
A refração usa os índices da tabela.
</div>
</div>
<div class="legend" id="legend">
<strong>Feixe branco →</strong>
<span class="legend-item red"><i class="swatch"></i>650 nm</span>
<span class="legend-item yellow"><i class="swatch"></i>580 nm</span>
<span class="legend-item green"><i class="swatch"></i>540 nm</span>
<span class="legend-item blue"><i class="swatch"></i>460 nm</span>
<span class="legend-item violet"><i class="swatch"></i>420 nm</span>
</div>
</div>
<div class="diagnostics" id="diagnostics" role="status" aria-live="polite">
<div class="diagnostic-icon" id="diagnosticIcon">✓</div>
<div>
<p id="diagnosticTitle">Validando a geometria…</p>
<p id="diagnosticDetail"></p>
</div>
</div>
</section>
<aside>
<section class="control-card">
<div class="section-head">
<h2>Controles dos módulos</h2>
<span class="micro">alterações testadas em tempo real</span>
</div>
<div class="button-grid">
<button class="control-button active" id="dispersionButton" type="button" aria-pressed="true">
Dispersão: ligada
</button>
<button class="control-button" id="reflectionButton" type="button" aria-pressed="false">
Reflexão: desligada
</button>
</div>
<div class="camera-row">
<button class="control-button" id="threeQuarterButton" type="button">Vista 3/4</button>
<button class="control-button" id="frontButton" type="button">Vista frontal</button>
</div>
<div class="separator"></div>
<p class="micro" style="margin:0">
O estado inicial é <strong style="color:#cdeeff">dispersão ligada</strong> e
<strong style="color:#cdeeff">reflexão desligada</strong>.
Assim, as cinco trajetórias coloridas pertencem inequivocamente ao prisma.
</p>
</section>
<section class="table-card">
<div class="section-head">
<h2>Índices refrativos ilustrativos</h2>
<span class="micro">5 trajetórias</span>
</div>
<table aria-label="Tabela de cores, comprimentos de onda e índices refrativos">
<thead>
<tr>
<th>Cor</th>
<th>λ</th>
<th>n</th>
</tr>
</thead>
<tbody id="wavelengthRows">
<tr data-ray="Vermelho">
<td><span class="color-cell red"><i class="dot"></i>Vermelho</span></td>
<td>650 nm</td>
<td class="index-value">1,400</td>
</tr>
<tr data-ray="Amarelo">
<td><span class="color-cell yellow"><i class="dot"></i>Amarelo</span></td>
<td>580 nm</td>
<td class="index-value">1,445</td>
</tr>
<tr data-ray="Verde">
<td><span class="color-cell green"><i class="dot"></i>Verde</span></td>
<td>540 nm</td>
<td class="index-value">1,490</td>
</tr>
<tr data-ray="Azul">
<td><span class="color-cell blue"><i class="dot"></i>Azul</span></td>
<td>460 nm</td>
<td class="index-value">1,520</td>
</tr>
<tr data-ray="Violeta">
<td><span class="color-cell violet"><i class="dot"></i>Violeta</span></td>
<td>420 nm</td>
<td class="index-value">1,540</td>
</tr>
</tbody>
</table>
<p class="index-note">
Conjunto didático ilustrativo, não uma tabela de vidro comercial.
O índice cresce para os comprimentos de onda menores, produzindo a separação angular.
</p>
</section>
<section class="reflection-card">
<div class="section-head reflection-head">
<div>
<h2>Módulo B · Reflexão simples</h2>
<span class="micro">espelho planar independente</span>
</div>
<span class="reflection-label" id="reflectionState">desativada</span>
</div>
<canvas id="reflectionCanvas" aria-label="Demonstração isolada de reflexão simples em um espelho"></canvas>
<p class="reflection-note">
<strong>Sem dispersão e sem cor verde:</strong> este módulo representa somente a
reflexão de um feixe branco no espelho. Ele não modifica nem substitui os cinco
trajetos do prisma.
</p>
</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 mainCanvas = document.getElementById("mainCanvas");
const reflectionCanvas = document.getElementById("reflectionCanvas");
const mainRenderer = new THREE.WebGLRenderer({
canvas: mainCanvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
mainRenderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
mainRenderer.outputColorSpace = THREE.SRGBColorSpace;
mainRenderer.setClearColor(0x07111f, 0);
const reflectionRenderer = new THREE.WebGLRenderer({
canvas: reflectionCanvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
reflectionRenderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
reflectionRenderer.outputColorSpace = THREE.SRGBColorSpace;
reflectionRenderer.setClearColor(0x07111f, 0);
const mainScene = new THREE.Scene();
const reflectionScene = new THREE.Scene();
const mainCamera = new THREE.OrthographicCamera(-4, 4, 2.5, -2.5, 0.1, 100);
const reflectionCamera = new THREE.OrthographicCamera(-2.7, 2.7, 1.4, -1.4, 0.1, 50);
const cameraTarget = new THREE.Vector3(-0.05, -0.02, 0);
mainCamera.position.set(2.45, 1.48, 8.2);
mainCamera.lookAt(cameraTarget);
reflectionCamera.position.set(0.55, 0.25, 6);
reflectionCamera.lookAt(0, 0.15, 0);
mainScene.add(new THREE.HemisphereLight(0xbcecff, 0x102036, 2.1));
const mainLight = new THREE.DirectionalLight(0xffffff, 2.3);
mainLight.position.set(3, 5, 6);
mainScene.add(mainLight);
reflectionScene.add(new THREE.HemisphereLight(0xe7f7ff, 0x152039, 2.4));
const reflectionLight = new THREE.DirectionalLight(0xffffff, 2.5);
reflectionLight.position.set(2, 4, 5);
reflectionScene.add(reflectionLight);
const wavelengths = [
{ name: "Vermelho", lambda: 650, n: 1.400, color: 0xff4d57, css: "red", z: -0.32 },
{ name: "Amarelo", lambda: 580, n: 1.445, color: 0xffd84a, css: "yellow", z: -0.16 },
{ name: "Verde", lambda: 540, n: 1.490, color: 0x38e889, css: "green", z: 0.00 },
{ name: "Azul", lambda: 460, n: 1.520, color: 0x4a91ff, css: "blue", z: 0.16 },
{ name: "Violeta", lambda: 420, n: 1.540, color: 0xc16bff, css: "violet", z: 0.32 }
];
const state = {
dispersion: true,
reflection: false,
traces: [],
reflectionTrace: null,
lastTest: null
};
// Cross-section of the triangular prism, ordered counter-clockwise.
const prismPolygon = [
[-1.65, -1.45],
[ 1.65, -1.45],
[ 0.00, 1.55]
];
const sourceXY = [-2.95, 0.15];
const prismDepth = 1.56;
const mainRayGroup = new THREE.Group();
mainRayGroup.name = "Trajetórias de dispersão";
mainScene.add(mainRayGroup);
const reflectionRayGroup = new THREE.Group();
reflectionRayGroup.name = "Reflexão simples isolada";
reflectionScene.add(reflectionRayGroup);
const animatedMarkers = [];
function add2(a, b) {
return [a[0] + b[0], a[1] + b[1]];
}
function sub2(a, b) {
return [a[0] - b[0], a[1] - b[1]];
}
function mul2(a, k) {
return [a[0] * k, a[1] * k];
}
function dot2(a, b) {
return a[0] * b[0] + a[1] * b[1];
}
function cross2(a, b) {
return a[0] * b[1] - a[1] * b[0];
}
function length2(a) {
return Math.hypot(a[0], a[1]);
}
function normalize2(a) {
const length = length2(a);
if (length < 1e-12) return [0, 0];
return [a[0] / length, a[1] / length];
}
function outwardNormal(edgeIndex) {
const a = prismPolygon[edgeIndex];
const b = prismPolygon[(edgeIndex + 1) % prismPolygon.length];
const edge = sub2(b, a);
return normalize2([edge[1], -edge[0]]);
}
function intersectRayPolygon(origin, direction) {
let best = null;
for (let i = 0; i < prismPolygon.length; i++) {
const a = prismPolygon[i];
const b = prismPolygon[(i + 1) % prismPolygon.length];
const edge = sub2(b, a);
const denominator = cross2(direction, edge);
if (Math.abs(denominator) < 1e-10) continue;
const relative = sub2(a, origin);
const t = cross2(relative, edge) / denominator;
const u = cross2(relative, direction) / denominator;
if (t > 1e-6 && u >= -1e-7 && u <= 1 + 1e-7) {
if (!best || t < best.t) {
best = {
t,
edgeIndex: i,
point: add2(origin, mul2(direction, t))
};
}
}
}
return best;
}
function refract2(direction, surfaceNormal, n1, n2) {
let normal = surfaceNormal.slice();
if (dot2(direction, normal) > 0) normal = mul2(normal, -1);
const eta = n1 / n2;
const cosIncident = Math.max(-1, Math.min(1, -dot2(direction, normal)));
const discriminant = 1 - eta * eta * (1 - cosIncident * cosIncident);
if (discriminant < -1e-9) return null;
const coefficient = eta * cosIncident - Math.sqrt(Math.max(0, discriminant));
return normalize2(add2(mul2(direction, eta), mul2(normal, coefficient)));
}
function tracePrismRay(index) {
const wavelength = wavelengths[index];
const incidentDirection = [1, 0];
const entryHit = intersectRayPolygon(sourceXY, incidentDirection);
if (!entryHit) {
return { ok: false, reason: "O feixe não encontrou a face de entrada.", tir: false };
}
const internalDirection = refract2(
incidentDirection,
outwardNormal(entryHit.edgeIndex),
1,
wavelength.n
);
if (!internalDirection) {
return { ok: false, reason: "Refração total na entrada.", tir: true };
}
const internalOrigin = add2(entryHit.point, mul2(internalDirection, 1e-5));
const exitHit = intersectRayPolygon(internalOrigin, internalDirection);
if (!exitHit) {
return { ok: false, reason: "O raio não encontrou uma saída do prisma.", tir: false };
}
const outputDirection = refract2(
internalDirection,
outwardNormal(exitHit.edgeIndex),
wavelength.n,
1
);
if (!outputDirection) {
return { ok: false, reason: "Refração total na face de saída.", tir: true };
}
const outputDirection3Check = dot2(outputDirection, outwardNormal(exitHit.edgeIndex));
if (outputDirection3Check <= 0) {
return { ok: false, reason: "A direção de saída aponta para dentro do prisma.", tir: false };
}
const outputEnd = add2(exitHit.point, mul2(outputDirection, 1.72));
return {
ok: true,
tir: false,
wavelength,
entry: entryHit.point,
entryEdge: entryHit.edgeIndex,
exit: exitHit.point,
exitEdge: exitHit.edgeIndex,
internalDirection,
outputDirection,
outputEnd,
internalLength: length2(sub2(exitHit.point, entryHit.point)),
outputLength: length2(sub2(outputEnd, exitHit.point))
};
}
function addCylinder(group, start, end, radius, material, radialSegments = 7) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
if (length < 1e-6) return null;
const geometry = new THREE.CylinderGeometry(radius, radius, length, radialSegments, 1, false);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
mesh.renderOrder = 5;
group.add(mesh);
return mesh;
}
function addArrow(group, point, direction, material, scale = 1) {
const geometry = new THREE.ConeGeometry(0.075 * scale, 0.19 * scale, 7, 1);
const arrow = new THREE.Mesh(geometry, material);
arrow.position.copy(point);
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
arrow.renderOrder = 6;
group.add(arrow);
return arrow;
}
function addSphere(group, point, radius, material, segments = 8) {
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(radius, segments, Math.max(4, segments - 2)),
material
);
mesh.position.copy(point);
mesh.renderOrder = 6;
group.add(mesh);
return mesh;
}
function makeRayMaterial(color, opacity = 0.96) {
return new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false,
depthTest: false,
toneMapped: false
});
}
function clearDynamicGroup(group) {
const geometries = new Set();
const materials = new Set();
group.traverse(object => {
if (object.geometry) geometries.add(object.geometry);
if (object.material) {
if (Array.isArray(object.material)) object.material.forEach(m => materials.add(m));
else materials.add(object.material);
}
});
geometries.forEach(geometry => geometry.dispose());
materials.forEach(material => material.dispose());
group.clear();
}
function samplePolyline(points, t) {
const lengths = [];
let total = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
lengths.push(length);
total += length;
}
let remaining = Math.max(0, Math.min(1, t)) * total;
for (let i = 0; i < lengths.length; i++) {
if (remaining <= lengths[i] || i === lengths.length - 1) {
const localT = lengths[i] > 0 ? remaining / lengths[i] : 0;
return points[i].clone().lerp(points[i + 1], localT);
}
remaining -= lengths[i];
}
return points[points.length - 1].clone();
}
function buildGrid() {
const positions = [];
const xMin = -4.2;
const xMax = 4.2;
const yMin = -2.2;
const yMax = 2.2;
const step = 0.4;
for (let x = xMin; x <= xMax + 1e-6; x += step) {
positions.push(x, yMin, -1.03, x, yMax, -1.03);
}
for (let y = yMin; y <= yMax + 1e-6; y += step) {
positions.push(xMin, y, -1.03, xMax, y, -1.03);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
const grid = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: 0x29516b,
transparent: true,
opacity: 0.27,
depthWrite: false
})
);
grid.renderOrder = 0;
mainScene.add(grid);
const axisMaterial = new THREE.LineBasicMaterial({
color: 0x3a7896,
transparent: true,
opacity: 0.45,
depthWrite: false
});
const axisGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-4.2, 0, -1.02),
new THREE.Vector3(4.2, 0, -1.02),
new THREE.Vector3(0, -2.2, -1.02),
new THREE.Vector3(0, 2.2, -1.02)
]);
const axes = new THREE.LineSegments(axisGeometry, axisMaterial);
axes.renderOrder = 0;
mainScene.add(axes);
}
function buildPrism() {
const shape = new THREE.Shape();
shape.moveTo(prismPolygon[0][0], prismPolygon[0][1]);
shape.lineTo(prismPolygon[1][0], prismPolygon[1][1]);
shape.lineTo(prismPolygon[2][0], prismPolygon[2][1]);
shape.closePath();
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: prismDepth,
steps: 1,
bevelEnabled: false,
curveSegments: 1
});
geometry.translate(0, 0, -prismDepth / 2);
geometry.computeVertexNormals();
const prism = new THREE.Mesh(
geometry,
new THREE.MeshPhysicalMaterial({
color: 0x55d9f2,
roughness: 0.24,
metalness: 0.05,
transparent: true,
opacity: 0.17,
transmission: 0.12,
side: THREE.DoubleSide,
depthWrite: false
})
);
prism.renderOrder = 1;
mainScene.add(prism);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({
color: 0xa8efff,
transparent: true,
opacity: 0.85,
depthWrite: false
})
);
edges.renderOrder = 2;
mainScene.add(edges);
const wire = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color: 0x87e9ff,
wireframe: true,
transparent: true,
opacity: 0.075,
depthWrite: false
})
);
wire.renderOrder = 2;
mainScene.add(wire);
const sourceHousing = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.44, 1.02),
new THREE.MeshStandardMaterial({
color: 0xc8dbe8,
roughness: 0.34,
metalness: 0.45
})
);
sourceHousing.position.set(-3.10, sourceXY[1], 0);
sourceHousing.renderOrder = 2;
mainScene.add(sourceHousing);
const aperture = addCylinder(
mainScene,
new THREE.Vector3(-2.94, sourceXY[1], 0),
new THREE.Vector3(-2.83, sourceXY[1], 0),
0.15,
new THREE.MeshBasicMaterial({
color: 0xf3fbff,
transparent: true,
opacity: 0.9,
depthWrite: false
}),
12
);
if (aperture) aperture.renderOrder = 3;
}
function drawPrismRay(trace, rayIndex, isDispersion) {
const rayGroup = new THREE.Group();
rayGroup.userData.rayName = isDispersion ? trace.wavelength.name : "Branco";
rayGroup.userData.hasInternal = true;
const z = isDispersion ? trace.wavelength.z : 0;
const source = new THREE.Vector3(sourceXY[0], sourceXY[1], z);
const entry = new THREE.Vector3(trace.entry[0], trace.entry[1], z);
const exit = new THREE.Vector3(trace.exit[0], trace.exit[1], z);
const end = new THREE.Vector3(trace.outputEnd[0], trace.outputEnd[1], z);
const whiteMaterial = makeRayMaterial(0xf3f8ff, 0.62);
const rayMaterial = makeRayMaterial(
isDispersion ? trace.wavelength.color : 0xf4f8ff,
isDispersion ? 0.98 : 0.92
);
addCylinder(rayGroup, source, entry, isDispersion ? 0.013 : 0.026, whiteMaterial, 6);
addCylinder(rayGroup, entry, exit, isDispersion ? 0.029 : 0.039, rayMaterial, 7);
addCylinder(rayGroup, exit, end, isDispersion ? 0.029 : 0.039, rayMaterial, 7);
const internalDirection3 = exit.clone().sub(entry).normalize();
const outputDirection3 = end.clone().sub(exit).normalize();
addArrow(
rayGroup,
entry.clone().lerp(exit, 0.67),
internalDirection3,
rayMaterial,
isDispersion ? 0.83 : 0.95
);
addArrow(
rayGroup,
exit.clone().lerp(end, 0.72),
outputDirection3,
rayMaterial,
isDispersion ? 0.95 : 1.05
);
addSphere(rayGroup, entry, isDispersion ? 0.043 : 0.052, rayMaterial);
addSphere(rayGroup, exit, isDispersion ? 0.047 : 0.055, rayMaterial);
addSphere(rayGroup, end, isDispersion ? 0.047 : 0.055, rayMaterial);
const markerMaterial = makeRayMaterial(
isDispersion ? trace.wavelength.color : 0xffffff,
1
);
const marker = addSphere(rayGroup, entry, 0.052, markerMaterial, 7);
animatedMarkers.push({
mesh: marker,
points: [entry, exit, end],
phase: (rayIndex + 0.15) / Math.max(1, wavelengths.length),
speed: 0.19
});
mainRayGroup.add(rayGroup);
}
function buildMainRays() {
clearDynamicGroup(mainRayGroup);
for (let i = animatedMarkers.length - 1; i >= 0; i--) {
if (animatedMarkers[i].owner === "prism") animatedMarkers.splice(i, 1);
}
state.traces = [];
if (state.dispersion) {
wavelengths.forEach((wavelength, index) => {
const trace = tracePrismRay(index);
state.traces.push(trace);
if (trace.ok) drawPrismRay(trace, index, true);
});
} else {
const trace = tracePrismRay(2);
state.traces.push(trace);
if (trace.ok) drawPrismRay(trace, 0, false);
}
mainRayGroup.children.forEach(child => {
if (child.userData.rayName) child.userData.owner = "prism";
});
animatedMarkers.forEach(marker => {
if (marker.owner === undefined) marker.owner = "prism";
});
}
function buildMirror() {
const mirrorGroup = new THREE.Group();
reflectionScene.add(mirrorGroup);
const impact = new THREE.Vector3(-0.12, -0.25, 0);
const angle = THREE.MathUtils.degToRad(20);
const tangent = new THREE.Vector3(Math.cos(angle), Math.sin(angle), 0);
const normal = new THREE.Vector3(-Math.sin(angle), Math.cos(angle), 0);
const mirror = new THREE.Mesh(
new THREE.BoxGeometry(1.76, 0.10, 0.34),
new THREE.MeshStandardMaterial({
color: 0x87c5d9,
roughness: 0.18,
metalness: 0.72
})
);
mirror.position.copy(impact);
mirror.rotation.z = angle;
mirrorGroup.add(mirror);
const back = new THREE.Mesh(
new THREE.BoxGeometry(1.82, 0.16, 0.10),
new THREE.MeshStandardMaterial({ color: 0x334a5c, roughness: 0.68 })
);
back.position.copy(impact).add(new THREE.Vector3(0, -0.07, -0.12));
back.rotation.z = angle;
mirrorGroup.add(back);
const stand = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.65, 0.18),
new THREE.MeshStandardMaterial({ color: 0x3a5266, roughness: 0.72 })
);
stand.position.set(-0.25, -0.67, -0.08);
mirrorGroup.add(stand);
return { impact, tangent, normal };
}
const mirrorGeometry = buildMirror();
function buildReflection() {
clearDynamicGroup(reflectionRayGroup);
for (let i = animatedMarkers.length - 1; i >= 0; i--) {
if (animatedMarkers[i].owner === "reflection") animatedMarkers.splice(i, 1);
}
state.reflectionTrace = null;
if (!state.reflection) return;
const source = new THREE.Vector3(-1.90, 1.16, 0);
const impact = mirrorGeometry.impact.clone();
const incomingDirection = impact.clone().sub(source).normalize();
const reflectedDirection = incomingDirection.clone()
.addScaledVector(
mirrorGeometry.normal,
-2 * incomingDirection.dot(mirrorGeometry.normal)
)
.normalize();
const end = impact.clone().addScaledVector(reflectedDirection, 1.57);
const beamMaterial = makeRayMaterial(0xf8fbff, 0.96);
const impactMaterial = makeRayMaterial(0xffe19a, 1);
addCylinder(reflectionRayGroup, source, impact, 0.027, beamMaterial, 7);
addCylinder(reflectionRayGroup, impact, end, 0.027, beamMaterial, 7);
addArrow(reflectionRayGroup, source.clone().lerp(impact, 0.72), incomingDirection, beamMaterial, 0.9);
addArrow(reflectionRayGroup, impact.clone().lerp(end, 0.68), reflectedDirection, beamMaterial, 0.9);
addSphere(reflectionRayGroup, impact, 0.065, impactMaterial, 9);
const marker = addSphere(reflectionRayGroup, source, 0.052, beamMaterial, 8);
animatedMarkers.push({
mesh: marker,
points: [source, impact, end],
phase: 0.20,
speed: 0.28,
owner: "reflection"
});
state.reflectionTrace = {
ok: true,
source,
impact,
end,
incomingDirection,
reflectedDirection,
pathLength: source.distanceTo(impact) + impact.distanceTo(end)
};
}
function testCurrentState() {
const issues = [];
if (state.dispersion) {
if (state.traces.length !== 5) {
issues.push(`foram calculados ${state.traces.length} trajetos em vez de 5`);
}
state.traces.forEach(trace => {
if (!trace.ok) {
issues.push(`${trace.wavelength?.name || "raio"}: ${trace.reason}`);
} else {
if (trace.internalLength < 0.20) issues.push(`${trace.wavelength.name}: trecho interno curto`);
if (trace.outputLength < 0.80) issues.push(`${trace.wavelength.name}: saída curta`);
if (trace.tir) issues.push(`${trace.wavelength.name}: reflexão total inesperada`);
if (trace.exitEdge !== 1) issues.push(`${trace.wavelength.name}: saída pela face incorreta`);
}
});
const renderedGreen = mainRayGroup.children.some(
child => child.userData.rayName === "Verde" && child.userData.hasInternal === true
);
if (!renderedGreen) {
issues.push("a trajetória verde não está renderizada dentro do prisma");
}
} else {
if (state.traces.length !== 1) issues.push("o modo sem dispersão não produziu um único feixe");
const renderedColored = mainRayGroup.children.some(
child => child.userData.rayName !== "Branco"
);
if (renderedColored) issues.push("permanecem trajetos coloridos com a dispersão desligada");
}
if (state.reflection) {
if (!state.reflectionTrace?.ok) {
issues.push("a reflexão simples não.produziu uma trajetória válida");
}
if (reflectionRayGroup.children.length === 0) {
issues.push("o módulo de reflexão está vazio despite o estado ligado");
}
const greenReflection = reflectionRayGroup.children.some(
object => object.material?.color?.getHex?.() === 0x38e889
);
if (greenReflection) issues.push("uma cor da tabela foi reutilizada no módulo de reflexão");
} else if (reflectionRayGroup.children.length !== 0) {
issues.push("o módulo de reflexão ainda contém raios com a reflexão desligada");
}
state.lastTest = {
ok: issues.length === 0,
issues,
timestamp: new Date().toISOString()
};
return state.lastTest;
}
function updateDiagnostics() {
const result = testCurrentState();
const diagnostics = document.getElementById("diagnostics");
const icon = document.getElementById("diagnosticIcon");
const title = document.getElementById("diagnosticTitle");
const detail = document.getElementById("diagnosticDetail");
diagnostics.classList.toggle("error", !result.ok);
icon.textContent = result.ok ? "✓" : "!";
if (!result.ok) {
title.textContent = "Falha na validação geométrica";
detail.textContent = result.issues.join(" · ");
return;
}
if (state.dispersion) {
title.textContent = "Geometria validada: 5 trajetórias no prisma";
detail.textContent =
`Dispersão ligada · Reflexão ${state.reflection ? "ligada" : "desligada"} — ` +
"5/5 cores têm entrada, trecho interno e saída; o verde foi confirmado dentro do prisma.";
} else {
title.textContent = "Geometria validada: feixe branco único";
detail.textContent =
`Dispersão desligada · Reflexão ${state.reflection ? "ligada" : "desligada"} — ` +
"há 1/1 trajeto branco e 0/0 trajetos coloridos no módulo do prisma.";
}
if (state.reflection) {
detail.textContent += " A reflexão branca do módulo separado também foi validada.";
}
}
function updateControls() {
const dispersionButton = document.getElementById("dispersionButton");
const reflectionButton = document.getElementById("reflectionButton");
const reflectionState = document.getElementById("reflectionState");
dispersionButton.textContent = state.dispersion ? "Dispersão: ligada" : "Dispersão: desligada";
dispersionButton.classList.toggle("active", state.dispersion);
dispersionButton.setAttribute("aria-pressed", String(state.dispersion));
reflectionButton.textContent = state.reflection ? "Reflexão: ligada" : "Reflexão: desligada";
reflectionButton.classList.toggle("active", state.reflection);
reflectionButton.classList.toggle("reflection-active", state.reflection);
reflectionButton.setAttribute("aria-pressed", String(state.reflection));
reflectionState.textContent = state.reflection ? "ativada" : "desativada";
const legend = document.getElementById("legend");
if (state.dispersion) {
legend.innerHTML = `
<strong>Feixe branco →</strong>
<span class="legend-item red"><i class="swatch"></i>650 nm</span>
<span class="legend-item yellow"><i class="swatch"></i>580 nm</span>
<span class="legend-item green"><i class="swatch"></i>540 nm</span>
<span class="legend-item blue"><i class="swatch"></i>460 nm</span>
<span class="legend-item violet"><i class="swatch"></i>420 nm</span>
`;
} else {
legend.innerHTML = "<strong>Feixe branco único</strong><span>Dispersão desligada: as cores foram combinadas.</span>";
}
document.querySelectorAll("#wavelengthRows tr").forEach(row => {
row.style.opacity = state.dispersion ? "1" : "0.43";
});
}
function rebuildAll() {
buildMainRays();
buildReflection();
updateControls();
updateDiagnostics();
}
function setCamera(mode) {
if (mode === "front") {
mainCamera.position.set(0, 0.02, 9.5);
cameraTarget.set(-0.05, -0.02, 0);
} else {
mainCamera.position.set(2.45, 1.48, 8.2);
cameraTarget.set(-0.05, -0.02, 0);
}
mainCamera.lookAt(cameraTarget);
}
document.getElementById("dispersionButton").addEventListener("click", () => {
state.dispersion = !state.dispersion;
rebuildAll();
});
document.getElementById("reflectionButton").addEventListener("click", () => {
state.reflection = !state.reflection;
rebuildAll();
});
document.getElementById("threeQuarterButton").addEventListener("click", () => setCamera("three-quarter"));
document.getElementById("frontButton").addEventListener("click", () => setCamera("front"));
document.getElementById("threeQuarterButton").addEventListener("click", () => {
document.getElementById("threeQuarterButton").classList.add("active");
document.getElementById("frontButton").classList.remove("active");
});
document.getElementById("frontButton").addEventListener("click", () => {
document.getElementById("frontButton").classList.add("active");
document.getElementById("threeQuarterButton").classList.remove("active");
});
function resizeMain() {
const width = Math.max(1, mainCanvas.clientWidth);
const height = Math.max(1, mainCanvas.clientHeight);
const aspect = width / height;
const viewHeight = Math.max(4.35, 6.9 / aspect);
mainCamera.left = -viewHeight * aspect / 2;
mainCamera.right = viewHeight * aspect / 2;
mainCamera.top = viewHeight / 2;
mainCamera.bottom = -viewHeight / 2;
mainCamera.updateProjectionMatrix();
mainRenderer.setSize(width, height, false);
}
function resizeReflection() {
const width = Math.max(1, reflectionCanvas.clientWidth);
const height = Math.max(1, reflectionCanvas.clientHeight);
const aspect = width / height;
const viewHeight = Math.max(2.75, 5.05 / aspect);
reflectionCamera.left = -viewHeight * aspect / 2;
reflectionCamera.right = viewHeight * aspect / 2;
reflectionCamera.top = viewHeight / 2;
reflectionCamera.bottom = -viewHeight / 2;
reflectionCamera.updateProjectionMatrix();
reflectionRenderer.setSize(width, height, false);
}
const mainResizeObserver = new ResizeObserver(resizeMain);
mainResizeObserver.observe(mainCanvas);
const reflectionResizeObserver = new ResizeObserver(resizeReflection);
reflectionResizeObserver.observe(reflectionCanvas);
buildGrid();
buildPrism();
resizeMain();
resizeReflection();
rebuildAll();
document.getElementById("threeQuarterButton").classList.add("active");
function animate(now) {
const seconds = now * 0.001;
animatedMarkers.forEach(marker => {
const t = (seconds * marker.speed + marker.phase) % 1;
marker.mesh.position.copy(samplePolyline(marker.points, t));
});
mainRenderer.render(mainScene, mainCamera);
reflectionRenderer.render(reflectionScene, reflectionCamera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// Exposed for automated inspection in addition to the visible on-screen diagnostics.
window.__prismDiagnostics = {
getState: () => ({ dispersion: state.dispersion, reflection: state.reflection }),
test: () => testCurrentState(),
getTraces: () => state.traces.map(trace => ({
name: trace.wavelength?.name,
ok: trace.ok,
tir: trace.tir,
internalLength: trace.internalLength,
outputLength: trace.outputLength,
entry: trace.entry,
exit: trace.exit
}))
};
</script>
</body>
</html>
```