Prompt specification
Build or customize the Three.js 3D scene "Wide and narrow opening comparison" 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: Wide and narrow opening comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/wide-and-narrow-opening-comparison-x1530
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this stylized scene: Place two barriers under identical incident waves with different slit widths; show stronger angular spreading for the narrower opening within the stated diffraction model.
Working Three.js Starter (wide-and-narrow-opening-comparison-x1530):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Single-Slit Diffraction Comparison</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: rgba(9, 20, 35, 0.78);
--panel-border: rgba(151, 205, 230, 0.16);
--text: #e8f5fb;
--muted: #8da9b9;
--cyan: #54ddff;
--amber: #ffb45e;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 42%, #102238 0%, #07101d 58%, #040912 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 16px;
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(15px) saturate(120%);
-webkit-backdrop-filter: blur(15px) saturate(120%);
}
.intro {
position: absolute;
top: 22px;
left: 22px;
width: min(470px, calc(100vw - 44px));
padding: 20px 22px;
}
.eyebrow,
.panel-kicker {
margin: 0 0 8px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(27px, 3.1vw, 42px);
line-height: 1.02;
letter-spacing: -0.045em;
font-weight: 720;
}
.intro p:last-child {
margin: 11px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.comparison {
position: absolute;
top: 22px;
right: 22px;
width: min(430px, calc(100vw - 44px));
padding: 17px;
}
.compare-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.case {
position: relative;
overflow: hidden;
padding: 13px 13px 12px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
}
.case::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--case-color);
box-shadow: 0 0 18px var(--case-color);
}
.case.wide {
--case-color: var(--cyan);
}
.case.narrow {
--case-color: var(--amber);
}
.case-name {
color: var(--case-color);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.case-value {
margin-top: 7px;
font-size: 26px;
font-weight: 720;
letter-spacing: -0.035em;
}
.case-label {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
}
.model {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.equation {
color: #dff7ff;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 12px;
line-height: 1.6;
}
.model p {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.controls {
position: absolute;
left: 22px;
bottom: 22px;
width: min(430px, calc(100vw - 44px));
padding: 17px;
pointer-events: auto;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
}
.control-title {
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.control-value {
color: var(--cyan);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 13px;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 15px 0 7px;
appearance: none;
border-radius: 999px;
background: linear-gradient(
90deg,
var(--cyan) 0%,
var(--cyan) var(--fill, 37%),
rgba(255, 255, 255, 0.12) var(--fill, 37%),
rgba(255, 255, 255, 0.12) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
appearance: none;
border: 2px solid #dffaff;
border-radius: 50%;
background: #0b2031;
box-shadow: 0 0 0 4px rgba(84, 221, 255, 0.13);
}
input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border: 2px solid #dffaff;
border-radius: 50%;
background: #0b2031;
box-shadow: 0 0 0 4px rgba(84, 221, 255, 0.13);
}
.range-labels {
display: flex;
justify-content: space-between;
color: #688394;
font-size: 10px;
}
.buttons {
display: flex;
gap: 8px;
margin-top: 14px;
}
button {
appearance: none;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 9px;
padding: 9px 12px;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease, transform 150ms ease;
}
button:hover {
background: rgba(84, 221, 255, 0.1);
border-color: rgba(84, 221, 255, 0.35);
}
button:active {
transform: translateY(1px);
}
.legend {
position: absolute;
right: 22px;
bottom: 22px;
padding: 13px 15px;
color: var(--muted);
font-size: 11px;
line-height: 1.8;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
white-space: nowrap;
}
.swatch {
width: 23px;
height: 2px;
border-radius: 2px;
box-shadow: 0 0 10px currentColor;
background: currentColor;
}
.hint {
position: absolute;
left: 50%;
bottom: 24px;
transform: translateX(-50%);
color: rgba(196, 222, 235, 0.58);
font-size: 10px;
letter-spacing: 0.04em;
text-align: center;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: var(--cyan);
background: #07101d;
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
@media (max-width: 900px) {
.intro {
width: 390px;
}
.comparison {
width: 360px;
}
.hint {
display: none;
}
}
@media (max-width: 700px) {
.intro {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 14px 16px;
}
.intro p:last-child,
.model p {
display: none;
}
.comparison {
top: 126px;
left: 10px;
right: 10px;
width: auto;
padding: 12px;
}
.model {
display: none;
}
.controls {
left: 10px;
bottom: 10px;
width: calc(100vw - 20px);
padding: 13px;
}
.legend {
display: none;
}
.case-value {
font-size: 21px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional single-slit diffraction comparison"></canvas>
<div class="hud">
<section class="panel intro">
<p class="eyebrow">Wave optics · comparison 01</p>
<h1>One wave.<br />Two openings.</h1>
<p>
Both barriers receive the same monochromatic plane wave. Only the slit width changes,
revealing how a narrower aperture produces a wider angular diffraction pattern.
</p>
</section>
<section class="panel comparison">
<p class="panel-kicker">Angular spreading comparison</p>
<div class="compare-grid">
<article class="case wide">
<div class="case-name">Wide slit</div>
<div class="case-value">a = 1.70</div>
<div class="case-label">
first zero: <strong id="wide-angle">14.3°</strong><br />
central lobe: <strong id="wide-lobe">28.6°</strong>
</div>
</article>
<article class="case narrow">
<div class="case-name">Narrow slit</div>
<div class="case-value">a = 0.80</div>
<div class="case-label">
first zero: <strong id="narrow-angle">31.7°</strong><br />
central lobe: <strong id="narrow-lobe">63.4°</strong>
</div>
</article>
</div>
<div class="model">
<div class="equation">
I(θ) ∝ [sin β / β]², β = πa sin θ / λ<br />
first minimum: |θ₁| = asin(λ/a)
</div>
<p>
Far-field single-slit model. Screen patterns are normalized to compare shape;
dashed rays mark the first-zero angular limits.
</p>
</div>
</section>
<section class="panel controls">
<div class="control-row">
<label class="control-title" for="wavelength">
Common incident wavelength
</label>
<span class="control-value" id="lambda-value">λ = 0.42</span>
</div>
<input
id="wavelength"
type="range"
min="0.25"
max="0.58"
step="0.01"
value="0.42"
aria-label="Common incident wavelength"
/>
<div class="range-labels">
<span>shorter λ</span>
<span>longer λ</span>
</div>
<div class="buttons">
<button id="play" type="button">Pause waves</button>
<button id="reset-camera" type="button">Reset view</button>
</div>
</section>
<aside class="panel legend">
<div class="legend-row">
<span class="swatch" style="color: #54ddff"></span>
Incident wave / wide-slit output
</div>
<div class="legend-row">
<span class="swatch" style="color: #ffb45e"></span>
Narrow-slit output
</div>
</aside>
<div class="hint">Drag to orbit · wheel to zoom · shift-drag to pan</div>
</div>
<div id="loading">Initializing wave laboratory…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading");
const config = {
lambda: 0.42,
wideAperture: 1.7,
narrowAperture: 0.8,
waveSpeed: 1.25,
waveStart: -11.4,
waveLength: 11.4,
outputDistance: 10.2,
screenHeight: 16
};
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.FogExp2(0x07101d, 0.012);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
150
);
const hemisphere = new THREE.HemisphereLight(0x9ddfff, 0x07101d, 1.8);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd7f3ff, 3.1);
keyLight.position.set(-5, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 15;
keyLight.shadow.camera.bottom = -15;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xffa858, 1.25);
rimLight.position.set(9, 5, -12);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(48, 32),
new THREE.MeshStandardMaterial({
color: 0x081421,
roughness: 0.92,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -9;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(46, 46, 0x23465d, 0x11283a);
grid.position.y = -8.985;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const cameraState = {
radius: 28,
phi: 1.18,
theta: 0.64,
target: new THREE.Vector3(0, -0.5, 0)
};
function applyCamera() {
const spherical = new THREE.Spherical(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.setFromSpherical(spherical).add(cameraState.target);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.radius = window.innerWidth < 700 ? 35 : 28;
cameraState.phi = 1.18;
cameraState.theta = 0.64;
cameraState.target.set(0, -0.5, 0);
applyCamera();
}
resetCamera();
function makeRoundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width * 0.5, height * 0.5);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeLabel(text, color, width = 4.4) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 768;
labelCanvas.height = 160;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 768, 160);
makeRoundedRect(ctx, 8, 8, 752, 144, 30);
ctx.fillStyle = "rgba(5, 17, 29, 0.84)";
ctx.fill();
ctx.strokeStyle = color;
ctx.lineWidth = 4;
ctx.stroke();
ctx.fillStyle = color;
ctx.font = "700 48px Inter, system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 384, 82);
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, width * (160 / 768), 1);
sprite.renderOrder = 20;
return sprite;
}
function addBox(group, dimensions, position, material, edgeColor) {
const geometry = new THREE.BoxGeometry(...dimensions);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
if (edgeColor) {
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: edgeColor,
transparent: true,
opacity: 0.28
})
);
mesh.add(edges);
}
return mesh;
}
function createBarrier(lane) {
const group = new THREE.Group();
group.position.z = lane.z;
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x18283a,
metalness: 0.78,
roughness: 0.28
});
const totalHeight = 5.4;
const totalWidth = 2.7;
const apertureWidth = 0.72;
const sideWidth = (totalWidth - apertureWidth) * 0.5;
const capHeight = (totalHeight - lane.aperture) * 0.5;
const depth = 0.46;
const sideOffset = apertureWidth * 0.5 + sideWidth * 0.5;
const capOffset = lane.aperture * 0.5 + capHeight * 0.5;
addBox(
group,
[depth, totalHeight, sideWidth],
[0, 0, -sideOffset],
bodyMaterial,
0x526a7d
);
addBox(
group,
[depth, totalHeight, sideWidth],
[0, 0, sideOffset],
bodyMaterial,
0x526a7d
);
addBox(
group,
[depth, capHeight, apertureWidth],
[0, capOffset, 0],
bodyMaterial,
0x526a7d
);
addBox(
group,
[depth, capHeight, apertureWidth],
[0, -capOffset, 0],
bodyMaterial,
0x526a7d
);
const aperturePlane = new THREE.Mesh(
new THREE.PlaneGeometry(apertureWidth, lane.aperture),
new THREE.MeshBasicMaterial({
color: lane.accent,
transparent: true,
opacity: 0.12,
side: THREE.DoubleSide,
depthWrite: false
})
);
aperturePlane.rotation.y = Math.PI / 2;
aperturePlane.position.x = 0.04;
group.add(aperturePlane);
const outlinePoints = [
new THREE.Vector3(0.255, -lane.aperture / 2, -apertureWidth / 2),
new THREE.Vector3(0.255, lane.aperture / 2, -apertureWidth / 2),
new THREE.Vector3(0.255, lane.aperture / 2, apertureWidth / 2),
new THREE.Vector3(0.255, -lane.aperture / 2, apertureWidth / 2)
];
const apertureOutline = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(outlinePoints),
new THREE.LineBasicMaterial({
color: lane.accent,
transparent: true,
opacity: 0.95
})
);
group.add(apertureOutline);
const label = makeLabel(
lane.key === "wide"
? "WIDE SLIT a = 1.70"
: "NARROW SLIT a = 0.80",
lane.key === "wide" ? "#54ddff" : "#ffb45e",
4.3
);
label.position.set(0, 3.65, 0);
group.add(label);
scene.add(group);
}
function firstMinimumAngle(aperture) {
return Math.asin(Math.min(config.lambda / aperture, 0.999));
}
function sincSquared(beta) {
if (Math.abs(beta) < 1e-7) return 1;
const s = Math.sin(beta) / beta;
return s * s;
}
function disposeGroup(group) {
group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
group.clear();
}
const rayVertexShader = `
attribute float aStrength;
varying float vStrength;
varying float vX;
void main() {
vStrength = aStrength;
vX = position.x;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const rayFragmentShader = `
uniform vec3 uColor;
uniform float uTime;
varying float vStrength;
varying float vX;
void main() {
float wave = 0.5 + 0.5 * sin(vX * 1.25 - uTime * 4.2);
float pulse = pow(wave, 12.0);
float alpha = vStrength * (0.17 + 0.83 * pulse);
gl_FragColor = vec4(uColor, alpha);
}
`;
function buildOutput(lane) {
if (lane.output) {
scene.remove(lane.output);
disposeGroup(lane.output);
}
const output = new THREE.Group();
const theta1 = firstMinimumAngle(lane.aperture);
const distance = config.outputDistance;
const startX = 0.29;
const rayCount = 27;
const positions = [];
const strengths = [];
for (let i = 0; i < rayCount - 1; i++) {
const angleA = -theta1 + (i / (rayCount - 1)) * theta1 * 2;
const angleB =
-theta1 + ((i + 1) / (rayCount - 1)) * theta1 * 2;
positions.push(
startX, 0, lane.z,
distance, Math.tan(angleB) * distance, lane.z
);
const beta =
(Math.PI * lane.aperture * Math.sin(angleA)) / config.lambda;
strengths.push(sincSquared(beta), sincSquared(beta));
}
const rayGeometry = new THREE.BufferGeometry();
rayGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
rayGeometry.setAttribute(
"aStrength",
new THREE.Float32BufferAttribute(strengths, 1)
);
const rayMaterial = new THREE.ShaderMaterial({
uniforms: {
uColor: { value: new THREE.Color(lane.accent) },
uTime: { value: 0 }
},
vertexShader: rayVertexShader,
fragmentShader: rayFragmentShader,
transparent: true,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const rays = new THREE.LineSegments(rayGeometry, rayMaterial);
rays.renderOrder = 6;
output.add(rays);
// First-zero boundaries of the central diffraction lobe.
for (const sign of [-1, 1]) {
const angle = sign * theta1;
const boundary = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(startX, 0, lane.z),
new THREE.Vector3(
distance,
Math.tan(angle) * distance,
lane.z
)
]),
new THREE.LineDashedMaterial({
color: lane.accent,
transparent: true,
opacity: 0.46,
dashSize: 0.28,
gapSize: 0.17
})
);
boundary.computeLineDistances();
boundary.renderOrder = 5;
output.add(boundary);
}
// A faint wedge communicates the angular envelope.
const wedgeGeometry = new THREE.BufferGeometry();
wedgeGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(
[
startX, 0, lane.z,
distance, -Math.tan(theta1) * distance, lane.z,
distance, Math.tan(theta1) * distance, lane.z
],
3
)
);
wedgeGeometry.computeVertexNormals();
const wedge = new THREE.Mesh(
wedgeGeometry,
new THREE.MeshBasicMaterial({
color: lane.accent,
transparent: true,
opacity: 0.028,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
wedge.renderOrder = 2;
output.add(wedge);
// Expanding wavefront arcs, schematic within the central lobe.
const radii = [1.45, 3.05, 4.65, 6.25, 7.85, 9.45];
radii.forEach((radius, index) => {
const points = [];
const segments = 72;
for (let i = 0; i <= segments; i++) {
const angle = -theta1 + (i / segments) * theta1 * 2;
points.push(
new THREE.Vector3(
startX + radius * Math.cos(angle),
radius * Math.sin(angle),
lane.z
)
);
}
const arc = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineBasicMaterial({
color: lane.accent,
transparent: true,
opacity: 0.12 + index * 0.009
})
);
arc.renderOrder = 3;
output.add(arc);
});
const axis = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(startX, 0, lane.z),
new THREE.Vector3(distance, 0, lane.z)
]),
new THREE.LineBasicMaterial({
color: lane.accent,
transparent: true,
opacity: 0.28
})
);
output.add(axis);
scene.add(output);
lane.output = output;
}
const screenVertexShader = `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const screenFragmentShader = `
uniform float uAperture;
uniform float uLambda;
uniform float uHeight;
uniform float uDistance;
uniform vec3 uColor;
varying vec2 vUv;
void main() {
float vertical = (vUv.y - 0.5) * uHeight;
float theta = atan(vertical, uDistance);
float beta = 3.14159265359 * uAperture * sin(theta) / uLambda;
float s = abs(beta) < 0.00001 ? 1.0 : sin(beta) / beta;
float intensity = s * s;
float visiblePattern = smoothstep(0.008, 0.10, intensity);
float centerLine = 1.0 - smoothstep(0.0, 0.035, abs(vertical));
vec3 dark = vec3(0.012, 0.035, 0.060);
vec3 bright = uColor * (0.55 + 1.2 * intensity);
vec3 color = mix(dark, bright, visiblePattern * 0.92);
color += centerLine * vec3(0.08, 0.13, 0.16);
float alpha = 0.24 + visiblePattern * 0.57;
gl_FragColor = vec4(color, alpha);
}
`;
function createScreen(lane) {
const geometry = new THREE.PlaneGeometry(2.7, config.screenHeight);
const material = new THREE.ShaderMaterial({
uniforms: {
uAperture: { value: lane.aperture },
uLambda: { value: config.lambda },
uHeight: { value: config.screenHeight },
uDistance: { value: config.outputDistance },
uColor: { value: new THREE.Color(lane.accent) }
},
vertexShader: screenVertexShader,
fragmentShader: screenFragmentShader,
transparent: true,
side: THREE.DoubleSide,
depthWrite: false
});
const screen = new THREE.Mesh(geometry, material);
screen.rotation.y = Math.PI / 2;
screen.position.set(config.outputDistance, 0, lane.z);
screen.renderOrder = 1;
scene.add(screen);
const frame = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: lane.accent,
transparent: true,
opacity: 0.42
})
);
screen.add(frame);
lane.screenMaterial = material;
}
function buildWavefronts(lane) {
if (lane.waveGroup) {
scene.remove(lane.waveGroup);
disposeGroup(lane.waveGroup);
}
const group = new THREE.Group();
const spacing = config.lambda;
const count = Math.ceil(config.waveLength / spacing) + 1;
const planeGeometry = new THREE.PlaneGeometry(2.66, 5.15);
const planeMaterial = new THREE.MeshBasicMaterial({
color: 0x54ddff,
transparent: true,
opacity: 0.035,
side: THREE.DoubleSide,
depthWrite: false
});
const edgeGeometry = new THREE.EdgesGeometry(planeGeometry);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x54ddff,
transparent: true,
opacity: 0.16,
depthWrite: false
});
for (let i = 0; i < count; i++) {
const front = new THREE.Group();
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.rotation.y = Math.PI / 2;
front.add(plane);
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
edges.rotation.y = Math.PI / 2;
front.add(edges);
front.position.z = lane.z;
front.userData.baseOffset = i * spacing;
group.add(front);
}
scene.add(group);
lane.waveGroup = group;
lane.waveSpacing = spacing;
}
function updateWavefronts(lane, elapsed) {
if (!lane.waveGroup) return;
lane.waveGroup.children.forEach((front) => {
const travel =
(front.userData.baseOffset + elapsed * config.waveSpeed) %
config.waveLength;
front.position.x = config.waveStart + travel;
});
}
const lanes = [
{
key: "wide",
z: -4.2,
aperture: config.wideAperture,
accent: 0x54ddff
},
{
key: "narrow",
z: 4.2,
aperture: config.narrowAperture,
accent: 0xffb45e
}
];
lanes.forEach((lane) => {
createBarrier(lane);
createScreen(lane);
buildWavefronts(lane);
buildOutput(lane);
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(-11.9, 0, lane.z),
1.25,
0x54ddff,
0.32,
0.2
);
scene.add(arrow);
});
function updateInterface() {
const wideTheta = firstMinimumAngle(config.wideAperture);
const narrowTheta = firstMinimumAngle(config.narrowAperture);
const toDegrees = (radians) => radians * 180 / Math.PI;
document.querySelector("#lambda-value").textContent =
`λ = ${config.lambda.toFixed(2)}`;
document.querySelector("#wide-angle").textContent =
`${toDegrees(wideTheta).toFixed(1)}°`;
document.querySelector("#narrow-angle").textContent =
`${toDegrees(narrowTheta).toFixed(1)}°`;
document.querySelector("#wide-lobe").textContent =
`${toDegrees(wideTheta * 2).toFixed(1)}°`;
document.querySelector("#narrow-lobe").textContent =
`${toDegrees(narrowTheta * 2).toFixed(1)}°`;
const slider = document.querySelector("#wavelength");
const percentage =
((config.lambda - Number(slider.min)) /
(Number(slider.max) - Number(slider.min))) * 100;
slider.style.setProperty("--fill", `${percentage}%`);
}
const wavelengthInput = document.querySelector("#wavelength");
wavelengthInput.addEventListener("input", () => {
config.lambda = Number(wavelengthInput.value);
lanes.forEach((lane) => {
lane.screenMaterial.uniforms.uLambda.value = config.lambda;
buildWavefronts(lane);
buildOutput(lane);
});
updateInterface();
});
let playing = true;
let elapsed = 0;
const clock = new THREE.Clock();
const playButton = document.querySelector("#play");
playButton.addEventListener("click", () => {
playing = !playing;
playButton.textContent = playing ? "Pause waves" : "Play waves";
});
document.querySelector("#reset-camera").addEventListener("click", resetCamera);
// Direct camera controls; no Three.js examples/addons are used.
let dragging = false;
let panning = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
panning = event.button === 2 || event.shiftKey;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (panning) {
const right = new THREE.Vector3();
const up = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, up, new THREE.Vector3());
const panScale = cameraState.radius * 0.0014;
cameraState.target.addScaledVector(right, -dx * panScale);
cameraState.target.addScaledVector(up, dy * panScale);
} else {
cameraState.theta -= dx * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.16,
Math.PI - 0.16
);
}
applyCamera();
});
function endDrag(event) {
dragging = false;
panning = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
52
);
applyCamera();
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
updateInterface();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) elapsed += delta;
lanes.forEach((lane) => {
updateWavefronts(lane, elapsed);
if (lane.output) {
lane.output.traverse((object) => {
if (
object.material &&
object.material.uniforms &&
object.material.uniforms.uTime
) {
object.material.uniforms.uTime.value = elapsed;
}
});
}
});
renderer.render(scene, camera);
}
renderer.render(scene, camera);
loading.style.opacity = "0";
setTimeout(() => loading.remove(), 400);
animate();
</script>
</body>
</html>
```