Prompt specification
Build or customize the Three.js 3D scene "Streetlamp distance teaching scene" 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: Streetlamp distance teaching scene
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/streetlamp-distance-teaching-scene-x1555
Scene Description Prompt:
A voxel streetlamp illuminates ground markers beside a radial-spreading inset, separating distance, emission direction, and incidence-angle effects. Standalone HTML using Three.js from cdnjs.
Working Three.js Starter (streetlamp-distance-teaching-scene-x1555):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Beam Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07101b;
--panel: #0b1624;
--panel-2: #101e2e;
--line: #213449;
--text: #edf5ff;
--muted: #8fa4b9;
--cyan: #53d9f2;
--violet: #b49aff;
--green: #65e3ad;
--amber: #ffc96b;
--danger: #ff8e78;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
width: 100vw;
height: 100vh;
}
#stage {
position: relative;
min-width: 0;
overflow: hidden;
background:
radial-gradient(circle at 55% 35%, #14263a 0, #07101b 58%, #040a12 100%);
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.stage-heading {
position: absolute;
top: 28px;
left: 30px;
z-index: 4;
max-width: 430px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 9px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.stage-heading h1 {
margin: 0;
font-size: clamp(27px, 3vw, 43px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 1;
}
.stage-heading p {
max-width: 390px;
margin: 13px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.legend {
position: absolute;
left: 30px;
bottom: 28px;
z-index: 4;
display: flex;
flex-wrap: wrap;
gap: 8px;
max-width: 520px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid rgba(100, 133, 160, 0.23);
border-radius: 999px;
background: rgba(5, 12, 21, 0.72);
color: #b7c7d7;
font-size: 11px;
backdrop-filter: blur(8px);
}
.legend-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.legend-dot.cyan {
color: var(--cyan);
}
.legend-dot.amber {
color: var(--amber);
}
.legend-dot.green {
color: var(--green);
}
.stage-help {
position: absolute;
right: 24px;
bottom: 26px;
z-index: 4;
color: #6f879d;
font-size: 11px;
pointer-events: none;
}
.world-label {
position: absolute;
z-index: 3;
transform: translate(-50%, -100%);
padding: 5px 8px;
border: 1px solid rgba(255, 201, 107, 0.38);
border-radius: 5px;
background: rgba(8, 16, 26, 0.86);
color: var(--amber);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
pointer-events: none;
white-space: nowrap;
}
#lamp-label {
color: var(--cyan);
border-color: rgba(83, 217, 242, 0.32);
}
#panel {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 25px 24px 30px;
border-left: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(15, 29, 45, 0.97), rgba(8, 18, 30, 0.99));
box-shadow: -18px 0 50px rgba(0, 0, 0, 0.18);
scrollbar-width: thin;
scrollbar-color: #294057 transparent;
}
.panel-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 20px;
}
.panel-title h2 {
margin: 0 0 5px;
font-size: 18px;
letter-spacing: -0.02em;
}
.panel-title p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#reset {
flex: 0 0 auto;
padding: 7px 10px;
border: 1px solid #2a4055;
border-radius: 7px;
background: #102033;
color: #a9bdd0;
font-size: 11px;
cursor: pointer;
}
#reset:hover {
border-color: #47627d;
color: white;
}
.card {
margin-bottom: 16px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(13, 27, 42, 0.78);
}
.card-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
}
.card-heading strong {
font-size: 12px;
letter-spacing: 0.015em;
}
.card-heading span {
color: #6f879d;
font-size: 10px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.mode-tabs {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
margin-bottom: 10px;
}
.mode-btn {
min-width: 0;
padding: 8px 4px;
border: 1px solid #263b50;
border-radius: 7px;
background: #0c1a2a;
color: #8399ad;
font-size: 10px;
font-weight: 700;
cursor: pointer;
transition: 120ms ease;
}
.mode-btn:hover {
border-color: #426078;
color: white;
}
.mode-btn.active {
border-color: rgba(255, 201, 107, 0.55);
background: rgba(255, 201, 107, 0.11);
color: var(--amber);
}
#mode-description {
min-height: 31px;
margin: 0;
color: #8198ad;
font-size: 11px;
line-height: 1.45;
}
.radial-card {
padding-bottom: 12px;
}
#radial-svg {
display: block;
width: 100%;
height: auto;
margin-top: 2px;
overflow: visible;
}
.inset-caption {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 5px;
color: #6f879d;
font-size: 10px;
}
.inset-caption b {
color: #a7bbcc;
font-weight: 600;
}
.control {
margin-top: 17px;
}
.control:first-of-type {
margin-top: 0;
}
.control-top {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
}
.control label {
color: #c7d5e2;
font-size: 12px;
font-weight: 650;
}
.control output {
color: var(--amber);
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.control small {
display: block;
margin-top: 5px;
color: #6f879d;
font-size: 10px;
line-height: 1.35;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
outline: none;
appearance: none;
-webkit-appearance: none;
background: linear-gradient(
90deg,
var(--amber) 0%,
var(--amber) 50%,
#263c51 50%,
#263c51 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #0c1a2a;
border-radius: 50%;
appearance: none;
-webkit-appearance: none;
background: var(--amber);
box-shadow: 0 0 0 1px rgba(255, 201, 107, 0.6);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #0c1a2a;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 0 1px rgba(255, 201, 107, 0.6);
}
.beam-toggle {
display: flex;
align-items: center;
gap: 8px;
margin-top: 17px;
color: #8fa4b9;
font-size: 11px;
cursor: pointer;
}
.beam-toggle input {
accent-color: var(--amber);
}
.metric {
margin-top: 13px;
}
.metric-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 6px;
color: #9eb2c5;
font-size: 11px;
}
.metric-top b {
color: #dbe8f3;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.metric-track {
height: 5px;
overflow: hidden;
border-radius: 99px;
background: #192c3f;
}
.metric-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--cyan);
transition: width 120ms ease;
}
#distance-fill {
background: var(--cyan);
}
#direction-fill {
background: var(--violet);
}
#incidence-fill {
background: var(--green);
}
#combined-fill {
background: var(--amber);
}
.formula {
margin-top: 17px;
padding: 12px;
border: 1px dashed #2a4259;
border-radius: 8px;
background: rgba(4, 12, 21, 0.38);
color: #8fa4b9;
font-size: 11px;
line-height: 1.65;
}
.formula strong {
color: #dce8f2;
font-weight: 650;
}
.formula .distance {
color: var(--cyan);
}
.formula .direction {
color: var(--violet);
}
.formula .incidence {
color: var(--green);
}
#error-message {
position: absolute;
inset: 0;
z-index: 20;
display: none;
place-items: center;
padding: 30px;
background: #07101b;
color: #ffb3a5;
text-align: center;
}
@media (max-width: 900px) {
body {
overflow: auto;
}
#app {
grid-template-columns: 1fr;
height: auto;
}
#stage {
height: 62vh;
min-height: 460px;
}
#panel {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.stage-heading {
top: 20px;
left: 20px;
}
.legend {
left: 20px;
bottom: 18px;
}
.stage-help {
display: none;
}
}
</style>
</head>
<body>
<div id="app">
<main id="stage">
<div class="stage-heading">
<div class="eyebrow">Interactive optics study</div>
<h1>Voxel Beam Lab</h1>
<p>
Move the active ground marker, turn the lamp, and tilt its receiving
surface. Switch views to isolate each lighting factor.
</p>
</div>
<div id="active-label" class="world-label">ACTIVE PROBE</div>
<div id="lamp-label" class="world-label">VOXEL LAMP</div>
<div class="legend">
<div class="legend-item">
<span class="legend-dot amber"></span>
Active combined probe
</div>
<div class="legend-item">
<span class="legend-dot cyan"></span>
Distance-only references
</div>
<div class="legend-item">
<span class="legend-dot green"></span>
Surface normal
</div>
</div>
<div class="stage-help">
Drag to orbit · Shift/right-drag to pan · Wheel to zoom
</div>
</main>
<aside id="panel">
<div class="panel-title">
<div>
<h2>Lighting controls</h2>
<p>Independent factors, one visible response.</p>
</div>
<button id="reset" type="button">Reset</button>
</div>
<section class="card">
<div class="card-heading">
<strong>Display mode</strong>
<span>Solo / combined</span>
</div>
<div class="mode-tabs">
<button class="mode-btn active" data-mode="combined" type="button">
All
</button>
<button class="mode-btn" data-mode="distance" type="button">
Distance
</button>
<button class="mode-btn" data-mode="direction" type="button">
Direction
</button>
<button class="mode-btn" data-mode="incidence" type="button">
Incidence
</button>
</div>
<p id="mode-description">
Combined response multiplies attenuation, emission alignment, and
cosine incidence.
</p>
</section>
<section class="card radial-card">
<div class="card-heading">
<strong>Radial spread</strong>
<span>Plan view</span>
</div>
<svg id="radial-svg" viewBox="0 0 280 180" aria-label="Radial beam spread inset">
<defs>
<linearGradient id="wedge-gradient" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#ffc96b" stop-opacity="0.04" />
<stop offset="1" stop-color="#ffc96b" stop-opacity="0.28" />
</linearGradient>
<filter id="soft-glow" x="-100%" y="-100%" width="300%" height="300%">
<feGaussianBlur stdDeviation="3" result="blur" />
<feMerge>
<feMergeNode in="blur" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
<g fill="none" stroke="#263c51" stroke-width="1">
<circle cx="38" cy="91" r="35" />
<circle cx="38" cy="91" r="70" />
<circle cx="38" cy="91" r="105" />
<circle cx="38" cy="91" r="140" />
</g>
<g stroke="#1d3145" stroke-width="1" stroke-dasharray="3 5">
<path d="M38 10V171 M38 91H264" />
</g>
<path
id="inset-wedge"
d=""
fill="url(#wedge-gradient)"
stroke="#ffc96b"
stroke-opacity="0.65"
stroke-width="1.2"
/>
<line
id="inset-beam-axis"
x1="38"
y1="91"
x2="150"
y2="91"
stroke="#ffc96b"
stroke-width="1"
stroke-dasharray="4 4"
/>
<line
id="inset-target-line"
x1="38"
y1="91"
x2="120"
y2="91"
stroke="#53d9f2"
stroke-opacity="0.5"
/>
<circle cx="38" cy="91" r="5" fill="#ffc96b" filter="url(#soft-glow)" />
<circle
id="inset-marker"
cx="120"
cy="91"
r="5"
fill="#53d9f2"
stroke="#dff8ff"
stroke-width="1.5"
/>
<g fill="#718ba1" font-size="9" font-family="system-ui, sans-serif">
<text x="43" y="174">2 m</text>
<text x="78" y="174">6 m</text>
<text x="113" y="174">10 m</text>
<text x="228" y="94">range →</text>
</g>
<text
id="inset-readout"
x="245"
y="25"
fill="#b6c8d8"
font-size="10"
text-anchor="end"
font-family="system-ui, sans-serif"
>
6.0 m
</text>
</svg>
<div class="inset-caption">
<span>Footprint grows with range</span>
<b>r = d · tan θ</b>
</div>
</section>
<section class="card">
<div class="card-heading">
<strong>Experiment parameters</strong>
<span>Live</span>
</div>
<div class="control">
<div class="control-top">
<label for="distance">Marker distance</label>
<output id="distance-output" for="distance">6.0 m</output>
</div>
<input id="distance" type="range" min="2" max="12" step="0.1" value="6">
<small>Controls inverse-square attenuation relative to a 4 m reference.</small>
</div>
<div class="control">
<div class="control-top">
<label for="yaw">Emission direction</label>
<output id="yaw-output" for="yaw">0°</output>
</div>
<input id="yaw" type="range" min="-35" max="35" step="1" value="0">
<small>Rotates the lamp around the ideal line toward the active marker.</small>
</div>
<div class="control">
<div class="control-top">
<label for="incidence">Incidence angle</label>
<output id="incidence-output" for="incidence">28°</output>
</div>
<input id="incidence" type="range" min="0" max="80" step="1" value="28">
<small>Receiver angle to the incoming light; response follows cos θ.</small>
</div>
<div class="control">
<div class="control-top">
<label for="spread">Beam half-angle</label>
<output id="spread-output" for="spread">16°</output>
</div>
<input id="spread" type="range" min="5" max="28" step="1" value="16">
<small>Changes the radial footprint and the lamp's angular acceptance.</small>
</div>
<label class="beam-toggle">
<input id="show-beam" type="checkbox" checked>
Show beam volume, footprint, and direction axis
</label>
</section>
<section class="card">
<div class="card-heading">
<strong>Factor response</strong>
<span>Relative to ideal</span>
</div>
<div class="metric">
<div class="metric-top">
<span>Distance attenuation</span>
<b id="distance-value">100%</b>
</div>
<div class="metric-track"><div id="distance-fill" class="metric-fill"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span>Emission alignment</span>
<b id="direction-value">100%</b>
</div>
<div class="metric-track"><div id="direction-fill" class="metric-fill"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span>Incidence cosine</span>
<b id="incidence-value">88%</b>
</div>
<div class="metric-track"><div id="incidence-fill" class="metric-fill"></div></div>
</div>
<div class="metric">
<div class="metric-top">
<span>Combined response</span>
<b id="combined-value">88%</b>
</div>
<div class="metric-track"><div id="combined-fill" class="metric-fill"></div></div>
</div>
<div class="formula">
<strong>Relative irradiance</strong><br>
<span class="distance">(4 m / r)²</span>
×
<span class="direction">A(Δφ)</span>
×
<span class="incidence">cos θᵢ</span>
<br>
<span style="color:#647d93">Distance, direction, and incidence are evaluated independently.</span>
</div>
</section>
</aside>
</div>
<div id="error-message">
WebGL could not be initialized. Please try a browser with hardware acceleration enabled.
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.querySelector("#stage");
const errorMessage = document.querySelector("#error-message");
const state = {
distance: 6,
yaw: 0,
incidence: 28,
spread: 16,
mode: "combined",
showBeam: true
};
const palette = {
amber: 0xffc96b,
cyan: 0x53d9f2,
violet: 0xb49aff,
green: 0x65e3ad
};
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
} catch (error) {
console.error(error);
errorMessage.style.display = "grid";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101b);
scene.fog = new THREE.Fog(0x07101b, 19, 43);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 100);
const cameraTarget = new THREE.Vector3(0.8, 1.15, 0);
const spherical = new THREE.Spherical(16.8, 1.08, 0.58);
function updateCameraFromSpherical() {
spherical.phi = THREE.MathUtils.clamp(spherical.phi, 0.18, Math.PI * 0.48);
spherical.radius = THREE.MathUtils.clamp(spherical.radius, 6.5, 31);
spherical.makeSafe();
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
updateCameraFromSpherical();
const ambient = new THREE.HemisphereLight(0xaed8ff, 0x111722, 1.7);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xdcecff, 2.5);
keyLight.position.set(7, 13, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x507cff, 1.1);
rimLight.position.set(-8, 5, -7);
scene.add(rimLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x0a1420,
roughness: 0.94,
metalness: 0.04
});
const ground = new THREE.Mesh(new THREE.PlaneGeometry(48, 32), groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.set(1, -0.015, 0);
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(40, 40, 0x29455f, 0x182c3e);
grid.position.set(1, 0.006, 0);
grid.material.transparent = true;
grid.material.opacity = 0.48;
scene.add(grid);
const lampX = -4;
const lampPosition = new THREE.Vector3(-3.45, 6.15, 0);
const groundY = 0;
const materialCache = new Map();
function voxelMaterial(color, emissive = 0x000000, emissiveIntensity = 0) {
const key = `${color}-${emissive}-${emissiveIntensity}`;
if (!materialCache.has(key)) {
materialCache.set(
key,
new THREE.MeshStandardMaterial({
color,
roughness: 0.7,
metalness: 0.12,
emissive,
emissiveIntensity
})
);
}
return materialCache.get(key);
}
function addVoxel(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const lampGroup = new THREE.Group();
scene.add(lampGroup);
const darkMetal = voxelMaterial(0x172231);
const edgeMetal = voxelMaterial(0x26384a);
const paleMetal = voxelMaterial(0x4a5a68);
addVoxel(lampGroup, new THREE.Vector3(1.45, 0.28, 1.45), new THREE.Vector3(lampX, 0.14, 0), darkMetal);
addVoxel(lampGroup, new THREE.Vector3(1.08, 0.22, 1.08), new THREE.Vector3(lampX, 0.37, 0), edgeMetal);
addVoxel(lampGroup, new THREE.Vector3(0.72, 0.18, 0.72), new THREE.Vector3(lampX, 0.56, 0), darkMetal);
for (let i = 0; i < 6; i++) {
addVoxel(
lampGroup,
new THREE.Vector3(0.34, 0.88, 0.34),
new THREE.Vector3(lampX, 1.02 + i * 0.86, 0),
i % 2 ? edgeMetal : darkMetal
);
}
addVoxel(
lampGroup,
new THREE.Vector3(1.25, 0.28, 0.38),
new THREE.Vector3(lampX + 0.55, 5.82, 0),
edgeMetal
);
addVoxel(
lampGroup,
new THREE.Vector3(0.7, 0.48, 0.58),
new THREE.Vector3(lampX + 1.12, 6.03, 0),
darkMetal
);
const lampHead = new THREE.Group();
lampHead.position.copy(lampPosition);
scene.add(lampHead);
addVoxel(
lampHead,
new THREE.Vector3(1.22, 0.76, 1.0),
new THREE.Vector3(0, 0, 0),
paleMetal
);
addVoxel(
lampHead,
new THREE.Vector3(1.32, 0.17, 1.08),
new THREE.Vector3(0, 0.43, 0),
edgeMetal
);
const lensMaterial = new THREE.MeshStandardMaterial({
color: 0x5b4324,
emissive: palette.amber,
emissiveIntensity: 3.2,
roughness: 0.32,
metalness: 0.08
});
addVoxel(
lampHead,
new THREE.Vector3(0.92, 0.09, 0.73),
new THREE.Vector3(0, -0.42, 0),
lensMaterial,
false
);
const lensGlow = new THREE.PointLight(palette.amber, 7, 3.4, 2);
lensGlow.position.copy(lampPosition);
scene.add(lensGlow);
const spotLight = new THREE.SpotLight(
0xffd48b,
130,
30,
THREE.MathUtils.degToRad(16),
0.45,
2
);
spotLight.position.copy(lampPosition);
spotLight.castShadow = true;
spotLight.shadow.mapSize.set(1024, 1024);
spotLight.shadow.bias = -0.0005;
const spotTarget = new THREE.Object3D();
spotTarget.position.set(0, 0, 0);
scene.add(spotTarget);
spotLight.target = spotTarget;
scene.add(spotLight);
const activeGroup = new THREE.Group();
scene.add(activeGroup);
const activeMaterial = new THREE.MeshStandardMaterial({
color: 0x302719,
emissive: palette.amber,
emissiveIntensity: 2.4,
roughness: 0.5,
metalness: 0.08,
side: THREE.DoubleSide
});
const activeCard = new THREE.Mesh(
new THREE.PlaneGeometry(0.88, 0.88),
activeMaterial
);
activeCard.castShadow = true;
activeCard.receiveShadow = true;
activeGroup.add(activeCard);
const activeFrame = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.PlaneGeometry(0.9, 0.9)),
new THREE.LineBasicMaterial({
color: palette.amber,
transparent: true,
opacity: 0.85
})
);
activeFrame.position.z = 0.008;
activeGroup.add(activeFrame);
const activeFoot = addVoxel(
scene,
new THREE.Vector3(0.26, 0.08, 0.26),
new THREE.Vector3(lampX + state.distance, 0.04, 0),
voxelMaterial(0x27384a),
false
);
const referenceProbes = [];
const referenceDistances = [2, 4, 6, 8, 10];
for (const distance of referenceDistances) {
const material = new THREE.MeshStandardMaterial({
color: 0x0d2933,
emissive: palette.cyan,
emissiveIntensity: 1,
roughness: 0.65
});
const probe = new THREE.Mesh(
new THREE.BoxGeometry(0.54, 0.065, 0.54),
material
);
probe.position.set(lampX + distance, 0.045, 1.55);
probe.castShadow = true;
probe.receiveShadow = true;
scene.add(probe);
referenceProbes.push({ mesh: probe, material, distance });
}
const railGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(lampX + 1.7, 0.018, 1.55),
new THREE.Vector3(lampX + 10.4, 0.018, 1.55)
]);
const rail = new THREE.Line(
railGeometry,
new THREE.LineBasicMaterial({
color: 0x24475a,
transparent: true,
opacity: 0.65
})
);
scene.add(rail);
for (const distance of [2, 4, 6, 8, 10]) {
const tick = addVoxel(
scene,
new THREE.Vector3(0.035, 0.025, 0.22),
new THREE.Vector3(lampX + distance, 0.018, 1.55),
voxelMaterial(0x345166),
false
);
tick.receiveShadow = false;
}
const coneMaterial = new THREE.MeshBasicMaterial({
color: palette.amber,
transparent: true,
opacity: 0.07,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const innerConeMaterial = coneMaterial.clone();
innerConeMaterial.opacity = 0.045;
const outerCone = new THREE.Mesh(
new THREE.ConeGeometry(1, 1, 64, 1, true),
coneMaterial
);
const innerCone = new THREE.Mesh(
new THREE.ConeGeometry(1, 1, 64, 1, true),
innerConeMaterial
);
scene.add(outerCone, innerCone);
const footprintPositions = new Float32Array(64 * 9 * 3);
const footprintGeometry = new THREE.BufferGeometry();
footprintGeometry.setAttribute(
"position",
new THREE.BufferAttribute(footprintPositions, 3)
);
footprintGeometry.setDrawRange(0, 0);
const footprint = new THREE.Mesh(
footprintGeometry,
new THREE.MeshBasicMaterial({
color: palette.amber,
transparent: true,
opacity: 0.105,
side: THREE.DoubleSide,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
scene.add(footprint);
const footprintLinePositions = new Float32Array(64 * 3);
const footprintLineGeometry = new THREE.BufferGeometry();
footprintLineGeometry.setAttribute(
"position",
new THREE.BufferAttribute(footprintLinePositions, 3)
);
footprintLineGeometry.setDrawRange(0, 0);
const footprintLine = new THREE.LineLoop(
footprintLineGeometry,
new THREE.LineBasicMaterial({
color: palette.amber,
transparent: true,
opacity: 0.48
})
);
scene.add(footprintLine);
const normalArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(),
1.3,
palette.green,
0.24,
0.13
);
scene.add(normalArrow);
const directionArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
lampPosition,
2.3,
palette.violet,
0.28,
0.15
);
scene.add(directionArrow);
const lightRayGeometry = new THREE.BufferGeometry();
lightRayGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const lightRay = new THREE.Line(
lightRayGeometry,
new THREE.LineDashedMaterial({
color: 0xd8e6f2,
transparent: true,
opacity: 0.48,
dashSize: 0.16,
gapSize: 0.11
})
);
scene.add(lightRay);
const directionAxis = new THREE.Vector3(0, -1, 0);
const worldUp = new THREE.Vector3(0, 1, 0);
const cardNormal = new THREE.Vector3();
const markerPosition = new THREE.Vector3();
const idealDirection = new THREE.Vector3();
const beamDirection = new THREE.Vector3();
let modelDirty = true;
let distanceFactor = 1;
let directionFactor = 1;
let incidenceFactor = 1;
let combinedFactor = 1;
const modeDescriptions = {
combined:
"Combined response multiplies attenuation, emission alignment, and cosine incidence.",
distance:
"Only inverse-square attenuation is applied; the active marker ignores direction and incidence.",
direction:
"Only angular emission alignment is applied; distance and incidence are held neutral.",
incidence:
"Only cosine incidence is applied; distance and emission alignment are held neutral."
};
const modeColors = {
combined: palette.amber,
distance: palette.cyan,
direction: palette.violet,
incidence: palette.green
};
function smoothstep01(value) {
const t = THREE.MathUtils.clamp(value, 0, 1);
return t * t * (3 - 2 * t);
}
function setConeTransform(mesh, direction, length, radius) {
mesh.position.copy(lampPosition).addScaledVector(direction, length * 0.5);
mesh.scale.set(radius, length, radius);
mesh.quaternion.setFromUnitVectors(
worldUp,
direction.clone().negate()
);
}
function updateFootprint(direction, halfAngle) {
const u = new THREE.Vector3()
.crossVectors(direction, new THREE.Vector3(0, 0, 1))
.normalize();
const v = new THREE.Vector3()
.crossVectors(u, direction)
.normalize();
const points = [];
const segments = 64;
const sinAngle = Math.sin(halfAngle);
const cosAngle = Math.cos(halfAngle);
for (let i = 0; i < segments; i++) {
const phi = (i / segments) * Math.PI * 2;
const ray = direction
.clone()
.multiplyScalar(cosAngle)
.addScaledVector(u, Math.cos(phi) * sinAngle)
.addScaledVector(v, Math.sin(phi) * sinAngle);
if (ray.y < -0.0001) {
const t = (groundY - lampPosition.y) / ray.y;
if (t > 0) {
points.push(
new THREE.Vector3(
lampPosition.x + ray.x * t,
0.018,
lampPosition.z + ray.z * t
)
);
}
}
}
if (points.length < 3) {
footprintGeometry.setDrawRange(0, 0);
footprintLineGeometry.setDrawRange(0, 0);
return;
}
const center = new THREE.Vector3();
for (const point of points) center.add(point);
center.multiplyScalar(1 / points.length);
let vertexOffset = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
footprintPositions[vertexOffset++] = center.x;
footprintPositions[vertexOffset++] = center.y;
footprintPositions[vertexOffset++] = center.z;
footprintPositions[vertexOffset++] = a.x;
footprintPositions[vertexOffset++] = a.y;
footprintPositions[vertexOffset++] = a.z;
footprintPositions[vertexOffset++] = b.x;
footprintPositions[vertexOffset++] = b.y;
footprintPositions[vertexOffset++] = b.z;
}
footprintGeometry.attributes.position.needsUpdate = true;
footprintGeometry.setDrawRange(0, points.length * 3);
footprintGeometry.computeBoundingSphere();
for (let i = 0; i < points.length; i++) {
footprintLinePositions[i * 3] = points[i].x;
footprintLinePositions[i * 3 + 1] = points[i].y;
footprintLinePositions[i * 3 + 2] = points[i].z;
}
footprintLineGeometry.attributes.position.needsUpdate = true;
footprintLineGeometry.setDrawRange(0, points.length);
footprintLineGeometry.computeBoundingSphere();
}
function updateInset(yawRadians, halfAngle) {
const centerX = 38;
const centerY = 91;
const rangePixels = state.distance * 11.5;
const markerX = centerX + rangePixels;
const markerY = centerY;
const axisAngle = yawRadians;
const endX = centerX + Math.cos(axisAngle) * rangePixels;
const endY = centerY + Math.sin(axisAngle) * rangePixels;
const halfWidth = rangePixels * Math.tan(halfAngle);
const normalX = -Math.sin(axisAngle);
const normalY = Math.cos(axisAngle);
const wedgePath = [
`M ${centerX} ${centerY}`,
`L ${endX + normalX * halfWidth} ${endY + normalY * halfWidth}`,
`L ${endX - normalX * halfWidth} ${endY - normalY * halfWidth}`,
"Z"
].join(" ");
document.querySelector("#inset-wedge").setAttribute("d", wedgePath);
const axis = document.querySelector("#inset-beam-axis");
axis.setAttribute("x2", endX.toFixed(2));
axis.setAttribute("y2", endY.toFixed(2));
const targetLine = document.querySelector("#inset-target-line");
targetLine.setAttribute("x2", markerX.toFixed(2));
const marker = document.querySelector("#inset-marker");
marker.setAttribute("cx", markerX.toFixed(2));
marker.setAttribute("cy", markerY.toFixed(2));
document.querySelector("#inset-readout").textContent =
`${state.distance.toFixed(1)} m`;
}
function updateUI() {
document.querySelector("#distance-output").textContent =
`${state.distance.toFixed(1)} m`;
document.querySelector("#yaw-output").textContent =
`${state.yaw > 0 ? "+" : ""}${state.yaw.toFixed(0)}°`;
document.querySelector("#incidence-output").textContent =
`${state.incidence.toFixed(0)}°`;
document.querySelector("#spread-output").textContent =
`${state.spread.toFixed(0)}°`;
document.querySelector("#mode-description").textContent =
modeDescriptions[state.mode];
const values = {
distance: distanceFactor,
direction: directionFactor,
incidence: incidenceFactor,
combined: combinedFactor
};
for (const [name, value] of Object.entries(values)) {
document.querySelector(`#${name}-value`).textContent =
`${Math.round(value * 100)}%`;
document.querySelector(`#${name}-fill`).style.width =
`${Math.min(100, Math.max(0, value * 100))}%`;
}
for (const input of document.querySelectorAll('input[type="range"]')) {
const percent =
((Number(input.value) - Number(input.min)) /
(Number(input.max) - Number(input.min))) *
100;
input.style.background = `linear-gradient(
90deg,
var(--amber) 0%,
var(--amber) ${percent}%,
#263c51 ${percent}%,
#263c51 100%
)`;
}
}
function updateModel() {
const yawRadians = THREE.MathUtils.degToRad(state.yaw);
const incidenceRadians = THREE.MathUtils.degToRad(state.incidence);
const halfAngle = THREE.MathUtils.degToRad(state.spread);
const innerAngle = halfAngle * 0.42;
markerPosition.set(lampX + state.distance, 0.075, 0);
idealDirection
.copy(markerPosition)
.sub(lampPosition)
.normalize();
beamDirection
.copy(idealDirection)
.applyAxisAngle(worldUp, yawRadians)
.normalize();
const directionError = Math.abs(yawRadians);
if (directionError <= innerAngle) {
directionFactor = 1;
} else if (directionError >= halfAngle) {
directionFactor = 0;
} else {
directionFactor = smoothstep01(
(halfAngle - directionError) / (halfAngle - innerAngle)
);
}
distanceFactor = Math.pow(4 / state.distance, 2);
incidenceFactor = Math.cos(incidenceRadians);
combinedFactor = distanceFactor * directionFactor * incidenceFactor;
const toLight = lampPosition.clone().sub(markerPosition).normalize();
const perpendicular = worldUp
.clone()
.addScaledVector(toLight, -toLight.dot(worldUp))
.normalize();
cardNormal
.copy(toLight)
.multiplyScalar(Math.cos(incidenceRadians))
.addScaledVector(perpendicular, Math.sin(incidenceRadians))
.normalize();
activeGroup.position.copy(markerPosition).addScaledVector(cardNormal, 0.035);
activeGroup.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 0, 1),
cardNormal
);
activeFoot.position.set(markerPosition.x, 0.04, markerPosition.z);
const chosenFactor =
state.mode === "distance"
? distanceFactor
: state.mode === "direction"
? directionFactor
: state.mode === "incidence"
? incidenceFactor
: combinedFactor;
const selectedColor = modeColors[state.mode];
activeMaterial.color.setHex(selectedColor).multiplyScalar(0.22);
activeMaterial.emissive.setHex(selectedColor);
activeMaterial.emissiveIntensity = 0.08 + chosenFactor * 2.8;
activeFrame.material.color.setHex(selectedColor);
activeFrame.material.opacity = 0.35 + chosenFactor * 0.65;
for (const probe of referenceProbes) {
const attenuation = Math.pow(4 / probe.distance, 2);
probe.material.emissiveIntensity = 0.05 + attenuation * 1.75;
probe.material.color.setHex(palette.cyan).multiplyScalar(
0.06 + attenuation * 0.1
);
}
lampHead.quaternion.setFromUnitVectors(directionAxis, beamDirection);
spotTarget.position.copy(lampPosition).addScaledVector(beamDirection, 12);
spotLight.angle = halfAngle;
spotLight.intensity = 18 + directionFactor * 145;
lensMaterial.emissiveIntensity = 1.8 + directionFactor * 2.1;
lensGlow.intensity = 3 + directionFactor * 6;
const coneLength = 12.4;
const outerRadius = Math.tan(halfAngle) * coneLength;
const innerRadius = Math.tan(innerAngle) * coneLength;
setConeTransform(outerCone, beamDirection, coneLength, outerRadius);
setConeTransform(innerCone, beamDirection, coneLength, innerRadius);
coneMaterial.opacity = 0.025 + directionFactor * 0.065;
innerConeMaterial.opacity = 0.012 + directionFactor * 0.04;
outerCone.visible = state.showBeam;
innerCone.visible = state.showBeam;
footprint.visible = state.showBeam;
footprintLine.visible = state.showBeam;
directionArrow.visible = state.showBeam;
updateFootprint(beamDirection, halfAngle);
directionArrow.position.copy(lampPosition);
directionArrow.setDirection(beamDirection);
directionArrow.setLength(2.3, 0.28, 0.15);
normalArrow.position
.copy(markerPosition)
.addScaledVector(cardNormal, 0.08);
normalArrow.setDirection(cardNormal);
normalArrow.setLength(1.28, 0.23, 0.12);
const rayPositions = lightRayGeometry.attributes.position;
rayPositions.setXYZ(0, markerPosition.x, markerPosition.y, markerPosition.z);
rayPositions.setXYZ(1, lampPosition.x, lampPosition.y, lampPosition.z);
rayPositions.needsUpdate = true;
lightRay.computeLineDistances();
updateInset(yawRadians, halfAngle);
updateUI();
modelDirty = false;
}
function bindRange(inputId, key) {
const input = document.querySelector(`#${inputId}`);
input.addEventListener("input", () => {
state[key] = Number(input.value);
modelDirty = true;
});
}
bindRange("distance", "distance");
bindRange("yaw", "yaw");
bindRange("incidence", "incidence");
bindRange("spread", "spread");
document.querySelector("#show-beam").addEventListener("change", (event) => {
state.showBeam = event.target.checked;
modelDirty = true;
});
for (const button of document.querySelectorAll(".mode-btn")) {
button.addEventListener("click", () => {
for (const other of document.querySelectorAll(".mode-btn")) {
other.classList.toggle("active", other === button);
}
state.mode = button.dataset.mode;
modelDirty = true;
});
}
document.querySelector("#reset").addEventListener("click", () => {
state.distance = 6;
state.yaw = 0;
state.incidence = 28;
state.spread = 16;
state.mode = "combined";
state.showBeam = true;
document.querySelector("#distance").value = 6;
document.querySelector("#yaw").value = 0;
document.querySelector("#incidence").value = 28;
document.querySelector("#spread").value = 16;
document.querySelector("#show-beam").checked = true;
for (const button of document.querySelectorAll(".mode-btn")) {
button.classList.toggle("active", button.dataset.mode === "combined");
}
modelDirty = true;
});
/* --------------------------------------------------------------------------
Custom camera controls: orbit, pan, and zoom.
No Three.js examples/addons are used.
-------------------------------------------------------------------------- */
let dragging = false;
let dragButton = 0;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
dragging = true;
dragButton = event.button;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
const panning = dragButton === 2 || event.shiftKey;
if (panning) {
const right = new THREE.Vector3();
const up = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, up, new THREE.Vector3());
const scale = (2 * spherical.radius) / stage.clientHeight;
cameraTarget
.addScaledVector(right, -dx * scale)
.addScaledVector(up, dy * scale);
cameraTarget.x = THREE.MathUtils.clamp(cameraTarget.x, -7, 10);
cameraTarget.z = THREE.MathUtils.clamp(cameraTarget.z, -9, 9);
} else {
spherical.theta -= dx * 0.006;
spherical.phi -= dy * 0.006;
}
updateCameraFromSpherical();
});
function endDrag(event) {
dragging = false;
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();
spherical.radius *= Math.exp(event.deltaY * 0.001);
updateCameraFromSpherical();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraTarget.set(0.8, 1.15, 0);
spherical.set(16.8, 1.08, 0.58);
updateCameraFromSpherical();
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
const step = 0.08;
if (event.key === "ArrowLeft") spherical.theta += step;
else if (event.key === "ArrowRight") spherical.theta -= step;
else if (event.key === "ArrowUp") spherical.phi -= step;
else if (event.key === "ArrowDown") spherical.phi += step;
else if (event.key === "+" || event.key === "=") spherical.radius *= 0.92;
else if (event.key === "-") spherical.radius *= 1.08;
else if (event.key === "0") {
cameraTarget.set(0.8, 1.15, 0);
spherical.set(16.8, 1.08, 0.58);
} else {
return;
}
updateCameraFromSpherical();
event.preventDefault();
});
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(stage);
resize();
const activeLabel = document.querySelector("#active-label");
const lampLabel = document.querySelector("#lamp-label");
function positionWorldLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.1 &&
Math.abs(projected.y) < 1.1;
element.style.display = visible ? "block" : "none";
const x = (projected.x * 0.5 + 0.5) * stage.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * stage.clientHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
renderer.setAnimationLoop(() => {
if (modelDirty) updateModel();
positionWorldLabel(
activeLabel,
activeGroup.position.clone().addScaledVector(cardNormal, 0.82)
);
positionWorldLabel(
lampLabel,
lampPosition.clone().add(new THREE.Vector3(0, 0.65, 0))
);
renderer.render(scene, camera);
});
</script>
</body>
</html>
```