Prompt specification
Build or customize the Three.js 3D scene "Overlapping leaf light interception" 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: Overlapping leaf light interception
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/overlapping-leaf-light-interception-x0721
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring forest-canopy light competition. Place two broad leaves at different heights under parallel light rays; show the upper leaf's shadow reducing the illuminated area on the lower leaf. Stylized solid forms.
Working Three.js Starter (overlapping-leaf-light-interception-x0721):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Canopy — Light Competition</title>
<style>
:root {
color-scheme: dark;
--cream: #f4f0dc;
--muted: #a8b9aa;
--gold: #ffd474;
--green: #77d69b;
--panel: rgba(8, 25, 17, 0.76);
--line: rgba(207, 236, 210, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07160f;
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;
cursor: grab;
}
canvas.dragging {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 35%, rgba(1, 10, 6, 0.38) 100%),
linear-gradient(180deg, rgba(2, 13, 8, 0.15), transparent 28%);
z-index: 2;
}
.panel {
position: fixed;
z-index: 5;
pointer-events: none;
color: var(--cream);
}
.intro {
top: 28px;
left: 30px;
width: min(390px, calc(100vw - 60px));
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: var(--gold);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 24px;
height: 1px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
h1 {
margin: 0;
font-size: clamp(30px, 4.5vw, 58px);
font-weight: 520;
line-height: 0.98;
letter-spacing: -0.045em;
}
.intro p {
max-width: 355px;
margin: 15px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.65;
}
.metric {
top: 28px;
right: 30px;
min-width: 190px;
padding: 16px 18px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
backdrop-filter: blur(14px);
box-shadow: 0 15px 45px rgba(0, 0, 0, 0.22);
}
.metric-label {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.metric-value {
display: block;
margin-top: 5px;
color: var(--green);
font-size: 30px;
font-weight: 650;
letter-spacing: -0.04em;
}
.metric-note {
display: block;
margin-top: 2px;
color: #7f9787;
font-size: 10px;
}
.legend {
bottom: 28px;
left: 30px;
display: flex;
gap: 20px;
padding: 13px 16px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel);
backdrop-filter: blur(14px);
color: var(--muted);
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
white-space: nowrap;
}
.swatch {
width: 17px;
height: 3px;
border-radius: 3px;
background: var(--green);
box-shadow: 0 0 8px rgba(119, 214, 155, 0.35);
}
.swatch.ray {
background: var(--gold);
box-shadow: 0 0 8px rgba(255, 212, 116, 0.45);
}
.swatch.shade {
height: 9px;
border-radius: 3px;
background: #15583b;
box-shadow: none;
}
.controls {
position: fixed;
right: 30px;
bottom: 28px;
z-index: 6;
display: flex;
align-items: center;
gap: 8px;
}
button {
appearance: none;
border: 1px solid var(--line);
border-radius: 9px;
padding: 10px 13px;
background: rgba(8, 25, 17, 0.78);
color: var(--cream);
font: inherit;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
cursor: pointer;
backdrop-filter: blur(12px);
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
button:hover {
border-color: rgba(255, 212, 116, 0.5);
background: rgba(18, 47, 31, 0.88);
}
button:active {
transform: translateY(1px);
}
button.active {
border-color: rgba(255, 212, 116, 0.55);
color: var(--gold);
}
.hint {
position: fixed;
right: 30px;
bottom: 76px;
z-index: 5;
color: rgba(184, 204, 189, 0.58);
font-size: 9px;
letter-spacing: 0.06em;
pointer-events: none;
}
#markers {
position: fixed;
inset: 0;
z-index: 4;
pointer-events: none;
overflow: hidden;
}
.marker {
position: absolute;
display: flex;
align-items: center;
gap: 8px;
transform: translate(-50%, -50%);
white-space: nowrap;
filter: drop-shadow(0 5px 12px rgba(0, 0, 0, 0.45));
transition: opacity 120ms linear;
}
.marker-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border: 2px solid rgba(255, 255, 255, 0.78);
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px currentColor;
}
.marker.gold .marker-dot {
color: var(--gold);
background: var(--gold);
}
.marker.shade .marker-dot {
color: #3bbf79;
background: #26724c;
}
.marker-text {
padding: 7px 9px;
border: 1px solid rgba(219, 239, 221, 0.13);
border-radius: 8px;
background: rgba(5, 20, 12, 0.72);
backdrop-filter: blur(8px);
}
.marker-text b {
display: block;
color: var(--cream);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
}
.marker-text small {
display: block;
margin-top: 2px;
color: #91a795;
font-size: 9px;
}
@media (max-width: 720px) {
.intro {
top: 18px;
left: 18px;
}
.intro p {
display: none;
}
.metric {
top: 18px;
right: 18px;
min-width: 125px;
padding: 12px 13px;
}
.metric-value {
font-size: 24px;
}
.legend {
left: 18px;
bottom: 18px;
gap: 11px;
padding: 10px 12px;
}
.legend-item {
font-size: 9px;
}
.controls {
right: 18px;
bottom: 18px;
}
.hint,
#lowerMarker {
display: none;
}
button {
padding: 10px;
}
}
</style>
</head>
<body>
<main id="app" aria-label="Interactive forest canopy light competition scene"></main>
<div class="vignette"></div>
<section class="panel intro">
<div class="eyebrow">Forest Canopy Study</div>
<h1>Light<br />competition.</h1>
<p>
A higher broad leaf intercepts parallel sunlight before it reaches the
understory. Its cast shadow removes a measurable patch of direct light
from the lower leaf.
</p>
</section>
<section class="panel metric" aria-live="polite">
<span class="metric-label">Cast-shade coverage</span>
<strong class="metric-value" id="shadeNumber">—</strong>
<span class="metric-note">approx. area of lower leaf shaded</span>
</section>
<div id="markers">
<div class="marker gold" id="upperMarker">
<span class="marker-dot"></span>
<div class="marker-text">
<b>UPPER LEAF</b>
<small>intercepts direct light</small>
</div>
</div>
<div class="marker" id="lowerMarker">
<span class="marker-dot"></span>
<div class="marker-text">
<b>LOWER LEAF</b>
<small>receives filtered light</small>
</div>
</div>
<div class="marker shade" id="shadeMarker">
<span class="marker-dot"></span>
<div class="marker-text">
<b>CAST SHADE</b>
<small>direct light removed</small>
</div>
</div>
</div>
<section class="panel legend">
<div class="legend-item">
<span class="swatch ray"></span>
parallel sunlight
</div>
<div class="legend-item">
<span class="swatch"></span>
illuminated tissue
</div>
<div class="legend-item">
<span class="swatch shade"></span>
cast shade
</div>
</section>
<div class="hint">DRAG TO ORBIT · SCROLL TO ZOOM</div>
<div class="controls">
<button id="orbitButton" type="button">Auto orbit</button>
<button id="resetButton" type="button">Reset view</button>
</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 app = document.querySelector("#app");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute(
"aria-label",
"Two broad leaves at different heights, with parallel sunlight and a cast shadow"
);
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07160f);
scene.fog = new THREE.FogExp2(0x07160f, 0.032);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
60
);
const cameraTarget = new THREE.Vector3(0, 1.25, 0.15);
const defaultView = {
azimuth: 0.72,
polar: 1.10,
radius: 9.3
};
const view = { ...defaultView };
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(0xa9dfbd, 0x15271b, 1.15);
scene.add(hemisphere);
const sunlight = new THREE.DirectionalLight(0xffdfa0, 3.65);
sunlight.position.set(5.5, 10, -4.5);
sunlight.target.position.set(0, 0, 0);
sunlight.castShadow = true;
sunlight.shadow.mapSize.set(2048, 2048);
sunlight.shadow.camera.left = -7;
sunlight.shadow.camera.right = 7;
sunlight.shadow.camera.top = 7;
sunlight.shadow.camera.bottom = -7;
sunlight.shadow.camera.near = 1;
sunlight.shadow.camera.far = 28;
sunlight.shadow.bias = -0.00025;
sunlight.shadow.normalBias = 0.025;
sunlight.shadow.radius = 3;
scene.add(sunlight);
scene.add(sunlight.target);
const lightDirection = new THREE.Vector3()
.subVectors(sunlight.target.position, sunlight.position)
.normalize();
// -------------------------------------------------------------------------
// Ground and simplified forest surroundings
// -------------------------------------------------------------------------
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x0c2b1c,
roughness: 1,
metalness: 0
});
const ground = new THREE.Mesh(
new THREE.CircleGeometry(16, 64),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.03;
ground.receiveShadow = true;
scene.add(ground);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x183325,
roughness: 1,
flatShading: true
});
const canopyMaterials = [
new THREE.MeshStandardMaterial({
color: 0x123b25,
roughness: 1,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x19492c,
roughness: 1,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x0e3321,
roughness: 1,
flatShading: true
})
];
const backgroundTrees = [
{ x: -7.2, z: -5.5, h: 7.2, r: 0.48 },
{ x: -3.8, z: -8.2, h: 8.6, r: 0.57 },
{ x: 0.4, z: -9.5, h: 8.1, r: 0.52 },
{ x: 4.6, z: -8.0, h: 8.9, r: 0.6 },
{ x: 8.0, z: -5.1, h: 7.0, r: 0.47 },
{ x: -9.2, z: 0.8, h: 8.0, r: 0.55 }
];
backgroundTrees.forEach((tree, index) => {
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(
tree.r * 0.65,
tree.r,
tree.h,
7
),
trunkMaterial
);
trunk.position.set(tree.x, tree.h * 0.5, tree.z);
trunk.rotation.z = (index % 2 ? 1 : -1) * 0.035;
scene.add(trunk);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.9, 1),
canopyMaterials[index % canopyMaterials.length]
);
crown.position.set(tree.x, tree.h - 0.15, tree.z);
crown.scale.set(1.55, 0.72, 1.1);
crown.rotation.set(index * 0.31, index * 0.73, index * 0.18);
scene.add(crown);
});
// A few faceted stones make the floor read as a stylized forest floor.
const stoneMaterial = new THREE.MeshStandardMaterial({
color: 0x294436,
roughness: 0.95,
flatShading: true
});
[
[-4.3, -1.5, 0.46],
[4.5, -2.1, 0.35],
[-3.1, 2.8, 0.27],
[5.7, 1.9, 0.42]
].forEach(([x, z, size]) => {
const stone = new THREE.Mesh(
new THREE.IcosahedronGeometry(size, 0),
stoneMaterial
);
stone.position.set(x, size * 0.55, z);
stone.scale.set(1.25, 0.72, 0.9);
stone.rotation.set(x, z, 0.2);
stone.castShadow = true;
stone.receiveShadow = true;
scene.add(stone);
});
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
const upAxis = new THREE.Vector3(0, 1, 0);
function cylinderBetween(a, b, radius, material, radialSegments = 8) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments,
1,
false
),
material
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
upAxis,
direction.clone().normalize()
);
return mesh;
}
function makeLeafData(length, width) {
const first = new THREE.CubicBezierCurve(
new THREE.Vector2(-length * 0.5, 0),
new THREE.Vector2(-length * 0.33, -width * 0.50),
new THREE.Vector2(length * 0.22, -width * 0.56),
new THREE.Vector2(length * 0.5, 0)
);
const second = new THREE.CubicBezierCurve(
new THREE.Vector2(length * 0.5, 0),
new THREE.Vector2(length * 0.25, width * 0.56),
new THREE.Vector2(-length * 0.28, width * 0.50),
new THREE.Vector2(-length * 0.5, 0)
);
const outline = first
.getPoints(18)
.concat(second.getPoints(18).slice(1));
return { first, second, outline };
}
function makeLeaf({
length,
width,
depth,
position,
yaw,
color,
veinColor
}) {
const group = new THREE.Group();
group.position.copy(position);
group.rotation.y = yaw;
const data = makeLeafData(length, width);
const shape = new THREE.Shape();
shape.moveTo(data.first.v0.x, data.first.v0.y);
shape.bezierCurveTo(
data.first.v1.x,
data.first.v1.y,
data.first.v2.x,
data.first.v2.y,
data.first.v3.x,
data.first.v3.y
);
shape.bezierCurveTo(
data.second.v1.x,
data.second.v1.y,
data.second.v2.x,
data.second.v2.y,
data.second.v3.x,
data.second.v3.y
);
const geometry = new THREE.ExtrudeGeometry(shape, {
depth,
steps: 1,
curveSegments: 24,
bevelEnabled: true,
bevelSegments: 3,
bevelSize: 0.045,
bevelThickness: 0.035
});
geometry.translate(0, 0, -depth * 0.5);
geometry.rotateX(-Math.PI * 0.5);
geometry.computeVertexNormals();
const leafMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0
});
const leaf = new THREE.Mesh(geometry, leafMaterial);
leaf.castShadow = true;
leaf.receiveShadow = true;
group.add(leaf);
const veinMaterial = new THREE.MeshStandardMaterial({
color: veinColor,
roughness: 0.9,
metalness: 0
});
const top = depth * 0.5 + 0.065;
const midrib = cylinderBetween(
new THREE.Vector3(-length * 0.46, top, 0),
new THREE.Vector3(length * 0.46, top, 0),
0.022,
veinMaterial,
8
);
group.add(midrib);
const veinStations = [-0.25, -0.1, 0.06, 0.21];
veinStations.forEach((station, index) => {
const x = station * length;
const spread = width * (0.38 - Math.abs(station) * 0.12);
[-1, 1].forEach((side) => {
const branch = cylinderBetween(
new THREE.Vector3(x, top, 0),
new THREE.Vector3(
x + length * (index === 3 ? 0.08 : 0.115),
top,
side * spread
),
0.011,
veinMaterial,
6
);
group.add(branch);
});
});
scene.add(group);
return { group, data, leaf };
}
// -------------------------------------------------------------------------
// Main leaves
// -------------------------------------------------------------------------
const lowerPosition = new THREE.Vector3(0, 0.72, 0.65);
const upperPosition = new THREE.Vector3(0.74, 2.72, -0.05);
const lowerYaw = 0.06;
const upperYaw = -0.16;
const lowerLeaf = makeLeaf({
length: 4.5,
width: 2.1,
depth: 0.1,
position: lowerPosition,
yaw: lowerYaw,
color: 0x43ae72,
veinColor: 0xa8d77b
});
const upperLeaf = makeLeaf({
length: 3.1,
width: 1.45,
depth: 0.1,
position: upperPosition,
yaw: upperYaw,
color: 0x2a8959,
veinColor: 0x79bd69
});
// Support stems remain stylized and do not affect the shadow calculation.
const stemMaterial = new THREE.MeshStandardMaterial({
color: 0x416239,
roughness: 1
});
const lowerStem = cylinderBetween(
new THREE.Vector3(-2.21, 0.01, 0.78),
new THREE.Vector3(-2.17, 0.66, 0.77),
0.075,
stemMaterial,
7
);
scene.add(lowerStem);
const upperBranch = cylinderBetween(
new THREE.Vector3(-3.55, 1.55, -2.85),
new THREE.Vector3(-0.8, 2.62, -0.3),
0.085,
stemMaterial,
7
);
scene.add(upperBranch);
// -------------------------------------------------------------------------
// Parallel light-ray visualization
// -------------------------------------------------------------------------
const rayMaterial = new THREE.MeshBasicMaterial({
color: 0xffd36c,
transparent: true,
opacity: 0.34,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const raySamples = [
[-0.92, 0.08],
[-0.48, -0.33],
[-0.08, 0.28],
[0.28, -0.34],
[0.62, 0.18],
[0.92, -0.08],
[-0.35, 0.48],
[0.38, 0.46]
];
const rayTravel = (lowerPosition.y - upperPosition.y) / lightDirection.y;
raySamples.forEach(([localX, localZ]) => {
const hit = new THREE.Vector3(localX, 0, localZ)
.applyAxisAngle(upAxis, upperYaw)
.add(upperPosition);
hit.y = upperPosition.y + 0.115;
const aboveStart = hit.clone().addScaledVector(lightDirection, -2.35);
const aboveRay = cylinderBetween(
aboveStart,
hit,
0.013,
rayMaterial,
6
);
scene.add(aboveRay);
const belowStart = hit.clone().addScaledVector(lightDirection, 0.13);
const belowEnd = hit.clone().addScaledVector(lightDirection, rayTravel);
const belowRay = cylinderBetween(
belowStart,
belowEnd,
0.011,
rayMaterial,
6
);
scene.add(belowRay);
});
// -------------------------------------------------------------------------
// Polygon utilities for approximate cast-shade coverage
// -------------------------------------------------------------------------
function signedArea(poly) {
let area = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
area += a.x * b.z - b.x * a.z;
}
return area * 0.5;
}
function ensureCounterClockwise(poly) {
return signedArea(poly) < 0 ? [...poly].reverse() : poly;
}
function cross(ax, az, bx, bz) {
return ax * bz - az * bx;
}
function transformOutline(outline, position, yaw) {
return outline.map((point) => {
const v = new THREE.Vector3(point.x, 0, -point.y)
.applyAxisAngle(upAxis, yaw)
.add(position);
return { x: v.x, z: v.z };
});
}
function lineIntersection(p1, p2, a, b) {
const rx = p2.x - p1.x;
const rz = p2.z - p1.z;
const sx = b.x - a.x;
const sz = b.z - a.z;
const denominator = cross(rx, rz, sx, sz);
if (Math.abs(denominator) < 1e-9) return null;
const qx = a.x - p1.x;
const qz = a.z - p1.z;
const t = cross(qx, qz, sx, sz) / denominator;
return {
x: p1.x + rx * t,
z: p1.z + rz * t
};
}
function clipPolygon(subject, clipper) {
let output = [...subject];
for (let i = 0; i < clipper.length; i++) {
if (output.length === 0) break;
const a = clipper[i];
const b = clipper[(i + 1) % clipper.length];
const input = output;
output = [];
const inside = (p) =>
cross(
b.x - a.x,
b.z - a.z,
p.x - a.x,
p.z - a.z
) >= -1e-8;
for (let j = 0; j < input.length; j++) {
const previous = input[(j + input.length - 1) % input.length];
const current = input[j];
const previousInside = inside(previous);
const currentInside = inside(current);
if (currentInside) {
if (!previousInside) {
const intersection = lineIntersection(
previous,
current,
a,
b
);
if (intersection) output.push(intersection);
}
output.push(current);
} else if (previousInside) {
const intersection = lineIntersection(
previous,
current,
a,
b
);
if (intersection) output.push(intersection);
}
}
}
return output;
}
function polygonCentroid(poly) {
if (!poly.length) return { x: 0, z: 0 };
let area = 0;
let x = 0;
let z = 0;
for (let i = 0; i < poly.length; i++) {
const a = poly[i];
const b = poly[(i + 1) % poly.length];
const c = a.x * b.z - b.x * a.z;
area += c;
x += (a.x + b.x) * c;
z += (a.z + b.z) * c;
}
area *= 0.5;
if (Math.abs(area) < 1e-8) {
return {
x: poly.reduce((sum, p) => sum + p.x, 0) / poly.length,
z: poly.reduce((sum, p) => sum + p.z, 0) / poly.length
};
}
return {
x: x / (6 * area),
z: z / (6 * area)
};
}
const lowerPolygon = ensureCounterClockwise(
transformOutline(
lowerLeaf.data.outline,
lowerPosition,
lowerYaw
)
);
const upperProjected = transformOutline(
upperLeaf.data.outline,
upperPosition,
upperYaw
).map((point) => ({
x: point.x + lightDirection.x * rayTravel,
z: point.z + lightDirection.z * rayTravel
}));
const shadeIntersection = clipPolygon(
ensureCounterClockwise(upperProjected),
lowerPolygon
);
const lowerArea = Math.abs(signedArea(lowerPolygon));
const shadeArea = Math.abs(signedArea(shadeIntersection));
const shadeRatio = lowerArea > 0 ? shadeArea / lowerArea : 0;
document.querySelector("#shadeNumber").textContent =
`${Math.round(shadeRatio * 100)}%`;
const shadeCentroid = polygonCentroid(shadeIntersection);
const shadeAnchor = new THREE.Vector3(
shadeCentroid.x,
lowerPosition.y + 0.22,
shadeCentroid.z
);
// -------------------------------------------------------------------------
// Direct camera controls implemented without external addons
// -------------------------------------------------------------------------
let dragging = false;
let previousX = 0;
let previousY = 0;
let autoOrbit = false;
function updateCamera() {
const sinPolar = Math.sin(view.polar);
camera.position.set(
cameraTarget.x +
view.radius * sinPolar * Math.sin(view.azimuth),
cameraTarget.y + view.radius * Math.cos(view.polar),
cameraTarget.z +
view.radius * sinPolar * Math.cos(view.azimuth)
);
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
view.azimuth -= dx * 0.005;
view.polar = THREE.MathUtils.clamp(
view.polar - dy * 0.005,
0.43,
1.43
);
previousX = event.clientX;
previousY = event.clientY;
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event.pointerId !== undefined) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
view.radius = THREE.MathUtils.clamp(
view.radius * Math.exp(event.deltaY * 0.001),
6.2,
13.5
);
updateCamera();
},
{ passive: false }
);
document.querySelector("#resetButton").addEventListener("click", () => {
view.azimuth = defaultView.azimuth;
view.polar = defaultView.polar;
view.radius = defaultView.radius;
updateCamera();
});
const orbitButton = document.querySelector("#orbitButton");
orbitButton.addEventListener("click", () => {
autoOrbit = !autoOrbit;
orbitButton.classList.toggle("active", autoOrbit);
orbitButton.textContent = autoOrbit ? "Stop orbit" : "Auto orbit";
});
// -------------------------------------------------------------------------
// Projected HTML labels
// -------------------------------------------------------------------------
const upperMarker = document.querySelector("#upperMarker");
const lowerMarker = document.querySelector("#lowerMarker");
const shadeMarker = document.querySelector("#shadeMarker");
const upperAnchor = new THREE.Vector3(
upperPosition.x - 0.35,
upperPosition.y + 0.42,
upperPosition.z - 0.1
);
const lowerAnchor = new THREE.Vector3(
lowerPosition.x + 1.35,
lowerPosition.y + 0.25,
lowerPosition.z - 0.25
);
function placeMarker(element, worldPosition, offsetX, offsetY) {
const projected = worldPosition.clone().project(camera);
if (
projected.z < -1 ||
projected.z > 1 ||
projected.x < -1.4 ||
projected.x > 1.4 ||
projected.y < -1.4 ||
projected.y > 1.4
) {
element.style.opacity = "0";
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 + offsetX}px`;
element.style.top = `${y + offsetY}px`;
element.style.opacity = "1";
}
function updateMarkers() {
placeMarker(upperMarker, upperAnchor, 34, -28);
placeMarker(lowerMarker, lowerAnchor, 42, 28);
placeMarker(shadeMarker, shadeAnchor, -54, 36);
}
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
updateCamera();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
if (autoOrbit && !dragging) {
view.azimuth += delta * 0.09;
updateCamera();
}
rayMaterial.opacity = 0.29 + Math.sin(elapsed * 1.35) * 0.055;
updateMarkers();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```