Prompt specification
Build or customize the Three.js 3D scene "Real and virtual image 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: Real and virtual image comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/real-and-virtual-image-comparison-x1558
Scene Description Prompt:
Compare stylized real and virtual images through a converging lens, distinguishing screen images from backward ray extensions. Three.js from cdnjs, one HTML file.
Working Three.js Starter (real-and-virtual-image-comparison-x1558):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real vs. Virtual Images — Converging Lens</title>
<style>
:root {
color-scheme: dark;
--bg: #050914;
--panel: rgba(14, 23, 39, 0.88);
--panel-border: rgba(148, 177, 214, 0.18);
--text: #edf4ff;
--muted: #99abc5;
--real: #52e3b6;
--virtual: #9c8cff;
--light: #ffc857;
--extension: #ff5fcf;
--cyan: #6ed9ff;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 15% 0%, rgba(46, 111, 166, 0.18), transparent 35%),
radial-gradient(circle at 90% 10%, rgba(125, 76, 190, 0.17), transparent 34%),
var(--bg);
}
button,
input {
font: inherit;
}
.app {
width: min(1480px, calc(100% - 28px));
margin: 0 auto;
padding: 24px 0 30px;
}
.header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
margin-bottom: 18px;
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.65rem, 3vw, 2.55rem);
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
max-width: 760px;
margin: 10px 0 0;
color: var(--muted);
font-size: 0.94rem;
line-height: 1.55;
}
.equation {
flex: 0 0 auto;
padding: 11px 15px;
border: 1px solid var(--panel-border);
border-radius: 12px;
color: #c8d8ee;
background: rgba(10, 18, 32, 0.72);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.84rem;
white-space: nowrap;
}
.stage {
position: relative;
height: clamp(540px, 67vh, 720px);
overflow: hidden;
border: 1px solid var(--panel-border);
border-radius: 20px;
background: #07101d;
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.38);
}
#canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#canvas:active {
cursor: grabbing;
}
.stage::after {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
content: "";
pointer-events: none;
background: linear-gradient(
transparent,
rgba(180, 207, 240, 0.22) 15%,
rgba(180, 207, 240, 0.22) 85%,
transparent
);
}
.panel-overlay {
position: absolute;
z-index: 2;
top: 16px;
width: 50%;
pointer-events: none;
}
.panel-overlay.left {
left: 18px;
}
.panel-overlay.right {
left: calc(50% + 18px);
}
.panel-kicker {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--muted);
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 14px currentColor;
}
.real .dot {
color: var(--real);
}
.virtual .dot {
color: var(--virtual);
}
.panel-title {
margin: 0;
font-size: clamp(1.05rem, 2vw, 1.4rem);
letter-spacing: -0.02em;
}
.panel-note {
max-width: 430px;
margin-top: 5px;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.45;
}
.stage-hint {
position: absolute;
z-index: 3;
bottom: 12px;
left: 50%;
padding: 7px 11px;
border: 1px solid rgba(163, 191, 225, 0.16);
border-radius: 999px;
color: #9eb1ca;
background: rgba(5, 10, 20, 0.72);
font-size: 0.68rem;
transform: translateX(-50%);
pointer-events: none;
white-space: nowrap;
backdrop-filter: blur(10px);
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 13px 0;
padding: 10px 12px;
border: 1px solid var(--panel-border);
border-radius: 14px;
background: rgba(10, 18, 31, 0.72);
}
.toolbar-group {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.tool-button {
padding: 8px 12px;
border: 1px solid rgba(160, 190, 226, 0.2);
border-radius: 9px;
color: #dce8f8;
background: rgba(87, 120, 160, 0.1);
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease;
}
.tool-button:hover {
border-color: rgba(160, 190, 226, 0.42);
background: rgba(87, 120, 160, 0.2);
}
.toggle {
display: inline-flex;
align-items: center;
gap: 7px;
color: #b7c7dc;
font-size: 0.76rem;
cursor: pointer;
user-select: none;
}
.toggle input {
width: 15px;
height: 15px;
accent-color: var(--cyan);
}
.control-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 13px;
}
.control-card {
padding: 17px 18px;
border: 1px solid var(--panel-border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.14);
}
.control-card.real-card {
border-top: 2px solid rgba(82, 227, 182, 0.65);
}
.control-card.virtual-card {
border-top: 2px solid rgba(156, 140, 255, 0.7);
}
.card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.card-head h2 {
margin: 0;
font-size: 0.98rem;
}
.card-head p {
margin: 4px 0 0;
color: var(--muted);
font-size: 0.73rem;
}
.metric {
color: #cbd9eb;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.69rem;
text-align: right;
line-height: 1.55;
white-space: nowrap;
}
.range-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 11px;
color: var(--muted);
font-size: 0.74rem;
}
input[type="range"] {
width: 100%;
accent-color: var(--real);
cursor: pointer;
}
.virtual-card input[type="range"] {
accent-color: var(--virtual);
}
.range-value {
min-width: 48px;
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: right;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px 20px;
margin-top: 13px;
padding: 14px 16px;
border: 1px solid var(--panel-border);
border-radius: 14px;
color: #aebed3;
background: rgba(9, 16, 28, 0.72);
font-size: 0.75rem;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 29px;
height: 3px;
border-radius: 999px;
background: var(--light);
box-shadow: 0 0 8px rgba(255, 200, 87, 0.5);
}
.swatch.extension {
background: repeating-linear-gradient(
90deg,
var(--extension) 0 7px,
transparent 7px 11px
);
box-shadow: none;
}
.swatch.screen-image {
height: 15px;
background: var(--real);
box-shadow: 0 0 9px rgba(82, 227, 182, 0.35);
}
.swatch.virtual-image {
height: 15px;
border: 2px dashed var(--virtual);
background: rgba(156, 140, 255, 0.12);
box-shadow: none;
}
footer {
margin-top: 12px;
color: #71849f;
font-size: 0.69rem;
line-height: 1.5;
text-align: center;
}
@media (max-width: 760px) {
.app {
width: min(100% - 18px, 1480px);
padding-top: 17px;
}
.header {
display: block;
}
.equation {
display: inline-block;
margin-top: 13px;
}
.stage {
height: 790px;
}
.stage::after {
top: 50%;
right: 0;
bottom: auto;
left: 0;
width: auto;
height: 1px;
background: linear-gradient(
90deg,
transparent,
rgba(180, 207, 240, 0.22) 15%,
rgba(180, 207, 240, 0.22) 85%,
transparent
);
}
.panel-overlay {
left: 13px;
width: calc(100% - 26px);
}
.panel-overlay.right {
top: calc(50% + 13px);
left: 13px;
}
.panel-note {
max-width: 90%;
}
.control-grid {
grid-template-columns: 1fr;
}
.stage-hint {
bottom: 8px;
}
}
</style>
</head>
<body>
<main class="app">
<header class="header">
<div>
<div class="eyebrow">Geometric Optics · Interactive Comparison</div>
<h1>Real vs. virtual images with a converging lens</h1>
<p class="subtitle">
The solid amber paths are physical light rays. A real image forms where
those rays physically meet on a screen. For a virtual image, the
outgoing rays diverge; dashed magenta lines are only backward
extensions used to locate the apparent image.
</p>
</div>
<div class="equation">1/f = 1/d<sub>o</sub> + 1/d<sub>i</sub></div>
</header>
<section class="stage" id="stage" aria-label="Interactive optics comparison">
<canvas id="canvas"></canvas>
<div class="panel-overlay left real">
<div class="panel-kicker"><span class="dot"></span>Physical convergence</div>
<h2 class="panel-title">Real image on a screen</h2>
<div class="panel-note">
Object beyond the focal point. Refracted rays meet and form an
inverted image.
</div>
</div>
<div class="panel-overlay right virtual">
<div class="panel-kicker"><span class="dot"></span>Apparent convergence</div>
<h2 class="panel-title">Virtual image from backward extensions</h2>
<div class="panel-note">
Object inside the focal point. The rays diverge; their dashed
extensions intersect on the object side.
</div>
</div>
<div class="stage-hint">
Drag to orbit · Wheel to zoom · Double-click to reset
</div>
</section>
<nav class="toolbar" aria-label="Visualization controls">
<div class="toolbar-group">
<button class="tool-button" id="motionButton" type="button">
Pause light animation
</button>
<button class="tool-button" id="resetButton" type="button">
Reset cameras
</button>
</div>
<div class="toolbar-group">
<label class="toggle">
<input id="raysToggle" type="checkbox" checked>
Physical rays
</label>
<label class="toggle">
<input id="extensionsToggle" type="checkbox" checked>
Backward extensions
</label>
<label class="toggle">
<input id="labelsToggle" type="checkbox" checked>
Labels
</label>
</div>
</nav>
<section class="control-grid">
<article class="control-card real-card">
<div class="card-head">
<div>
<h2>Real-image experiment</h2>
<p>Move the object farther than one focal length.</p>
</div>
<div class="metric" id="realMetric" aria-live="polite"></div>
</div>
<div class="range-row">
<label for="realDistance">Object distance</label>
<input
id="realDistance"
type="range"
min="2.4"
max="5.2"
step="0.05"
value="4.2"
>
<output class="range-value" id="realValue">4.20</output>
</div>
</article>
<article class="control-card virtual-card">
<div class="card-head">
<div>
<h2>Virtual-image experiment</h2>
<p>Move the object closer than one focal length.</p>
</div>
<div class="metric" id="virtualMetric" aria-live="polite"></div>
</div>
<div class="range-row">
<label for="virtualDistance">Object distance</label>
<input
id="virtualDistance"
type="range"
min="0.6"
max="1.05"
step="0.01"
value="0.82"
>
<output class="range-value" id="virtualValue">0.82</output>
</div>
</article>
</section>
<section class="legend" aria-label="Diagram legend">
<span class="legend-item">
<span class="swatch"></span>
Physical light rays
</span>
<span class="legend-item">
<span class="swatch screen-image"></span>
Real image on screen
</span>
<span class="legend-item">
<span class="swatch virtual-image"></span>
Virtual, upright image
</span>
<span class="legend-item">
<span class="swatch extension"></span>
Backward ray extensions — not actual light
</span>
</section>
<footer>
Paraxial thin-lens model with focal length f = 1.50 units.
Camera orbit and zoom are implemented directly with Three.js core.
</footer>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Constants and state
// ------------------------------------------------------------
const FOCAL_LENGTH = 1.5;
const OBJECT_HEIGHT = 0.95;
const RIGHT_RAY_END = 2.35;
const stage = document.getElementById("stage");
const canvas = document.getElementById("canvas");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.autoClear = false;
const showState = {
rays: true,
extensions: true,
labels: true,
motion: !window.matchMedia("(prefers-reduced-motion: reduce)").matches
};
const cameraState = {
yaw: 0,
pitch: 0.10,
zoom: 1,
dragging: false,
lastX: 0,
lastY: 0
};
const COLORS = {
ray: 0xffc857,
rayBright: 0xffe39a,
object: 0xffa84d,
realImage: 0x52e3b6,
virtualImage: 0x9c8cff,
extension: 0xff5fcf,
lens: 0x67d8ff,
axis: 0x8294ad,
focus: 0xdcecff
};
const Y_AXIS = new THREE.Vector3(0, 1, 0);
// ------------------------------------------------------------
// Scene construction
// ------------------------------------------------------------
function createScenario(kind, objectDistance) {
const scene = new THREE.Scene();
scene.background = new THREE.Color(
kind === "real" ? 0x071421 : 0x120b22
);
scene.add(new THREE.AmbientLight(0xffffff, 1.15));
const key = new THREE.DirectionalLight(0xffffff, 2.1);
key.position.set(3, 5, 8);
scene.add(key);
const rim = new THREE.PointLight(
kind === "real" ? 0x52e3b6 : 0x9c8cff,
14,
16
);
rim.position.set(-2, 1, 5);
scene.add(rim);
const camera = new THREE.OrthographicCamera(-5, 5, 5, -5, 0.1, 100);
const scenario = {
kind,
do: objectDistance,
scene,
camera,
root: null,
rayGroup: null,
extensionGroup: null,
labelGroup: null,
paths: [],
pulses: [],
bounds: null
};
buildScenario(scenario);
return scenario;
}
const realScenario = createScenario("real", 4.2);
const virtualScenario = createScenario("virtual", 0.82);
// ------------------------------------------------------------
// Resource management
// ------------------------------------------------------------
function disposeGroup(group) {
const geometries = new Set();
const materials = new Set();
const textures = new Set();
group.traverse((object) => {
if (object.geometry) {
geometries.add(object.geometry);
}
const objectMaterials = Array.isArray(object.material)
? object.material
: object.material
? [object.material]
: [];
objectMaterials.forEach((material) => {
materials.add(material);
if (material.map) {
textures.add(material.map);
}
});
});
geometries.forEach((geometry) => geometry.dispose());
textures.forEach((texture) => texture.dispose());
materials.forEach((material) => material.dispose());
}
// ------------------------------------------------------------
// Geometry helpers
// ------------------------------------------------------------
function makeGrid() {
const points = [];
const z = -0.28;
for (let x = -6; x <= 5; x += 0.5) {
points.push(
new THREE.Vector3(x, -4, z),
new THREE.Vector3(x, 4, z)
);
}
for (let y = -4; y <= 4; y += 0.5) {
points.push(
new THREE.Vector3(-6, y, z),
new THREE.Vector3(5, y, z)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0x8ba5c8,
transparent: true,
opacity: 0.075,
depthWrite: false
});
return new THREE.LineSegments(geometry, material);
}
function makeAxis() {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-6, 0, -0.12),
new THREE.Vector3(5, 0, -0.12)
]);
const material = new THREE.LineBasicMaterial({
color: COLORS.axis,
transparent: true,
opacity: 0.62
});
return new THREE.Line(geometry, material);
}
function makeLens() {
const group = new THREE.Group();
const radius = 1.55;
const halfThickness = 0.24;
const shape = new THREE.Shape();
const segments = 40;
const profile = (y) =>
halfThickness * Math.sqrt(Math.max(0, 1 - (y / radius) ** 2));
shape.moveTo(profile(-radius), -radius);
for (let i = 0; i <= segments; i++) {
const y = -radius + (2 * radius * i) / segments;
shape.lineTo(profile(y), y);
}
for (let i = segments; i >= 0; i--) {
const y = -radius + (2 * radius * i) / segments;
shape.lineTo(-profile(y), y);
}
shape.closePath();
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: 0.18,
bevelEnabled: false,
curveSegments: 24
});
geometry.translate(0, 0, -0.09);
const material = new THREE.MeshPhongMaterial({
color: COLORS.lens,
emissive: 0x0b3850,
emissiveIntensity: 0.7,
transparent: true,
opacity: 0.34,
side: THREE.DoubleSide,
depthWrite: false
});
const mesh = new THREE.Mesh(geometry, material);
mesh.renderOrder = 2;
group.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry, 18),
new THREE.LineBasicMaterial({
color: 0xa9edff,
transparent: true,
opacity: 0.85
})
);
group.add(edges);
return group;
}
function makeFocusMarker(x) {
const group = new THREE.Group();
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.075),
new THREE.MeshBasicMaterial({ color: COLORS.focus })
);
marker.position.set(x, 0, -0.07);
group.add(marker);
const tickGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(x, -0.12, -0.08),
new THREE.Vector3(x, 0.12, -0.08)
]);
group.add(
new THREE.Line(
tickGeometry,
new THREE.LineBasicMaterial({
color: COLORS.focus,
transparent: true,
opacity: 0.65
})
)
);
return group;
}
function makeSolidArrow(x, height, color, z = 0.04) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const headHeight = Math.min(0.28, height * 0.3);
const shaftHeight = Math.max(0.05, height - headHeight);
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(
0.047,
0.065,
shaftHeight,
16
),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.32,
roughness: 0.38,
metalness: 0.08
})
);
shaft.position.y = shaftHeight / 2;
group.add(shaft);
const head = new THREE.Mesh(
new THREE.ConeGeometry(0.17, headHeight, 18),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.32,
roughness: 0.38,
metalness: 0.08
})
);
head.position.y = shaftHeight + headHeight / 2;
group.add(head);
const foot = new THREE.Mesh(
new THREE.CylinderGeometry(0.17, 0.17, 0.035, 20),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.24,
roughness: 0.45
})
);
foot.position.y = 0.017;
group.add(foot);
return group;
}
function makeGhostArrow(x, height, z = 0.04) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const headHeight = Math.min(0.28, height * 0.3);
const shaftTop = height - headHeight;
const shape = new THREE.Shape();
shape.moveTo(-0.065, 0);
shape.lineTo(0.065, 0);
shape.lineTo(0.065, shaftTop);
shape.lineTo(0.2, shaftTop);
shape.lineTo(0, height);
shape.lineTo(-0.2, shaftTop);
shape.lineTo(-0.065, shaftTop);
shape.closePath();
const fill = new THREE.Mesh(
new THREE.ShapeGeometry(shape),
new THREE.MeshBasicMaterial({
color: COLORS.virtualImage,
transparent: true,
opacity: 0.10,
side: THREE.DoubleSide,
depthWrite: false
})
);
group.add(fill);
const points = [
new THREE.Vector3(0, 0, 0.025),
new THREE.Vector3(0, shaftTop, 0.025),
new THREE.Vector3(0, height, 0.025),
new THREE.Vector3(-0.2, shaftTop, 0.025),
new THREE.Vector3(0, height, 0.025),
new THREE.Vector3(0.2, shaftTop, 0.025)
];
const line = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineDashedMaterial({
color: COLORS.virtualImage,
dashSize: 0.11,
gapSize: 0.075,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
line.computeLineDistances();
line.renderOrder = 8;
group.add(line);
return group;
}
function makeScreen(x) {
const group = new THREE.Group();
const geometry = new THREE.PlaneGeometry(0.46, 3.35);
const material = new THREE.MeshBasicMaterial({
color: 0xb9e9ff,
transparent: true,
opacity: 0.105,
side: THREE.DoubleSide,
depthWrite: false
});
const panel = new THREE.Mesh(geometry, material);
panel.position.set(x, 0, -0.035);
group.add(panel);
const border = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0xb9e9ff,
transparent: true,
opacity: 0.42
})
);
border.position.copy(panel.position);
group.add(border);
return group;
}
function makeTextSprite(text, color = "#dcecff") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 640;
labelCanvas.height = 120;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 640, 120);
context.fillStyle = "rgba(5, 11, 22, 0.86)";
context.strokeStyle = color;
context.lineWidth = 3;
const radius = 24;
const x = 4;
const y = 4;
const width = 632;
const height = 112;
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
context.fill();
context.stroke();
context.fillStyle = color;
context.font = "700 34px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 320, 61);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
const labelWidth = Math.max(0.48, Math.min(3.65, text.length * 0.108));
sprite.scale.set(labelWidth, 0.34, 1);
sprite.renderOrder = 20;
return sprite;
}
function addSolidSegment(parent, start, end, color, radius = 0.016) {
const direction = end.clone().sub(start);
const length = direction.length();
if (length < 0.0001) {
return null;
}
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
10,
1,
false
);
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.94
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
Y_AXIS,
direction.clone().normalize()
);
parent.add(mesh);
return mesh;
}
function addArrowhead(parent, position, direction, color) {
const geometry = new THREE.ConeGeometry(0.065, 0.17, 12);
const material = new THREE.MeshBasicMaterial({ color });
const arrow = new THREE.Mesh(geometry, material);
arrow.position.copy(position);
arrow.quaternion.setFromUnitVectors(
Y_AXIS,
direction.clone().normalize()
);
parent.add(arrow);
return arrow;
}
// ------------------------------------------------------------
// Scenario rebuilding
// ------------------------------------------------------------
function buildScenario(scenario) {
if (scenario.root) {
scenario.scene.remove(scenario.root);
disposeGroup(scenario.root);
}
const root = new THREE.Group();
scenario.scene.add(root);
scenario.root = root;
const rayGroup = new THREE.Group();
const extensionGroup = new THREE.Group();
const labelGroup = new THREE.Group();
root.add(rayGroup, extensionGroup, labelGroup);
scenario.rayGroup = rayGroup;
scenario.extensionGroup = extensionGroup;
scenario.labelGroup = labelGroup;
scenario.paths = [];
scenario.pulses = [];
const doDistance = scenario.do;
const di =
(FOCAL_LENGTH * doDistance) /
(doDistance - FOCAL_LENGTH);
const magnification = -di / doDistance;
const imageHeight = Math.abs(magnification) * OBJECT_HEIGHT;
const imageY = magnification * OBJECT_HEIGHT;
const objectPoint = new THREE.Vector3(
-doDistance,
OBJECT_HEIGHT,
0
);
const imagePoint = new THREE.Vector3(di, imageY, 0);
root.add(makeGrid());
root.add(makeAxis());
root.add(makeLens());
root.add(makeFocusMarker(-FOCAL_LENGTH));
root.add(makeFocusMarker(FOCAL_LENGTH));
const objectArrow = makeSolidArrow(
-doDistance,
OBJECT_HEIGHT,
COLORS.object,
0.045
);
root.add(objectArrow);
if (scenario.kind === "real") {
root.add(makeScreen(di));
const imageArrow = makeSolidArrow(
di,
imageHeight,
COLORS.realImage,
0.065
);
// The solid image arrow points down, showing real-image inversion.
imageArrow.rotation.z = Math.PI;
root.add(imageArrow);
} else {
root.add(makeGhostArrow(di, imageHeight, 0.045));
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.065, 16, 12),
new THREE.MeshBasicMaterial({
color: COLORS.virtualImage,
depthTest: false
})
);
marker.position.set(di, imageY, 0.085);
marker.renderOrder = 10;
root.add(marker);
}
// Three physical paraxial rays:
// 1. Through the optical center.
// 2. Initially parallel to the axis.
// 3. An arbitrary off-axis ray.
const rayDefinitions = [
{ lensY: 0 },
{ lensY: OBJECT_HEIGHT },
{ lensY: -0.34 * OBJECT_HEIGHT }
];
const pulseGeometry = new THREE.SphereGeometry(0.052, 12, 10);
const pulseMaterial = new THREE.MeshBasicMaterial({
color: 0xfff3bd,
depthTest: false
});
rayDefinitions.forEach((definition, index) => {
const lensPoint = new THREE.Vector3(
0,
definition.lensY,
0
);
const incomingSlope =
(definition.lensY - OBJECT_HEIGHT) / doDistance;
// Thin-lens refraction in the paraxial approximation.
const outgoingSlope =
incomingSlope - definition.lensY / FOCAL_LENGTH;
let outgoingEnd;
if (scenario.kind === "real") {
// All refracted rays physically meet at the screen.
outgoingEnd = imagePoint.clone();
} else {
// Actual light diverges after the lens.
outgoingEnd = new THREE.Vector3(
RIGHT_RAY_END,
definition.lensY +
outgoingSlope * RIGHT_RAY_END,
0
);
}
addSolidSegment(
rayGroup,
objectPoint,
lensPoint,
COLORS.ray,
0.017
);
addSolidSegment(
rayGroup,
lensPoint,
outgoingEnd,
COLORS.rayBright,
0.017
);
const incidentArrowPosition = objectPoint
.clone()
.lerp(lensPoint, 0.57);
addArrowhead(
rayGroup,
incidentArrowPosition,
lensPoint.clone().sub(objectPoint),
COLORS.ray
);
const outgoingArrowPosition = lensPoint
.clone()
.lerp(outgoingEnd, 0.52);
addArrowhead(
rayGroup,
outgoingArrowPosition,
outgoingEnd.clone().sub(lensPoint),
COLORS.rayBright
);
if (scenario.kind === "virtual") {
// This is not light: it is the backward extension of the
// outgoing ray and therefore cannot be observed physically.
const extension = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
lensPoint.clone().setZ(0.026),
imagePoint.clone().setZ(0.026)
]),
new THREE.LineDashedMaterial({
color: COLORS.extension,
dashSize: 0.12,
gapSize: 0.085,
transparent: true,
opacity: 0.92
})
);
extension.computeLineDistances();
extension.renderOrder = 6;
extensionGroup.add(extension);
}
const pulse = new THREE.Mesh(
pulseGeometry,
pulseMaterial
);
pulse.position.copy(objectPoint);
pulse.renderOrder = 12;
rayGroup.add(pulse);
scenario.paths.push([
objectPoint.clone(),
lensPoint.clone(),
outgoingEnd.clone()
]);
scenario.pulses.push({
mesh: pulse,
phase: index * 0.17
});
});
// Scene labels.
const objectLabel = makeTextSprite("OBJECT", "#ffc27a");
objectLabel.position.set(
-doDistance,
OBJECT_HEIGHT + 0.43,
0.15
);
labelGroup.add(objectLabel);
const lensLabel = makeTextSprite("CONVERGING LENS", "#8fe5ff");
lensLabel.position.set(0, 2.15, 0.15);
labelGroup.add(lensLabel);
const leftFocus = makeTextSprite("F", "#dcecff");
leftFocus.position.set(-FOCAL_LENGTH, -0.42, 0.12);
leftFocus.scale.multiplyScalar(0.72);
labelGroup.add(leftFocus);
const rightFocus = makeTextSprite("F′", "#dcecff");
rightFocus.position.set(FOCAL_LENGTH, -0.42, 0.12);
rightFocus.scale.multiplyScalar(0.72);
labelGroup.add(rightFocus);
if (scenario.kind === "real") {
const screenLabel = makeTextSprite(
"SCREEN · REAL IMAGE",
"#72f0c5"
);
screenLabel.position.set(di, 2.02, 0.16);
labelGroup.add(screenLabel);
} else {
const imageLabel = makeTextSprite(
"VIRTUAL IMAGE",
"#b4a7ff"
);
imageLabel.position.set(di, imageHeight + 0.43, 0.16);
labelGroup.add(imageLabel);
}
// Camera bounds include visible labels and outgoing ray endpoints.
let minX = Math.min(-doDistance, di) - 0.45;
let maxX = Math.max(di, RIGHT_RAY_END) + 0.45;
let minY = Math.min(-0.45, imageY - 0.3);
let maxY = Math.max(OBJECT_HEIGHT + 0.62, imageY + 0.62, 2.45);
scenario.paths.forEach((path) => {
path.forEach((point) => {
minX = Math.min(minX, point.x - 0.12);
maxX = Math.max(maxX, point.x + 0.12);
minY = Math.min(minY, point.y - 0.12);
maxY = Math.max(maxY, point.y + 0.12);
});
});
scenario.bounds = {
minX,
maxX,
minY,
maxY,
centerX: (minX + maxX) / 2,
centerY: (minY + maxY) / 2
};
applyVisibility(scenario);
updateReadout(scenario);
}
// ------------------------------------------------------------
// Animation
// ------------------------------------------------------------
function pointOnPolyline(points, fraction) {
const firstLength = points[0].distanceTo(points[1]);
const secondLength = points[1].distanceTo(points[2]);
const totalLength = firstLength + secondLength;
let distance = ((fraction % 1) + 1) % 1 * totalLength;
if (distance <= firstLength && firstLength > 0) {
return points[0]
.clone()
.lerp(points[1], distance / firstLength);
}
if (secondLength > 0) {
return points[1]
.clone()
.lerp(
points[2],
(distance - firstLength) / secondLength
);
}
return points[2].clone();
}
let animationTime = 0;
function updatePulses(deltaTime) {
if (showState.motion) {
animationTime += deltaTime;
}
realScenario.paths.forEach((path, index) => {
const pulse = realScenario.pulses[index];
const fraction =
(animationTime * 0.18 + pulse.phase) % 1;
pulse.mesh.position.copy(pointOnPolyline(path, fraction));
});
virtualScenario.paths.forEach((path, index) => {
const pulse = virtualScenario.pulses[index];
const fraction =
(animationTime * 0.18 + pulse.phase) % 1;
pulse.mesh.position.copy(pointOnPolyline(path, fraction));
});
}
// ------------------------------------------------------------
// Direct camera controls
// ------------------------------------------------------------
function resetCamera() {
cameraState.yaw = 0;
cameraState.pitch = 0.10;
cameraState.zoom = 1;
}
function updateCamera(scenario, aspect) {
const bounds = scenario.bounds;
const halfWidth = (bounds.maxX - bounds.minX) / 2;
const halfHeight = (bounds.maxY - bounds.minY) / 2;
const requiredHalfHeight = Math.max(
halfHeight * 1.22,
(halfWidth * 1.20) / aspect
);
const visibleHalfHeight =
requiredHalfHeight / cameraState.zoom;
scenario.camera.left = -visibleHalfHeight * aspect;
scenario.camera.right = visibleHalfHeight * aspect;
scenario.camera.top = visibleHalfHeight;
scenario.camera.bottom = -visibleHalfHeight;
const target = new THREE.Vector3(
bounds.centerX,
bounds.centerY,
0
);
const radius = 12;
const cosPitch = Math.cos(cameraState.pitch);
const offset = new THREE.Vector3(
Math.sin(cameraState.yaw) * cosPitch,
Math.sin(cameraState.pitch),
Math.cos(cameraState.yaw) * cosPitch
).multiplyScalar(radius);
scenario.camera.position.copy(target).add(offset);
scenario.camera.lookAt(target);
scenario.camera.updateProjectionMatrix();
}
canvas.addEventListener("pointerdown", (event) => {
cameraState.dragging = true;
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!cameraState.dragging) {
return;
}
const deltaX = event.clientX - cameraState.lastX;
const deltaY = event.clientY - cameraState.lastY;
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
cameraState.yaw = THREE.MathUtils.clamp(
cameraState.yaw - deltaX * 0.0045,
-0.58,
0.58
);
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + deltaY * 0.0035,
-0.32,
0.45
);
});
function endDrag(event) {
cameraState.dragging = false;
if (event.pointerId !== undefined) {
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.65,
1.8
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
document.getElementById("resetButton").addEventListener(
"click",
resetCamera
);
// ------------------------------------------------------------
// UI controls
// ------------------------------------------------------------
function applyVisibility(scenario) {
if (scenario.rayGroup) {
scenario.rayGroup.visible = showState.rays;
}
if (scenario.extensionGroup) {
scenario.extensionGroup.visible = showState.extensions;
}
if (scenario.labelGroup) {
scenario.labelGroup.visible = showState.labels;
}
}
function applyAllVisibility() {
applyVisibility(realScenario);
applyVisibility(virtualScenario);
}
function updateReadout(scenario) {
const di =
(FOCAL_LENGTH * scenario.do) /
(scenario.do - FOCAL_LENGTH);
const magnification = -di / scenario.do;
if (scenario.kind === "real") {
document.getElementById("realValue").value =
scenario.do.toFixed(2);
document.getElementById("realMetric").innerHTML =
`d<sub>o</sub> = ${scenario.do.toFixed(2)}<br>` +
`d<sub>i</sub> = ${di.toFixed(2)} · ` +
`|m| = ${Math.abs(magnification).toFixed(2)}<br>` +
`<span style="color:#72f0c5">light reaches the screen</span>`;
} else {
document.getElementById("virtualValue").value =
scenario.do.toFixed(2);
document.getElementById("virtualMetric").innerHTML =
`d<sub>o</sub> = ${scenario.do.toFixed(2)}<br>` +
`d<sub>i</sub> = ${di.toFixed(2)} · ` +
`|m| = ${Math.abs(magnification).toFixed(2)}<br>` +
`<span style="color:#b4a7ff">only extensions reach the image</span>`;
}
}
document
.getElementById("realDistance")
.addEventListener("input", (event) => {
realScenario.do = Number(event.target.value);
buildScenario(realScenario);
});
document
.getElementById("virtualDistance")
.addEventListener("input", (event) => {
virtualScenario.do = Number(event.target.value);
buildScenario(virtualScenario);
});
document
.getElementById("raysToggle")
.addEventListener("change", (event) => {
showState.rays = event.target.checked;
applyAllVisibility();
});
document
.getElementById("extensionsToggle")
.addEventListener("change", (event) => {
showState.extensions = event.target.checked;
applyAllVisibility();
});
document
.getElementById("labelsToggle")
.addEventListener("change", (event) => {
showState.labels = event.target.checked;
applyAllVisibility();
});
const motionButton = document.getElementById("motionButton");
function updateMotionButton() {
motionButton.textContent = showState.motion
? "Pause light animation"
: "Resume light animation";
}
motionButton.addEventListener("click", () => {
showState.motion = !showState.motion;
updateMotionButton();
});
updateMotionButton();
// ------------------------------------------------------------
// Responsive rendering with two Three.js viewports
// ------------------------------------------------------------
let viewportWidth = 1;
let viewportHeight = 1;
function resizeRenderer() {
viewportWidth = Math.max(1, Math.floor(stage.clientWidth));
viewportHeight = Math.max(1, Math.floor(stage.clientHeight));
renderer.setPixelRatio(
Math.min(window.devicePixelRatio || 1, 2)
);
renderer.setSize(
viewportWidth,
viewportHeight,
false
);
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
resizeRenderer();
function renderView(scenario, x, y, width, height) {
const aspect = width / height;
updateCamera(scenario, aspect);
renderer.setViewport(x, y, width, height);
renderer.setScissor(x, y, width, height);
renderer.setClearColor(scenario.scene.background, 1);
renderer.clear(true, true, true);
renderer.render(scenario.scene, scenario.camera);
}
function renderScenes() {
renderer.setScissorTest(false);
renderer.setViewport(0, 0, viewportWidth, viewportHeight);
renderer.setScissor(0, 0, viewportWidth, viewportHeight);
renderer.setClearColor(0x07101d, 1);
renderer.clear(true, true, true);
renderer.setScissorTest(true);
const stacked = window.innerWidth <= 760;
if (stacked) {
const halfHeight = Math.floor(viewportHeight / 2);
renderView(
realScenario,
0,
viewportHeight - halfHeight,
viewportWidth,
halfHeight
);
renderView(
virtualScenario,
0,
0,
viewportWidth,
viewportHeight - halfHeight
);
} else {
const halfWidth = Math.floor(viewportWidth / 2);
renderView(
realScenario,
0,
0,
halfWidth,
viewportHeight
);
renderView(
virtualScenario,
halfWidth,
0,
viewportWidth - halfWidth,
viewportHeight
);
}
renderer.setScissorTest(false);
}
let previousTime = performance.now();
renderer.setAnimationLoop((time) => {
const deltaTime = Math.min(
0.05,
(time - previousTime) / 1000
);
previousTime = time;
updatePulses(deltaTime);
renderScenes();
});
</script>
</body>
</html>
```