Prompt specification
Build or customize the Three.js 3D scene "Critical-angle exploration tool" 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: Critical-angle exploration tool
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/critical-angle-exploration-tool-x1576
Scene Description Prompt:
Critical-angle exploration tool. Let users vary incidence from a higher-index to a lower-index medium; show refraction below the critical angle and total internal reflection above it with correct boundary handling. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (critical-angle-exploration-tool-x1576):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Critical Angle Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 20, 35, 0.88);
--panel-border: rgba(170, 205, 235, 0.16);
--text: #edf7ff;
--muted: #8fa8bd;
--incident: #f5fbff;
--reflected: #ff5f9f;
--transmitted: #56e4ff;
--upper: #ffc36b;
}
* {
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;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
#labels {
position: fixed;
inset: 0;
z-index: 3;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
transform: translate(-50%, -50%);
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 7px;
background: rgba(5, 13, 24, 0.78);
box-shadow: 0 5px 18px rgba(0, 0, 0, 0.2);
color: #edf7ff;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.01em;
white-space: nowrap;
backdrop-filter: blur(8px);
}
.world-label.incident {
color: var(--incident);
border-color: rgba(245, 251, 255, 0.25);
}
.world-label.reflected {
color: var(--reflected);
border-color: rgba(255, 95, 159, 0.3);
}
.world-label.transmitted {
color: var(--transmitted);
border-color: rgba(86, 228, 255, 0.32);
}
.world-label.medium {
padding: 7px 10px;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.world-label.n1 {
color: #84c8ff;
}
.world-label.n2 {
color: var(--upper);
}
.world-label.critical {
color: #a7e8ff;
border-color: rgba(86, 228, 255, 0.25);
font-size: 11px;
}
#panel {
position: fixed;
z-index: 5;
top: 18px;
right: 18px;
bottom: 18px;
width: 370px;
padding: 22px;
overflow-y: auto;
border: 1px solid var(--panel-border);
border-radius: 20px;
background:
linear-gradient(180deg, rgba(24, 43, 64, 0.32), transparent 28%),
var(--panel);
box-shadow:
0 25px 80px rgba(0, 0, 0, 0.38),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(120, 170, 205, 0.3) transparent;
}
.eyebrow {
color: #68d8ff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 7px;
font-size: 27px;
line-height: 1.1;
letter-spacing: -0.035em;
}
.lede {
margin: 0 0 18px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.mode-box {
position: relative;
margin-bottom: 18px;
padding: 14px 14px 14px 40px;
overflow: hidden;
border: 1px solid rgba(86, 228, 255, 0.22);
border-radius: 13px;
background: rgba(86, 228, 255, 0.07);
}
.mode-box::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--transmitted);
}
.mode-dot {
position: absolute;
top: 18px;
left: 17px;
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--transmitted);
box-shadow: 0 0 16px var(--transmitted);
}
.mode-box[data-mode="above"] {
border-color: rgba(255, 95, 159, 0.26);
background: rgba(255, 95, 159, 0.075);
}
.mode-box[data-mode="above"]::before,
.mode-box[data-mode="above"] .mode-dot {
background: var(--reflected);
box-shadow: 0 0 16px var(--reflected);
}
.mode-box[data-mode="critical"] {
border-color: rgba(255, 195, 107, 0.3);
background: rgba(255, 195, 107, 0.075);
}
.mode-box[data-mode="critical"]::before,
.mode-box[data-mode="critical"] .mode-dot {
background: var(--upper);
box-shadow: 0 0 16px var(--upper);
}
.mode-title {
display: block;
margin-bottom: 4px;
font-size: 14px;
}
.mode-detail {
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.control {
margin: 16px 0;
}
.control-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
color: #d9e9f5;
font-size: 12px;
font-weight: 700;
}
output {
min-width: 62px;
padding: 3px 7px;
border: 1px solid rgba(117, 181, 222, 0.15);
border-radius: 6px;
background: rgba(0, 0, 0, 0.18);
color: #8de5ff;
text-align: center;
font-variant-numeric: tabular-nums;
}
.range-shell {
position: relative;
padding: 5px 0;
}
input[type="range"] {
width: 100%;
height: 22px;
margin: 0;
appearance: none;
background: transparent;
cursor: pointer;
}
input[type="range"]::-webkit-slider-runnable-track {
height: 5px;
border-radius: 999px;
background:
linear-gradient(90deg, rgba(86, 228, 255, 0.3), rgba(86, 228, 255, 0.08)),
rgba(255, 255, 255, 0.08);
}
input[type="range"]::-moz-range-track {
height: 5px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.09);
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
margin-top: -6px;
appearance: none;
border: 3px solid #dff8ff;
border-radius: 50%;
background: #35c9ee;
box-shadow: 0 0 0 4px rgba(53, 201, 238, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #dff8ff;
border-radius: 50%;
background: #35c9ee;
box-shadow: 0 0 0 4px rgba(53, 201, 238, 0.12);
}
#criticalTick {
position: absolute;
top: 1px;
width: 2px;
height: 22px;
border-radius: 2px;
background: var(--upper);
box-shadow: 0 0 9px rgba(255, 195, 107, 0.65);
pointer-events: none;
transform: translateX(-1px);
}
.range-scale {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 1px;
color: #718ba0;
font-size: 10px;
}
.critical-jump {
padding: 3px 7px;
border: 1px solid rgba(255, 195, 107, 0.24);
border-radius: 6px;
background: rgba(255, 195, 107, 0.08);
color: #ffd08f;
font: inherit;
font-size: 10px;
cursor: pointer;
}
.critical-jump:hover {
background: rgba(255, 195, 107, 0.15);
}
.index-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 13px;
margin-top: 16px;
padding-top: 15px;
border-top: 1px solid rgba(255, 255, 255, 0.07);
}
.index-card {
padding: 11px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.index-title {
margin-bottom: 8px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.index-card output {
min-width: 48px;
padding: 2px 5px;
}
.index-card .control-heading {
gap: 5px;
font-size: 10px;
}
.presets {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 0 0 17px;
}
.preset {
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 7px;
background: rgba(255, 255, 255, 0.035);
color: #afc4d4;
font: inherit;
font-size: 10px;
cursor: pointer;
}
.preset:hover {
border-color: rgba(86, 228, 255, 0.28);
color: #dff8ff;
}
.section-label {
margin: 18px 0 8px;
color: #7690a5;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.readouts {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.readout {
padding: 10px 8px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 9px;
background: rgba(0, 0, 0, 0.12);
text-align: center;
}
.readout span {
display: block;
margin-bottom: 4px;
color: #738da2;
font-size: 9px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.readout strong {
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.power-row {
margin: 10px 0;
}
.power-title {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
color: #9eb5c7;
font-size: 10px;
}
.power-track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.07);
}
.power-fill {
width: 0;
height: 100%;
border-radius: inherit;
transition: width 120ms ease;
}
#reflectedFill {
background: linear-gradient(90deg, #ca3b83, var(--reflected));
}
#transmittedFill {
background: linear-gradient(90deg, #279cb9, var(--transmitted));
}
.legend {
display: grid;
gap: 7px;
margin-top: 14px;
color: #9db4c6;
font-size: 11px;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
}
.legend-line {
width: 26px;
height: 3px;
border-radius: 3px;
background: currentColor;
box-shadow: 0 0 8px currentColor;
}
.legend-item.incident {
color: var(--incident);
}
.legend-item.reflected {
color: var(--reflected);
}
.legend-item.transmitted {
color: var(--transmitted);
}
.legend-item span:last-child {
color: #9db4c6;
}
.equation {
margin-top: 16px;
padding: 11px;
border: 1px solid rgba(86, 228, 255, 0.11);
border-radius: 9px;
background: rgba(86, 228, 255, 0.045);
color: #a5bccd;
text-align: center;
font-family: Georgia, "Times New Roman", serif;
font-size: 14px;
}
.equation small {
display: block;
margin-top: 5px;
color: #718a9d;
font-family: inherit;
font-size: 10px;
}
#viewHint {
position: fixed;
z-index: 4;
left: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 10px;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 10px;
background: rgba(7, 17, 31, 0.72);
color: #8ca5b9;
font-size: 10px;
backdrop-filter: blur(10px);
}
#resetView {
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 6px;
background: rgba(255, 255, 255, 0.05);
color: #c5d9e7;
font: inherit;
font-size: 10px;
cursor: pointer;
}
#resetView:hover {
color: white;
background: rgba(255, 255, 255, 0.1);
}
@media (max-width: 760px) {
#panel {
top: auto;
right: 0;
bottom: 0;
left: 0;
width: auto;
max-height: 47vh;
padding: 17px;
border-right: 0;
border-bottom: 0;
border-left: 0;
border-radius: 19px 19px 0 0;
}
#viewHint {
top: 12px;
bottom: auto;
left: 12px;
}
h1 {
font-size: 23px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="labels"></div>
<aside id="panel">
<div class="eyebrow">Optics / Interactive</div>
<h1>Critical Angle Lab</h1>
<p class="lede">
Rotate an incident ray from the higher-index medium into the lower-index
medium. Voxel blocks make the two media and their shared interface explicit.
</p>
<div id="modeBox" class="mode-box" data-mode="below" aria-live="polite">
<span class="mode-dot"></span>
<strong id="modeTitle" class="mode-title">Partial refraction</strong>
<span id="modeDetail" class="mode-detail"></span>
</div>
<div class="control">
<div class="control-heading">
<span>Incidence angle θ₁</span>
<output id="incidenceOut">32.0°</output>
</div>
<div class="range-shell">
<input
id="incidence"
type="range"
min="0"
max="89.5"
step="0.01"
value="32"
aria-label="Incidence angle"
>
<span id="criticalTick"></span>
</div>
<div class="range-scale">
<span>0°</span>
<button id="criticalJump" class="critical-jump" type="button">
Set θc
</button>
<span>89.5°</span>
</div>
</div>
<div class="index-grid">
<div class="index-card">
<div class="index-title">Higher-index medium</div>
<div class="control-heading">
<span>n₁</span>
<output id="n1Out">1.60</output>
</div>
<input
id="n1"
type="range"
min="1.01"
max="2.50"
step="0.01"
value="1.60"
aria-label="Higher refractive index"
>
</div>
<div class="index-card">
<div class="index-title">Lower-index medium</div>
<div class="control-heading">
<span>n₂</span>
<output id="n2Out">1.00</output>
</div>
<input
id="n2"
type="range"
min="1.00"
max="2.49"
step="0.01"
value="1.00"
aria-label="Lower refractive index"
>
</div>
</div>
<div class="presets">
<button class="preset" data-n1="1.52" data-n2="1.00" type="button">
Glass → Air
</button>
<button class="preset" data-n1="1.33" data-n2="1.00" type="button">
Water → Air
</button>
<button class="preset" data-n1="2.42" data-n2="1.00" type="button">
Diamond → Air
</button>
</div>
<div class="section-label">Angular readouts</div>
<div class="readouts">
<div class="readout">
<span>Critical θc</span>
<strong id="criticalOut">38.7°</strong>
</div>
<div class="readout">
<span>Reflected θr</span>
<strong id="reflectedAngleOut">32.0°</strong>
</div>
<div class="readout">
<span>Refracted θ₂</span>
<strong id="refractedOut">54.1°</strong>
</div>
</div>
<div class="section-label">Average power split</div>
<div class="power-row">
<div class="power-title">
<span>Reflected</span>
<span id="reflectedPowerOut">0%</span>
</div>
<div class="power-track">
<div id="reflectedFill" class="power-fill"></div>
</div>
</div>
<div class="power-row">
<div class="power-title">
<span>Transmitted</span>
<span id="transmittedPowerOut">0%</span>
</div>
<div class="power-track">
<div id="transmittedFill" class="power-fill"></div>
</div>
</div>
<div class="legend">
<div class="legend-item incident">
<span class="legend-line"></span>
<span>Incident ray</span>
</div>
<div class="legend-item reflected">
<span class="legend-line"></span>
<span>Reflected ray</span>
</div>
<div class="legend-item transmitted">
<span class="legend-line"></span>
<span>Transmitted / grazing ray</span>
</div>
</div>
<div class="equation">
n₁ sin θ₁ = n₂ sin θ₂
<small>θc = arcsin(n₂ / n₁), for n₁ > n₂</small>
</div>
</aside>
<div id="viewHint">
<span>Drag to orbit · Scroll to zoom</span>
<button id="resetView" type="button">Reset view</button>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const DEG = Math.PI / 180;
const MAX_THETA = 89.5;
const RAY_Z = 3.24;
const HIT_X = -1.5;
const SOURCE_RADIUS = 5.8;
const state = {
theta: 32,
n1: 1.60,
n2: 1.00
};
// -----------------------------------------------------------------------
// Renderer and scene
// -----------------------------------------------------------------------
const viewport = $("viewport");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 36, 72);
const camera = new THREE.OrthographicCamera(-15, 15, 9, -9, 0.1, 150);
const hemisphere = new THREE.HemisphereLight(0xb8dcff, 0x172338, 1.55);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd9efff, 2.2);
keyLight.position.set(-8, 13, 18);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5ac8ff, 1.2);
rimLight.position.set(14, 4, -12);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffb75f, 16, 30, 2);
warmLight.position.set(9, 5, 8);
scene.add(warmLight);
// -----------------------------------------------------------------------
// Voxel media: two actual cube lattices sharing the y = 0 boundary
// -----------------------------------------------------------------------
const cubeGeometry = new THREE.BoxGeometry(0.92, 0.92, 0.92);
const lowerMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.76,
metalness: 0.04
});
const upperMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.72,
metalness: 0.03,
emissive: 0x160b02,
emissiveIntensity: 0.22
});
const NX = 28;
const NY = 6;
const NZ = 6;
const lowerVoxels = new THREE.InstancedMesh(
cubeGeometry,
lowerMaterial,
NX * NY * NZ
);
const upperVoxels = new THREE.InstancedMesh(
cubeGeometry,
upperMaterial,
NX * NY * NZ
);
const matrix = new THREE.Matrix4();
const instanceColor = new THREE.Color();
function fillVoxels(mesh, yStart, hue, saturation, lightness, warmShift = 0) {
let index = 0;
for (let ix = 0; ix < NX; ix++) {
for (let iy = 0; iy < NY; iy++) {
for (let iz = 0; iz < NZ; iz++) {
const x = -NX / 2 + ix + 0.5;
const y = yStart + iy + 0.5;
const z = -3 + iz + 0.5;
matrix.makeTranslation(x, y, z);
mesh.setMatrixAt(index, matrix);
const variation =
0.018 * Math.sin(ix * 1.73 + iy * 2.11 + iz * 0.81);
instanceColor.setHSL(
hue + variation + warmShift,
saturation + variation * 0.35,
lightness + variation * 1.5
);
mesh.setColorAt(index, instanceColor);
index++;
}
}
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) {
mesh.instanceColor.needsUpdate = true;
}
}
fillVoxels(lowerVoxels, -6, 0.56, 0.64, 0.48);
fillVoxels(upperVoxels, 0, 0.095, 0.72, 0.55);
scene.add(lowerVoxels, upperVoxels);
const grid = new THREE.GridHelper(42, 42, 0x19334a, 0x10263a);
grid.position.y = -6.02;
grid.material.transparent = true;
grid.material.opacity = 0.45;
scene.add(grid);
// A faint physical membrane marks the exact interface.
const interfacePlane = new THREE.Mesh(
new THREE.PlaneGeometry(28, 6),
new THREE.MeshBasicMaterial({
color: 0xd9f3ff,
transparent: true,
opacity: 0.075,
side: THREE.DoubleSide,
depthWrite: false
})
);
interfacePlane.rotation.x = -Math.PI / 2;
interfacePlane.position.set(0, 0, 0);
scene.add(interfacePlane);
const interfaceLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-14, 0, 3.12),
new THREE.Vector3(14, 0, 3.12)
]),
new THREE.LineBasicMaterial({
color: 0xd9f3ff,
transparent: true,
opacity: 0.7
})
);
scene.add(interfaceLine);
// -----------------------------------------------------------------------
// Rays, arcs, normal, and markers
// -----------------------------------------------------------------------
const unitCylinder = new THREE.CylinderGeometry(1, 1, 1, 12);
const unitCone = new THREE.ConeGeometry(1, 1, 16);
const yAxis = new THREE.Vector3(0, 1, 0);
function createRay(color) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 1,
depthTest: false,
depthWrite: false
});
const shaft = new THREE.Mesh(unitCylinder, material);
const head = new THREE.Mesh(unitCone, material);
shaft.renderOrder = 30;
head.renderOrder = 31;
group.add(shaft, head);
scene.add(group);
return { group, shaft, head, material };
}
const incidentRay = createRay(0xf5fbff);
const reflectedRay = createRay(0xff5f9f);
const transmittedRay = createRay(0x56e4ff);
function setRay(ray, start, end, visible = true) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
if (!visible || length < 0.001) {
ray.group.visible = false;
return;
}
ray.group.visible = true;
direction.normalize();
const headLength = Math.min(0.38, length * 0.22);
const shaftEnd = end.clone().addScaledVector(direction, -headLength);
const shaftLength = Math.max(0.001, shaftEnd.distanceTo(start));
const midpoint = start.clone().add(shaftEnd).multiplyScalar(0.5);
ray.shaft.position.copy(midpoint);
ray.shaft.quaternion.setFromUnitVectors(yAxis, direction);
ray.shaft.scale.set(0.034, shaftLength, 0.034);
ray.head.position.copy(end).addScaledVector(direction, -headLength * 0.5);
ray.head.quaternion.setFromUnitVectors(yAxis, direction);
ray.head.scale.set(0.13, headLength, 0.13);
}
function makeOverlayLine(color, dashed = false) {
const material = dashed
? new THREE.LineDashedMaterial({
color,
dashSize: 0.22,
gapSize: 0.15,
transparent: true,
opacity: 0.58,
depthTest: false,
depthWrite: false
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.82,
depthTest: false,
depthWrite: false
});
const line = new THREE.Line(new THREE.BufferGeometry(), material);
line.renderOrder = 25;
scene.add(line);
return line;
}
const normalLine = makeOverlayLine(0xa8bbca, true);
const criticalGuide = makeOverlayLine(0xffc36b, true);
const incidentArc = makeOverlayLine(0xf5fbff);
const reflectedArc = makeOverlayLine(0xff5f9f);
const transmittedArc = makeOverlayLine(0x56e4ff);
function setLinePoints(line, points) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
if (line.material.isLineDashedMaterial) {
line.computeLineDistances();
}
}
function setArc(line, radius, startAngle, endAngle) {
const points = [];
const segments = 40;
for (let i = 0; i <= segments; i++) {
const t = i / segments;
const angle = THREE.MathUtils.lerp(startAngle, endAngle, t);
points.push(
new THREE.Vector3(
HIT_X + Math.cos(angle) * radius,
Math.sin(angle) * radius,
RAY_Z + 0.08
)
);
}
setLinePoints(line, points);
}
const hitMarker = new THREE.Group();
const hitSphere = new THREE.Mesh(
new THREE.SphereGeometry(0.095, 16, 12),
new THREE.MeshBasicMaterial({
color: 0xffffff,
depthTest: false,
depthWrite: false
})
);
const hitRing = new THREE.Mesh(
new THREE.TorusGeometry(0.22, 0.022, 8, 32),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.8,
depthTest: false,
depthWrite: false
})
);
hitMarker.add(hitSphere, hitRing);
hitMarker.position.set(HIT_X, 0, RAY_Z + 0.09);
hitMarker.renderOrder = 40;
scene.add(hitMarker);
const sourceMarker = new THREE.Group();
const sourceSphere = new THREE.Mesh(
new THREE.SphereGeometry(0.12, 16, 12),
new THREE.MeshBasicMaterial({
color: 0xffffff,
depthTest: false,
depthWrite: false
})
);
const sourceRing = new THREE.Mesh(
new THREE.TorusGeometry(0.27, 0.022, 8, 32),
new THREE.MeshBasicMaterial({
color: 0x8cdeff,
transparent: true,
opacity: 0.85,
depthTest: false,
depthWrite: false
})
);
sourceMarker.add(sourceSphere, sourceRing);
sourceMarker.renderOrder = 40;
scene.add(sourceMarker);
// -----------------------------------------------------------------------
// Projected HTML labels
// -----------------------------------------------------------------------
function createLabel(text, className) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
$("labels").appendChild(element);
return element;
}
const labels = {
n1: createLabel("n₁ = 1.60", "medium n1"),
n2: createLabel("n₂ = 1.00", "medium n2"),
interface: createLabel("Interface", "critical"),
incident: createLabel("θ₁ = 32.0°", "incident"),
reflected: createLabel("θr = 32.0°", "reflected"),
transmitted: createLabel("θ₂ = 54.1°", "transmitted"),
critical: createLabel("Critical-angle guide", "critical")
};
const anchors = {
n1: new THREE.Vector3(-10.1, -4.4, RAY_Z),
n2: new THREE.Vector3(8.4, 4.5, RAY_Z),
interface: new THREE.Vector3(11.6, 0.35, RAY_Z),
incident: new THREE.Vector3(),
reflected: new THREE.Vector3(),
transmitted: new THREE.Vector3(),
critical: new THREE.Vector3()
};
function positionLabel(element, worldPosition, visible = true) {
if (!visible) {
element.style.display = "none";
return;
}
const projected = worldPosition.clone().project(camera);
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.display = "block";
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateProjectedLabels() {
positionLabel(labels.n1, anchors.n1);
positionLabel(labels.n2, anchors.n2);
positionLabel(labels.interface, anchors.interface);
positionLabel(labels.incident, anchors.incident);
positionLabel(labels.reflected, anchors.reflected);
positionLabel(
labels.transmitted,
anchors.transmitted,
labels.transmitted.style.display !== "none"
);
positionLabel(labels.critical, anchors.critical);
}
// -----------------------------------------------------------------------
// Optical calculation
// -----------------------------------------------------------------------
function endpointInMedium(start, direction) {
let distance = 9.5;
if (direction.x > 1e-7) {
distance = Math.min(distance, (13.55 - start.x) / direction.x);
}
if (direction.y < -1e-7) {
distance = Math.min(distance, (-6.15 - start.y) / -direction.y);
} else if (direction.y > 1e-7) {
distance = Math.min(distance, (6.15 - start.y) / direction.y);
}
return start.clone().addScaledVector(direction, Math.max(0, distance));
}
function computeFresnel(theta, n1, n2, thetaT, mode) {
if (mode === "above") {
return { reflected: 1, transmitted: 0 };
}
const cosI = Math.cos(theta * DEG);
const cosT = mode === "critical" ? 0 : Math.cos(thetaT * DEG);
const rs =
(n1 * cosI - n2 * cosT) /
(n1 * cosI + n2 * cosT);
const rp =
(n2 * cosI - n1 * cosT) /
(n2 * cosI + n1 * cosT);
const reflected = THREE.MathUtils.clamp(
0.5 * (rs * rs + rp * rp),
0,
1
);
return {
reflected,
transmitted: Math.max(0, 1 - reflected)
};
}
function updateOptics() {
const theta = state.theta;
const n1 = state.n1;
const n2 = state.n2;
const critical = Math.asin(n2 / n1) / DEG;
let mode;
let thetaT = null;
if (Math.abs(theta - critical) < 1e-9) {
mode = "critical";
thetaT = 90;
} else if (theta < critical) {
mode = "below";
const sinT = (n1 / n2) * Math.sin(theta * DEG);
thetaT = Math.asin(Math.min(1, sinT)) / DEG;
} else {
mode = "above";
}
const power = computeFresnel(theta, n1, n2, thetaT, mode);
// UI values.
$("incidence").value = theta.toFixed(2);
$("incidenceOut").textContent = `${theta.toFixed(1)}°`;
$("n1").value = n1.toFixed(2);
$("n2").value = n2.toFixed(2);
$("n1Out").textContent = n1.toFixed(2);
$("n2Out").textContent = n2.toFixed(2);
$("criticalOut").textContent = `${critical.toFixed(1)}°`;
$("reflectedAngleOut").textContent = `${theta.toFixed(1)}°`;
$("criticalJump").textContent = `Set θc = ${critical.toFixed(1)}°`;
$("criticalTick").style.left = `${(critical / MAX_THETA) * 100}%`;
$("modeBox").dataset.mode = mode;
if (mode === "below") {
$("modeTitle").textContent = "Partial refraction";
$("modeDetail").textContent =
"A propagating ray enters the lower-index medium and bends away from the normal.";
$("refractedOut").textContent = `${thetaT.toFixed(1)}°`;
} else if (mode === "critical") {
$("modeTitle").textContent = "Critical-angle limit";
$("modeDetail").textContent =
"The refracted direction is parallel to the interface (θ₂ = 90°). Normal power transmission is zero.";
$("refractedOut").textContent = "90.0°";
} else {
$("modeTitle").textContent = "Total internal reflection";
$("modeDetail").textContent =
"No propagating transmitted ray exists. All incident power is reflected; the boundary field is evanescent.";
$("refractedOut").textContent = "—";
}
$("reflectedPowerOut").textContent = `${(power.reflected * 100).toFixed(1)}%`;
$("transmittedPowerOut").textContent = `${(power.transmitted * 100).toFixed(1)}%`;
$("reflectedFill").style.width = `${power.reflected * 100}%`;
$("transmittedFill").style.width = `${power.transmitted * 100}%`;
// Geometry.
const thetaRad = theta * DEG;
const hit = new THREE.Vector3(HIT_X, 0, RAY_Z);
const source = new THREE.Vector3(
HIT_X - Math.sin(thetaRad) * SOURCE_RADIUS,
-Math.cos(thetaRad) * SOURCE_RADIUS,
RAY_Z
);
const incidentDirection = new THREE.Vector3(
Math.sin(thetaRad),
Math.cos(thetaRad),
0
);
const reflectedDirection = new THREE.Vector3(
Math.sin(thetaRad),
-Math.cos(thetaRad),
0
);
const reflectedEnd = endpointInMedium(hit, reflectedDirection);
setRay(incidentRay, source, hit, true);
setRay(reflectedRay, hit, reflectedEnd, true);
incidentRay.material.opacity = 1;
reflectedRay.material.opacity = 0.38 + 0.62 * power.reflected;
let transmittedEnd = null;
if (mode !== "above") {
const thetaTRad = thetaT * DEG;
const transmittedDirection =
mode === "critical"
? new THREE.Vector3(1, 0, 0)
: new THREE.Vector3(
Math.sin(thetaTRad),
Math.cos(thetaTRad),
0
);
transmittedEnd = endpointInMedium(hit, transmittedDirection);
setRay(transmittedRay, hit, transmittedEnd, true);
transmittedRay.material.opacity =
mode === "critical" ? 0.36 : 0.3 + 0.7 * power.transmitted;
} else {
setRay(transmittedRay, hit, hit, false);
}
sourceMarker.position.copy(source);
sourceMarker.position.z += 0.09;
// Normal.
setLinePoints(normalLine, [
new THREE.Vector3(HIT_X, -6.2, RAY_Z + 0.02),
new THREE.Vector3(HIT_X, 6.2, RAY_Z + 0.02)
]);
// Dashed critical-angle guide.
const criticalRad = critical * DEG;
const criticalSource = new THREE.Vector3(
HIT_X - Math.sin(criticalRad) * SOURCE_RADIUS,
-Math.cos(criticalRad) * SOURCE_RADIUS,
RAY_Z - 0.1
);
setLinePoints(criticalGuide, [criticalSource, hit]);
// Angular arcs.
setArc(incidentArc, 1.18, Math.PI / 2, Math.PI / 2 - thetaRad);
setArc(reflectedArc, 1.38, Math.PI / 2, Math.PI / 2 + thetaRad);
if (mode !== "above") {
setArc(
transmittedArc,
mode === "critical" ? 1.62 : 1.38,
Math.PI / 2,
Math.PI / 2 - thetaT * DEG
);
}
// Label content and anchors.
labels.n1.textContent = `n₁ = ${n1.toFixed(2)} · higher index`;
labels.n2.textContent = `n₂ = ${n2.toFixed(2)} · lower index`;
labels.incident.textContent = `θ₁ = ${theta.toFixed(1)}°`;
labels.reflected.textContent = `θr = ${theta.toFixed(1)}°`;
labels.transmitted.textContent =
mode === "critical"
? "θ₂ = 90.0° · grazing"
: `θ₂ = ${thetaT.toFixed(1)}°`;
const incidentAngle = Math.PI / 2 - thetaRad * 0.5;
const reflectedAngle = Math.PI / 2 + thetaRad * 0.5;
const transmittedAngle = Math.PI / 2 - (thetaT ?? 0) * DEG * 0.5;
anchors.incident.set(
HIT_X + Math.cos(incidentAngle) * 1.65,
Math.sin(incidentAngle) * 1.65,
RAY_Z + 0.15
);
anchors.reflected.set(
HIT_X + Math.cos(reflectedAngle) * 1.82,
Math.sin(reflectedAngle) * 1.82,
RAY_Z + 0.15
);
anchors.transmitted.set(
HIT_X + Math.cos(transmittedAngle) * 1.9,
Math.sin(transmittedAngle) * 1.9,
RAY_Z + 0.15
);
anchors.critical.copy(criticalSource).lerp(hit, 0.54);
anchors.critical.y -= 0.48;
}
// -----------------------------------------------------------------------
// Direct camera controls: no addon modules
// -----------------------------------------------------------------------
const orbit = {
azimuth: 0.14,
elevation: 0.17,
zoom: 1,
targetAzimuth: 0.14,
targetElevation: 0.17,
targetZoom: 1
};
function resetView() {
orbit.targetAzimuth = 0.14;
orbit.targetElevation = 0.17;
orbit.targetZoom = 1;
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height, false);
// Preserve at least 31 world units of horizontal scene width.
const viewHeight = Math.max(17.5, 31 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
}
function updateCamera() {
const azimuth = orbit.azimuth;
const elevation = orbit.elevation;
const distance = 50;
camera.position.set(
distance * Math.sin(azimuth) * Math.cos(elevation),
distance * Math.sin(elevation),
distance * Math.cos(azimuth) * Math.cos(elevation)
);
camera.lookAt(0, 0, 0);
camera.zoom = orbit.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
let dragging = false;
let lastX = 0;
let lastY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
orbit.targetAzimuth += dx * 0.006;
orbit.targetElevation = THREE.MathUtils.clamp(
orbit.targetElevation + dy * 0.0045,
-0.48,
0.56
);
});
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();
orbit.targetZoom = THREE.MathUtils.clamp(
orbit.targetZoom * Math.exp(-event.deltaY * 0.001),
0.62,
2.3
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetView);
$("resetView").addEventListener("click", resetView);
window.addEventListener("resize", resize);
// -----------------------------------------------------------------------
// UI events
// -----------------------------------------------------------------------
$("incidence").addEventListener("input", (event) => {
state.theta = Number(event.target.value);
updateOptics();
});
function updateIndex(whichChanged) {
let n1 = Number($("n1").value);
let n2 = Number($("n2").value);
// Enforce n1 > n2 without allowing the controls to cross.
if (n1 <= n2) {
if (whichChanged === "n1") {
n2 = Math.max(1, n1 - 0.01);
} else {
n1 = Math.min(2.5, n2 + 0.01);
}
}
state.n1 = Number(n1.toFixed(2));
state.n2 = Number(n2.toFixed(2));
updateOptics();
}
$("n1").addEventListener("input", () => updateIndex("n1"));
$("n2").addEventListener("input", () => updateIndex("n2"));
$("criticalJump").addEventListener("click", () => {
const critical = Math.asin(state.n2 / state.n1) / DEG;
state.theta = critical;
updateOptics();
});
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
state.n1 = Number(button.dataset.n1);
state.n2 = Number(button.dataset.n2);
updateOptics();
});
});
// -----------------------------------------------------------------------
// Render loop
// -----------------------------------------------------------------------
resize();
updateOptics();
updateCamera();
function animate() {
requestAnimationFrame(animate);
orbit.azimuth +=
(orbit.targetAzimuth - orbit.azimuth) * 0.12;
orbit.elevation +=
(orbit.targetElevation - orbit.elevation) * 0.12;
orbit.zoom +=
(orbit.targetZoom - orbit.zoom) * 0.12;
updateCamera();
updateProjectedLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```