Prompt specification
Build or customize the Three.js 3D scene "Slit-width diffraction 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: Slit-width diffraction explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/slit-width-diffraction-explorer-x1532
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows wave diffraction through openings. Let users adjust opening width and wavelength in a scalar far-field model; update normalized intensity and explicitly handle the central limit without dividing by zero. Low-poly.
Working Three.js Starter (slit-width-diffraction-explorer-x1532):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Low-Poly Slit Diffraction Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: #0b1726;
--panel-2: #101f31;
--line: #22364d;
--text: #e8f2ff;
--muted: #8ba1b8;
--cyan: #52e0d0;
--cyan-2: #21aeb8;
--orange: #ffb454;
--purple: #8b79d6;
}
* {
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:focus-visible,
input:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
.app {
display: grid;
grid-template-rows: 68px minmax(0, 1fr);
width: 100%;
height: 100%;
}
header {
z-index: 5;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(7, 17, 29, 0.96);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 30px;
height: 30px;
flex: 0 0 auto;
border: 2px solid var(--cyan);
transform: rotate(45deg);
}
.brand-mark::after {
content: "";
position: absolute;
top: 5px;
bottom: 5px;
left: 12px;
width: 3px;
background: var(--orange);
}
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.1;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
}
.header-status {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 10px;
border: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
white-space: nowrap;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
main {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
min-height: 0;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 42%, rgba(31, 95, 115, 0.14), transparent 45%),
var(--bg);
}
#stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.stage-hud {
position: absolute;
z-index: 2;
pointer-events: none;
}
.stage-hud.top-left {
top: 22px;
left: 24px;
}
.stage-hud.bottom-left {
bottom: 20px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 20px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.stage-title {
margin-top: 7px;
font-size: clamp(20px, 2.5vw, 34px);
font-weight: 650;
letter-spacing: -0.03em;
}
.stage-subtitle {
max-width: 480px;
margin-top: 8px;
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
color: var(--muted);
font-size: 10px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 14px;
height: 3px;
background: var(--cyan);
}
.swatch.orange {
background: var(--orange);
}
.swatch.purple {
background: var(--purple);
}
.camera-tools {
display: flex;
gap: 8px;
pointer-events: auto;
}
.small-button {
border: 1px solid var(--line);
padding: 8px 10px;
background: rgba(11, 23, 38, 0.9);
color: var(--text);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
}
.small-button:hover {
border-color: var(--cyan);
color: var(--cyan);
}
aside {
z-index: 4;
min-height: 0;
overflow: auto;
padding: 22px;
border-left: 1px solid var(--line);
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 20px;
}
.panel-heading h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.01em;
}
.panel-heading p {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
}
.model-badge {
padding: 6px 8px;
border: 1px solid rgba(82, 224, 208, 0.32);
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
white-space: nowrap;
}
.control {
margin-bottom: 22px;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.control-label label {
font-size: 12px;
font-weight: 700;
}
output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
font-size: 12px;
font-weight: 750;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 6px 0;
appearance: none;
border-radius: 0;
background: linear-gradient(
to right,
var(--cyan) 0%,
var(--cyan) var(--fill, 50%),
var(--line) var(--fill, 50%),
var(--line) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 2px solid var(--panel);
border-radius: 0;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
transform: rotate(45deg);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid var(--panel);
border-radius: 0;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
transform: rotate(45deg);
}
.range-scale {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: #61778e;
font-size: 9px;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 0 0 20px;
}
.preset {
padding: 9px 5px;
border: 1px solid var(--line);
background: var(--panel-2);
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
cursor: pointer;
}
.preset:hover,
.preset.active {
border-color: var(--cyan);
color: var(--cyan);
}
.plot-card {
position: relative;
margin-bottom: 16px;
border: 1px solid var(--line);
background: #081321;
}
.plot-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 12px 13px;
border-bottom: 1px solid var(--line);
}
.plot-header strong {
font-size: 10px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.plot-header span {
color: var(--muted);
font-size: 9px;
}
#plot {
position: relative;
height: 205px;
}
#plot canvas {
display: block;
width: 100%;
height: 100%;
}
.plot-label {
position: absolute;
z-index: 2;
color: #6f8499;
font-size: 9px;
pointer-events: none;
font-variant-numeric: tabular-nums;
}
.plot-label.y-one {
top: 12px;
left: 8px;
}
.plot-label.y-half {
top: 51%;
left: 8px;
}
.plot-label.y-zero {
bottom: 21px;
left: 8px;
}
.plot-label.x-left {
bottom: 5px;
left: 9px;
}
.plot-label.x-center {
bottom: 5px;
left: 50%;
transform: translateX(-50%);
}
.plot-label.x-right {
right: 9px;
bottom: 5px;
}
.formula {
margin-bottom: 16px;
padding: 13px;
border-left: 2px solid var(--orange);
background: rgba(255, 180, 84, 0.055);
}
.formula-main {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
color: #f4d6ae;
}
.formula-note {
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 16px;
}
.metric {
min-width: 0;
padding: 11px;
border: 1px solid var(--line);
background: var(--panel-2);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 5px;
overflow: hidden;
color: var(--text);
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.limit-card {
display: flex;
align-items: center;
gap: 11px;
padding: 12px;
border: 1px solid rgba(82, 224, 208, 0.25);
background: rgba(82, 224, 208, 0.055);
}
.limit-icon {
display: grid;
width: 29px;
height: 29px;
flex: 0 0 auto;
place-items: center;
border: 1px solid var(--cyan);
color: var(--cyan);
font-size: 13px;
font-weight: 800;
}
.limit-card strong {
display: block;
color: var(--cyan);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.limit-card p {
margin: 4px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
@media (max-width: 900px) {
html,
body {
height: auto;
min-height: 100%;
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
grid-template-rows: 68px auto;
}
main {
grid-template-columns: 1fr;
}
#stage {
min-height: 58vh;
}
aside {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.stage-subtitle {
max-width: 390px;
}
}
@media (max-width: 520px) {
header {
padding: 0 15px;
}
.header-status {
display: none;
}
aside {
padding: 18px 15px;
}
.stage-hud.top-left {
top: 17px;
left: 16px;
}
.stage-hud.bottom-left {
left: 16px;
right: 16px;
align-items: flex-start;
flex-direction: column;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Slit / Field</h1>
<p>Low-poly scalar diffraction laboratory</p>
</div>
</div>
<div class="header-status">
<span class="status-dot"></span>
Real-time · 721 samples
</div>
</header>
<main>
<section id="stage" aria-label="Interactive three-dimensional diffraction model">
<div class="stage-hud top-left">
<div class="eyebrow">Fraunhofer single slit</div>
<div class="stage-title">Angular intensity field</div>
<div class="stage-subtitle">
Drag to orbit, scroll to zoom. The screen shows normalized
intensity against observation angle.
</div>
</div>
<div class="stage-hud bottom-left">
<div class="legend">
<span><i class="swatch"></i> Diffraction pattern</span>
<span><i class="swatch orange"></i> Intensity curve</span>
<span><i class="swatch purple"></i> Aperture</span>
</div>
<div class="camera-tools">
<button id="resetCamera" class="small-button" type="button">
Reset view
</button>
</div>
</div>
</section>
<aside>
<div class="panel-heading">
<div>
<h2>Model parameters</h2>
<p>Ideal slit in an infinitely long opaque barrier</p>
</div>
<div class="model-badge">λ / a</div>
</div>
<div class="control">
<div class="control-label">
<label for="width">Opening width, a</label>
<output id="widthOutput" for="width">0.85 µm</output>
</div>
<input
id="width"
type="range"
min="0.15"
max="3"
step="0.01"
value="0.85"
>
<div class="range-scale">
<span>0.15 µm</span>
<span>3.00 µm</span>
</div>
</div>
<div class="control">
<div class="control-label">
<label for="wavelength">Wavelength, λ</label>
<output id="wavelengthOutput" for="wavelength">0.45 µm</output>
</div>
<input
id="wavelength"
type="range"
min="0.15"
max="1.5"
step="0.01"
value="0.45"
>
<div class="range-scale">
<span>0.15 µm</span>
<span>1.50 µm</span>
</div>
</div>
<div class="presets" aria-label="Model presets">
<button class="preset" type="button" data-width="0.35" data-wavelength="0.45">
Broad
</button>
<button class="preset active" type="button" data-width="0.85" data-wavelength="0.45">
Classic
</button>
<button class="preset" type="button" data-width="2.4" data-wavelength="0.25">
Narrow lobe
</button>
</div>
<div class="plot-card">
<div class="plot-header">
<strong>Normalized intensity</strong>
<span>I / I<sub>max</sub></span>
</div>
<div id="plot" aria-label="Normalized intensity versus diffraction angle">
<span class="plot-label y-one">1.0</span>
<span class="plot-label y-half">0.5</span>
<span class="plot-label y-zero">0</span>
<span class="plot-label x-left">−90°</span>
<span class="plot-label x-center">0°</span>
<span class="plot-label x-right">+90°</span>
</div>
</div>
<div class="formula">
<div class="formula-main">
I(θ) = [sin(β) / β]²
</div>
<div class="formula-note">
β = π(a / λ) sin θ. The profile is normalized by its sampled
maximum, which occurs at θ = 0.
</div>
</div>
<div class="metrics">
<div class="metric">
<span>First minimum</span>
<strong id="firstMinimum">±31.97°</strong>
</div>
<div class="metric">
<span>Width / wavelength</span>
<strong id="ratioValue">1.89</strong>
</div>
<div class="metric">
<span>Approx. fringe count</span>
<strong id="lobeValue">1 interval</strong>
</div>
<div class="metric">
<span>Central value</span>
<strong id="centralValue">1.000</strong>
</div>
</div>
<div class="limit-card">
<div class="limit-icon">∑</div>
<div>
<strong>Central limit handled</strong>
<p>
At β = 0, the code returns lim<sub>β→0</sub>
[sin(β)/β]² = 1 directly, avoiding any division by zero.
</p>
</div>
</div>
</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 stage = document.querySelector("#stage");
const plotElement = document.querySelector("#plot");
const widthInput = document.querySelector("#width");
const wavelengthInput = document.querySelector("#wavelength");
const widthOutput = document.querySelector("#widthOutput");
const wavelengthOutput = document.querySelector("#wavelengthOutput");
const firstMinimumOutput = document.querySelector("#firstMinimum");
const ratioOutput = document.querySelector("#ratioValue");
const lobeOutput = document.querySelector("#lobeValue");
const centralOutput = document.querySelector("#centralValue");
const state = {
width: Number(widthInput.value),
wavelength: Number(wavelengthInput.value)
};
const PROFILE_COUNT = 721;
const MAIN_BAR_COUNT = 181;
const PLOT_BAR_COUNT = 181;
const RAY_COUNT = 33;
/*
Scalar Fraunhofer intensity for a single slit.
Explicit central limit:
lim (sin(beta) / beta)^2 as beta -> 0 is 1.
Returning 1 at beta = 0 avoids evaluating 0 / 0.
*/
function slitIntensity(theta, width, wavelength) {
const beta = Math.PI * (width / wavelength) * Math.sin(theta);
if (Math.abs(beta) < 1e-8) {
return 1;
}
const sinc = Math.sin(beta) / beta;
return sinc * sinc;
}
function computeProfile() {
const theta = new Float32Array(PROFILE_COUNT);
const raw = new Float32Array(PROFILE_COUNT);
const normalized = new Float32Array(PROFILE_COUNT);
let peak = 0;
for (let i = 0; i < PROFILE_COUNT; i++) {
const angle = -Math.PI / 2 + (Math.PI * i) / (PROFILE_COUNT - 1);
const intensity = slitIntensity(angle, state.width, state.wavelength);
theta[i] = angle;
raw[i] = intensity;
peak = Math.max(peak, intensity);
}
// The central sample is guaranteed to be 1, so peak is always positive.
const safePeak = peak > 1e-12 ? peak : 1;
for (let i = 0; i < PROFILE_COUNT; i++) {
normalized[i] = raw[i] / safePeak;
}
return { theta, raw, normalized };
}
// ---------------------------------------------------------------------
// Main Three.js scene
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x07111d, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x07111d, 16, 31);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 100);
const cameraState = {
target: new THREE.Vector3(0, -0.1, 2.1),
radius: 14.2,
theta: 0.70,
phi: 1.17
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0x8ed9ff, 0x182238, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
keyLight.position.set(4, 8, 10);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4de2d0, 1.2);
rimLight.position.set(-8, 2, -4);
scene.add(rimLight);
const apertureMaterial = new THREE.MeshStandardMaterial({
color: 0x7568b7,
roughness: 0.86,
metalness: 0.08,
flatShading: true
});
const apertureEdgeMaterial = new THREE.LineBasicMaterial({
color: 0xc2b9ff,
transparent: true,
opacity: 0.55
});
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function createApertureBlock() {
const block = new THREE.Mesh(unitBox, apertureMaterial);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(unitBox),
apertureEdgeMaterial
);
block.add(edges);
scene.add(block);
return block;
}
const leftBlock = createApertureBlock();
const rightBlock = createApertureBlock();
// Incoming plane-wave wireframes.
const wavePlanes = [];
for (let i = 0; i < 4; i++) {
const geometry = new THREE.PlaneGeometry(8.5, 5.1, 8, 5);
const material = new THREE.MeshBasicMaterial({
color: 0x39cdd0,
wireframe: true,
transparent: true,
opacity: 0.12,
depthWrite: false
});
const plane = new THREE.Mesh(geometry, material);
plane.position.z = -2 + i * 0.62;
scene.add(plane);
wavePlanes.push(plane);
}
// Central diffraction wedge.
const fanGeometry = new THREE.BufferGeometry();
fanGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(9), 3)
);
const fanMaterial = new THREE.MeshBasicMaterial({
color: 0x52e0d0,
transparent: true,
opacity: 0.075,
side: THREE.DoubleSide,
depthWrite: false
});
const fan = new THREE.Mesh(fanGeometry, fanMaterial);
scene.add(fan);
const fanOutlineGeometry = new THREE.BufferGeometry();
fanOutlineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(12), 3)
);
const fanOutline = new THREE.LineSegments(
fanOutlineGeometry,
new THREE.LineBasicMaterial({
color: 0x52e0d0,
transparent: true,
opacity: 0.3
})
);
scene.add(fanOutline);
// Screen frame and axes.
const screenVertices = [
-6.1, -2.2, 5.08, 6.1, -2.2, 5.08,
6.1, -2.2, 5.08, 6.1, 2.3, 5.08,
6.1, 2.3, 5.08, -6.1, 2.3, 5.08,
-6.1, 2.3, 5.08, -6.1, -2.2, 5.08,
-6.1, -1.85, 5.08, 6.1, -1.85, 5.08,
-6.1, -1.85, 5.08, -6.1, 2.3, 5.08
];
const screenGeometry = new THREE.BufferGeometry();
screenGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(screenVertices, 3)
);
scene.add(
new THREE.LineSegments(
screenGeometry,
new THREE.LineBasicMaterial({
color: 0x46637b,
transparent: true,
opacity: 0.65
})
)
);
// Main intensity bars on the angular screen.
const mainBarGeometry = new THREE.BoxGeometry(1, 1, 1);
const mainBarMaterial = new THREE.MeshBasicMaterial({ color: 0xffffff });
const mainBars = new THREE.InstancedMesh(
mainBarGeometry,
mainBarMaterial,
MAIN_BAR_COUNT
);
mainBars.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mainBars.frustumCulled = false;
scene.add(mainBars);
// Main intensity curve.
const mainCurvePositions = new Float32Array(PROFILE_COUNT * 3);
const mainCurveGeometry = new THREE.BufferGeometry();
mainCurveGeometry.setAttribute(
"position",
new THREE.BufferAttribute(mainCurvePositions, 3)
);
const mainCurve = new THREE.Line(
mainCurveGeometry,
new THREE.LineBasicMaterial({ color: 0xffb454 })
);
mainCurve.frustumCulled = false;
scene.add(mainCurve);
// Diffraction rays.
const rayPositions = new Float32Array(RAY_COUNT * 6);
const rayColors = new Float32Array(RAY_COUNT * 6);
const rayGeometry = new THREE.BufferGeometry();
rayGeometry.setAttribute(
"position",
new THREE.BufferAttribute(rayPositions, 3)
);
rayGeometry.setAttribute(
"color",
new THREE.BufferAttribute(rayColors, 3)
);
const rays = new THREE.LineSegments(
rayGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.25,
depthWrite: false
})
);
rays.frustumCulled = false;
scene.add(rays);
// ---------------------------------------------------------------------
// Plot Three.js scene
// ---------------------------------------------------------------------
const plotRenderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
plotRenderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
plotRenderer.setClearColor(0x081321, 1);
plotRenderer.outputColorSpace = THREE.SRGBColorSpace;
plotElement.prepend(plotRenderer.domElement);
const plotScene = new THREE.Scene();
const plotCamera = new THREE.OrthographicCamera(
-Math.PI / 2,
Math.PI / 2,
1.1,
0,
0.1,
20
);
plotCamera.position.z = 10;
// Plot grid.
const gridVertices = [];
for (let i = 0; i <= 6; i++) {
const x = -Math.PI / 2 + (Math.PI * i) / 6;
gridVertices.push(x, 0, 0, x, 1.1, 0);
}
for (let i = 0; i <= 4; i++) {
const y = (1.1 * i) / 4;
gridVertices.push(-Math.PI / 2, y, 0, Math.PI / 2, y, 0);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
plotScene.add(
new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x26394d,
transparent: true,
opacity: 0.7
})
)
);
const plotBars = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({ color: 0xffffff }),
PLOT_BAR_COUNT
);
plotBars.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
plotBars.frustumCulled = false;
plotScene.add(plotBars);
const plotCurvePositions = new Float32Array(PROFILE_COUNT * 3);
const plotCurveGeometry = new THREE.BufferGeometry();
plotCurveGeometry.setAttribute(
"position",
new THREE.BufferAttribute(plotCurvePositions, 3)
);
const plotCurve = new THREE.Line(
plotCurveGeometry,
new THREE.LineBasicMaterial({ color: 0xffb454 })
);
plotCurve.frustumCulled = false;
plotScene.add(plotCurve);
const centralGuide = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0.05),
new THREE.Vector3(0, 1.1, 0.05)
]),
new THREE.LineDashedMaterial({
color: 0xffb454,
dashSize: 0.035,
gapSize: 0.025,
transparent: true,
opacity: 0.65
})
);
centralGuide.computeLineDistances();
plotScene.add(centralGuide);
const centralMarker = new THREE.Mesh(
new THREE.CircleGeometry(0.034, 8),
new THREE.MeshBasicMaterial({ color: 0xffb454 })
);
centralMarker.position.set(0, 1, 0.16);
plotScene.add(centralMarker);
// ---------------------------------------------------------------------
// Updating the models
// ---------------------------------------------------------------------
const dummy = new THREE.Object3D();
const color = new THREE.Color();
function colorForIntensity(value, target) {
const t = THREE.MathUtils.clamp(value, 0, 1);
target.setHSL(0.51 - 0.47 * t, 0.72, 0.27 + 0.27 * t);
return target;
}
function updateMainScene(profile) {
const gap = 0.45 + state.width * 0.9;
const blockWidth = 2.05;
const blockHeight = 5.1;
const blockDepth = 0.32;
leftBlock.scale.set(blockWidth, blockHeight, blockDepth);
rightBlock.scale.set(blockWidth, blockHeight, blockDepth);
leftBlock.position.set(
-(gap / 2 + blockWidth / 2),
0,
0
);
rightBlock.position.set(
gap / 2 + blockWidth / 2,
0,
0
);
// Update intensity bars.
for (let i = 0; i < MAIN_BAR_COUNT; i++) {
const profileIndex = Math.round((i * (PROFILE_COUNT - 1)) / (MAIN_BAR_COUNT - 1));
const theta = profile.theta[profileIndex];
const intensity = profile.normalized[profileIndex];
const x = (theta / (Math.PI / 2)) * 5.85;
const height = Math.max(0.002, intensity * 3.8);
dummy.position.set(x, -1.85 + height / 2, 5.15);
dummy.scale.set(0.047, height, 0.07);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
mainBars.setMatrixAt(i, dummy.matrix);
mainBars.setColorAt(i, colorForIntensity(intensity, color));
}
mainBars.instanceMatrix.needsUpdate = true;
if (mainBars.instanceColor) {
mainBars.instanceColor.needsUpdate = true;
}
// Update the intensity curve.
const mainPosition = mainCurveGeometry.getAttribute("position");
for (let i = 0; i < PROFILE_COUNT; i++) {
const x = (profile.theta[i] / (Math.PI / 2)) * 5.85;
const y = -1.85 + profile.normalized[i] * 3.8;
mainPosition.setXYZ(i, x, y, 5.25);
}
mainPosition.needsUpdate = true;
// Update representative rays.
const rayPosition = rayGeometry.getAttribute("position");
const rayColor = rayGeometry.getAttribute("color");
for (let i = 0; i < RAY_COUNT; i++) {
const profileIndex = Math.round(
(i * (PROFILE_COUNT - 1)) / (RAY_COUNT - 1)
);
const theta = profile.theta[profileIndex];
const intensity = profile.normalized[profileIndex];
const endX = (theta / (Math.PI / 2)) * 5.85;
const startOffset = i * 6;
rayPosition.setXYZ(startOffset / 3, 0, 0.05, 0.02);
rayPosition.setXYZ(startOffset / 3 + 1, endX, 0.05, 5.02);
colorForIntensity(intensity, color);
rayColor.setXYZ(startOffset / 3, color.r, color.g, color.b);
rayColor.setXYZ(startOffset / 3 + 1, color.r, color.g, color.b);
}
rayPosition.needsUpdate = true;
rayColor.needsUpdate = true;
// The central wedge reaches the first physical minimum when one exists.
const minimumAngle = state.wavelength < state.width
? Math.asin(state.wavelength / state.width)
: Math.PI / 2;
const fanEdge = Math.min(
5.85,
Math.tan(Math.min(minimumAngle, 1.4)) * 5.05
);
const fanPosition = fanGeometry.getAttribute("position");
fanPosition.setXYZ(0, 0, 0, 0.02);
fanPosition.setXYZ(1, -fanEdge, 0, 5.02);
fanPosition.setXYZ(2, fanEdge, 0, 5.02);
fanPosition.needsUpdate = true;
const outlinePosition = fanOutlineGeometry.getAttribute("position");
outlinePosition.setXYZ(0, 0, 0, 0.03);
outlinePosition.setXYZ(1, -fanEdge, 0, 5.03);
outlinePosition.setXYZ(2, 0, 0, 0.03);
outlinePosition.setXYZ(3, fanEdge, 0, 5.03);
outlinePosition.needsUpdate = true;
}
function updatePlot(profile) {
for (let i = 0; i < PLOT_BAR_COUNT; i++) {
const profileIndex = Math.round((i * (PROFILE_COUNT - 1)) / (PLOT_BAR_COUNT - 1));
const theta = profile.theta[profileIndex];
const intensity = profile.normalized[profileIndex];
const height = Math.max(0.001, intensity);
dummy.position.set(theta, height / 2, 0.02);
dummy.scale.set((Math.PI / 180) * 0.7, height, 0.018);
dummy.rotation.set(0, 0, 0);
dummy.updateMatrix();
plotBars.setMatrixAt(i, dummy.matrix);
plotBars.setColorAt(i, colorForIntensity(intensity, color));
}
plotBars.instanceMatrix.needsUpdate = true;
if (plotBars.instanceColor) {
plotBars.instanceColor.needsUpdate = true;
}
const plotPosition = plotCurveGeometry.getAttribute("position");
for (let i = 0; i < PROFILE_COUNT; i++) {
plotPosition.setXYZ(
i,
profile.theta[i],
profile.normalized[i],
0.12
);
}
plotPosition.needsUpdate = true;
}
function updateReadouts() {
widthOutput.textContent = `${state.width.toFixed(2)} µm`;
wavelengthOutput.textContent = `${state.wavelength.toFixed(2)} µm`;
const ratio = state.width / state.wavelength;
ratioOutput.textContent = ratio.toFixed(2);
if (state.wavelength <= state.width) {
const firstMinimum = Math.asin(state.wavelength / state.width);
firstMinimumOutput.textContent =
`±${(firstMinimum * 180 / Math.PI).toFixed(2)}°`;
} else {
firstMinimumOutput.textContent = "Outside ±90°";
}
const intervals = Math.floor(ratio);
lobeOutput.textContent = intervals <= 0
? "Broad central lobe"
: `${intervals} interval${intervals === 1 ? "" : "s"}`;
centralOutput.textContent = "1.000";
for (const input of [widthInput, wavelengthInput]) {
const percent =
100 *
(Number(input.value) - Number(input.min)) /
(Number(input.max) - Number(input.min));
input.style.setProperty("--fill", `${percent}%`);
}
}
function updateAll() {
state.width = Number(widthInput.value);
state.wavelength = Number(wavelengthInput.value);
const profile = computeProfile();
updateReadouts();
updateMainScene(profile);
updatePlot(profile);
}
widthInput.addEventListener("input", updateAll);
wavelengthInput.addEventListener("input", updateAll);
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
widthInput.value = button.dataset.width;
wavelengthInput.value = button.dataset.wavelength;
document.querySelectorAll(".preset").forEach((preset) => {
preset.classList.toggle("active", preset === button);
});
updateAll();
});
});
// ---------------------------------------------------------------------
// Direct camera controls; no addon imports are used.
// ---------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.005,
0.35,
1.48
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
8,
24
);
updateCamera();
}, { passive: false });
document.querySelector("#resetCamera").addEventListener("click", () => {
cameraState.radius = 14.2;
cameraState.theta = 0.70;
cameraState.phi = 1.17;
updateCamera();
});
// ---------------------------------------------------------------------
// Resize handling
// ---------------------------------------------------------------------
function resizeMain() {
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();
}
function resizePlot() {
const width = Math.max(1, plotElement.clientWidth);
const height = Math.max(1, plotElement.clientHeight);
plotRenderer.setSize(width, height, false);
}
const mainResizeObserver = new ResizeObserver(resizeMain);
mainResizeObserver.observe(stage);
const plotResizeObserver = new ResizeObserver(resizePlot);
plotResizeObserver.observe(plotElement);
window.addEventListener("resize", () => {
resizeMain();
resizePlot();
});
// ---------------------------------------------------------------------
// Render loop
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const time = clock.getElapsedTime();
// Lightweight traveling plane-wave wireframes.
wavePlanes.forEach((plane, index) => {
plane.position.z = -2.15 + ((time * 0.58 + index * 0.64) % 2.1);
plane.material.opacity = 0.07 + 0.055 * (0.5 + 0.5 * Math.sin(time * 2 + index));
});
fanMaterial.opacity = 0.065 + 0.018 * (0.5 + 0.5 * Math.sin(time * 1.4));
renderer.render(scene, camera);
plotRenderer.render(plotScene, plotCamera);
}
resizeMain();
resizePlot();
updateAll();
animate();
</script>
</body>
</html>
```