Prompt specification
Build or customize the Three.js 3D scene "Rotate a Frame to Match a Shadow" 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: Rotate a Frame to Match a Shadow
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/rotate-a-frame-to-match-a-shadow-x3498
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring object and light alignment for target shadows. Create a tabletop frame and target outline on a wall. Let users rotate the frame and compare its actual projected silhouette with the target. Voxel style.
Working Three.js Starter (rotate-a-frame-to-match-a-shadow-x3498):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Shadow Lab</title>
<style>
:root {
--ink: #18313a;
--panel: rgba(250, 247, 233, 0.92);
--border: rgba(24, 49, 58, 0.18);
--mint: #30e6ae;
--orange: #ff9e45;
--shadow: #24363c;
--good: #16b98a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d8e1;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.brand {
position: absolute;
top: 24px;
left: 24px;
max-width: 310px;
pointer-events: none;
filter: drop-shadow(0 2px 0 rgba(255, 255, 255, 0.35));
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 6px 9px;
border: 1px solid rgba(24, 49, 58, 0.22);
background: rgba(250, 247, 233, 0.72);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
background: var(--mint);
box-shadow: 0 0 0 2px rgba(48, 230, 174, 0.25);
}
h1 {
margin: 12px 0 8px;
font-size: clamp(28px, 4vw, 48px);
line-height: 0.94;
letter-spacing: -0.055em;
text-transform: uppercase;
}
.brand p {
margin: 0;
max-width: 270px;
color: rgba(24, 49, 58, 0.75);
font-size: 13px;
line-height: 1.45;
}
.score-card {
position: absolute;
top: 24px;
right: 24px;
width: 198px;
padding: 16px;
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 6px 6px 0 rgba(24, 49, 58, 0.12);
pointer-events: none;
}
.score-label {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.score-label span:last-child {
color: rgba(24, 49, 58, 0.45);
}
.score-main {
display: flex;
align-items: center;
gap: 13px;
}
.score-ring {
position: relative;
width: 68px;
height: 68px;
flex: 0 0 68px;
border-radius: 50%;
background: conic-gradient(var(--good) 100%, rgba(24, 49, 58, 0.09) 0);
}
.score-ring::after {
content: "";
position: absolute;
inset: 7px;
border-radius: 50%;
background: #faf7e9;
}
.score-number {
position: absolute;
inset: 0;
z-index: 1;
display: grid;
place-items: center;
font: 900 18px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.score-copy strong {
display: block;
font-size: 13px;
line-height: 1.2;
}
.score-copy small {
display: block;
margin-top: 5px;
color: rgba(24, 49, 58, 0.56);
font: 700 10px/1.25 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
.offset {
display: flex;
justify-content: space-between;
margin-top: 12px;
padding-top: 10px;
border-top: 1px solid var(--border);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
.offset strong {
color: var(--good);
}
.controls {
position: absolute;
left: 24px;
bottom: 24px;
width: 304px;
padding: 16px;
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 6px 6px 0 rgba(24, 49, 58, 0.12);
pointer-events: auto;
}
.control-section + .control-section {
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--border);
}
.section-title {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
font: 900 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-title::before {
content: "";
width: 7px;
height: 7px;
background: var(--orange);
}
.control-section:last-of-type .section-title::before {
background: var(--mint);
}
.control {
margin-top: 11px;
}
.control:first-of-type {
margin-top: 0;
}
.control-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
font-size: 11px;
font-weight: 750;
}
output {
color: rgba(24, 49, 58, 0.58);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0 0;
appearance: none;
border-radius: 0;
background: rgba(24, 49, 58, 0.16);
cursor: ew-resize;
accent-color: var(--orange);
}
input[type="range"]::-webkit-slider-thumb {
width: 13px;
height: 18px;
appearance: none;
border: 2px solid var(--ink);
border-radius: 1px;
background: #fffaf0;
box-shadow: 2px 2px 0 rgba(24, 49, 58, 0.18);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 16px;
border: 2px solid var(--ink);
border-radius: 1px;
background: #fffaf0;
}
.toggles {
display: flex;
flex-wrap: wrap;
gap: 8px 14px;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.toggle {
display: inline-flex;
align-items: center;
gap: 7px;
cursor: pointer;
font: 750 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
.toggle input {
width: 13px;
height: 13px;
margin: 0;
accent-color: var(--mint);
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
button {
min-height: 36px;
border: 1px solid rgba(24, 49, 58, 0.28);
border-radius: 0;
background: #fffaf0;
color: var(--ink);
box-shadow: 3px 3px 0 rgba(24, 49, 58, 0.13);
cursor: pointer;
font: 900 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
text-transform: uppercase;
}
button:hover {
transform: translate(1px, 1px);
box-shadow: 2px 2px 0 rgba(24, 49, 58, 0.13);
}
button:active {
transform: translate(3px, 3px);
box-shadow: none;
}
button.active {
border-color: var(--good);
background: #d7f8e9;
}
.legend {
position: absolute;
right: 24px;
bottom: 24px;
display: flex;
gap: 14px;
padding: 10px 12px;
border: 1px solid var(--border);
background: rgba(250, 247, 233, 0.86);
font: 750 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
text-transform: uppercase;
pointer-events: none;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border: 1px solid rgba(24, 49, 58, 0.35);
}
.swatch.target {
background: var(--mint);
}
.swatch.shadow {
background: #26383c;
}
.swatch.guide {
border-color: var(--orange);
background: transparent;
border-top: 3px solid var(--orange);
}
.hint {
position: absolute;
left: 50%;
bottom: 27px;
transform: translateX(-50%);
padding: 9px 12px;
border-radius: 2px;
background: rgba(24, 49, 58, 0.78);
color: #fffaf0;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.035em;
white-space: nowrap;
pointer-events: none;
}
#loading {
position: fixed;
inset: 0;
z-index: 10;
display: grid;
place-items: center;
background: #b9d8e1;
transition: opacity 350ms ease;
}
#loading span {
padding: 14px 18px;
border: 1px solid rgba(24, 49, 58, 0.25);
background: rgba(250, 247, 233, 0.9);
box-shadow: 5px 5px 0 rgba(24, 49, 58, 0.12);
font: 900 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 760px) {
.brand {
top: 14px;
left: 14px;
max-width: 210px;
}
.brand p {
display: none;
}
h1 {
font-size: 27px;
}
.score-card {
top: 14px;
right: 14px;
width: 158px;
padding: 12px;
}
.score-ring {
width: 56px;
height: 56px;
flex-basis: 56px;
}
.score-copy small {
display: none;
}
.controls {
left: 14px;
bottom: 14px;
width: min(304px, calc(100vw - 28px));
max-height: 56vh;
overflow: auto;
}
.legend,
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<header class="brand">
<div class="eyebrow">Voxel optics / 01</div>
<h1>Shadow<br>Alignment Lab</h1>
<p>
Rotate the tabletop frame and reposition the studio light until its
projected silhouette registers with the wall target.
</p>
</header>
<section class="score-card">
<div class="score-label">
<span>Registration</span>
<span>Live</span>
</div>
<div class="score-main">
<div class="score-ring" id="scoreRing">
<div class="score-number" id="scoreNumber">100</div>
</div>
<div class="score-copy">
<strong id="scoreStatus">Locked</strong>
<small id="scoreDetail">Silhouette matches</small>
</div>
</div>
<div class="offset">
<span>Centroid offset</span>
<strong id="offsetValue">0.00 u</strong>
</div>
</section>
<aside class="controls">
<section class="control-section">
<div class="section-title">Object alignment</div>
<div class="control">
<div class="control-row">
<label for="yaw">Frame yaw</label>
<output id="yawOut" for="yaw">0°</output>
</div>
<input id="yaw" type="range" min="-80" max="80" step="1" value="0" />
</div>
<div class="control">
<div class="control-row">
<label for="tilt">Frame tilt</label>
<output id="tiltOut" for="tilt">0°</output>
</div>
<input id="tilt" type="range" min="-30" max="30" step="1" value="0" />
</div>
</section>
<section class="control-section">
<div class="section-title">Light alignment</div>
<div class="control">
<div class="control-row">
<label for="azimuth">Light azimuth</label>
<output id="azimuthOut" for="azimuth">-39°</output>
</div>
<input id="azimuth" type="range" min="-75" max="75" step="1" value="-39" />
</div>
<div class="control">
<div class="control-row">
<label for="elevation">Light elevation</label>
<output id="elevationOut" for="elevation">3°</output>
</div>
<input id="elevation" type="range" min="-5" max="60" step="1" value="3" />
</div>
<div class="control">
<div class="control-row">
<label for="beam">Beam width</label>
<output id="beamOut" for="beam">55°</output>
</div>
<input id="beam" type="range" min="30" max="75" step="1" value="55" />
</div>
</section>
<div class="toggles">
<label class="toggle">
<input id="targetToggle" type="checkbox" checked />
Target
</label>
<label class="toggle">
<input id="guideToggle" type="checkbox" checked />
Edge guide
</label>
</div>
<div class="buttons">
<button id="autoButton" type="button">Auto sweep</button>
<button id="resetButton" type="button">Reset</button>
<button id="cameraButton" type="button" style="grid-column: 1 / -1">
Reset camera
</button>
</div>
</aside>
<div class="legend">
<span><i class="swatch target"></i> Target</span>
<span><i class="swatch shadow"></i> Actual shadow</span>
<span><i class="swatch guide"></i> Projected edge</span>
</div>
<div class="hint">
Drag frame to rotate · Drag background to orbit · Scroll to zoom · Shift-drag to pan
</div>
</div>
<div id="loading">
<span>Blocking light…</span>
</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 sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d8e1);
scene.fog = new THREE.Fog(0xb9d8e1, 22, 43);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
yaw: 0.58,
pitch: 0.34,
distance: 17,
focus: new THREE.Vector3(1.4, 2.15, -0.9)
};
const cameraHome = {
yaw: 0.58,
pitch: 0.34,
distance: 17,
focus: new THREE.Vector3(1.4, 2.15, -0.9)
};
const hemisphere = new THREE.HemisphereLight(0xe8f8ff, 0x9c7458, 1.65);
scene.add(hemisphere);
const fill = new THREE.DirectionalLight(0xd9efff, 0.75);
fill.position.set(8, 10, 9);
scene.add(fill);
// -------------------------------------------------------------------------
// Shared geometry and materials
// -------------------------------------------------------------------------
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function standard(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
flatShading: true,
...options
});
}
const materials = {
floor: standard(0xb8aa93),
wall: standard(0xffffff),
table: standard(0xb67b48),
tableEdge: standard(0x75492f),
leg: standard(0x4e5b59),
frameA: standard(0xe7a652),
frameB: standard(0xc77935),
frameC: standard(0xf2bd69),
pedestal: standard(0x33484d),
target: new THREE.MeshBasicMaterial({ color: 0x30e6ae }),
guide: new THREE.LineBasicMaterial({
color: 0xff9e45,
transparent: true,
opacity: 0.85,
depthWrite: false
}),
lamp: standard(0x2d4148),
lampTrim: standard(0xffc45f),
lens: new THREE.MeshBasicMaterial({ color: 0xffe7a1 }),
decorA: standard(0xef725d),
decorB: standard(0x5db7b0),
decorC: standard(0xf5cf69)
};
function addBox(
parent,
width,
height,
depth,
material,
x = 0,
y = 0,
z = 0,
castShadow = true,
receiveShadow = true
) {
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Voxel environment
// -------------------------------------------------------------------------
const WALL_Z = -4.7;
addBox(scene, 32, 0.35, 28, materials.floor, 0, -0.25, 2, false, true);
function makeBrickTexture() {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#d9d6c6";
ctx.fillRect(0, 0, 256, 256);
const brickH = 64;
const brickW = 128;
for (let row = 0; row < 4; row++) {
const offset = row % 2 === 0 ? 0 : -brickW / 2;
for (let col = -1; col < 3; col++) {
const x = col * brickW + offset;
const y = row * brickH;
const tone = 225 + ((row * 7 + col * 11) % 18);
ctx.fillStyle = `rgb(${tone}, ${tone - 4}, ${tone - 16})`;
ctx.fillRect(x + 4, y + 4, brickW - 8, brickH - 8);
}
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(3, 1.5);
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestMipmapNearestFilter;
return texture;
}
materials.wall.map = makeBrickTexture();
materials.wall.needsUpdate = true;
addBox(
scene,
22,
11,
0.3,
materials.wall,
0,
5,
WALL_Z - 0.15,
false,
true
);
// Wall trim and decorative pixel poster.
addBox(scene, 22, 0.22, 0.22, materials.tableEdge, 0, 0.65, WALL_Z + 0.1, false, true);
addBox(scene, 22, 0.16, 0.18, materials.pedestal, 0, 10.35, WALL_Z + 0.08, false, true);
const poster = new THREE.Group();
poster.position.set(-7.2, 4.2, WALL_Z + 0.12);
scene.add(poster);
addBox(poster, 2.4, 2.25, 0.15, materials.pedestal, 0, 0, 0, false, true);
addBox(poster, 2.05, 1.9, 0.08, standard(0xf2e6c9), 0, 0, 0.1, false, true);
addBox(poster, 0.5, 0.5, 0.1, materials.decorA, -0.55, 0.45, 0.18, false, true);
addBox(poster, 0.42, 0.85, 0.1, materials.decorB, 0.05, 0.2, 0.18, false, true);
addBox(poster, 0.65, 0.35, 0.1, materials.decorC, 0.55, -0.4, 0.18, false, true);
// Voxel table.
addBox(scene, 14.2, 0.46, 7.2, materials.table, 0, 0.77, 1.3, true, true);
addBox(scene, 14.35, 0.18, 0.22, materials.tableEdge, 0, 0.88, -2.18, true, true);
addBox(scene, 14.35, 0.18, 0.22, materials.tableEdge, 0, 0.88, 4.78, true, true);
for (const x of [-5.8, -2.8, 2.8, 5.8]) {
for (const z of [-1.4, 3.9]) {
addBox(scene, 0.48, 1.4, 0.48, materials.leg, x, 0.15, z, true, true);
}
}
for (const x of [-4.8, -2.4, 0, 2.4, 4.8]) {
addBox(scene, 0.035, 0.025, 6.8, materials.tableEdge, x, 1.01, 1.3, false, true);
}
// Small voxel blocks on the table.
addBox(scene, 0.48, 0.48, 0.48, materials.decorB, -4.3, 1.24, 1.2, true, true);
addBox(scene, 0.42, 0.42, 0.42, materials.decorC, -3.72, 1.21, 1.45, true, true);
addBox(scene, 0.36, 0.36, 0.36, materials.decorA, -3.95, 1.62, 1.3, true, true);
// -------------------------------------------------------------------------
// Tabletop frame
// -------------------------------------------------------------------------
const FRAME_CENTER = new THREE.Vector3(0, 2.72, 0);
const FRAME_WIDTH = 3.2;
const FRAME_HEIGHT = 3.2;
const FRAME_DEPTH = 0.34;
const frame = new THREE.Group();
frame.position.copy(FRAME_CENTER);
frame.rotation.order = "YXZ";
scene.add(frame);
const cell = 0.32;
const frameMaterials = [
materials.frameA,
materials.frameB,
materials.frameC
];
// Top and bottom voxel rails.
for (let i = 0; i < 10; i++) {
const x = -FRAME_WIDTH / 2 + (i + 0.5) * cell;
for (const y of [
-FRAME_HEIGHT / 2 + cell / 2,
FRAME_HEIGHT / 2 - cell / 2
]) {
addBox(
frame,
cell * 0.96,
cell,
FRAME_DEPTH,
frameMaterials[(i + Math.round(y * 10)) % 3],
x,
y,
0
);
}
}
// Side voxel rails.
for (let i = 0; i < 8; i++) {
const y = -FRAME_HEIGHT / 2 + cell * 1.5 + i * cell;
for (const x of [
-FRAME_WIDTH / 2 + cell / 2,
FRAME_WIDTH / 2 - cell / 2
]) {
addBox(
frame,
cell,
cell * 0.96,
FRAME_DEPTH,
frameMaterials[(i + Math.round(x * 10)) % 3],
x,
y,
0
);
}
}
// Small corner caps.
for (const x of [-1.44, 1.44]) {
for (const y of [-1.44, 1.44]) {
addBox(
frame,
0.42,
0.42,
0.42,
materials.frameC,
x,
y,
0
);
}
}
// The support stays fixed while the frame rotates.
addBox(scene, 0.52, 0.2, 0.95, materials.pedestal, -1.05, 1.1, 0, true, true);
addBox(scene, 0.52, 0.2, 0.95, materials.pedestal, 1.05, 1.1, 0, true, true);
addBox(scene, 0.3, 1.12, 0.3, materials.pedestal, 0, 1.5, -0.1, true, true);
// -------------------------------------------------------------------------
// Spot light and voxel lamp housing
// -------------------------------------------------------------------------
const state = {
yaw: 0,
tilt: 0,
lightAzimuth: -39,
lightElevation: 3,
beam: 55,
lightRadius: 7.5,
auto: false
};
const lightPosition = new THREE.Vector3();
const spot = new THREE.SpotLight(0xfff0cf, 720, 32, THREE.MathUtils.degToRad(55), 0.08, 1.35);
spot.castShadow = true;
spot.target.position.copy(FRAME_CENTER);
spot.shadow.mapSize.set(2048, 2048);
spot.shadow.camera.near = 0.5;
spot.shadow.camera.far = 32;
spot.shadow.bias = -0.00018;
spot.shadow.normalBias = 0.025;
spot.shadow.focus = 1;
scene.add(spot);
scene.add(spot.target);
const lamp = new THREE.Group();
scene.add(lamp);
addBox(lamp, 0.68, 0.68, 0.72, materials.lamp, 0, 0, 0, false, false);
addBox(lamp, 0.44, 0.44, 0.09, materials.lens, 0, 0, 0.4, false, false);
addBox(lamp, 0.16, 0.76, 0.5, materials.lampTrim, 0, 0.08, -0.42, false, false);
addBox(lamp, 0.76, 0.16, 0.5, materials.lampTrim, 0, 0.08, -0.42, false, false);
const beamGeometry = new THREE.BufferGeometry();
beamGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const beamLine = new THREE.Line(
beamGeometry,
new THREE.LineBasicMaterial({
color: 0xffd37a,
transparent: true,
opacity: 0.22,
depthWrite: false
})
);
beamLine.frustumCulled = false;
scene.add(beamLine);
// Pivot reticle.
const pivotReticle = new THREE.Group();
pivotReticle.position.copy(FRAME_CENTER);
scene.add(pivotReticle);
const reticleMaterial = new THREE.MeshBasicMaterial({
color: 0xffa653,
transparent: true,
opacity: 0.48,
depthWrite: false
});
for (const x of [-0.24, 0.24]) {
for (const y of [-0.24, 0.24]) {
addBox(pivotReticle, 0.08, 0.08, 0.08, reticleMaterial, x, y, 0.22, false, false);
}
}
// -------------------------------------------------------------------------
// Projection mathematics
// -------------------------------------------------------------------------
const localCorners = [
new THREE.Vector3(-FRAME_WIDTH / 2, -FRAME_HEIGHT / 2, FRAME_DEPTH / 2),
new THREE.Vector3(FRAME_WIDTH / 2, -FRAME_HEIGHT / 2, FRAME_DEPTH / 2),
new THREE.Vector3(FRAME_WIDTH / 2, FRAME_HEIGHT / 2, FRAME_DEPTH / 2),
new THREE.Vector3(-FRAME_WIDTH / 2, FRAME_HEIGHT / 2, FRAME_DEPTH / 2)
];
function updateLightPosition() {
const azimuth = THREE.MathUtils.degToRad(state.lightAzimuth);
const elevation = THREE.MathUtils.degToRad(state.lightElevation);
const horizontal = state.lightRadius * Math.cos(elevation);
lightPosition.set(
FRAME_CENTER.x + horizontal * Math.sin(azimuth),
FRAME_CENTER.y + state.lightRadius * Math.sin(elevation),
FRAME_CENTER.z + horizontal * Math.cos(azimuth)
);
spot.position.copy(lightPosition);
spot.angle = THREE.MathUtils.degToRad(state.beam);
lamp.position.copy(lightPosition);
const direction = FRAME_CENTER.clone().sub(lightPosition).normalize();
lamp.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), direction);
const beamPositions = beamGeometry.attributes.position.array;
beamPositions[0] = lightPosition.x;
beamPositions[1] = lightPosition.y;
beamPositions[2] = lightPosition.z;
beamPositions[3] = FRAME_CENTER.x;
beamPositions[4] = FRAME_CENTER.y;
beamPositions[5] = FRAME_CENTER.z;
beamGeometry.attributes.position.needsUpdate = true;
}
function projectToWall(worldPoint) {
const t = (WALL_Z - lightPosition.z) / (worldPoint.z - lightPosition.z);
return lightPosition
.clone()
.add(worldPoint.clone().sub(lightPosition).multiplyScalar(t));
}
function projectedCorners() {
frame.updateMatrixWorld(true);
return localCorners.map((corner) => {
const world = frame.localToWorld(corner.clone());
return projectToWall(world);
});
}
function polygonCentroid(points) {
const center = new THREE.Vector3();
for (const point of points) {
center.add(point);
}
return center.multiplyScalar(1 / points.length);
}
function polygonArea(points) {
let area = 0;
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
area += a.x * b.y - b.x * a.y;
}
return Math.abs(area) * 0.5;
}
// Establish the fixed target from the default light/object registration.
updateLightPosition();
const targetCorners = projectedCorners();
const targetGroup = new THREE.Group();
scene.add(targetGroup);
function addVoxelTarget(points) {
const targetGeometry = new THREE.BoxGeometry(0.145, 0.145, 0.11);
for (let i = 0; i < points.length; i++) {
const a = points[i];
const b = points[(i + 1) % points.length];
const length = a.distanceTo(b);
const count = Math.max(2, Math.ceil(length / 0.125));
for (let j = 0; j < count; j++) {
const p = a.clone().lerp(b, (j + 0.5) / count);
const voxel = new THREE.Mesh(targetGeometry, materials.target);
voxel.position.set(p.x, p.y, WALL_Z + 0.08);
targetGroup.add(voxel);
}
}
// Larger registration cubes emphasize the corners.
for (const point of points) {
const corner = new THREE.Mesh(
new THREE.BoxGeometry(0.23, 0.23, 0.13),
materials.target
);
corner.position.set(point.x, point.y, WALL_Z + 0.09);
targetGroup.add(corner);
}
}
addVoxelTarget(targetCorners);
function makeLabelSprite(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 64;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(24,49,58,0.88)";
ctx.fillRect(0, 8, 256, 48);
ctx.fillStyle = color;
ctx.fillRect(0, 8, 9, 48);
ctx.font = "900 24px monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#fffaf0";
ctx.fillText(text, 132, 33);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.magFilter = THREE.NearestFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(2.0, 0.5, 1);
return sprite;
}
const targetCenter = polygonCentroid(targetCorners);
const targetLabel = makeLabelSprite("TARGET", "#30e6ae");
targetLabel.position.set(targetCenter.x, targetCenter.y + 2.55, WALL_Z + 0.25);
scene.add(targetLabel);
// Current projected outer edge.
const guideGeometry = new THREE.BufferGeometry();
guideGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(12), 3)
);
const projectedEdge = new THREE.LineLoop(guideGeometry, materials.guide);
projectedEdge.position.z = WALL_Z + 0.14;
projectedEdge.renderOrder = 4;
scene.add(projectedEdge);
// -------------------------------------------------------------------------
// UI and registration score
// -------------------------------------------------------------------------
const ui = {
yaw: document.getElementById("yaw"),
tilt: document.getElementById("tilt"),
azimuth: document.getElementById("azimuth"),
elevation: document.getElementById("elevation"),
beam: document.getElementById("beam"),
yawOut: document.getElementById("yawOut"),
tiltOut: document.getElementById("tiltOut"),
azimuthOut: document.getElementById("azimuthOut"),
elevationOut: document.getElementById("elevationOut"),
beamOut: document.getElementById("beamOut"),
autoButton: document.getElementById("autoButton"),
resetButton: document.getElementById("resetButton"),
cameraButton: document.getElementById("cameraButton"),
targetToggle: document.getElementById("targetToggle"),
guideToggle: document.getElementById("guideToggle"),
scoreRing: document.getElementById("scoreRing"),
scoreNumber: document.getElementById("scoreNumber"),
scoreStatus: document.getElementById("scoreStatus"),
scoreDetail: document.getElementById("scoreDetail"),
offsetValue: document.getElementById("offsetValue")
};
const targetArea = polygonArea(targetCorners);
const targetScale = Math.max(
0.001,
targetCorners[0].distanceTo(targetCorners[2])
);
function updateProjection() {
frame.rotation.set(state.tilt, state.yaw, 0, "YXZ");
const current = projectedCorners();
const guideArray = guideGeometry.attributes.position.array;
for (let i = 0; i < current.length; i++) {
guideArray[i * 3] = current[i].x;
guideArray[i * 3 + 1] = current[i].y;
guideArray[i * 3 + 2] = 0;
}
guideGeometry.attributes.position.needsUpdate = true;
guideGeometry.computeBoundingSphere();
const currentCenter = polygonCentroid(current);
const centerError = currentCenter.distanceTo(targetCenter) / targetScale;
let cornerError = 0;
for (let i = 0; i < current.length; i++) {
cornerError += current[i].distanceTo(targetCorners[i]) / targetScale;
}
cornerError /= current.length;
const currentArea = polygonArea(current);
const areaError = Math.abs(Math.log(currentArea / targetArea));
const shapeError = cornerError + areaError * 0.32;
const combinedError = centerError * 0.56 + shapeError * 0.44;
const score = Math.max(
0,
Math.min(100, Math.round(100 * Math.exp(-3.15 * combinedError)))
);
const scoreColor =
score > 90 ? "#16b98a" : score > 68 ? "#e2a132" : "#df6657";
ui.scoreRing.style.background =
`conic-gradient(${scoreColor} ${score}%, rgba(24,49,58,0.09) 0)`;
ui.scoreNumber.textContent = score;
ui.offsetValue.textContent = `${(centerError * targetScale).toFixed(2)} u`;
ui.offsetValue.style.color = scoreColor;
if (score > 97) {
ui.scoreStatus.textContent = "Locked";
ui.scoreDetail.textContent = "Silhouette matches";
} else if (score > 82) {
ui.scoreStatus.textContent = "Close";
ui.scoreDetail.textContent = "Fine-tune the shape";
} else if (score > 55) {
ui.scoreStatus.textContent = "Drifting";
ui.scoreDetail.textContent = "Offset is visible";
} else {
ui.scoreStatus.textContent = "Misaligned";
ui.scoreDetail.textContent = "Reset and realign";
}
}
function syncOutputs() {
ui.yaw.value = state.yaw;
ui.tilt.value = state.tilt;
ui.azimuth.value = state.lightAzimuth;
ui.elevation.value = state.lightElevation;
ui.beam.value = state.beam;
ui.yawOut.textContent = `${Math.round(state.yaw)}°`;
ui.tiltOut.textContent = `${Math.round(state.tilt)}°`;
ui.azimuthOut.textContent = `${Math.round(state.lightAzimuth)}°`;
ui.elevationOut.textContent = `${Math.round(state.lightElevation)}°`;
ui.beamOut.textContent = `${Math.round(state.beam)}°`;
}
function applyState() {
syncOutputs();
updateLightPosition();
updateProjection();
}
function stopAuto() {
state.auto = false;
ui.autoButton.classList.remove("active");
ui.autoButton.textContent = "Auto sweep";
}
function readControls() {
state.yaw = Number(ui.yaw.value);
state.tilt = Number(ui.tilt.value);
state.lightAzimuth = Number(ui.azimuth.value);
state.lightElevation = Number(ui.elevation.value);
state.beam = Number(ui.beam.value);
applyState();
}
for (const input of [ui.yaw, ui.tilt, ui.azimuth, ui.elevation, ui.beam]) {
input.addEventListener("input", () => {
stopAuto();
readControls();
});
}
ui.autoButton.addEventListener("click", () => {
state.auto = !state.auto;
ui.autoButton.classList.toggle("active", state.auto);
ui.autoButton.textContent = state.auto ? "Sweep on" : "Auto sweep";
});
ui.resetButton.addEventListener("click", () => {
stopAuto();
state.yaw = 0;
state.tilt = 0;
state.lightAzimuth = -39;
state.lightElevation = 3;
state.beam = 55;
applyState();
});
ui.cameraButton.addEventListener("click", resetCamera);
ui.targetToggle.addEventListener("change", () => {
targetGroup.visible = ui.targetToggle.checked;
targetLabel.visible = ui.targetToggle.checked;
});
ui.guideToggle.addEventListener("change", () => {
projectedEdge.visible = ui.guideToggle.checked;
});
// -------------------------------------------------------------------------
// Custom camera and object controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragMode = null;
let previousX = 0;
let previousY = 0;
function setPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function frameHit(event) {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObject(frame, true).length > 0;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
setPointer(event);
previousX = event.clientX;
previousY = event.clientY;
if (event.shiftKey || event.button === 2) {
dragMode = "pan";
} else if (frameHit(event)) {
dragMode = "frame";
stopAuto();
} else {
dragMode = "orbit";
}
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = dragMode === "frame" ? "ew-resize" : "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (!dragMode) {
renderer.domElement.style.cursor = frameHit(event) ? "ew-resize" : "grab";
return;
}
if (dragMode === "frame") {
state.yaw = THREE.MathUtils.clamp(state.yaw + dx * 0.32, -80, 80);
state.tilt = THREE.MathUtils.clamp(state.tilt + dy * 0.14, -30, 30);
applyState();
} else if (dragMode === "orbit") {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.1,
1.18
);
} else if (dragMode === "pan") {
const right = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion);
const up = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion);
const scale = cameraState.distance * 0.001;
cameraState.focus.addScaledVector(right, -dx * scale);
cameraState.focus.addScaledVector(up, dy * scale);
cameraState.focus.x = THREE.MathUtils.clamp(cameraState.focus.x, -6, 9);
cameraState.focus.y = THREE.MathUtils.clamp(cameraState.focus.y, 0.7, 7);
cameraState.focus.z = THREE.MathUtils.clamp(cameraState.focus.z, -4, 3);
}
});
function endPointer(event) {
dragMode = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "grab";
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
9,
28
);
},
{ passive: false }
);
function resetCamera() {
cameraState.yaw = cameraHome.yaw;
cameraState.pitch = cameraHome.pitch;
cameraState.distance = cameraHome.distance;
cameraState.focus.copy(cameraHome.focus);
}
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
ui.resetButton.click();
}
if (event.code === "Space" && document.activeElement?.tagName !== "INPUT") {
event.preventDefault();
ui.autoButton.click();
}
});
function updateCamera() {
const horizontal = Math.cos(cameraState.pitch) * cameraState.distance;
camera.position.set(
cameraState.focus.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.focus.y + Math.sin(cameraState.pitch) * cameraState.distance,
cameraState.focus.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.focus);
}
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
if (state.auto) {
state.yaw = Math.sin(elapsed * 0.85) * 68;
applyState();
}
updateCamera();
renderer.render(scene, camera);
}
applyState();
updateCamera();
animate();
requestAnimationFrame(() => {
document.getElementById("loading").classList.add("hidden");
});
</script>
</body>
</html>
```