Prompt specification
Build or customize the Three.js 3D scene "Apparent depth water-container exhibit" 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: Apparent depth water-container exhibit
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/apparent-depth-water-container-exhibit-x1574
Scene Description Prompt:
Show a submerged marker’s apparent depth with stylized light rays and an observer beside a tank. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (apparent-depth-water-container-exhibit-x1574):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Apparent Depth — Submerged Marker in a Tank</title>
<style>
:root{
--ink:#e8f2ff; --dim:#93b3cf; --cy:#7fd4ff; --am:#ff9a4d; --panel:rgba(10,22,38,.62);
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#060d17;
font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;color:var(--ink)}
#app{position:fixed;inset:0}
canvas{display:block}
#vignette{position:fixed;inset:0;pointer-events:none;
background:radial-gradient(120% 90% at 50% 45%,rgba(0,0,0,0) 45%,rgba(0,0,0,.55) 100%)}
#labels{position:fixed;inset:0;pointer-events:none;overflow:hidden}
.lab{position:absolute;transform:translate(-50%,-50%);white-space:nowrap;font-size:11.5px;letter-spacing:.02em;
background:rgba(8,18,32,.72);border:1px solid rgba(127,212,255,.35);color:var(--ink);
padding:4px 9px;border-radius:999px;backdrop-filter:blur(6px);box-shadow:0 4px 18px rgba(0,0,0,.45)}
.lab.am{border-color:rgba(255,154,77,.5);color:#ffd9b8}
.lab small{color:var(--dim);font-size:10px}
.panel{position:fixed;background:var(--panel);border:1px solid rgba(127,212,255,.18);border-radius:14px;
padding:14px 16px;backdrop-filter:blur(14px);box-shadow:0 18px 50px rgba(0,0,0,.5);z-index:5}
#left{left:16px;top:16px;width:330px}
#right{right:16px;top:16px;width:250px}
h1{font-size:15.5px;margin:0 0 4px;letter-spacing:.01em}
h2{font-size:11px;margin:0 0 10px;text-transform:uppercase;letter-spacing:.16em;color:var(--cy)}
.sub{font-size:11.5px;color:var(--dim);margin:0 0 12px;line-height:1.45}
.ros{display:grid;grid-template-columns:1fr 1fr;gap:7px 10px;margin-bottom:10px}
.ro{background:rgba(255,255,255,.045);border:1px solid rgba(255,255,255,.07);border-radius:9px;padding:6px 9px}
.ro label{display:block;font-size:9.5px;text-transform:uppercase;letter-spacing:.12em;color:var(--dim)}
.ro b{font-size:15px;font-variant-numeric:tabular-nums}
.bar{height:9px;border-radius:99px;background:rgba(255,255,255,.08);overflow:hidden;position:relative;margin:2px 0 6px}
.bar i{position:absolute;inset:0 auto 0 0;background:linear-gradient(90deg,#ff8a3d,#ffd08a);border-radius:99px;transition:width .12s}
.barlab{font-size:10.5px;color:var(--dim);margin-bottom:12px}
svg#inset{width:100%;height:auto;display:block;margin-bottom:6px}
.cap{font-size:10.5px;color:var(--dim);line-height:1.45;margin:0}
.cap b{color:#ffd9b8}
.ctl{margin-bottom:11px}
.ctl .row{display:flex;justify-content:space-between;font-size:11px;color:var(--dim);margin-bottom:5px}
.ctl .row b{color:var(--ink);font-variant-numeric:tabular-nums}
input[type=range]{width:100%;height:4px;-webkit-appearance:none;appearance:none;background:rgba(127,212,255,.22);border-radius:9px;outline:none}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:14px;height:14px;border-radius:50%;
background:linear-gradient(180deg,#bfe9ff,#4fb6e6);border:1px solid #0a1626;box-shadow:0 0 10px rgba(79,182,230,.7);cursor:pointer}
input[type=range]::-moz-range-thumb{width:13px;height:13px;border-radius:50%;background:#7fd4ff;border:1px solid #0a1626;cursor:pointer}
.tg{display:flex;flex-direction:column;gap:7px;margin:12px 0;font-size:11.5px;color:var(--dim)}
.tg label{display:flex;align-items:center;gap:8px;cursor:pointer}
input[type=checkbox]{accent-color:#7fd4ff;width:13px;height:13px}
button{width:100%;padding:7px;border-radius:9px;border:1px solid rgba(127,212,255,.3);background:rgba(127,212,255,.08);
color:var(--ink);font-size:11.5px;cursor:pointer;letter-spacing:.04em}
button:hover{background:rgba(127,212,255,.16)}
#hint{position:fixed;left:50%;bottom:14px;transform:translateX(-50%);font-size:11px;color:var(--dim);
background:rgba(8,18,32,.55);padding:5px 13px;border-radius:99px;border:1px solid rgba(255,255,255,.08);z-index:4}
#loading{position:fixed;inset:0;display:grid;place-items:center;color:var(--dim);font-size:13px;letter-spacing:.14em;z-index:9}
@media (max-width:900px){#left{width:280px}#right{width:220px}}
@media (max-width:680px){#left,#right{position:fixed;width:auto;left:10px;right:10px;top:auto}
#left{bottom:44px}#right{top:10px}#inset{display:none}}
</style>
</head>
<body>
<div id="app"></div>
<div id="vignette"></div>
<div id="labels"></div>
<div id="left" class="panel">
<h1>Apparent depth of a submerged marker</h1>
<p class="sub">Light bends toward the normal when it enters water, so the marker appears
<b style="color:#ffd9b8">shallower</b> than it really is. Drag the eye ray out of the tank to see why.</p>
<div class="ros">
<div class="ro"><label>Actual depth</label><b id="r-actual">—</b></div>
<div class="ro"><label>Apparent depth</label><b id="r-app">—</b></div>
<div class="ro"><label>Normal view D/n</label><b id="r-vert">—</b></div>
<div class="ro"><label>Angle air → water</label><b id="r-ang">—</b></div>
</div>
<div class="bar"><i id="bar-fill"></i></div>
<div class="barlab" id="bar-lab">—</div>
<svg id="inset" viewBox="0 0 230 158">
<rect x="0" y="0" width="230" height="158" rx="9" fill="rgba(6,16,28,.55)"/>
<line x1="18" y1="34" x2="212" y2="34" stroke="#7fd4ff" stroke-width="2"/>
<text x="18" y="25" fill="#7fd4ff" font-size="9.5" font-family="monospace">surface</text>
<line id="i-dash" x1="115" y1="34" x2="115" y2="136" stroke="#ff9a4d" stroke-width="1.4" stroke-dasharray="4 4"/>
<circle id="i-ghost" cx="115" cy="50" r="7" fill="rgba(127,212,255,.22)" stroke="#7fd4ff" stroke-width="2"/>
<circle id="i-actual" cx="115" cy="136" r="7" fill="#ff8a3d" stroke="#ffd9b8" stroke-width="1.5"/>
<text id="i-t1" x="130" y="54" fill="#9fdcff" font-size="10.5" font-family="monospace">apparent</text>
<text id="i-t2" x="130" y="140" fill="#ffc79a" font-size="10.5" font-family="monospace">actual</text>
<text x="18" y="151" fill="#8fb6d9" font-size="10" font-family="monospace">viewed from directly above: d = D / n</text>
</svg>
<p class="cap">Inset: seen straight down (normal incidence) the marker appears at <b>D/n</b> — about
<b>75 %</b> of its real depth in water (n ≈ 1.33). The oblique view from the observer gives a
virtual image that is lifted even further.</p>
</div>
<div id="right" class="panel">
<h2>Controls</h2>
<div class="ctl">
<div class="row"><span>Marker depth</span><b id="o-depth"></b></div>
<input type="range" id="s-depth" min="0.8" max="3.4" step="0.05" value="2.2">
</div>
<div class="ctl">
<div class="row"><span>Refractive index n</span><b id="o-n"></b></div>
<input type="range" id="s-n" min="1" max="1.6" step="0.01" value="1.33">
</div>
<div class="ctl">
<div class="row"><span>Observer eye height</span><b id="o-eye"></b></div>
<input type="range" id="s-eye" min="0.5" max="1.4" step="0.02" value="0.9">
</div>
<div class="tg">
<label><input type="checkbox" id="c-sun" checked> Stylised sunlight rays</label>
<label><input type="checkbox" id="c-app" checked> Virtual image + dashed ray</label>
<label><input type="checkbox" id="c-lab" checked> Labels</label>
</div>
<button id="reset">Reset scene</button>
</div>
<div id="hint">drag to orbit · scroll to zoom</div>
<div id="loading">LOADING…</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ───────────────────────── constants / state ───────────────────────── */
const SURF_Y = 0, TANK_FLOOR = -4.0, ROOM_FLOOR = -4.2;
const HW = 2.6, HD = 1.2, RIM_Y = 0.45, GLASS = 0.13;
const EYE_X = 3.2, U_TO_CM = 30; // 1 world unit = 30 cm
const state = { depth: 2.2, n: 1.33, eyeY: 0.9, sun: true, app: true, labels: true };
/* ───────────────────────── renderer / scene ───────────────────────── */
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
document.getElementById('app').appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x060d17);
scene.fog = new THREE.FogExp2(0x060d17, 0.017);
const camera = new THREE.PerspectiveCamera(38, innerWidth / innerHeight, 0.1, 120);
const target = new THREE.Vector3(0.75, -1.15, 0);
const orbit = { az: 0.20, el: 0.235, dist: 13.4, tAz: 0.20, tEl: 0.235, tDist: 13.4 };
function applyCamera() {
const { az, el, dist } = orbit;
camera.position.set(
target.x + dist * Math.cos(el) * Math.sin(az),
target.y + dist * Math.sin(el),
target.z + dist * Math.cos(el) * Math.cos(az));
camera.lookAt(target);
}
applyCamera();
/* lights */
scene.add(new THREE.HemisphereLight(0x9fd8ff, 0x081220, 0.65));
const sun = new THREE.DirectionalLight(0xfff1d8, 1.35);
sun.position.set(-7, 10, 7); scene.add(sun);
const rim = new THREE.DirectionalLight(0x6fd6ff, 0.55);
rim.position.set(7, 2, -6); scene.add(rim);
const tankGlow = new THREE.PointLight(0x49c8ff, 14, 12, 2);
tankGlow.position.set(0, -1.2, 0.6); scene.add(tankGlow);
/* ───────────────────────── helpers ───────────────────────── */
const V3 = (x, y, z) => new THREE.Vector3(x, y, z);
function capsuleBetween(a, b, r, mat) {
const len = a.distanceTo(b);
const g = new THREE.CapsuleGeometry(r, Math.max(len - 2 * r, 0.02), 4, 12);
const m = new THREE.Mesh(g, mat);
m.position.copy(a).add(b).multiplyScalar(0.5);
m.quaternion.setFromUnitVectors(V3(0, 1, 0), b.clone().sub(a).normalize());
return m;
}
function textSprite(text, color = '#bfe0ff', w = 0.46) {
const c = document.createElement('canvas'); c.width = 256; c.height = 96;
const x = c.getContext('2d');
x.font = 'bold 52px ui-monospace, Menlo, monospace';
x.textAlign = 'center'; x.textBaseline = 'middle';
x.fillStyle = color; x.fillText(text, 128, 50);
const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace;
const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: t, transparent: true, depthWrite: false, opacity: .9 }));
s.scale.set(w * (256 / 96), w, 1);
return s;
}
function glowSprite(color, size, opacity = .9) {
const c = document.createElement('canvas'); c.width = c.height = 128;
const x = c.getContext('2d');
const g = x.createRadialGradient(64, 64, 0, 64, 64, 64);
g.addColorStop(0, color); g.addColorStop(.25, color); g.addColorStop(1, 'rgba(0,0,0,0)');
x.fillStyle = g; x.fillRect(0, 0, 128, 128);
const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace;
const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: t, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, opacity }));
s.scale.set(size, size, 1);
return s;
}
/* beam quad (lives in the x-y diagram plane, faces the camera) */
const beamVert = `varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0); }`;
const beamFrag = `
uniform vec3 uColor; uniform float uOpacity,uTime,uPhase,uFlicker;
varying vec2 vUv;
void main(){
float head = smoothstep(0.0,0.16,vUv.x)*smoothstep(1.0,0.68,vUv.x);
float a = abs(vUv.y*2.0-1.0);
float edge = pow(max(0.0,1.0-a),1.5);
float core = pow(max(0.0,1.0-a),7.0);
float flick = 1.0 + uFlicker*0.28*sin(uTime*1.7+uPhase)*sin(uTime*0.83+uPhase*2.3);
float al = uOpacity*head*(edge*0.55+core*1.0)*flick;
gl_FragColor = vec4(uColor*(0.75+core*1.1), al);
}`;
function makeBeam(color, opacity, width, flicker = 0) {
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(12), 3));
g.setAttribute('uv', new THREE.Float32BufferAttribute([0, 0, 0, 1, 1, 0, 1, 1], 2));
g.setIndex([0, 1, 2, 2, 1, 3]);
const m = new THREE.ShaderMaterial({
vertexShader: beamVert, fragmentShader: beamFrag, transparent: true,
depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
uniforms: { uColor: { value: new THREE.Color(color) }, uOpacity: { value: opacity },
uTime: { value: 0 }, uPhase: { value: Math.random() * 6 }, uFlicker: { value: flicker } }
});
const mesh = new THREE.Mesh(g, m);
mesh.frustumCulled = false;
mesh.renderOrder = 4;
return mesh;
}
function setBeam(mesh, p0, p1, width) {
const dx = p1.x - p0.x, dy = p1.y - p0.y, L = Math.hypot(dx, dy) || 1;
const nx = -dy / L * width * .5, ny = dx / L * width * .5;
const a = mesh.geometry.attributes.position.array;
const put = (i, v, s) => { a[i * 3] = v.x + s * nx; a[i * 3 + 1] = v.y + s * ny; a[i * 3 + 2] = v.z; };
put(0, p0, 1); put(1, p0, -1); put(2, p1, 1); put(3, p1, -1);
mesh.geometry.attributes.position.needsUpdate = true;
mesh.geometry.computeBoundingSphere();
}
/* ───────────────────────── room floor + grid ───────────────────────── */
const floorMat = new THREE.MeshStandardMaterial({ color: 0x0d1826, roughness: .95, metalness: 0 });
const floor = new THREE.Mesh(new THREE.PlaneGeometry(60, 60), floorMat);
floor.rotation.x = -Math.PI / 2; floor.position.y = ROOM_FLOOR; scene.add(floor);
const grid = new THREE.GridHelper(40, 40, 0x1c3a52, 0x112437);
grid.position.y = ROOM_FLOOR + .002;
grid.material.transparent = true; grid.material.opacity = .35; scene.add(grid);
/* ───────────────────────── tank ───────────────────────── */
const tank = new THREE.Group(); scene.add(tank);
const glassMat = new THREE.MeshStandardMaterial({
color: 0x9fd8ff, transparent: true, opacity: .07, roughness: .06, metalness: .1,
side: THREE.DoubleSide, depthWrite: false
});
function glassPanel(w, h, d, x, y, z) {
const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), glassMat);
m.position.set(x, y, z); m.renderOrder = 6; tank.add(m); return m;
}
const tankH = RIM_Y - TANK_FLOOR, tankCY = (RIM_Y + TANK_FLOOR) / 2;
glassPanel(HW * 2 + .2, tankH, GLASS, 0, tankCY, -HD - GLASS / 2); // back
glassPanel(HW * 2 + .2, tankH, GLASS, 0, tankCY, HD + GLASS / 2); // front
glassPanel(GLASS, tankH, HD * 2, -HW - GLASS / 2, tankCY, 0); // left
glassPanel(GLASS, tankH, HD * 2, HW + GLASS / 2, tankCY, 0); // right
glassPanel(HW * 2 + .26, .2, HD * 2 + .26, 0, TANK_FLOOR - .1, 0); // base slab
const frame = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(HW * 2 + .26, tankH + .2, HD * 2 + .26)),
new THREE.LineBasicMaterial({ color: 0x8fd8ff, transparent: true, opacity: .55 }));
frame.position.set(0, tankCY + .1, 0); tank.add(frame);
/* water volume */
const water = new THREE.Mesh(
new THREE.BoxGeometry(HW * 2 - .02, -TANK_FLOOR, HD * 2 - .02),
new THREE.MeshStandardMaterial({ color: 0x1a7fb5, transparent: true, opacity: .26,
roughness: .18, metalness: .05, side: THREE.DoubleSide, depthWrite: false }));
water.position.set(0, TANK_FLOOR / 2, 0); water.renderOrder = 2; scene.add(water);
/* water surface (animated shader) */
const surfMat = new THREE.ShaderMaterial({
transparent: true, depthWrite: false, side: THREE.DoubleSide,
uniforms: { uTime: { value: 0 } },
vertexShader: `varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.0);} `,
fragmentShader: `
uniform float uTime; varying vec2 vUv;
void main(){
float w = sin(vUv.x*26.0+uTime*1.3)*0.5 + sin(vUv.y*20.0-uTime*1.05)*0.5 + sin((vUv.x+vUv.y)*15.0+uTime*.7)*0.3;
float rip = pow(max(0.0, sin(vUv.x*40.0+uTime*2.2)*0.5+0.5), 10.0);
vec3 deep = vec3(0.04,0.24,0.40);
vec3 shal = vec3(0.35,0.78,0.95);
vec3 col = mix(deep, shal, clamp(0.45+0.35*w,0.0,1.0));
col += rip*0.45*vec3(1.0,0.95,0.85);
gl_FragColor = vec4(col, 0.52);
}`
});
const surface = new THREE.Mesh(new THREE.PlaneGeometry(HW * 2 - .02, HD * 2 - .02), surfMat);
surface.rotation.x = -Math.PI / 2; surface.position.y = SURF_Y; surface.renderOrder = 3; scene.add(surface);
/* depth ruler on the back wall */
const ruler = new THREE.Group(); scene.add(ruler);
const rt = [];
for (let i = 0; i <= 8; i++) {
const y = -i * .5, major = i % 2 === 0;
rt.push(-2.28, y, -HD + .02, -2.28 + (major ? .28 : .15), y, -HD + .02);
}
ruler.add(new THREE.LineSegments(new THREE.BufferGeometry().setAttribute('position', new THREE.Float32BufferAttribute(rt, 3)),
new THREE.LineBasicMaterial({ color: 0x7fb6d8, transparent: true, opacity: .55 })));
for (let i = 1; i <= 4; i++) {
const sp = textSprite(String(i * 30), '#9fd0ea', .38);
sp.position.set(-2.56, -i, -HD + .05); ruler.add(sp);
}
/* ───────────────────────── submerged marker ───────────────────────── */
const marker = new THREE.Group(); scene.add(marker);
const rodMat = new THREE.MeshStandardMaterial({ color: 0xd8e4ef, roughness: .45, metalness: .55 });
const rod = new THREE.Mesh(new THREE.CylinderGeometry(.045, .045, 1, 12), rodMat); marker.add(rod);
const tipMat = new THREE.MeshStandardMaterial({ color: 0xff7a2f, emissive: 0xff5a10, emissiveIntensity: 1.5, roughness: .35 });
const tip = new THREE.Mesh(new THREE.SphereGeometry(.165, 24, 18), tipMat); marker.add(tip);
const tipGlow = glowSprite('#ff9a4d', 1.5, .55); marker.add(tipGlow);
const base = new THREE.Mesh(new THREE.CylinderGeometry(.26, .3, .05, 20),
new THREE.MeshStandardMaterial({ color: 0x516577, roughness: .6, metalness: .3 }));
base.position.y = TANK_FLOOR + .03; marker.add(base);
/* ───────────────────────── observer ───────────────────────── */
const obsGroup = new THREE.Group(); scene.add(obsGroup);
const skinMat = new THREE.MeshStandardMaterial({ color: 0x2c3c50, roughness: .72, metalness: .08 });
const limbMat = new THREE.MeshStandardMaterial({ color: 0x22303f, roughness: .8 });
const headMat = new THREE.MeshStandardMaterial({ color: 0x35506b, roughness: .62 });
const eyeMat = new THREE.MeshBasicMaterial({ color: 0x9df0ff });
let eyeLocal = V3(-.3, 0, 0);
function buildObserver() {
while (obsGroup.children.length) {
const c = obsGroup.children.pop(); c.geometry?.dispose();
}
const eyeY = state.eyeY - ROOM_FLOOR; // eye height above the floor
const shoulderY = eyeY - .82, hipY = shoulderY - 1.62;
obsGroup.position.set(EYE_X + .3, ROOM_FLOOR, 0);
eyeLocal = V3(-.3, eyeY, 0);
// legs + feet
obsGroup.add(capsuleBetween(V3(.04, .12, .17), V3(0, hipY, .13), .155, limbMat));
obsGroup.add(capsuleBetween(V3(-.02, .12, -.17), V3(0, hipY, -.12), .155, limbMat));
const footM = new THREE.MeshStandardMaterial({ color: 0x16222f, roughness: .9 });
const f1 = new THREE.Mesh(new THREE.BoxGeometry(.42, .13, .22), footM); f1.position.set(-.09, .07, .17); obsGroup.add(f1);
const f2 = f1.clone(); f2.position.z = -.17; obsGroup.add(f2);
// torso, neck, head
obsGroup.add(capsuleBetween(V3(0, hipY, 0), V3(-.1, shoulderY, 0), .33, skinMat));
obsGroup.add(capsuleBetween(V3(-.1, shoulderY, 0), V3(-.08, shoulderY + .3, 0), .12, skinMat));
const head = new THREE.Mesh(new THREE.SphereGeometry(.4, 26, 20), headMat);
head.position.set(-.04, eyeY + .3, 0); head.scale.set(1, 1.08, .92); obsGroup.add(head);
const eye = new THREE.Mesh(new THREE.SphereGeometry(.065, 12, 10), eyeMat);
eye.position.copy(eyeLocal); obsGroup.add(eye);
// arms: near arm gestures toward the tank
obsGroup.add(capsuleBetween(V3(-.04, shoulderY - .06, .3), V3(-.62, shoulderY - .62, .34), .105, skinMat));
obsGroup.add(capsuleBetween(V3(-.62, shoulderY - .62, .34), V3(-1.12, shoulderY - .18, .3), .095, skinMat));
obsGroup.add(capsuleBetween(V3(-.04, shoulderY - .06, -.3), V3(-.14, shoulderY - 1.5, -.28), .105, skinMat));
// soft shadow
const sh = new THREE.Mesh(new THREE.CircleGeometry(.62, 24), new THREE.MeshBasicMaterial({
color: 0x000000, transparent: true, opacity: .32, depthWrite: false }));
sh.rotation.x = -Math.PI / 2; sh.position.set(EYE_X + .3, ROOM_FLOOR + .012, 0); obsGroup.add(sh);
}
buildObserver();
/* ───────────────────────── eye ray, virtual image ───────────────────────── */
const rayWater = makeBeam('#7fe3ff', .95, .30);
const rayAir = makeBeam('#fff0d2', .85, .24);
scene.add(rayWater, rayAir);
const rayLineW = new THREE.Line(new THREE.BufferGeometry().setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(6), 3)),
new THREE.LineBasicMaterial({ color: 0xdff6ff, transparent: true, opacity: .85 }));
const rayLineA = new THREE.Line(new THREE.BufferGeometry().setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(6), 3)),
new THREE.LineBasicMaterial({ color: 0xfff3dc, transparent: true, opacity: .85 }));
scene.add(rayLineW, rayLineA);
const dashMat = new THREE.LineDashedMaterial({ color: 0x7fd4ff, dashSize: .16, gapSize: .12, transparent: true, opacity: .85 });
const dashBack = new THREE.Line(new THREE.BufferGeometry().setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(6), 3)), dashMat);
const dashLift = new THREE.Line(new THREE.BufferGeometry().setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(6), 3)),
new THREE.LineDashedMaterial({ color: 0xffa45c, dashSize: .13, gapSize: .1, transparent: true, opacity: .8 }));
scene.add(dashBack, dashLift);
const ghost = new THREE.Group(); scene.add(ghost);
const ghostFill = new THREE.Mesh(new THREE.SphereGeometry(.165, 20, 14),
new THREE.MeshBasicMaterial({ color: 0x7fe3ff, transparent: true, opacity: .22, depthWrite: false }));
const ghostWire = new THREE.Mesh(new THREE.SphereGeometry(.175, 14, 10),
new THREE.MeshBasicMaterial({ color: 0x9df0ff, wireframe: true, transparent: true, opacity: .8 }));
ghost.add(ghostFill, ghostWire);
const ghostGlow = glowSprite('#7fd4ff', 1.2, .45); ghost.add(ghostGlow);
/* refraction point marker */
const rp = new THREE.Mesh(new THREE.SphereGeometry(.075, 14, 10), new THREE.MeshBasicMaterial({ color: 0xfff0c0 }));
scene.add(rp);
const rpGlow = glowSprite('#ffe6b0', .9, .8); scene.add(rpGlow);
/* ───────────────────────── stylised sunlight ───────────────────────── */
const sunGroup = new THREE.Group(); scene.add(sunGroup);
const sunBeams = [];
const BEAMS = [
{ th: 24, tx: 0.00, tz: 0.00 },
{ th: 31, tx: -0.12, tz: -0.45 },
{ th: 38, tx: 0.30, tz: 0.42 },
{ th: 45, tx: -0.25, tz: 0.20 },
{ th: 52, tx: 0.75, tz: -0.62 }
];
for (const b of BEAMS) {
const air = makeBeam('#ffe9bd', .40, .46, 1);
const wat = makeBeam('#9fe8ff', .34, .34, 1);
const sparkle = glowSprite('#fff4d6', .55, .85);
const caustic = new THREE.Mesh(new THREE.CircleGeometry(.34, 22), new THREE.MeshBasicMaterial({
color: 0xbfefff, transparent: true, opacity: .30, blending: THREE.AdditiveBlending, depthWrite: false }));
caustic.rotation.x = -Math.PI / 2;
sunGroup.add(air, wat, sparkle, caustic);
sunBeams.push({ b, air, wat, sparkle, caustic });
}
const sunGlow = glowSprite('#ffd9a0', 5.5, .5); sunGlow.position.set(-4.4, 4.6, -1.5); scene.add(sunGlow);
/* ───────────────────────── particles ───────────────────────── */
function motes(n, box, color, size, opacity) {
const pos = new Float32Array(n * 3), seed = new Float32Array(n);
for (let i = 0; i < n; i++) {
pos[i * 3] = box[0] + Math.random() * (box[3] - box[0]);
pos[i * 3 + 1] = box[1] + Math.random() * (box[4] - box[1]);
pos[i * 3 + 2] = box[2] + Math.random() * (box[5] - box[2]);
seed[i] = Math.random() * 6.28;
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setAttribute('aSeed', new THREE.Float32BufferAttribute(seed, 1));
const m = new THREE.ShaderMaterial({
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
uniforms: { uTime: { value: 0 }, uColor: { value: new THREE.Color(color) }, uSize: { value: size }, uOp: { value: opacity } },
vertexShader: `attribute float aSeed; uniform float uTime,uSize; varying float vA;
void main(){ vec3 p=position; p.y+=sin(uTime*.5+aSeed)*.18; p.x+=sin(uTime*.32+aSeed*1.7)*.1;
vec4 mv=modelViewMatrix*vec4(p,1.0); gl_PointSize=uSize*(14.0/-mv.z);
vA=.5+.5*sin(uTime*1.4+aSeed); gl_Position=projectionMatrix*mv; }`,
fragmentShader: `uniform vec3 uColor; uniform float uOp; varying float vA;
void main(){ float d=length(gl_PointCoord-.5); float a=smoothstep(.5,.05,d);
gl_FragColor=vec4(uColor,a*uOp*(.4+.6*vA)); }`
});
const p = new THREE.Points(g, m); p.frustumCulled = false; scene.add(p); return p;
}
const waterMotes = motes(320, [-HW, TANK_FLOOR, -HD, HW, SURF_Y, HD], '#bfefff', 2.0, .55);
const airMotes = motes(220, [-6, .2, -3, 2.5, 5.0, 1.5], '#ffe6b8', 1.7, .40);
/* ───────────────────────── optics ───────────────────────── */
function solveOptics() {
const D = state.depth, n = state.n, ex = EYE_X, ey = Math.max(state.eyeY, .15);
const f = px => Math.sin(Math.atan(px / D)) - Math.sin(Math.atan((ex - px) / ey)) / n;
let lo = 0, hi = ex;
for (let i = 0; i < 90; i++) { const mid = (lo + hi) / 2; if (f(mid) < 0) lo = mid; else hi = mid; }
const px = (lo + hi) / 2;
const thW = Math.atan(px / D), thA = Math.atan((ex - px) / ey);
const app = ey * px / Math.max(ex - px, 1e-4);
return { px, thW, thA, app, ex, ey };
}
/* ───────────────────────── update ───────────────────────── */
const cm = u => (u * U_TO_CM).toFixed(0) + ' cm';
let obsDirty = false;
function update() {
const o = solveOptics();
const D = state.depth;
const tipV = V3(0, -D, 0), P = V3(o.px, SURF_Y, 0), E = V3(EYE_X, state.eyeY, 0);
const G = V3(0, -o.app, 0);
/* marker */
tip.position.copy(tipV); tipGlow.position.copy(tipV);
const rodLen = Math.max(D + TANK_FLOOR, .01);
rod.scale.y = rodLen; rod.position.set(0, TANK_FLOOR + rodLen / 2, 0);
/* eye ray */
setBeam(rayWater, tipV, P, .34); setBeam(rayAir, P, E, .26);
const lp = rayLineW.geometry.attributes.position.array;
lp.set([tipV.x, tipV.y, tipV.z, P.x, P.y, P.z]); rayLineW.geometry.attributes.position.needsUpdate = true;
rayLineW.geometry.computeBoundingSphere();
const la = rayLineA.geometry.attributes.position.array;
la.set([P.x, P.y, P.z, E.x, E.y, E.z]); rayLineA.geometry.attributes.position.needsUpdate = true;
rayLineA.geometry.computeBoundingSphere();
/* virtual image + dashed extensions */
ghost.position.copy(G); ghostGlow.position.set(0, 0, 0);
const db = dashBack.geometry.attributes.position.array;
db.set([P.x, P.y, P.z, G.x, G.y, G.z]); dashBack.geometry.attributes.position.needsUpdate = true;
dashBack.geometry.computeBoundingSphere(); dashBack.computeLineDistances();
const dl = dashLift.geometry.attributes.position.array;
dl.set([G.x, G.y, G.z, tipV.x, tipV.y, tipV.z]); dashLift.geometry.attributes.position.needsUpdate = true;
dashLift.geometry.computeBoundingSphere(); dashLift.computeLineDistances();
dashBack.visible = dashLift.visible = state.app;
ghost.visible = state.app;
rp.position.copy(P); rpGlow.position.copy(P);
/* sunlight beams */
const n = state.n;
for (const s of sunBeams) {
const thA = s.b.th * Math.PI / 180;
const thW = Math.asin(Math.min(.999, Math.sin(thA) / n));
const tx = s.b.tx, tz = s.b.tz;
const Q = V3(tx - D * Math.tan(thW), SURF_Y, tz);
const S = V3(Q.x - 4.2 * Math.tan(thA), 4.2, tz);
const F = V3(tx + (TANK_FLOOR + D) * Math.tan(thW), TANK_FLOOR, tz);
setBeam(s.air, S, Q, .5); setBeam(s.wat, Q, F, .38);
s.sparkle.position.copy(Q);
s.caustic.position.set(F.x, TANK_FLOOR + .015, F.z);
s.caustic.material.opacity = .22 + .12 * Math.sin(performance.now() * .002 + s.b.th);
}
sunGroup.visible = state.sun;
/* HUD */
const ratio = o.app / D;
document.getElementById('r-actual').textContent = cm(D);
document.getElementById('r-app').textContent = cm(o.app);
document.getElementById('r-vert').textContent = cm(D / n);
document.getElementById('r-ang').textContent =
`${(o.thA * 180 / Math.PI).toFixed(0)}° → ${(o.thW * 180 / Math.PI).toFixed(0)}°`;
document.getElementById('bar-fill').style.width = (ratio * 100).toFixed(1) + '%';
document.getElementById('bar-lab').textContent =
`marker appears at ${(ratio * 100).toFixed(0)}% of its true depth (lifted ${cm(D - o.app)})`;
/* inset svg */
const s30 = 30, gy = 34 + (D / n) * s30, ay = 34 + D * s30;
document.getElementById('i-ghost').setAttribute('cy', gy);
document.getElementById('i-actual').setAttribute('cy', ay);
document.getElementById('i-dash').setAttribute('y2', ay);
document.getElementById('i-t1').setAttribute('y', gy + 4);
document.getElementById('i-t2').setAttribute('y', ay + 4);
/* labels anchors */
anchors.actual = tipV.clone();
anchors.ghost = G.clone();
anchors.point = P.clone();
anchors.eye = E.clone();
anchors.sun = V3(-1.6, 2.6, 0);
anchors.surface = V3(-2.1, SURF_Y, 0);
}
/* ───────────────────────── HTML labels ───────────────────────── */
const labelsRoot = document.getElementById('labels');
const anchors = {};
function mkLabel(key, cls = '') {
const d = document.createElement('div');
d.className = 'lab ' + cls; d.innerHTML = `<span>${key}</span>`;
labelsRoot.appendChild(d); return d;
}
const labActual = mkLabel('Marker · actual depth', 'am');
const labGhost = mkLabel('Virtual image · apparent');
const labPoint = mkLabel('Refraction point');
const labEye = mkLabel('Observer eye');
const labSun = mkLabel('Sunlight');
const labSurf = mkLabel('Water surface');
function project(v) {
const p = v.clone().project(camera);
return { x: (p.x * .5 + .5) * innerWidth, y: (-p.y * .5 + .5) * innerHeight, ok: p.z < 1 };
}
function place(el, v, dx = 0, dy = 0) {
const p = project(v);
el.style.left = (p.x + dx) + 'px';
el.style.top = (p.y + dy) + 'px';
el.style.display = (p.ok && state.labels) ? '' : 'none';
}
/* ───────────────────────── controls ───────────────────────── */
const sDepth = document.getElementById('s-depth'), sN = document.getElementById('s-n'), sEye = document.getElementById('s-eye');
const oDepth = document.getElementById('o-depth'), oN = document.getElementById('o-n'), oEye = document.getElementById('o-eye');
function syncLabels() {
oDepth.textContent = (state.depth * U_TO_CM).toFixed(0) + ' cm';
oN.textContent = state.n.toFixed(2);
oEye.textContent = (state.eyeY * U_TO_CM).toFixed(0) + ' cm';
}
sDepth.addEventListener('input', e => { state.depth = +e.target.value; syncLabels(); update(); });
sN.addEventListener('input', e => { state.n = +e.target.value; syncLabels(); update(); });
sEye.addEventListener('input', e => { state.eyeY = +e.target.value; obsDirty = true; syncLabels(); update(); });
document.getElementById('c-sun').addEventListener('change', e => { state.sun = e.target.checked; update(); });
document.getElementById('c-app').addEventListener('change', e => { state.app = e.target.checked; update(); });
document.getElementById('c-lab').addEventListener('change', e => { state.labels = e.target.checked; });
document.getElementById('reset').addEventListener('click', () => {
state.depth = 2.2; state.n = 1.33; state.eyeY = .9; state.sun = true; state.app = true; state.labels = true;
sDepth.value = 2.2; sN.value = 1.33; sEye.value = .9;
document.getElementById('c-sun').checked = document.getElementById('c-app').checked = document.getElementById('c-lab').checked = true;
obsDirty = true; syncLabels(); update();
});
/* ───────────────────────── manual orbit controls ───────────────────────── */
let dragging = false, px0 = 0, py0 = 0;
renderer.domElement.addEventListener('pointerdown', e => { dragging = true; px0 = e.clientX; py0 = e.clientY; renderer.domElement.setPointerCapture(e.pointerId); });
renderer.domElement.addEventListener('pointerup', e => { dragging = false; });
renderer.domElement.addEventListener('pointermove', e => {
if (!dragging) return;
orbit.tAz = THREE.MathUtils.clamp(orbit.tAz + (e.clientX - px0) * .004, -.55, .62);
orbit.tEl = THREE.MathUtils.clamp(orbit.tEl + (e.clientY - py0) * .003, -.05, .60);
px0 = e.clientX; py0 = e.clientY;
});
renderer.domElement.addEventListener('wheel', e => {
e.preventDefault();
orbit.tDist = THREE.MathUtils.clamp(orbit.tDist + e.deltaY * .008, 8.5, 19);
}, { passive: false });
/* ───────────────────────── loop ───────────────────────── */
const clock = new THREE.Clock();
let first = true;
function animate() {
requestAnimationFrame(animate);
const t = clock.getElapsedTime();
orbit.az += (orbit.tAz - orbit.az) * .12;
orbit.el += (orbit.tEl - orbit.el) * .12;
orbit.dist += (orbit.tDist - orbit.dist) * .1;
applyCamera();
if (obsDirty) { buildObserver(); obsDirty = false; }
surfMat.uniforms.uTime.value = t;
waterMotes.material.uniforms.uTime.value = t;
airMotes.material.uniforms.uTime.value = t;
rayWater.material.uniforms.uTime.value = t;
rayAir.material.uniforms.uTime.value = t;
for (const s of sunBeams) { s.air.material.uniforms.uTime.value = t; s.wat.material.uniforms.uTime.value = t; }
tipGlow.material.opacity = .5 + .12 * Math.sin(t * 2.2);
ghostGlow.material.opacity = .42 + .1 * Math.sin(t * 1.7);
rpGlow.material.opacity = .7 + .2 * Math.sin(t * 3.1);
place(labActual, anchors.actual, 0, -30);
place(labGhost, anchors.ghost, 0, -30);
place(labPoint, anchors.point, 26, -12);
place(labEye, anchors.eye, 34, -14);
place(labSun, anchors.sun, -6, 0);
place(labSurf, anchors.surface, -8, -16);
labGhost.textContent = `Virtual image · apparent ${(anchors.ghost ? (state.depth * U_TO_CM) : 0) ? '' : ''}`;
labGhost.firstChild.textContent = `Virtual image · apparent ${(Math.abs(anchors.ghost.y) * U_TO_CM).toFixed(0)} cm`;
labActual.firstChild.textContent = `Marker · actual ${(state.depth * U_TO_CM).toFixed(0)} cm`;
renderer.render(scene, camera);
if (first) { first = false; document.getElementById('loading').style.display = 'none'; }
}
syncLabels(); update(); animate();
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
</script>
</body>
</html>
```
**What it shows**
- **A glass tank** with an animated water surface, a glowing survey‑marker staff on the bottom, a depth ruler on the back wall, and a stylized observer standing beside the tank.
- **The eye ray** is traced from the marker tip to the surface and out to the observer's eye, bending at the surface according to Snell's law (solved numerically each frame, so it stays correct as you change depth, index, or eye height).
- **The apparent depth** is the virtual image: the refracted ray is extended backward (dashed) to meet the vertical through the marker — the observer sees the marker lifted. A second dashed line shows the "lift" between the real and virtual positions.
- **Stylized light rays** enter from the upper left, bend toward the normal on entering the water, converge on the marker, and paint animated caustics on the tank floor.
- **Readouts**: actual depth, apparent depth, the vertical‑view limit `D/n` (≈75 % for water), and the air/water angles — plus a small SVG inset showing the classic top‑down case where the apparent depth is exactly `D/n`.
- Sliders for marker depth, refractive index and eye height; toggles for sunlight, the virtual image and labels; drag‑to‑orbit and scroll‑to‑zoom camera implemented directly in the file (no addons).
```