Prompt specification
Build or customize the Three.js 3D scene "Observer-centered rainbow cone" 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: Observer-centered rainbow cone
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/observer-centered-rainbow-cone-x1238
Scene Description Prompt:
Observer-centered rainbow cone. Place a viewer marker opposite a Sun arrow and an arc of droplets; show that visible rainbow positions depend on viewing geometry rather than fixed colored objects. Please build this with Three.js from cdnjs in one self-contained HTML file, using stylized solid shapes.
Working Three.js Starter (observer-centered-rainbow-cone-x1238):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Observer-Centered Rainbow Cone</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(8, 19, 34, 0.86);
--panel-border: rgba(154, 218, 255, 0.18);
--text: #e8f5ff;
--muted: #91abc0;
--cyan: #68e5ff;
--amber: #ffd166;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #071321;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel,
.controls {
position: absolute;
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
border-radius: 16px;
}
.panel {
top: 20px;
left: 20px;
width: min(390px, calc(100vw - 40px));
padding: 19px 20px 17px;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 8px 0 8px;
font-size: clamp(24px, 3vw, 34px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.panel p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.status {
display: flex;
align-items: flex-start;
gap: 9px;
margin-top: 14px;
padding: 10px 11px;
border: 1px solid rgba(104, 229, 255, 0.18);
border-radius: 10px;
background: rgba(62, 196, 228, 0.07);
color: #c9f3ff;
font-size: 12px;
line-height: 1.42;
}
.status::before {
content: "";
flex: 0 0 8px;
width: 8px;
height: 8px;
margin-top: 3px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.status.off {
border-color: rgba(255, 209, 102, 0.22);
background: rgba(255, 209, 102, 0.07);
color: #ffe6a7;
}
.status.off::before {
background: var(--amber);
box-shadow: 0 0 12px var(--amber);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 15px;
margin-top: 13px;
color: #a9bfd0;
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 50%;
background: #b9d9e7;
box-shadow: inset -2px -2px 3px rgba(0, 0, 0, 0.22);
}
.spectrum {
width: 30px;
height: 7px;
border-radius: 8px;
background: linear-gradient(
90deg,
#ff4141,
#ff9b32,
#ffe04b,
#65db58,
#3498ff,
#8b5cff
);
}
.controls {
left: 20px;
bottom: 20px;
width: 330px;
padding: 15px 16px 13px;
}
.control-row + .control-row {
margin-top: 12px;
}
.control-label {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 6px;
color: #d6e9f5;
font-size: 12px;
font-weight: 650;
}
output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
.control-footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-top: 12px;
padding-top: 10px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
button {
flex: 0 0 auto;
padding: 6px 10px;
border: 1px solid rgba(104, 229, 255, 0.25);
border-radius: 8px;
background: rgba(104, 229, 255, 0.08);
color: #dcf8ff;
font: inherit;
font-size: 10px;
cursor: pointer;
}
button:hover {
background: rgba(104, 229, 255, 0.16);
}
#inset-frame {
position: absolute;
border: 1px solid rgba(157, 223, 255, 0.34);
border-radius: 13px;
box-shadow:
0 16px 45px rgba(0, 0, 0, 0.32),
inset 0 0 0 1px rgba(255, 255, 255, 0.025);
pointer-events: none;
overflow: hidden;
}
#inset-frame::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
box-shadow: inset 0 0 45px rgba(2, 8, 16, 0.32);
pointer-events: none;
}
.inset-title {
position: absolute;
z-index: 2;
top: 0;
left: 0;
right: 0;
padding: 8px 10px;
background: linear-gradient(rgba(4, 12, 23, 0.82), transparent);
color: #dff7ff;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.15em;
}
.inset-note {
position: absolute;
z-index: 2;
right: 8px;
bottom: 7px;
padding: 4px 7px;
border-radius: 6px;
background: rgba(4, 12, 23, 0.65);
color: #b8d1df;
font-size: 9px;
}
.scene-label {
position: absolute;
z-index: 3;
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 6px;
background: rgba(5, 14, 26, 0.78);
color: #d7ebf6;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
white-space: nowrap;
transform: translate(-50%, -50%);
pointer-events: none;
}
.scene-label.amber {
color: #ffe29b;
border-color: rgba(255, 209, 102, 0.25);
}
.scene-label.cyan {
color: #9defff;
border-color: rgba(104, 229, 255, 0.25);
}
@media (max-width: 700px) {
.panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 14px 15px;
}
.panel p {
font-size: 12px;
}
.legend,
.status {
display: none;
}
.controls {
left: 10px;
bottom: 10px;
width: calc(100vw - 20px);
padding: 12px 13px;
}
.scene-label {
font-size: 8px;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="hud">
<section class="panel">
<div class="eyebrow">Geometry Lab / Rainbow 01</div>
<h1>The rainbow is in the look.</h1>
<p>
The droplets are initially neutral. Their colors are computed from the
viewing geometry: sunlight enters the droplets, and only rays returning
to the eye at the rainbow angle become visible.
</p>
<div id="status" class="status">
Full circular rainbow is centered in the viewer’s gaze.
</div>
<div class="legend">
<span><i class="swatch"></i> neutral droplet</span>
<span><i class="spectrum"></i> computed visible return</span>
</div>
</section>
<section class="controls">
<div class="control-row">
<div class="control-label">
<span>Sun / antisolar azimuth</span>
<output id="sun-output">0°</output>
</div>
<input
id="sun-angle"
type="range"
min="-120"
max="120"
step="1"
value="0"
>
</div>
<div class="control-row">
<div class="control-label">
<span>Observer gaze</span>
<output id="gaze-output">0°</output>
</div>
<input
id="gaze-angle"
type="range"
min="-120"
max="120"
step="1"
value="0"
>
</div>
<div class="control-footer">
<span>
Drag to orbit · wheel to zoom<br>
Band thickness is exaggerated for clarity.
</span>
<button id="reset" type="button">Reset</button>
</div>
</section>
<div id="inset-frame">
<div class="inset-title">VIEW THROUGH THE VIEWER</div>
<div class="inset-note">90° schematic field</div>
</div>
<div id="label-sun" class="scene-label amber">SUN</div>
<div id="label-viewer" class="scene-label cyan">VIEWER</div>
<div id="label-droplets" class="scene-label">DROPLETS</div>
<div id="label-cone" class="scene-label cyan">42° RAINBOW CONE</div>
<div id="label-return" class="scene-label">RETURN TO THE EYE</div>
</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 canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.setClearColor(0x071321, 1);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071321);
const camera = new THREE.PerspectiveCamera(
44,
window.innerWidth / window.innerHeight,
0.05,
80
);
const observerCamera = new THREE.PerspectiveCamera(
90,
1.5,
0.05,
40
);
const hemisphere = new THREE.HemisphereLight(0xc7efff, 0x142238, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.8);
keyLight.position.set(7, 10, 8);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58bfff, 1.4);
rimLight.position.set(-8, 3, -5);
scene.add(rimLight);
const Z_AXIS = new THREE.Vector3(0, 0, 1);
const Y_AXIS = new THREE.Vector3(0, 1, 0);
const OBSERVER = new THREE.Vector3(0, 0, 0);
const antiSolar = new THREE.Vector3(0, 0, 1);
const gazeDirection = new THREE.Vector3(0, 0, 1);
// ---------------------------------------------------------------------
// Optical model
//
// For a primary rainbow:
// sin(i) = sqrt((4 - n²) / 3)
// r = asin(sin(i) / n)
// scattering angle = π + 2i - 4r
// rainbow angle from the antisolar axis = π - scattering angle
//
// Wavelength-dependent refractive indices make the rings distinct.
// ---------------------------------------------------------------------
const wavelengthBands = [
[700, 0xff4141],
[640, 0xff872e],
[585, 0xffdf3d],
[545, 0x62dc50],
[490, 0x32b7ff],
[440, 0x7769ff],
[410, 0xc25cff]
];
const physicalMid =
(
rainbowAngleForIndex(1.318 + 0.010 / 0.700) +
rainbowAngleForIndex(1.318 + 0.010 / 0.410)
) / 2;
// The real red-violet radial separation is narrow. This factor expands
// the droplet band without changing its center or viewing dependence.
const BAND_EXAGGERATION = 2.15;
const bandMeta = wavelengthBands.map(([nanometers, color]) => {
const micrometers = nanometers / 1000;
const refractiveIndex = 1.318 + 0.010 / micrometers;
const physicalAngle = rainbowAngleForIndex(refractiveIndex);
return {
nanometers,
color: new THREE.Color(color),
refractiveIndex,
physicalAngle,
displayAngle:
physicalMid +
(physicalAngle - physicalMid) * BAND_EXAGGERATION
};
});
function rainbowAngleForIndex(n) {
const sinIncidenceSquared = (4 - n * n) / 3;
const incidence = Math.asin(
Math.sqrt(THREE.MathUtils.clamp(sinIncidenceSquared, 0, 1))
);
const refraction = Math.asin(
Math.sin(incidence) / n
);
const scatteringAngle =
Math.PI + 2 * incidence - 4 * refraction;
return Math.PI - scatteringAngle;
}
// ---------------------------------------------------------------------
// Optical group: local +Z is the antisolar axis.
// The Sun is opposite the observer on local -Z.
// ---------------------------------------------------------------------
const opticalGroup = new THREE.Group();
opticalGroup.position.copy(OBSERVER);
scene.add(opticalGroup);
const dropletDistance = 7.2;
const coneHeight = 6.4;
const outerDisplayAngle = Math.max(
...bandMeta.map((band) => band.displayAngle)
);
const coneRadius =
Math.tan(outerDisplayAngle) * coneHeight;
// Translucent, stylized cone shell.
const coneGeometry = new THREE.ConeGeometry(
coneRadius,
coneHeight,
64,
1,
true
);
coneGeometry.rotateX(-Math.PI / 2);
const coneMaterial = new THREE.MeshBasicMaterial({
color: 0x5fc7ef,
transparent: true,
opacity: 0.085,
side: THREE.DoubleSide,
depthWrite: false
});
const cone = new THREE.Mesh(coneGeometry, coneMaterial);
cone.position.z = coneHeight / 2;
opticalGroup.add(cone);
// Cone edge lines.
const coneEdgeMaterial = new THREE.LineBasicMaterial({
color: 0x68d9ff,
transparent: true,
opacity: 0.38
});
for (const angle of [0, Math.PI / 2]) {
const points = [
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(
Math.cos(angle) * coneRadius,
Math.sin(angle) * coneRadius,
coneHeight
)
];
const edge = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
coneEdgeMaterial
);
opticalGroup.add(edge);
}
const baseRingPoints = [];
for (let i = 0; i <= 96; i++) {
const angle = (i / 96) * Math.PI * 2;
baseRingPoints.push(
new THREE.Vector3(
Math.cos(angle) * coneRadius,
Math.sin(angle) * coneRadius,
coneHeight
)
);
}
opticalGroup.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(baseRingPoints),
coneEdgeMaterial
)
);
// Dashed antisolar axis.
const axis = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0, 0, 7.3)
]),
new THREE.LineDashedMaterial({
color: 0xa8e7ff,
dashSize: 0.16,
gapSize: 0.11,
transparent: true,
opacity: 0.5
})
);
axis.computeLineDistances();
opticalGroup.add(axis);
// ---------------------------------------------------------------------
// Neutral droplets, arranged as concentric rainbow-angle arcs.
// Their instance colors are assigned from geometry every update.
// ---------------------------------------------------------------------
const segmentsPerBand = 84;
const dropletCount = bandMeta.length * segmentsPerBand;
const dropletGeometry = new THREE.SphereGeometry(0.11, 10, 8);
const dropletMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.34,
metalness: 0.08
});
const droplets = new THREE.InstancedMesh(
dropletGeometry,
dropletMaterial,
dropletCount
);
const dummy = new THREE.Object3D();
const neutralDropletColor = new THREE.Color(0xb9d9e7);
const workingColor = new THREE.Color();
let dropletIndex = 0;
for (const band of bandMeta) {
band.positions = [];
const theta = band.displayAngle;
for (let segment = 0; segment < segmentsPerBand; segment++) {
const phi = (segment / segmentsPerBand) * Math.PI * 2;
const position = new THREE.Vector3(
dropletDistance * Math.sin(theta) * Math.cos(phi),
dropletDistance * Math.sin(theta) * Math.sin(phi),
dropletDistance * Math.cos(theta)
);
band.positions.push(position);
dummy.position.copy(position);
dummy.updateMatrix();
droplets.setMatrixAt(dropletIndex, dummy.matrix);
droplets.setColorAt(dropletIndex, neutralDropletColor);
dropletIndex++;
}
}
droplets.instanceMatrix.setUsage(THREE.StaticDrawUsage);
droplets.instanceColor.setUsage(THREE.DynamicDrawUsage);
droplets.instanceColor.needsUpdate = true;
opticalGroup.add(droplets);
// ---------------------------------------------------------------------
// Sun and incoming sunlight arrow
// ---------------------------------------------------------------------
const sunGroup = new THREE.Group();
sunGroup.position.z = -6.25;
opticalGroup.add(sunGroup);
const sun = new THREE.Mesh(
new THREE.SphereGeometry(0.72, 28, 20),
new THREE.MeshStandardMaterial({
color: 0xffcf58,
emissive: 0xff9f22,
emissiveIntensity: 2.2,
roughness: 0.48
})
);
sunGroup.add(sun);
const sunHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.98, 0.055, 8, 48),
new THREE.MeshStandardMaterial({
color: 0xffdf83,
emissive: 0xffa52d,
emissiveIntensity: 1.2,
roughness: 0.55
})
);
sunGroup.add(sunHalo);
const sunlight = new THREE.PointLight(0xffd36a, 16, 10, 2);
sunlight.position.z = 0.5;
sunGroup.add(sunlight);
const arrowShaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.055, 2.85, 12),
new THREE.MeshStandardMaterial({
color: 0xffd65b,
emissive: 0xff9f22,
emissiveIntensity: 0.75,
roughness: 0.5
})
);
arrowShaft.rotation.x = Math.PI / 2;
arrowShaft.position.z = -3.72;
opticalGroup.add(arrowShaft);
const arrowHead = new THREE.Mesh(
new THREE.ConeGeometry(0.24, 0.56, 16),
new THREE.MeshStandardMaterial({
color: 0xffd65b,
emissive: 0xff9f22,
emissiveIntensity: 0.6,
roughness: 0.5
})
);
arrowHead.rotation.x = Math.PI / 2;
arrowHead.position.z = -2.02;
opticalGroup.add(arrowHead);
// ---------------------------------------------------------------------
// One example ray: parallel incoming sunlight and a return ray to the eye.
// ---------------------------------------------------------------------
const selectedLocal = bandMeta[0].positions[8].clone();
const incomingStart = selectedLocal.clone();
incomingStart.z -= 5.6;
const incomingTube = new THREE.Mesh(
new THREE.TubeGeometry(
new THREE.LineCurve3(incomingStart, selectedLocal),
24,
0.025,
6,
false
),
new THREE.MeshStandardMaterial({
color: 0xffd45c,
emissive: 0xffa526,
emissiveIntensity: 0.45,
roughness: 0.55
})
);
const returnTube = new THREE.Mesh(
new THREE.TubeGeometry(
new THREE.LineCurve3(selectedLocal, new THREE.Vector3()),
24,
0.034,
6,
false
),
new THREE.MeshStandardMaterial({
color: bandMeta[0].color,
emissive: bandMeta[0].color,
emissiveIntensity: 0.42,
roughness: 0.38
})
);
const rayPathGroup = new THREE.Group();
rayPathGroup.add(incomingTube, returnTube);
opticalGroup.add(rayPathGroup);
// ---------------------------------------------------------------------
// Observer marker: a stylized solid eye at the cone apex.
// ---------------------------------------------------------------------
const viewerHardware = new THREE.Group();
scene.add(viewerHardware);
const eyeGroup = new THREE.Group();
viewerHardware.add(eyeGroup);
const eyeWhite = new THREE.Mesh(
new THREE.SphereGeometry(1, 32, 20),
new THREE.MeshStandardMaterial({
color: 0xe8f7ff,
roughness: 0.38,
metalness: 0.02
})
);
eyeWhite.scale.set(0.56, 0.35, 0.3);
eyeGroup.add(eyeWhite);
const iris = new THREE.Mesh(
new THREE.SphereGeometry(1, 24, 16),
new THREE.MeshStandardMaterial({
color: 0x35c8ef,
emissive: 0x0c6f8a,
emissiveIntensity: 0.6,
roughness: 0.28
})
);
iris.scale.set(0.18, 0.18, 0.1);
iris.position.z = 0.265;
eyeGroup.add(iris);
const pupil = new THREE.Mesh(
new THREE.SphereGeometry(1, 20, 14),
new THREE.MeshBasicMaterial({ color: 0x07111b })
);
pupil.scale.set(0.075, 0.075, 0.055);
pupil.position.z = 0.345;
eyeGroup.add(pupil);
const eyeRing = new THREE.Mesh(
new THREE.TorusGeometry(0.72, 0.035, 8, 48),
new THREE.MeshStandardMaterial({
color: 0x68e5ff,
emissive: 0x197b92,
emissiveIntensity: 0.7,
roughness: 0.36
})
);
eyeGroup.add(eyeRing);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.55, 0.45, 24),
new THREE.MeshStandardMaterial({
color: 0x24465d,
roughness: 0.72,
metalness: 0.08
})
);
pedestal.position.y = -0.54;
viewerHardware.add(pedestal);
const gazeArrow = new THREE.ArrowHelper(
gazeDirection,
OBSERVER,
2.25,
0x68e5ff,
0.32,
0.17
);
scene.add(gazeArrow);
// ---------------------------------------------------------------------
// Custom camera controls: no addons.
// ---------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0, 2.0);
const cameraState = {
radius: 15,
theta: 0.75,
phi: 1.08
};
function updateMainCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraTarget.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraTarget.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraTarget.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse" && event.button !== 0) return;
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.006,
0.23,
Math.PI - 0.23
);
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
8,
28
);
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Optical controls and computed droplet colors
// ---------------------------------------------------------------------
const sunInput = document.querySelector("#sun-angle");
const gazeInput = document.querySelector("#gaze-angle");
const sunOutput = document.querySelector("#sun-output");
const gazeOutput = document.querySelector("#gaze-output");
const status = document.querySelector("#status");
const resetButton = document.querySelector("#reset");
const VIEW_FOV = 90;
function updateDropletColors() {
let index = 0;
for (const band of bandMeta) {
const theoreticalScattering = Math.PI - band.physicalAngle;
for (const position of band.positions) {
const localDirection = position.clone().normalize();
const displayedAngle = Math.acos(
THREE.MathUtils.clamp(localDirection.z, -1, 1)
);
// Undo the visual band expansion before comparing with Snell's law.
const compressedAngle =
physicalMid +
(displayedAngle - physicalMid) / BAND_EXAGGERATION;
const actualScattering = Math.PI - compressedAngle;
const opticalError = Math.abs(
actualScattering - theoreticalScattering
);
const worldDirection = localDirection
.clone()
.applyQuaternion(opticalGroup.quaternion);
const angleFromGaze = Math.acos(
THREE.MathUtils.clamp(
worldDirection.dot(gazeDirection),
-1,
1
)
);
const viewFade =
1 -
THREE.MathUtils.smoothstep(
angleFromGaze,
THREE.MathUtils.degToRad(40),
THREE.MathUtils.degToRad(48)
);
workingColor.copy(neutralDropletColor);
if (opticalError < 0.0025 && viewFade > 0) {
workingColor.lerp(band.color, viewFade);
}
droplets.setColorAt(index, workingColor);
index++;
}
}
droplets.instanceColor.needsUpdate = true;
}
function updateOptics() {
const sunDegrees = Number(sunInput.value);
const gazeDegrees = Number(gazeInput.value);
sunOutput.textContent = `${sunDegrees}°`;
gazeOutput.textContent = `${gazeDegrees}°`;
const sunAngle = THREE.MathUtils.degToRad(sunDegrees);
const gazeAngle = THREE.MathUtils.degToRad(gazeDegrees);
// Moving the Sun moves the antisolar axis to the opposite side.
antiSolar
.set(Math.sin(sunAngle), 0, Math.cos(sunAngle))
.normalize();
// Observer gaze is absolute, so it does not automatically follow the Sun.
gazeDirection
.set(Math.sin(gazeAngle), 0, Math.cos(gazeAngle))
.normalize();
opticalGroup.quaternion.setFromUnitVectors(Z_AXIS, antiSolar);
opticalGroup.updateMatrixWorld(true);
eyeGroup.quaternion.setFromUnitVectors(Z_AXIS, gazeDirection);
gazeArrow.position.copy(OBSERVER);
gazeArrow.setDirection(gazeDirection);
gazeArrow.setLength(2.25, 0.32, 0.17);
observerCamera.position.copy(OBSERVER);
observerCamera.lookAt(
OBSERVER.clone().addScaledVector(gazeDirection, 10)
);
updateDropletColors();
const offset = Math.acos(
THREE.MathUtils.clamp(
antiSolar.dot(gazeDirection),
-1,
1
)
);
const offsetDegrees = THREE.MathUtils.radToDeg(offset);
const visible = offsetDegrees < 98;
status.classList.toggle("off", !visible);
if (!visible) {
status.textContent =
"The computed rainbow is outside the viewer’s current field of view.";
} else if (offsetDegrees < 7) {
status.textContent =
"Full circular rainbow is centered in the viewer’s gaze.";
} else {
status.textContent =
`Rainbow center is ${offsetDegrees.toFixed(0)}° off-axis; ` +
"only a partial arc is visible.";
}
}
sunInput.addEventListener("input", updateOptics);
gazeInput.addEventListener("input", updateOptics);
resetButton.addEventListener("click", () => {
sunInput.value = "0";
gazeInput.value = "0";
cameraState.radius = 15;
cameraState.theta = 0.75;
cameraState.phi = 1.08;
updateOptics();
});
// ---------------------------------------------------------------------
// Projected scene labels
// ---------------------------------------------------------------------
const labelElements = {
sun: document.querySelector("#label-sun"),
viewer: document.querySelector("#label-viewer"),
droplets: document.querySelector("#label-droplets"),
cone: document.querySelector("#label-cone"),
returnRay: document.querySelector("#label-return")
};
function positionLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.08 &&
projected.x < 1.08 &&
projected.y > -1.08 &&
projected.y < 1.08;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateLabels() {
const sunWorld = sun.getWorldPosition(new THREE.Vector3());
sunWorld.y += 0.95;
const viewerWorld = OBSERVER.clone();
viewerWorld.y += 0.85;
const dropletWorld = opticalGroup.localToWorld(
selectedLocal.clone().add(new THREE.Vector3(0, 0.35, 0))
);
const coneWorld = opticalGroup.localToWorld(
new THREE.Vector3(2.15, 1.55, 3.4)
);
const returnWorld = opticalGroup.localToWorld(
selectedLocal.clone().multiplyScalar(0.52)
);
returnWorld.y += 0.25;
positionLabel(labelElements.sun, sunWorld);
positionLabel(labelElements.viewer, viewerWorld);
positionLabel(labelElements.droplets, dropletWorld);
positionLabel(labelElements.cone, coneWorld);
positionLabel(labelElements.returnRay, returnWorld);
}
// ---------------------------------------------------------------------
// Responsive main viewport and observer-view inset
// ---------------------------------------------------------------------
const insetFrame = document.querySelector("#inset-frame");
let insetX = 0;
let insetY = 0;
let insetWidth = 0;
let insetHeight = 0;
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
const mobile = width < 700;
insetWidth = mobile
? Math.min(250, width - 24)
: Math.min(340, width * 0.34);
insetHeight = Math.round(insetWidth * 0.66);
insetX = width - insetWidth - 14;
let frameTop;
if (mobile) {
frameTop = Math.max(
12,
Math.min(220, height - insetHeight - 12)
);
insetY = height - insetHeight - frameTop;
} else {
insetY = 20;
frameTop = height - insetHeight - 20;
}
insetFrame.style.left = `${insetX}px`;
insetFrame.style.top = `${frameTop}px`;
insetFrame.style.width = `${insetWidth}px`;
insetFrame.style.height = `${insetHeight}px`;
observerCamera.aspect = insetWidth / insetHeight;
observerCamera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
// ---------------------------------------------------------------------
// Render loop
// ---------------------------------------------------------------------
function render() {
requestAnimationFrame(render);
updateMainCamera();
updateLabels();
// Main schematic view.
renderer.setScissorTest(false);
renderer.setViewport(0, 0, window.innerWidth, window.innerHeight);
renderer.clear(true, true, true);
renderer.render(scene, camera);
// Observer view. Hide the observer hardware and ray-path helpers so
// they cannot obscure the view from inside the eye.
viewerHardware.visible = false;
gazeArrow.visible = false;
rayPathGroup.visible = false;
renderer.setScissorTest(true);
renderer.setScissor(insetX, insetY, insetWidth, insetHeight);
renderer.setViewport(insetX, insetY, insetWidth, insetHeight);
renderer.clear(true, true, true);
renderer.render(scene, observerCamera);
viewerHardware.visible = true;
gazeArrow.visible = true;
rayPathGroup.visible = true;
renderer.setScissorTest(false);
renderer.setViewport(
0,
0,
window.innerWidth,
window.innerHeight
);
}
resize();
updateOptics();
updateMainCamera();
render();
</script>
</body>
</html>
```