Prompt specification
Build or customize the Three.js 3D scene "Thin-lens object image bench" 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: Thin-lens object image bench
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/thin-lens-object-image-bench-x1557
Scene Description Prompt:
Trace paraxial rays from an arrow through a converging thin lens onto a movable screen. Low-poly optical bench; Three.js from cdnjs, standalone HTML.
Working Three.js Starter (thin-lens-object-image-bench-x1557):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Paraxial Ray Tracing Optical Bench</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(9, 20, 31, 0.88);
--border: rgba(126, 224, 255, 0.22);
--cyan: #78e7ff;
--gold: #ffd166;
--green: #72f0a6;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #071018;
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app,
canvas {
width: 100%;
height: 100%;
display: block;
}
#ui {
position: fixed;
top: 18px;
left: 18px;
width: min(340px, calc(100vw - 36px));
padding: 18px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
color: #e9f8ff;
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
user-select: none;
z-index: 10;
}
h1 {
margin: 0 0 4px;
font-size: 19px;
letter-spacing: 0.02em;
}
.subtitle {
margin: 0 0 16px;
color: #8eb0c3;
font-size: 12px;
line-height: 1.45;
}
.control {
margin-top: 15px;
}
.control label,
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
font-size: 12px;
}
.control label {
margin-bottom: 7px;
color: #c9e9f7;
}
output {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-weight: 700;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.equation {
margin: 16px 0;
padding: 10px 12px;
border: 1px solid rgba(120, 231, 255, 0.12);
border-radius: 10px;
background: rgba(0, 0, 0, 0.18);
color: #b9d8e6;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
line-height: 1.6;
text-align: center;
}
.readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 13px 0;
}
.readout {
padding: 9px 10px;
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
}
.readout span {
display: block;
color: #7899aa;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.readout strong {
display: block;
margin-top: 3px;
color: #e8f9ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 13px;
}
.status {
display: flex;
align-items: center;
gap: 9px;
margin: 12px 0;
padding: 10px 12px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.03em;
}
#statusDot {
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px currentColor;
color: var(--green);
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 36px;
border: 1px solid rgba(120, 231, 255, 0.28);
border-radius: 9px;
background: rgba(120, 231, 255, 0.08);
color: #dff8ff;
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
button:hover {
background: rgba(120, 231, 255, 0.16);
}
button.primary {
border-color: rgba(114, 240, 166, 0.36);
background: rgba(114, 240, 166, 0.1);
color: #baffd5;
}
.check {
margin-top: 12px;
color: #a9c7d5;
font-size: 12px;
cursor: pointer;
}
.check input {
accent-color: var(--cyan);
margin-right: 7px;
}
#help {
position: fixed;
left: 50%;
bottom: 16px;
transform: translateX(-50%);
padding: 8px 14px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 999px;
background: rgba(5, 13, 20, 0.72);
color: #a9c2cf;
font-size: 11px;
pointer-events: none;
white-space: nowrap;
z-index: 5;
}
@media (max-width: 650px) {
#ui {
top: 10px;
left: 10px;
width: min(320px, calc(100vw - 20px));
padding: 14px;
}
#help {
display: none;
}
}
</style>
</head>
<body>
<div id="app"></div>
<section id="ui">
<h1>Paraxial Ray Bench</h1>
<p class="subtitle">
A luminous arrow, a converging thin lens, and a movable observation screen.
</p>
<div class="control">
<label>
<span>Lens focal length</span>
<output id="focalValue">120 mm</output>
</label>
<input id="focalRange" type="range" min="90" max="160" step="1" value="120">
</div>
<div class="control">
<label>
<span>Screen distance</span>
<output id="screenValue">264 mm</output>
</label>
<input id="screenRange" type="range" min="120" max="330" step="1" value="264">
</div>
<div class="equation">
1/f = 1/s + 1/s′<br>
s = 220 mm · s′ = fs/(s−f)
</div>
<div class="readouts">
<div class="readout">
<span>Image plane</span>
<strong id="imageValue">264 mm</strong>
</div>
<div class="readout">
<span>Defocus</span>
<strong id="defocusValue">0 mm</strong>
</div>
</div>
<div class="status">
<span id="statusDot"></span>
<span id="statusText">IMAGE PLANE LOCKED</span>
</div>
<div class="buttons">
<button id="focusButton" class="primary">Move screen to focus</button>
<button id="resetButton">Reset view</button>
</div>
<label class="check">
<input id="raysToggle" type="checkbox" checked>
Show traced ray bundles
</label>
</section>
<div id="help">
Drag background to orbit · Wheel to zoom · Drag the yellow screen handle to move it
</div>
<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 OBJECT_DISTANCE = 220;
const OBJECT_X = -OBJECT_DISTANCE;
const LENS_X = 0;
const AXIS_Y = 95;
const SCREEN_WIDTH = 150;
const SCREEN_HEIGHT = 190;
const SCREEN_CENTER_Y = 100;
let focalLength = 120;
let screenX = 264;
const app = document.getElementById("app");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071018);
scene.fog = new THREE.Fog(0x071018, 700, 1450);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.5,
2500
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xa9ddff, 0x15202a, 1.65));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(-180, 420, 260);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -450;
keyLight.shadow.camera.right = 450;
keyLight.shadow.camera.top = 320;
keyLight.shadow.camera.bottom = -220;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 1000;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4cc9ff, 1.4);
rimLight.position.set(300, 150, -300);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Materials and geometry helpers
// -------------------------------------------------------------------------
const benchMaterial = new THREE.MeshStandardMaterial({
color: 0x26333c,
roughness: 0.78,
metalness: 0.25,
flatShading: true
});
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x7a8b96,
roughness: 0.34,
metalness: 0.82,
flatShading: true
});
const darkMetal = new THREE.MeshStandardMaterial({
color: 0x17212a,
roughness: 0.5,
metalness: 0.7,
flatShading: true
});
const yellowMetal = new THREE.MeshStandardMaterial({
color: 0xffc857,
roughness: 0.42,
metalness: 0.35,
flatShading: true
});
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(
parent,
radius,
height,
position,
material,
radialSegments = 16
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, height, radialSegments),
material
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Labels
// -------------------------------------------------------------------------
function createLabel(initialText, color = "#bff7ff") {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 140;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(112, 24.5, 1);
sprite.renderOrder = 20;
sprite.userData.setText = (text) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(4, 13, 20, 0.82)";
context.fillRect(12, 18, 616, 102);
context.strokeStyle = color;
context.globalAlpha = 0.55;
context.lineWidth = 3;
context.strokeRect(12, 18, 616, 102);
context.globalAlpha = 1;
context.fillStyle = color;
context.font = "700 35px ui-monospace, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 320, 70);
texture.needsUpdate = true;
};
sprite.userData.setText(initialText);
return sprite;
}
// -------------------------------------------------------------------------
// Bench
// -------------------------------------------------------------------------
const bench = new THREE.Group();
scene.add(bench);
addBox(
bench,
new THREE.Vector3(700, 12, 190),
new THREE.Vector3(20, -6, 0),
benchMaterial
);
addBox(
bench,
new THREE.Vector3(700, 5, 8),
new THREE.Vector3(20, 3, -76),
railMaterial
);
addBox(
bench,
new THREE.Vector3(700, 5, 8),
new THREE.Vector3(20, 3, 76),
railMaterial
);
const tickMaterial = new THREE.MeshStandardMaterial({
color: 0xa9b8c1,
roughness: 0.6,
metalness: 0.45
});
for (let x = -300; x <= 340; x += 20) {
const major = x % 100 === 0;
addBox(
bench,
new THREE.Vector3(1.4, 1.5, major ? 13 : 8),
new THREE.Vector3(x, 1, -67),
tickMaterial,
false
);
}
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(2200, 2200),
new THREE.MeshStandardMaterial({
color: 0x0b151d,
roughness: 0.95,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -13;
floor.receiveShadow = true;
scene.add(floor);
// Optical axis.
const axisGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-280, AXIS_Y, 0),
new THREE.Vector3(345, AXIS_Y, 0)
]);
const axisLine = new THREE.Line(
axisGeometry,
new THREE.LineDashedMaterial({
color: 0x7ab8ca,
dashSize: 8,
gapSize: 7,
transparent: true,
opacity: 0.38
})
);
axisLine.computeLineDistances();
scene.add(axisLine);
// -------------------------------------------------------------------------
// Arrow object
// -------------------------------------------------------------------------
// Arrow outline in transverse coordinates. The arrow points upward.
const arrowOutline = [
[-8, -55],
[8, -55],
[8, 8],
[34, 8],
[0, 62],
[-34, 8],
[-8, 8]
];
const arrowShape = new THREE.Shape();
arrowShape.moveTo(arrowOutline[0][0], arrowOutline[0][1]);
for (let i = 1; i < arrowOutline.length; i++) {
arrowShape.lineTo(arrowOutline[i][0], arrowOutline[i][1]);
}
arrowShape.closePath();
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0xffca62,
side: THREE.DoubleSide
});
const arrowMesh = new THREE.Mesh(
new THREE.ShapeGeometry(arrowShape),
arrowMaterial
);
arrowMesh.rotation.y = Math.PI / 2;
arrowMesh.position.set(OBJECT_X, AXIS_Y, 0);
scene.add(arrowMesh);
const arrowEdgePoints = [...arrowOutline, arrowOutline[0]].map(
([z, y]) => new THREE.Vector3(OBJECT_X + 0.5, AXIS_Y + y, -z)
);
const arrowEdge = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(arrowEdgePoints),
new THREE.LineBasicMaterial({ color: 0xfff0b3 })
);
scene.add(arrowEdge);
// Object frame and support.
addBox(
scene,
new THREE.Vector3(5, 136, 5),
new THREE.Vector3(OBJECT_X - 2, AXIS_Y - 3, -44),
darkMetal
);
addBox(
scene,
new THREE.Vector3(5, 136, 5),
new THREE.Vector3(OBJECT_X - 2, AXIS_Y - 3, 44),
darkMetal
);
addBox(
scene,
new THREE.Vector3(5, 5, 93),
new THREE.Vector3(OBJECT_X - 2, AXIS_Y - 70, 0),
darkMetal
);
addBox(
scene,
new THREE.Vector3(5, 5, 93),
new THREE.Vector3(OBJECT_X - 2, AXIS_Y + 70, 0),
darkMetal
);
addCylinder(
scene,
5,
40,
new THREE.Vector3(OBJECT_X, 20, 48),
darkMetal
);
addBox(
scene,
new THREE.Vector3(34, 8, 28),
new THREE.Vector3(OBJECT_X, 4, 48),
darkMetal
);
const objectLabel = createLabel("ARROW OBJECT", "#ffd166");
objectLabel.position.set(OBJECT_X, 180, 0);
scene.add(objectLabel);
// -------------------------------------------------------------------------
// Thin converging lens
// -------------------------------------------------------------------------
const lens = new THREE.Mesh(
new THREE.CylinderGeometry(58, 58, 3.2, 32, 1, false),
new THREE.MeshPhysicalMaterial({
color: 0x8ee8ff,
transparent: true,
opacity: 0.34,
roughness: 0.08,
metalness: 0,
transmission: 0.3,
thickness: 3,
side: THREE.DoubleSide,
depthWrite: false
})
);
lens.rotation.z = Math.PI / 2;
lens.position.set(LENS_X, AXIS_Y, 0);
scene.add(lens);
const lensRing = new THREE.Mesh(
new THREE.TorusGeometry(58, 3.2, 6, 32),
railMaterial
);
lensRing.rotation.y = Math.PI / 2;
lensRing.position.set(LENS_X, AXIS_Y, 0);
scene.add(lensRing);
addCylinder(scene, 6, 37, new THREE.Vector3(LENS_X, 18.5, 0), darkMetal);
addBox(
scene,
new THREE.Vector3(42, 8, 35),
new THREE.Vector3(LENS_X, 4, 0),
darkMetal
);
const lensLabel = createLabel("THIN LENS f = 120 mm", "#9cecff");
lensLabel.position.set(LENS_X, 174, 0);
scene.add(lensLabel);
// -------------------------------------------------------------------------
// Movable screen
// -------------------------------------------------------------------------
const screenGroup = new THREE.Group();
scene.add(screenGroup);
const screenCanvas = document.createElement("canvas");
screenCanvas.width = 256;
screenCanvas.height = 320;
const screenContext = screenCanvas.getContext("2d");
const screenTexture = new THREE.CanvasTexture(screenCanvas);
screenTexture.colorSpace = THREE.SRGBColorSpace;
screenTexture.minFilter = THREE.LinearFilter;
screenTexture.magFilter = THREE.LinearFilter;
const screenBack = addBox(
screenGroup,
new THREE.Vector3(5, 198, 158),
new THREE.Vector3(-3, SCREEN_CENTER_Y, 0),
new THREE.MeshStandardMaterial({
color: 0x101b24,
roughness: 0.82,
metalness: 0.25
})
);
const screenPanel = new THREE.Mesh(
new THREE.PlaneGeometry(SCREEN_WIDTH, SCREEN_HEIGHT),
new THREE.MeshBasicMaterial({
map: screenTexture,
side: THREE.DoubleSide
})
);
screenPanel.rotation.y = Math.PI / 2;
screenPanel.position.set(0.1, SCREEN_CENTER_Y, 0);
screenGroup.add(screenPanel);
addBox(
screenGroup,
new THREE.Vector3(7, 200, 6),
new THREE.Vector3(0, SCREEN_CENTER_Y, -79),
railMaterial
);
addBox(
screenGroup,
new THREE.Vector3(7, 200, 6),
new THREE.Vector3(0, SCREEN_CENTER_Y, 79),
railMaterial
);
addBox(
screenGroup,
new THREE.Vector3(7, 6, 164),
new THREE.Vector3(0, 4, 0),
railMaterial
);
addBox(
screenGroup,
new THREE.Vector3(7, 6, 164),
new THREE.Vector3(0, 196, 0),
railMaterial
);
const screenHandle = new THREE.Mesh(
new THREE.SphereGeometry(7, 12, 8),
yellowMetal
);
screenHandle.position.set(8, AXIS_Y, 88);
screenHandle.castShadow = true;
screenGroup.add(screenHandle);
const screenLabel = createLabel("SCREEN 264 mm", "#d9f8ff");
screenLabel.position.set(0, 218, 0);
screenGroup.add(screenLabel);
// -------------------------------------------------------------------------
// Ideal image-plane marker
// -------------------------------------------------------------------------
const imagePlane = new THREE.Group();
scene.add(imagePlane);
const imagePlaneGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 5, -75),
new THREE.Vector3(0, 195, -75),
new THREE.Vector3(0, 195, 75),
new THREE.Vector3(0, 5, 75)
]);
const imagePlaneOutline = new THREE.LineLoop(
imagePlaneGeometry,
new THREE.LineDashedMaterial({
color: 0x72f0a6,
dashSize: 7,
gapSize: 6,
transparent: true,
opacity: 0.68
})
);
imagePlaneOutline.computeLineDistances();
imagePlane.add(imagePlaneOutline);
const imagePlaneLabel = createLabel("IMAGE PLANE 264 mm", "#72f0a6");
imagePlaneLabel.position.set(0, 215, 0);
imagePlane.add(imagePlaneLabel);
// -------------------------------------------------------------------------
// Ray source samples
// -------------------------------------------------------------------------
function samplePolyline(points, spacing = 8) {
const samples = [];
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const length = Math.hypot(dx, dy);
const divisions = Math.max(1, Math.ceil(length / spacing));
for (let j = 0; j < divisions; j++) {
const t = j / divisions;
samples.push({
relY: THREE.MathUtils.lerp(a[1], b[1], t),
relZ: THREE.MathUtils.lerp(a[0], b[0], t)
});
}
}
return samples;
}
const sourceSamples = samplePolyline(arrowOutline, 8);
const mainApertures = [
{ h: -40, z: -12 },
{ h: -20, z: 0 },
{ h: 0, z: 12 },
{ h: 20, z: 0 },
{ h: 40, z: -12 }
];
const tipApertures = [
{ h: -48, z: 0 },
{ h: -32, z: 0 },
{ h: -16, z: 0 },
{ h: 0, z: 0 },
{ h: 16, z: 0 },
{ h: 32, z: 0 },
{ h: 48, z: 0 }
];
// -------------------------------------------------------------------------
// Dynamic ray geometry
// -------------------------------------------------------------------------
const mainRayPositions = new Float32Array(
sourceSamples.length * mainApertures.length * 12
);
const mainRayColors = new Float32Array(mainRayPositions.length);
const mainRayGeometry = new THREE.BufferGeometry();
const mainPositionAttribute = new THREE.BufferAttribute(
mainRayPositions,
3
);
mainPositionAttribute.setUsage(THREE.DynamicDrawUsage);
mainRayGeometry.setAttribute("position", mainPositionAttribute);
mainRayGeometry.setAttribute(
"color",
new THREE.BufferAttribute(mainRayColors, 3)
);
const mainRayLines = new THREE.LineSegments(
mainRayGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.38,
blending: THREE.AdditiveBlending,
depthWrite: false
})
);
mainRayLines.frustumCulled = false;
scene.add(mainRayLines);
const tipRayPositions = new Float32Array(tipApertures.length * 12);
const tipRayColors = new Float32Array(tipRayPositions.length);
const tipRayGeometry = new THREE.BufferGeometry();
const tipPositionAttribute = new THREE.BufferAttribute(tipRayPositions, 3);
tipPositionAttribute.setUsage(THREE.DynamicDrawUsage);
tipRayGeometry.setAttribute("position", tipPositionAttribute);
tipRayGeometry.setAttribute(
"color",
new THREE.BufferAttribute(tipRayColors, 3)
);
const tipRayLines = new THREE.LineSegments(
tipRayGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.92,
blending: THREE.AdditiveBlending,
depthWrite: false
})
);
tipRayLines.frustumCulled = false;
scene.add(tipRayLines);
const maximumPointCount =
sourceSamples.length * mainApertures.length + tipApertures.length;
const pointPositions = new Float32Array(maximumPointCount * 3);
const pointColors = new Float32Array(maximumPointCount * 3);
const pointGeometry = new THREE.BufferGeometry();
const pointPositionAttribute = new THREE.BufferAttribute(pointPositions, 3);
pointPositionAttribute.setUsage(THREE.DynamicDrawUsage);
pointGeometry.setAttribute("position", pointPositionAttribute);
pointGeometry.setAttribute(
"color",
new THREE.BufferAttribute(pointColors, 3)
);
const rayPoints = new THREE.Points(
pointGeometry,
new THREE.PointsMaterial({
size: 3.2,
sizeAttenuation: true,
vertexColors: true,
transparent: true,
opacity: 0.95,
blending: THREE.AdditiveBlending,
depthWrite: false
})
);
rayPoints.frustumCulled = false;
scene.add(rayPoints);
// -------------------------------------------------------------------------
// Paraxial thin-lens trace
//
// Object plane: x = -s
// Lens plane: x = 0
// Screen plane: x = d
//
// Incident slope: u = (h_l - h_o)/s
// Refracted slope: u' = u - h_l/f
// Screen height: h_s = h_l + d*u'
//
// The same equations are used in the two transverse directions.
// -------------------------------------------------------------------------
function traceRay(source, aperture, distance) {
const incidentY =
(aperture.h - source.relY) / OBJECT_DISTANCE;
const refractedY = incidentY - aperture.h / focalLength;
const incidentZ =
(aperture.z - source.relZ) / OBJECT_DISTANCE;
const refractedZ = incidentZ - aperture.z / focalLength;
return {
object: new THREE.Vector3(
OBJECT_X,
AXIS_Y + source.relY,
source.relZ
),
lens: new THREE.Vector3(
LENS_X,
AXIS_Y + aperture.h,
aperture.z
),
screen: new THREE.Vector3(
distance,
AXIS_Y + aperture.h + distance * refractedY,
aperture.z + distance * refractedZ
)
};
}
function appendSegment(array, a, b) {
array.push(
a.x, a.y, a.z,
b.x, b.y, b.z
);
}
function appendColor(array, color) {
array.push(
color.r, color.g, color.b,
color.r, color.g, color.b
);
}
function updateRays() {
const mainPositions = [];
const mainColors = [];
const tipPositions = [];
const tipColors = [];
const points = [];
const pointColors = [];
// Main outline bundles.
for (const source of sourceSamples) {
const hue = THREE.MathUtils.clamp(
0.52 + source.relY / 620,
0.43,
0.59
);
const rayColor = new THREE.Color().setHSL(hue, 0.9, 0.65);
for (const aperture of mainApertures) {
const ray = traceRay(source, aperture, screenX);
appendSegment(mainPositions, ray.object, ray.lens);
appendSegment(mainPositions, ray.lens, ray.screen);
appendColor(mainColors, rayColor);
points.push(ray.screen);
pointColors.push(rayColor);
}
}
// Highlight the arrow-tip bundle in gold.
const tipSource = { relY: 62, relZ: 0 };
const tipColor = new THREE.Color(0xffd166);
for (const aperture of tipApertures) {
const ray = traceRay(tipSource, aperture, screenX);
appendSegment(tipPositions, ray.object, ray.lens);
appendSegment(tipPositions, ray.lens, ray.screen);
appendColor(tipColors, tipColor);
points.push(ray.screen);
pointColors.push(tipColor);
}
mainPositionAttribute.array.set(mainPositions);
mainPositionAttribute.needsUpdate = true;
mainRayGeometry.setDrawRange(0, mainPositions.length / 3);
mainRayGeometry.attributes.color.array.set(mainColors);
mainRayGeometry.attributes.color.needsUpdate = true;
tipPositionAttribute.array.set(tipPositions);
tipPositionAttribute.needsUpdate = true;
tipRayGeometry.setDrawRange(0, tipPositions.length / 3);
tipRayGeometry.attributes.color.array.set(tipColors);
tipRayGeometry.attributes.color.needsUpdate = true;
pointPositionAttribute.array.set(
points.flatMap((point) => [point.x, point.y, point.z])
);
pointPositionAttribute.needsUpdate = true;
pointGeometry.setDrawRange(0, points.length);
pointGeometry.attributes.color.array.set(
pointColors.flatMap((color) => [color.r, color.g, color.b])
);
pointGeometry.attributes.color.needsUpdate = true;
drawScreenTexture(points, pointColors);
}
// -------------------------------------------------------------------------
// Screen texture: physical ray-intersection density
// -------------------------------------------------------------------------
function drawScreenTexture(points, colors) {
const context = screenContext;
const width = screenCanvas.width;
const height = screenCanvas.height;
context.clearRect(0, 0, width, height);
const background = context.createLinearGradient(0, 0, 0, height);
background.addColorStop(0, "#0b1a25");
background.addColorStop(1, "#061018");
context.fillStyle = background;
context.fillRect(0, 0, width, height);
// Subtle screen grid.
context.strokeStyle = "rgba(120, 200, 225, 0.07)";
context.lineWidth = 1;
for (let x = 16; x < width; x += 16) {
context.beginPath();
context.moveTo(x, 0);
context.lineTo(x, height);
context.stroke();
}
for (let y = 16; y < height; y += 16) {
context.beginPath();
context.moveTo(0, y);
context.lineTo(width, y);
context.stroke();
}
context.globalCompositeOperation = "lighter";
for (let i = 0; i < points.length; i++) {
const point = points[i];
const color = colors[i];
// Account for the screen's local UV orientation.
const x = ((75 - point.z) / SCREEN_WIDTH) * width;
const y = ((190 - point.y) / SCREEN_HEIGHT) * height;
if (x < -8 || x > width + 8 || y < -8 || y > height + 8) {
continue;
}
const red = Math.round(color.r * 255);
const green = Math.round(color.g * 255);
const blue = Math.round(color.b * 255);
context.fillStyle = `rgba(${red}, ${green}, ${blue}, 0.13)`;
context.beginPath();
context.arc(x, y, 4.1, 0, Math.PI * 2);
context.fill();
context.fillStyle = `rgba(${red}, ${green}, ${blue}, 0.92)`;
context.beginPath();
context.arc(x, y, 1.55, 0, Math.PI * 2);
context.fill();
}
context.globalCompositeOperation = "source-over";
screenTexture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// UI and optical updates
// -------------------------------------------------------------------------
const focalRange = document.getElementById("focalRange");
const screenRange = document.getElementById("screenRange");
const focalValue = document.getElementById("focalValue");
const screenValue = document.getElementById("screenValue");
const imageValue = document.getElementById("imageValue");
const defocusValue = document.getElementById("defocusValue");
const statusText = document.getElementById("statusText");
const statusDot = document.getElementById("statusDot");
function idealImageDistance() {
return (focalLength * OBJECT_DISTANCE) /
(OBJECT_DISTANCE - focalLength);
}
function updateOptics() {
focalLength = Number(focalRange.value);
screenX = THREE.MathUtils.clamp(screenX, 120, 330);
const imageDistance = idealImageDistance();
const defocus = screenX - imageDistance;
screenGroup.position.x = screenX;
imagePlane.position.x = imageDistance;
focalValue.textContent = `${focalLength.toFixed(0)} mm`;
screenValue.textContent = `${screenX.toFixed(0)} mm`;
imageValue.textContent = `${imageDistance.toFixed(1)} mm`;
defocusValue.textContent = `${Math.abs(defocus).toFixed(1)} mm`;
screenRange.value = String(Math.round(screenX));
lensLabel.userData.setText(
`THIN LENS f = ${focalLength.toFixed(0)} mm`
);
screenLabel.userData.setText(
`SCREEN ${screenX.toFixed(0)} mm`
);
imagePlaneLabel.userData.setText(
`IMAGE PLANE ${imageDistance.toFixed(0)} mm`
);
if (Math.abs(defocus) <= 1.5) {
statusText.textContent = "IMAGE PLANE LOCKED";
statusText.style.color = "#baffd5";
statusDot.style.background = "#72f0a6";
statusDot.style.color = "#72f0a6";
} else {
statusText.textContent =
`DEFOCUSED • ${Math.abs(defocus).toFixed(0)} mm ` +
(defocus < 0 ? "BEFORE FOCUS" : "AFTER FOCUS");
statusText.style.color = "#ffd9a0";
statusDot.style.background = "#ffbd59";
statusDot.style.color = "#ffbd59";
}
updateRays();
}
function setScreen(value) {
screenX = THREE.MathUtils.clamp(value, 120, 330);
updateOptics();
}
focalRange.addEventListener("input", updateOptics);
screenRange.addEventListener("input", (event) => {
setScreen(Number(event.target.value));
});
document.getElementById("focusButton").addEventListener("click", () => {
setScreen(idealImageDistance());
});
document.getElementById("raysToggle").addEventListener("change", (event) => {
mainRayLines.visible = event.target.checked;
tipRayLines.visible = event.target.checked;
rayPoints.visible = event.target.checked;
});
// -------------------------------------------------------------------------
// Custom camera controls
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(20, 70, 0);
let cameraRadius = 630;
let cameraTheta = 0.58;
let cameraPhi = 1.12;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraRadius = 630;
cameraTheta = 0.58;
cameraPhi = 1.12;
cameraTarget.set(20, 70, 0);
updateCamera();
}
document.getElementById("resetButton").addEventListener("click", resetCamera);
updateCamera();
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -AXIS_Y);
let pointerMode = null;
let previousPointerX = 0;
let previousPointerY = 0;
let screenDrag = null;
function setPointerFromEvent(event) {
pointer.x = (event.clientX / innerWidth) * 2 - 1;
pointer.y = -(event.clientY / innerHeight) * 2 + 1;
}
function projectedWorldX(x) {
const point = new THREE.Vector3(x, AXIS_Y, 0).project(camera);
return (point.x * 0.5 + 0.5) * innerWidth;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(
[screenPanel, screenHandle],
false
);
if (hits.length > 0) {
const projectedLeft = projectedWorldX(screenX - 10);
const projectedRight = projectedWorldX(screenX + 10);
const pixelsPerUnit =
(projectedRight - projectedLeft) / 20;
screenDrag = {
startClientX: event.clientX,
startScreenX: screenX,
unitsPerPixel:
Math.abs(pixelsPerUnit) > 0.02
? 1 / pixelsPerUnit
: 0.5
};
pointerMode = "screen";
} else {
pointerMode = "orbit";
previousPointerX = event.clientX;
previousPointerY = event.clientY;
}
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerMode === "screen" && screenDrag) {
const delta = event.clientX - screenDrag.startClientX;
setScreen(
screenDrag.startScreenX + delta * screenDrag.unitsPerPixel
);
event.preventDefault();
return;
}
if (pointerMode === "orbit") {
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
cameraTheta -= deltaX * 0.005;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + deltaY * 0.005,
0.35,
1.46
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
updateCamera();
event.preventDefault();
}
});
function endPointer(event) {
pointerMode = null;
screenDrag = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
260,
1150
);
updateCamera();
event.preventDefault();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
updateOptics();
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>
</body>
</html>
```