Prompt specification
Build or customize the Three.js 3D scene "Near and distant object focus rig" 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: Near and distant object focus rig
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/near-and-distant-object-focus-rig-x1034
Scene Description Prompt:
Adjust a schematic eye lens to focus near and distant objects on a retinal screen. Use a cutaway; Three.js from cdnjs, standalone HTML.
Working Three.js Starter (near-and-distant-object-focus-rig-x1034):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Interactive Accommodation of the Eye</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(8, 19, 31, 0.78);
--line: rgba(148, 205, 225, 0.18);
--text: #e9f7fb;
--muted: #91aab7;
--cyan: #67e8f9;
--green: #7cf2b5;
--amber: #ffd27a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 72% 28%, rgba(22, 81, 105, 0.35), transparent 34%),
radial-gradient(circle at 18% 72%, rgba(29, 66, 91, 0.28), transparent 38%),
#050c13;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.title-card {
position: fixed;
top: 22px;
left: 24px;
max-width: 430px;
pointer-events: none;
text-shadow: 0 2px 20px rgba(0, 0, 0, 0.75);
}
.eyebrow {
margin-bottom: 8px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 42px);
font-weight: 760;
line-height: 1.04;
letter-spacing: -0.035em;
}
.subtitle {
max-width: 390px;
margin: 12px 0 0;
color: #a9c0cc;
font-size: 14px;
line-height: 1.55;
}
.controls {
position: fixed;
bottom: 22px;
left: 22px;
width: min(355px, calc(100vw - 44px));
padding: 18px;
border: 1px solid var(--line);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.42);
backdrop-filter: blur(18px) saturate(130%);
-webkit-backdrop-filter: blur(18px) saturate(130%);
}
.control-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.control-header strong {
font-size: 13px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.focus-status {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 9px;
border: 1px solid rgba(124, 242, 181, 0.28);
border-radius: 999px;
background: rgba(124, 242, 181, 0.09);
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
white-space: nowrap;
}
.focus-status::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.focus-status.blurred {
border-color: rgba(255, 210, 122, 0.3);
background: rgba(255, 210, 122, 0.09);
color: var(--amber);
}
.control {
margin-top: 14px;
}
.control-label {
display: flex;
justify-content: space-between;
gap: 14px;
margin-bottom: 8px;
color: #bed2dc;
font-size: 12px;
}
.control-label output {
color: #f1fbff;
font-variant-numeric: tabular-nums;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 4px 0;
border-radius: 999px;
appearance: none;
background: linear-gradient(
90deg,
rgba(103, 232, 249, 0.75),
rgba(103, 232, 249, 0.12)
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #dffaff;
border-radius: 50%;
appearance: none;
background: #38c9e1;
box-shadow: 0 0 14px rgba(103, 232, 249, 0.65);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid #dffaff;
border-radius: 50%;
background: #38c9e1;
box-shadow: 0 0 14px rgba(103, 232, 249, 0.65);
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #718d9c;
font-size: 10px;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 17px;
}
button {
min-height: 38px;
border: 1px solid rgba(142, 205, 226, 0.2);
border-radius: 11px;
background: rgba(122, 191, 218, 0.08);
color: #dff8ff;
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease;
}
button:hover {
border-color: rgba(103, 232, 249, 0.52);
background: rgba(103, 232, 249, 0.16);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button.primary {
grid-column: 1 / -1;
border-color: rgba(103, 232, 249, 0.38);
background: linear-gradient(135deg, rgba(45, 183, 209, 0.28), rgba(70, 108, 215, 0.2));
}
.equation {
margin-top: 13px;
padding: 10px 12px;
border: 1px solid rgba(148, 205, 225, 0.12);
border-radius: 11px;
background: rgba(0, 0, 0, 0.17);
color: #a9c5d2;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 11px;
line-height: 1.55;
}
.hint {
position: fixed;
right: 24px;
bottom: 24px;
padding: 10px 13px;
border: 1px solid rgba(148, 205, 225, 0.13);
border-radius: 999px;
background: rgba(6, 14, 22, 0.55);
color: #829cab;
font-size: 11px;
pointer-events: none;
backdrop-filter: blur(12px);
}
.hint span {
color: #c7e3ee;
}
.annotation {
position: fixed;
top: 0;
left: 0;
padding: 5px 8px;
border: 1px solid rgba(129, 217, 237, 0.22);
border-radius: 6px;
background: rgba(5, 14, 23, 0.72);
color: #b9dbe7;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
pointer-events: none;
text-transform: uppercase;
transform: translate(-50%, -50%);
white-space: nowrap;
backdrop-filter: blur(7px);
}
.annotation.cyan {
border-color: rgba(103, 232, 249, 0.45);
color: var(--cyan);
}
.annotation.amber {
border-color: rgba(255, 160, 114, 0.45);
color: #ffb18f;
}
@media (max-width: 700px) {
.title-card {
top: 16px;
left: 17px;
}
.subtitle {
display: none;
}
.controls {
bottom: 13px;
left: 13px;
width: calc(100vw - 26px);
padding: 14px;
}
.hint {
display: none;
}
.annotation {
font-size: 8px;
}
}
</style>
</head>
<body>
<div class="title-card">
<div class="eyebrow">Interactive optical model</div>
<h1>How the Eye Focuses</h1>
<p class="subtitle">
Move the target, then change the lens curvature. The rays demonstrate how
accommodation brings a near or distant image into focus on the retina.
</p>
</div>
<section class="controls" aria-label="Eye controls">
<div class="control-header">
<strong>Optical controls</strong>
<span id="focusStatus" class="focus-status">IN FOCUS</span>
</div>
<div class="control">
<label class="control-label" for="distanceSlider">
<span>Object distance</span>
<output id="distanceValue">7.5 u</output>
</label>
<input
id="distanceSlider"
type="range"
min="5.5"
max="12.5"
step="0.1"
value="7.5"
/>
<div class="range-ends">
<span>Near</span>
<span>Far</span>
</div>
</div>
<div class="control">
<label class="control-label" for="powerSlider">
<span>Lens accommodation</span>
<output id="powerValue">56%</output>
</label>
<input
id="powerSlider"
type="range"
min="0"
max="100"
step="1"
value="56"
/>
<div class="range-ends">
<span>Relaxed</span>
<span>More convex</span>
</div>
</div>
<div class="button-row">
<button id="nearButton" type="button">Focus near object</button>
<button id="farButton" type="button">Focus distant object</button>
<button id="matchButton" class="primary" type="button">
Match lens to current object
</button>
</div>
<div class="equation" id="equation"></div>
</section>
<div class="hint">
<span>Drag</span> to orbit · <span>Scroll / pinch</span> to zoom ·
<span>Double-click</span> to reset
</div>
<div class="annotation cyan" id="objectLabel">Object</div>
<div class="annotation" id="corneaLabel">Cornea</div>
<div class="annotation cyan" id="lensLabel">Adaptive lens</div>
<div class="annotation amber" id="retinaLabel">Retinal screen</div>
<div class="annotation" id="nerveLabel">Optic nerve</div>
<div class="annotation cyan" id="rayLabel">Refracted rays</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.05,
120
);
const ambient = new THREE.AmbientLight(0xbad8e8, 1.2);
scene.add(ambient);
const hemisphere = new THREE.HemisphereLight(
0x9fe8ff,
0x132536,
1.55
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xe4f7ff, 2.6);
keyLight.position.set(4, 7, 9);
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x48dfff, 28, 18, 2);
rimLight.position.set(-4, 2, 5);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff876c, 16, 10, 2);
warmLight.position.set(2.8, -0.8, 1.8);
scene.add(warmLight);
// -------------------------------------------------------------------------
// Optical constants. The optical axis is the X axis.
// -------------------------------------------------------------------------
const EYE_RADIUS = 2.7;
const LENS_X = -1.35;
const RETINA_X = 2.5;
const LENS_TO_RETINA = RETINA_X - LENS_X;
const APERTURE_RADIUS = 0.72;
const RAY_COUNT = 9;
let objectDistance = 7.5;
let accommodation = 0.56;
const objectX = () => LENS_X - objectDistance;
function focalLength() {
return THREE.MathUtils.lerp(3.05, 2.15, accommodation);
}
function requiredFocalLength(distance = objectDistance) {
return 1 / (1 / distance + 1 / LENS_TO_RETINA);
}
function accommodationForDistance(distance) {
const required = requiredFocalLength(distance);
return THREE.MathUtils.clamp(
(3.05 - required) / (3.05 - 2.15),
0,
1
);
}
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
function createEyeShell(radius) {
const uSegments = 80;
const vSegments = 44;
const positions = [];
const normals = [];
const uvs = [];
const indices = [];
// Retain z <= 0, producing a cutaway with the open half facing the camera.
for (let i = 0; i <= uSegments; i++) {
const u = (i / uSegments) * Math.PI * 2;
for (let j = 0; j <= vSegments; j++) {
const theta = Math.PI + (j / vSegments) * Math.PI;
const sinU = Math.sin(u);
const x = radius * Math.cos(u);
const y = radius * sinU * Math.cos(theta);
const z = radius * sinU * Math.sin(theta);
positions.push(x, y, z);
normals.push(x / radius, y / radius, z / radius);
uvs.push(i / uSegments, j / vSegments);
}
}
for (let i = 0; i < uSegments; i++) {
for (let j = 0; j < vSegments; j++) {
const a = i * (vSegments + 1) + j;
const b = (i + 1) * (vSegments + 1) + j;
const c = (i + 1) * (vSegments + 1) + j + 1;
const d = i * (vSegments + 1) + j + 1;
indices.push(a, b, d, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"normal",
new THREE.Float32BufferAttribute(normals, 3)
);
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
return geometry;
}
function createCornea(radius = 1.03) {
const radialSegments = 18;
const angularSegments = 64;
const positions = [];
const uvs = [];
const indices = [];
for (let i = 0; i <= radialSegments; i++) {
const t = i / radialSegments;
const r = radius * t;
const x = -EYE_RADIUS - 0.36 * (1 - t * t) + 0.08 * t * t;
for (let j = 0; j <= angularSegments; j++) {
const angle = (j / angularSegments) * Math.PI * 2;
positions.push(
x,
r * Math.cos(angle),
r * Math.sin(angle)
);
uvs.push(t, j / angularSegments);
}
}
for (let i = 0; i < radialSegments; i++) {
for (let j = 0; j < angularSegments; j++) {
const a = i * (angularSegments + 1) + j;
const b = (i + 1) * (angularSegments + 1) + j;
const c = (i + 1) * (angularSegments + 1) + j + 1;
const d = i * (angularSegments + 1) + j + 1;
indices.push(a, b, d, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function createLensGeometry(bulge) {
const radius = 0.92;
const edgeThickness = 0.1;
const radialSegments = 16;
const angularSegments = 64;
const positions = [];
const uvs = [];
const indices = [];
const sides = [-1, 1];
for (const side of sides) {
for (let i = 0; i <= radialSegments; i++) {
const t = i / radialSegments;
const r = radius * t;
const x =
LENS_X +
side * (edgeThickness * 0.5 + bulge * (1 - t * t));
for (let j = 0; j <= angularSegments; j++) {
const angle = (j / angularSegments) * Math.PI * 2;
positions.push(
x,
r * Math.cos(angle),
r * Math.sin(angle)
);
uvs.push(j / angularSegments, t);
}
}
}
const sideStride = (radialSegments + 1) * (angularSegments + 1);
for (let side = 0; side < 2; side++) {
const offset = side * sideStride;
for (let i = 0; i < radialSegments; i++) {
for (let j = 0; j < angularSegments; j++) {
const a = offset + i * (angularSegments + 1) + j;
const b = offset + (i + 1) * (angularSegments + 1) + j;
const c = offset + (i + 1) * (angularSegments + 1) + j + 1;
const d = offset + i * (angularSegments + 1) + j + 1;
if (side === 0) {
indices.push(a, b, d, b, c, d);
} else {
indices.push(a, d, b, b, d, c);
}
}
}
}
// Close the rim of the lens.
const frontOuter = radialSegments * (angularSegments + 1);
const backOuter = sideStride + frontOuter;
for (let j = 0; j < angularSegments; j++) {
const a = frontOuter + j;
const b = frontOuter + j + 1;
const c = backOuter + j;
const d = backOuter + j + 1;
indices.push(a, c, b, b, c, d);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function createRetinaGeometry() {
const retinalRadius = 2.55;
const patchRadius = 1.24;
const radialSegments = 28;
const angularSegments = 80;
const positions = [];
const uvs = [];
const indices = [];
for (let i = 0; i <= radialSegments; i++) {
const t = i / radialSegments;
const r = patchRadius * t;
const x = Math.sqrt(retinalRadius * retinalRadius - r * r);
for (let j = 0; j <= angularSegments; j++) {
const angle = (j / angularSegments) * Math.PI * 2;
positions.push(
x,
r * Math.cos(angle),
r * Math.sin(angle)
);
uvs.push(j / angularSegments, t);
}
}
for (let i = 0; i < radialSegments; i++) {
for (let j = 0; j < angularSegments; j++) {
const a = i * (angularSegments + 1) + j;
const b = (i + 1) * (angularSegments + 1) + j;
const c = (i + 1) * (angularSegments + 1) + j + 1;
const d = i * (angularSegments + 1) + j + 1;
indices.push(a, b, d, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function createRetinaTexture() {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 512;
const ctx = canvas.getContext("2d");
const gradient = ctx.createRadialGradient(256, 256, 20, 256, 256, 260);
gradient.addColorStop(0, "#b74438");
gradient.addColorStop(0.45, "#70242c");
gradient.addColorStop(1, "#210d19");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 512, 512);
for (let i = 0; i < 1800; i++) {
const x = Math.random() * 512;
const y = Math.random() * 512;
const radius = 0.45 + Math.random() * 1.15;
ctx.fillStyle =
Math.random() > 0.5
? "rgba(255,182,106,0.55)"
: "rgba(255,82,76,0.42)";
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
ctx.strokeStyle = "rgba(255,230,190,0.12)";
ctx.lineWidth = 1;
for (let i = 0; i <= 16; i++) {
const p = (i / 16) * 512;
ctx.beginPath();
ctx.moveTo(p, 0);
ctx.lineTo(p, 512);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, p);
ctx.lineTo(512, p);
ctx.stroke();
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
return texture;
}
// -------------------------------------------------------------------------
// Eye model
// -------------------------------------------------------------------------
const sclera = new THREE.Mesh(
createEyeShell(EYE_RADIUS),
new THREE.MeshPhysicalMaterial({
color: 0xc7e8ef,
roughness: 0.3,
metalness: 0,
transparent: true,
opacity: 0.4,
transmission: 0.12,
thickness: 0.4,
side: THREE.DoubleSide,
depthWrite: false
})
);
sclera.renderOrder = 2;
scene.add(sclera);
const innerCoat = new THREE.Mesh(
createEyeShell(EYE_RADIUS - 0.13),
new THREE.MeshPhysicalMaterial({
color: 0x174d61,
roughness: 0.48,
transparent: true,
opacity: 0.2,
side: THREE.DoubleSide,
depthWrite: false
})
);
innerCoat.renderOrder = 1;
scene.add(innerCoat);
// Bright rims define the cut plane.
for (const theta of [Math.PI, Math.PI * 2]) {
const points = [];
for (let i = 0; i <= 80; i++) {
const u = (i / 80) * Math.PI * 2;
points.push(
new THREE.Vector3(
EYE_RADIUS * Math.cos(u),
EYE_RADIUS * Math.sin(u) * Math.cos(theta),
EYE_RADIUS * Math.sin(u) * Math.sin(theta)
)
);
}
const curve = new THREE.CatmullRomCurve3(points);
const rim = new THREE.Mesh(
new THREE.TubeGeometry(curve, 100, 0.038, 8, false),
new THREE.MeshStandardMaterial({
color: 0xa9dfea,
emissive: 0x234a57,
emissiveIntensity: 0.35,
roughness: 0.45
})
);
scene.add(rim);
}
const cornea = new THREE.Mesh(
createCornea(),
new THREE.MeshPhysicalMaterial({
color: 0x8eeaff,
roughness: 0.06,
metalness: 0,
transparent: true,
opacity: 0.25,
transmission: 0.5,
thickness: 0.12,
side: THREE.DoubleSide,
depthWrite: false
})
);
cornea.renderOrder = 4;
scene.add(cornea);
const iris = new THREE.Mesh(
new THREE.TorusGeometry(0.97, 0.095, 16, 96),
new THREE.MeshStandardMaterial({
color: 0x184b5c,
roughness: 0.42,
metalness: 0.12
})
);
iris.rotation.y = Math.PI / 2;
iris.position.x = -2.48;
scene.add(iris);
const ciliaryBody = new THREE.Mesh(
new THREE.TorusGeometry(0.88, 0.11, 16, 96),
new THREE.MeshStandardMaterial({
color: 0x71424d,
roughness: 0.62
})
);
ciliaryBody.rotation.y = Math.PI / 2;
ciliaryBody.position.x = -1.91;
scene.add(ciliaryBody);
const lensMesh = new THREE.Mesh(
createLensGeometry(0.2),
new THREE.MeshPhysicalMaterial({
color: 0x76e6ff,
emissive: 0x0b4c60,
emissiveIntensity: 0.16,
roughness: 0.05,
metalness: 0,
transparent: true,
opacity: 0.5,
transmission: 0.32,
thickness: 0.5,
side: THREE.DoubleSide,
depthWrite: false
})
);
lensMesh.renderOrder = 5;
scene.add(lensMesh);
const lensRim = new THREE.Mesh(
new THREE.TorusGeometry(0.92, 0.028, 10, 96),
new THREE.MeshBasicMaterial({
color: 0xa6f4ff,
transparent: true,
opacity: 0.72
})
);
lensRim.rotation.y = Math.PI / 2;
lensRim.position.x = LENS_X;
scene.add(lensRim);
// Suspensory fibers.
const fiberPositions = [];
for (let i = 0; i < 8; i++) {
const angle = (i / 8) * Math.PI * 2;
fiberPositions.push(
-1.91,
0.88 * Math.cos(angle),
0.88 * Math.sin(angle),
LENS_X,
0.92 * Math.cos(angle),
0.92 * Math.sin(angle)
);
}
const fiberGeometry = new THREE.BufferGeometry();
fiberGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(fiberPositions, 3)
);
scene.add(
new THREE.LineSegments(
fiberGeometry,
new THREE.LineBasicMaterial({
color: 0xe7d8b9,
transparent: true,
opacity: 0.52,
depthTest: false
})
)
);
const retina = new THREE.Mesh(
createRetinaGeometry(),
new THREE.MeshStandardMaterial({
map: createRetinaTexture(),
color: 0xffffff,
emissive: 0x641b20,
emissiveIntensity: 0.6,
roughness: 0.88,
side: THREE.DoubleSide
})
);
retina.renderOrder = 1;
scene.add(retina);
const opticNerve = new THREE.Mesh(
new THREE.CylinderGeometry(0.24, 0.3, 1.25, 24),
new THREE.MeshStandardMaterial({
color: 0xd4b28d,
roughness: 0.8
})
);
opticNerve.rotation.z = -Math.PI / 2;
opticNerve.position.x = 3.05;
scene.add(opticNerve);
const nerveEnd = new THREE.Mesh(
new THREE.CylinderGeometry(0.3, 0.3, 0.12, 24),
new THREE.MeshStandardMaterial({
color: 0x9d8064,
roughness: 0.86
})
);
nerveEnd.rotation.z = -Math.PI / 2;
nerveEnd.position.x = 3.72;
scene.add(nerveEnd);
// -------------------------------------------------------------------------
// Object target
// -------------------------------------------------------------------------
const targetCanvas = document.createElement("canvas");
targetCanvas.width = 256;
targetCanvas.height = 256;
const targetContext = targetCanvas.getContext("2d");
const targetTexture = new THREE.CanvasTexture(targetCanvas);
targetTexture.colorSpace = THREE.SRGBColorSpace;
const targetSprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: targetTexture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
targetSprite.scale.set(1.35, 1.35, 1);
targetSprite.renderOrder = 12;
scene.add(targetSprite);
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function drawTarget(distance) {
const ctx = targetContext;
const label = distance < 8 ? "NEAR" : "FAR";
ctx.clearRect(0, 0, 256, 256);
ctx.shadowColor = "rgba(71,220,255,0.7)";
ctx.shadowBlur = 22;
roundedRect(ctx, 18, 18, 220, 220, 34);
ctx.fillStyle = "rgba(5,24,37,0.94)";
ctx.fill();
ctx.shadowBlur = 0;
ctx.strokeStyle = "rgba(116,230,255,0.85)";
ctx.lineWidth = 5;
ctx.stroke();
ctx.beginPath();
ctx.arc(128, 105, 53, 0, Math.PI * 2);
ctx.strokeStyle = "rgba(255,255,255,0.94)";
ctx.lineWidth = 7;
ctx.stroke();
ctx.fillStyle = "#ffffff";
ctx.font = "bold 64px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("A", 128, 106);
ctx.fillStyle = "#67e8f9";
ctx.font = "bold 23px sans-serif";
ctx.fillText(label, 128, 190);
targetTexture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Rays and retinal focus marker
// -------------------------------------------------------------------------
const rayPositionArray = new Float32Array(RAY_COUNT * 18);
const rayColorArray = new Float32Array(RAY_COUNT * 18);
for (let i = 0; i < RAY_COUNT; i++) {
const color = new THREE.Color().setHSL(
i % 3 === 0 ? 0.11 : 0.52,
0.9,
i % 3 === 0 ? 0.72 : 0.66
);
for (let v = 0; v < 6; v++) {
const offset = (i * 6 + v) * 3;
rayColorArray[offset] = color.r;
rayColorArray[offset + 1] = color.g;
rayColorArray[offset + 2] = color.b;
}
}
const rayGeometry = new THREE.BufferGeometry();
rayGeometry.setAttribute(
"position",
new THREE.BufferAttribute(rayPositionArray, 3)
);
rayGeometry.setAttribute(
"color",
new THREE.BufferAttribute(rayColorArray, 3)
);
const rays = new THREE.LineSegments(
rayGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.9,
depthTest: false,
depthWrite: false
})
);
rays.renderOrder = 10;
scene.add(rays);
const focusDisk = new THREE.Mesh(
new THREE.CircleGeometry(1, 64),
new THREE.MeshBasicMaterial({
color: 0xfff0ae,
transparent: true,
opacity: 0.82,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
})
);
focusDisk.rotation.y = Math.PI / 2;
focusDisk.position.x = 2.515;
focusDisk.renderOrder = 14;
scene.add(focusDisk);
const focusRing = new THREE.Mesh(
new THREE.RingGeometry(0.77, 1, 64),
new THREE.MeshBasicMaterial({
color: 0xffc868,
transparent: true,
opacity: 0.65,
side: THREE.DoubleSide,
depthTest: false,
depthWrite: false
})
);
focusRing.rotation.y = Math.PI / 2;
focusRing.position.x = 2.52;
focusRing.renderOrder = 13;
scene.add(focusRing);
function updateRays() {
const f = focalLength();
const positions = rayGeometry.attributes.position.array;
const ox = objectX();
const oy = 0;
const oz = 0;
let maximumBlur = 0;
for (let i = 0; i < RAY_COUNT; i++) {
const angle = (i / RAY_COUNT) * Math.PI * 2;
const radius = APERTURE_RADIUS * (i % 2 === 0 ? 1 : 0.78);
const lensY = radius * Math.cos(angle);
const lensZ = radius * Math.sin(angle);
// Thin-lens slope after refraction.
const slopeY = lensY * (1 / objectDistance - 1 / f);
const slopeZ = lensZ * (1 / objectDistance - 1 / f);
const retinaY = lensY + slopeY * LENS_TO_RETINA;
const retinaZ = lensZ + slopeZ * LENS_TO_RETINA;
const beyondY = retinaY + slopeY * 0.18;
const beyondZ = retinaZ + slopeZ * 0.18;
maximumBlur = Math.max(
maximumBlur,
Math.hypot(retinaY, retinaZ)
);
const offset = i * 18;
positions[offset] = ox;
positions[offset + 1] = oy;
positions[offset + 2] = oz;
positions[offset + 3] = LENS_X;
positions[offset + 4] = lensY;
positions[offset + 5] = lensZ;
positions[offset + 6] = LENS_X;
positions[offset + 7] = lensY;
positions[offset + 8] = lensZ;
positions[offset + 9] = RETINA_X;
positions[offset + 10] = retinaY;
positions[offset + 11] = retinaZ;
positions[offset + 12] = RETINA_X;
positions[offset + 13] = retinaY;
positions[offset + 14] = retinaZ;
positions[offset + 15] = RETINA_X + 0.18;
positions[offset + 16] = beyondY;
positions[offset + 17] = beyondZ;
}
rayGeometry.attributes.position.needsUpdate = true;
const visualRadius = THREE.MathUtils.clamp(
Math.max(0.027, maximumBlur),
0.027,
0.82
);
focusDisk.scale.set(visualRadius, visualRadius, 1);
focusRing.scale.set(visualRadius * 1.28, visualRadius * 1.28, 1);
const defocus = Math.abs(
1 + LENS_TO_RETINA * (1 / objectDistance - 1 / f)
);
const focused = defocus < 0.045;
focusDisk.material.opacity = focused ? 0.92 : 0.48;
focusRing.material.opacity = focused ? 0.72 : 0.32;
return { focused, maximumBlur };
}
// -------------------------------------------------------------------------
// UI and model updates
// -------------------------------------------------------------------------
const distanceSlider = document.getElementById("distanceSlider");
const powerSlider = document.getElementById("powerSlider");
const distanceValue = document.getElementById("distanceValue");
const powerValue = document.getElementById("powerValue");
const focusStatus = document.getElementById("focusStatus");
const equation = document.getElementById("equation");
function updateLensMesh() {
// A stronger accommodation setting produces a more convex lens.
const bulge = 0.11 + accommodation * 0.16;
const oldGeometry = lensMesh.geometry;
lensMesh.geometry = createLensGeometry(bulge);
oldGeometry.dispose();
}
function updateModel() {
const f = focalLength();
const required = requiredFocalLength();
updateLensMesh();
targetSprite.position.set(objectX(), 0, 0);
drawTarget(objectDistance);
distanceValue.textContent = `${objectDistance.toFixed(1)} u`;
powerValue.textContent = `${Math.round(accommodation * 100)}%`;
const result = updateRays();
if (result.focused) {
focusStatus.textContent = "IN FOCUS";
focusStatus.classList.remove("blurred");
} else {
focusStatus.textContent = "OUT OF FOCUS";
focusStatus.classList.add("blurred");
}
const direction =
f > required
? "Increase accommodation to make the lens more convex."
: "Relax the lens to reduce its optical power.";
equation.innerHTML = `
1/f = 1/d<sub>o</sub> + 1/d<sub>i</sub><br>
1/${f.toFixed(2)} = 1/${objectDistance.toFixed(1)} +
1/${LENS_TO_RETINA.toFixed(2)}<br>
<span style="color:#698391">
${result.focused ? "Image plane coincides with the retina." : direction}
</span>
`;
}
function matchLensToObject() {
accommodation = accommodationForDistance(objectDistance);
powerSlider.value = String(Math.round(accommodation * 100));
updateModel();
}
distanceSlider.addEventListener("input", () => {
objectDistance = Number(distanceSlider.value);
updateModel();
});
powerSlider.addEventListener("input", () => {
accommodation = Number(powerSlider.value) / 100;
updateModel();
});
document.getElementById("nearButton").addEventListener("click", () => {
objectDistance = 6;
distanceSlider.value = "6";
matchLensToObject();
});
document.getElementById("farButton").addEventListener("click", () => {
objectDistance = 12;
distanceSlider.value = "12";
matchLensToObject();
});
document.getElementById("matchButton").addEventListener("click", () => {
matchLensToObject();
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit, wheel/pinch zoom, and reset
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(-3.1, 0, 0),
yaw: 0.64,
pitch: 0.31,
radius: 16.5
};
function applyCamera() {
const cp = Math.cos(cameraState.pitch);
const sp = Math.sin(cameraState.pitch);
camera.position.set(
cameraState.target.x +
cameraState.radius * cp * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.radius * sp,
cameraState.target.z +
cameraState.radius * cp * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.yaw = 0.64;
cameraState.pitch = 0.31;
cameraState.radius = 16.5;
cameraState.target.set(-3.1, 0, 0);
applyCamera();
}
const pointers = new Map();
let pinchDistance = 0;
function currentPinchDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
pinchDistance = currentPinchDistance();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const pointer = pointers.get(event.pointerId);
if (pointers.size === 1) {
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
-1.2,
1.2
);
pointer.x = event.clientX;
pointer.y = event.clientY;
applyCamera();
} else if (pointers.size === 2) {
const previousPinch = currentPinchDistance();
pointer.x = event.clientX;
pointer.y = event.clientY;
const nextPinch = currentPinchDistance();
if (previousPinch > 0 && nextPinch > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (previousPinch / nextPinch),
7,
32
);
applyCamera();
}
}
});
function removePointer(event) {
pointers.delete(event.pointerId);
pinchDistance = currentPinchDistance();
}
renderer.domElement.addEventListener("pointerup", removePointer);
renderer.domElement.addEventListener("pointercancel", removePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
32
);
applyCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
window.addEventListener("keydown", (event) => {
if (["INPUT", "BUTTON"].includes(document.activeElement?.tagName)) {
return;
}
if (event.key === "ArrowRight") {
accommodation = THREE.MathUtils.clamp(accommodation + 0.02, 0, 1);
powerSlider.value = String(Math.round(accommodation * 100));
updateModel();
}
if (event.key === "ArrowLeft") {
accommodation = THREE.MathUtils.clamp(accommodation - 0.02, 0, 1);
powerSlider.value = String(Math.round(accommodation * 100));
updateModel();
}
if (event.key.toLowerCase() === "n") {
objectDistance = 6;
distanceSlider.value = "6";
matchLensToObject();
}
if (event.key.toLowerCase() === "f") {
objectDistance = 12;
distanceSlider.value = "12";
matchLensToObject();
}
if (event.key.toLowerCase() === "r") {
resetCamera();
}
});
// -------------------------------------------------------------------------
// Screen-space annotations
// -------------------------------------------------------------------------
const annotations = [
{
element: document.getElementById("objectLabel"),
position: new THREE.Vector3(objectX(), 0.95, 0)
},
{
element: document.getElementById("corneaLabel"),
position: new THREE.Vector3(-2.75, 1.25, 0)
},
{
element: document.getElementById("lensLabel"),
position: new THREE.Vector3(LENS_X, 1.12, 0)
},
{
element: document.getElementById("retinaLabel"),
position: new THREE.Vector3(2.35, -1.22, 0)
},
{
element: document.getElementById("nerveLabel"),
position: new THREE.Vector3(3.3, -0.48, 0)
},
{
element: document.getElementById("rayLabel"),
position: new THREE.Vector3(-0.1, 1.6, 0)
}
];
const projected = new THREE.Vector3();
function updateAnnotations() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const annotation of annotations) {
projected.copy(annotation.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
annotation.element.style.display = visible ? "block" : "none";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
annotation.element.style.transform =
`translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
}
}
}
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
applyCamera();
updateModel();
renderer.setAnimationLoop(() => {
annotations[0].position.set(objectX(), 0.95, 0);
renderer.render(scene, camera);
updateAnnotations();
});
</script>
</body>
</html>
```