Prompt specification
Build or customize the Three.js 3D scene "Forced-Perspective Stage Puzzle" 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: Forced-Perspective Stage Puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/forced-perspective-stage-puzzle-x3320
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows perspective, projection, and visual composition. Construct a compact stage where separated shapes align from one marked viewpoint. Let users orbit away to reveal the spatial trick and inspect the true arrangement. Voxel style.
Working Three.js Starter (forced-perspective-stage-puzzle-x3320):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Parallax Study — Three Places, One Image</title>
<style>
:root {
--bg: #08100f;
--panel: rgba(12, 22, 20, 0.78);
--line: rgba(210, 232, 221, 0.18);
--text: #e8eee9;
--muted: #8ca39a;
--teal: #48d5c2;
--yellow: #f1c75b;
--coral: #ff7164;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
--serif: Georgia, "Times New Roman", serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #172723 0%, #0b1513 42%, #060a09 100%);
color: var(--text);
font-family: var(--mono);
}
button,
canvas {
-webkit-tap-highlight-color: transparent;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
background:
linear-gradient(180deg, rgba(3, 7, 6, 0.42), transparent 20%, transparent 76%, rgba(3, 7, 6, 0.58)),
radial-gradient(circle at 50% 45%, transparent 42%, rgba(2, 5, 4, 0.42) 100%);
}
.ui {
position: fixed;
z-index: 5;
pointer-events: none;
}
.topbar {
top: 0;
left: 0;
right: 0;
height: 58px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 34px;
border-bottom: 1px solid var(--line);
background: linear-gradient(180deg, rgba(7, 13, 12, 0.86), rgba(7, 13, 12, 0.18));
font-size: 10px;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
width: 12px;
height: 12px;
border: 2px solid var(--teal);
box-shadow: 5px 5px 0 -3px var(--coral);
transform: rotate(45deg);
}
.top-meta {
display: flex;
align-items: center;
gap: 24px;
color: var(--muted);
}
.top-meta strong {
color: var(--text);
font-weight: 500;
}
.intro {
top: 104px;
left: 38px;
width: min(360px, 31vw);
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 18px;
color: var(--teal);
font-size: 10px;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 30px;
height: 1px;
background: currentColor;
}
h1 {
margin: 0;
font-family: var(--serif);
font-size: clamp(44px, 5.3vw, 76px);
font-weight: 400;
line-height: 0.89;
letter-spacing: -0.055em;
text-wrap: balance;
}
h1 em {
color: var(--yellow);
font-style: italic;
}
.intro p {
max-width: 310px;
margin: 24px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.75;
letter-spacing: 0.035em;
}
.intro-rule {
width: 92px;
height: 3px;
margin-top: 24px;
display: flex;
}
.intro-rule span {
flex: 1;
}
.intro-rule span:nth-child(1) {
background: var(--teal);
}
.intro-rule span:nth-child(2) {
background: var(--yellow);
}
.intro-rule span:nth-child(3) {
background: var(--coral);
}
.readout {
top: 94px;
right: 32px;
width: 244px;
padding: 16px;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(14px);
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.panel-head span:last-child {
color: var(--teal);
}
#preview {
display: block;
width: 100%;
aspect-ratio: 1;
border: 1px solid rgba(210, 232, 221, 0.12);
background: #08100f;
image-rendering: pixelated;
}
.formula {
margin: 13px 0 14px;
padding-bottom: 13px;
border-bottom: 1px solid var(--line);
}
.formula small {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.formula code {
color: var(--text);
font-family: var(--mono);
font-size: 11px;
}
.formula code span {
color: var(--yellow);
}
.depth-stack {
display: grid;
gap: 8px;
}
.depth-row {
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: 9px;
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.depth-row i {
width: 8px;
height: 8px;
}
.depth-row b {
color: var(--muted);
font-weight: 400;
}
.depth-row.far i {
background: var(--teal);
}
.depth-row.mid i {
background: var(--yellow);
}
.depth-row.near i {
background: var(--coral);
}
.instructions {
left: 36px;
bottom: 30px;
display: flex;
align-items: center;
gap: 14px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.mouse {
position: relative;
width: 20px;
height: 29px;
border: 1px solid rgba(232, 238, 233, 0.55);
border-radius: 11px;
}
.mouse::before {
content: "";
position: absolute;
top: 5px;
left: 9px;
width: 1px;
height: 7px;
background: var(--text);
}
.alignment {
left: 50%;
bottom: 26px;
width: min(340px, 34vw);
transform: translateX(-50%);
}
.alignment-status {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 9px;
font-size: 9px;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#status {
color: var(--coral);
}
#status.locked {
color: var(--teal);
}
#angle {
color: var(--text);
font-size: 11px;
font-weight: 500;
}
.track {
position: relative;
height: 3px;
overflow: hidden;
background: rgba(232, 238, 233, 0.12);
}
#alignment-fill {
display: block;
width: 100%;
height: 100%;
background: var(--coral);
transition: background 180ms ease;
}
#alignment-fill.locked {
background: var(--teal);
}
.scale {
display: flex;
justify-content: space-between;
margin-top: 8px;
color: #647970;
font-size: 7px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.reset-wrap {
right: 32px;
bottom: 27px;
pointer-events: auto;
}
#reset {
position: relative;
display: flex;
align-items: center;
gap: 12px;
min-width: 194px;
padding: 14px 16px;
border: 1px solid rgba(232, 238, 233, 0.28);
border-radius: 0;
background: rgba(12, 22, 20, 0.76);
color: var(--text);
font-family: var(--mono);
font-size: 9px;
letter-spacing: 0.13em;
text-transform: uppercase;
cursor: pointer;
backdrop-filter: blur(12px);
transition: border-color 180ms ease, background 180ms ease;
}
#reset:hover,
#reset:focus-visible {
border-color: var(--teal);
background: rgba(19, 38, 34, 0.9);
outline: none;
}
#reset.is-locked {
border-color: rgba(72, 213, 194, 0.65);
}
.view-icon {
position: relative;
width: 24px;
height: 15px;
border: 1px solid var(--teal);
}
.view-icon::before {
content: "";
position: absolute;
top: 3px;
left: 4px;
width: 7px;
height: 7px;
border: 1px solid var(--teal);
border-radius: 50%;
}
.view-icon::after {
content: "";
position: absolute;
top: 3px;
right: 3px;
width: 5px;
height: 5px;
border-right: 1px solid var(--teal);
border-top: 1px solid var(--teal);
}
kbd {
margin-left: auto;
padding: 2px 5px;
border: 1px solid rgba(232, 238, 233, 0.2);
color: var(--muted);
font-family: var(--mono);
font-size: 8px;
font-weight: 400;
}
#loader {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: #08100f;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.2em;
text-transform: uppercase;
transition: opacity 400ms ease, visibility 400ms ease;
}
#loader.hidden {
opacity: 0;
visibility: hidden;
}
.loader-inner {
display: flex;
align-items: center;
gap: 12px;
}
.loader-dot {
width: 8px;
height: 8px;
background: var(--teal);
animation: pulse 900ms ease-in-out infinite alternate;
}
@keyframes pulse {
to {
opacity: 0.2;
transform: scale(0.65);
}
}
@media (max-width: 900px) {
.readout {
width: 210px;
}
.intro {
width: 300px;
}
.intro p {
max-width: 260px;
}
}
@media (max-width: 700px) {
.topbar {
height: 50px;
padding: 0 18px;
}
.top-meta span:first-child {
display: none;
}
.intro {
top: 76px;
left: 20px;
width: calc(100vw - 40px);
}
h1 {
font-size: clamp(38px, 12vw, 58px);
}
.intro p {
max-width: 270px;
margin-top: 15px;
font-size: 9px;
}
.intro-rule {
display: none;
}
.readout {
display: none;
}
.instructions {
left: 20px;
bottom: 86px;
}
.instructions span:last-child {
display: none;
}
.alignment {
left: 20px;
bottom: 32px;
width: calc(100vw - 40px);
transform: none;
}
.reset-wrap {
right: 20px;
bottom: 78px;
}
#reset {
min-width: auto;
padding: 12px;
}
#reset .button-text,
#reset kbd {
display: none;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
scroll-behavior: auto !important;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional voxel composition"></canvas>
<div class="vignette"></div>
<header class="ui topbar">
<div class="brand">
<span class="brand-mark" aria-hidden="true"></span>
<span>Parallax Laboratory</span>
</div>
<div class="top-meta">
<span>Study <strong>01</strong></span>
<span>Three.js / Perspective</span>
<span>Voxel / 15 × 15</span>
</div>
</header>
<section class="ui intro">
<div class="eyebrow">Optical composition</div>
<h1>Three places.<br><em>One image.</em></h1>
<p>
Three separated voxel strokes resolve into a single letter only along
the marked optical axis. Orbit away to inspect the hidden construction.
</p>
<div class="intro-rule" aria-hidden="true">
<span></span><span></span><span></span>
</div>
</section>
<aside class="ui readout" aria-label="Projection readout">
<div class="panel-head">
<span>Camera output</span>
<span>Axis A</span>
</div>
<canvas id="preview" width="240" height="240"></canvas>
<div class="formula">
<small>Pin-hole projection</small>
<code>x′ = f · x / (<span id="camera-z">16.0</span> − z)</code>
</div>
<div class="depth-stack">
<div class="depth-row far">
<i></i><span>Far / left stroke</span><b>z −3.2</b>
</div>
<div class="depth-row mid">
<i></i><span>Mid / crossbar</span><b>z 0.0</b>
</div>
<div class="depth-row near">
<i></i><span>Near / right stroke</span><b>z +3.2</b>
</div>
</div>
</aside>
<div class="ui instructions">
<span class="mouse" aria-hidden="true"></span>
<span>Drag to orbit · Scroll to dolly</span>
</div>
<div class="ui alignment" aria-live="polite">
<div class="alignment-status">
<span id="status">Marked view · locked</span>
<strong id="angle">0.0°</strong>
</div>
<div class="track"><i id="alignment-fill" class="locked"></i></div>
<div class="scale">
<span>Off axis</span>
<span>Optical axis</span>
</div>
</div>
<div class="ui reset-wrap">
<button id="reset" type="button" aria-label="Return to the marked camera viewpoint">
<span class="view-icon" aria-hidden="true"></span>
<span class="button-text">Marked viewpoint</span>
<kbd>R</kbd>
</button>
</div>
<div id="loader">
<div class="loader-inner">
<span class="loader-dot"></span>
<span>Calibrating projection</span>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* ------------------------------------------------------------------
Scene
------------------------------------------------------------------ */
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.setClearColor(0x08100f, 0);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x08100f, 25, 62);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
120
);
const target = new THREE.Vector3(0, 3.2, 0);
const HOME = Object.freeze({
radius: 16,
theta: 0,
phi: Math.PI / 2
});
const current = { ...HOME };
const desired = { ...HOME };
const palette = {
far: 0x48d5c2,
mid: 0xf1c75b,
near: 0xff7164
};
/* ------------------------------------------------------------------
Lighting
------------------------------------------------------------------ */
scene.add(new THREE.HemisphereLight(0xc9eee2, 0x07100d, 1.45));
const keyLight = new THREE.DirectionalLight(0xffefd3, 2.9);
keyLight.position.set(7, 13, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -4;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x53dac7, 1.4);
rimLight.position.set(-9, 7, -8);
scene.add(rimLight);
const coralLight = new THREE.PointLight(palette.near, 13, 17, 2);
coralLight.position.set(4.5, 4.2, 4.5);
scene.add(coralLight);
const tealLight = new THREE.PointLight(palette.far, 12, 17, 2);
tealLight.position.set(-4.5, 3.4, -3.5);
scene.add(tealLight);
const yellowLight = new THREE.PointLight(palette.mid, 9, 14, 2);
yellowLight.position.set(0, 5.8, 1.5);
scene.add(yellowLight);
/* ------------------------------------------------------------------
Stage and construction lines
------------------------------------------------------------------ */
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x09110f,
roughness: 1,
metalness: 0
});
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.32;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(70, 70, 0x3b5c52, 0x20352f);
grid.position.y = -0.305;
grid.material.transparent = true;
grid.material.opacity = 0.26;
scene.add(grid);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x111c19,
roughness: 0.86,
metalness: 0.08
});
const platform = new THREE.Mesh(
new THREE.BoxGeometry(10.8, 0.3, 9.8),
platformMaterial
);
platform.position.set(0, -0.16, 0);
platform.receiveShadow = true;
platform.castShadow = true;
scene.add(platform);
const platformEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(platform.geometry),
new THREE.LineBasicMaterial({
color: 0x49635a,
transparent: true,
opacity: 0.36
})
);
platformEdges.position.copy(platform.position);
scene.add(platformEdges);
const targetFrameMaterial = new THREE.LineBasicMaterial({
color: 0xb9ccc3,
transparent: true,
opacity: 0.22,
depthWrite: false
});
const framePoints = [
new THREE.Vector3(-3.05, 0.03, 0),
new THREE.Vector3( 3.05, 0.03, 0),
new THREE.Vector3( 3.05, 6.38, 0),
new THREE.Vector3(-3.05, 6.38, 0)
];
const targetFrame = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(framePoints),
targetFrameMaterial
);
scene.add(targetFrame);
function makeDashedLine(points, color, opacity, dashSize = 0.16, gapSize = 0.11) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineDashedMaterial({
color,
dashSize,
gapSize,
transparent: true,
opacity,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
return line;
}
const viewpoint = new THREE.Vector3(0, target.y, HOME.radius);
// Projection rays remain anchored to the marked camera position.
for (const corner of framePoints) {
const ray = makeDashedLine(
[viewpoint, corner],
0xb8d0c6,
0.13,
0.18,
0.12
);
scene.add(ray);
}
const viewpointDrop = makeDashedLine(
[
new THREE.Vector3(0, 0.025, HOME.radius),
viewpoint
],
0x8ba49a,
0.26,
0.13,
0.09
);
scene.add(viewpointDrop);
// Floor marker for Camera 01.
const markerRing = new THREE.Mesh(
new THREE.RingGeometry(0.43, 0.49, 48),
new THREE.MeshBasicMaterial({
color: 0xe4eee8,
transparent: true,
opacity: 0.48,
side: THREE.DoubleSide,
depthWrite: false
})
);
markerRing.rotation.x = -Math.PI / 2;
markerRing.position.set(0, -0.002, HOME.radius);
scene.add(markerRing);
const arrowGeometry = new THREE.BufferGeometry();
arrowGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute([
-0.16, 0.006, 15.91,
0.16, 0.006, 15.91,
0.00, 0.006, 15.48
], 3)
);
arrowGeometry.computeVertexNormals();
const arrow = new THREE.Mesh(
arrowGeometry,
new THREE.MeshBasicMaterial({
color: 0xe4eee8,
transparent: true,
opacity: 0.58,
side: THREE.DoubleSide
})
);
scene.add(arrow);
const floorLead = makeDashedLine(
[
new THREE.Vector3(0, 0.006, 11.4),
new THREE.Vector3(0, 0.006, 15.3)
],
0x9db2aa,
0.25,
0.13,
0.1
);
scene.add(floorLead);
function makeLabel(text, color) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 96;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 512, 96);
ctx.fillStyle = "rgba(7, 14, 12, 0.78)";
ctx.fillRect(0, 0, 512, 96);
ctx.fillStyle = color;
ctx.fillRect(0, 0, 7, 96);
ctx.font = "600 31px ui-monospace, monospace";
ctx.fillStyle = "#dce7e1";
ctx.fillText(text, 22, 58);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(2.25, 0.42, 1);
return sprite;
}
const cameraLabel = makeLabel("CAMERA 01 / AXIS", "#dce7e1");
cameraLabel.position.set(0, 0.38, 16.7);
scene.add(cameraLabel);
/* ------------------------------------------------------------------
Voxel target
The exact 15 x 15 "A" is split into three depth layers.
------------------------------------------------------------------ */
const activeRows = [
[5, 6, 7, 8, 9],
[4, 5, 9, 10],
[3, 4, 10, 11],
[2, 3, 11, 12],
[2, 3, 11, 12],
[1, 2, 12, 13],
[1, 2, 12, 13],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
[1, 2, 12, 13],
[1, 2, 12, 13],
[2, 3, 11, 12],
[2, 3, 11, 12],
[3, 4, 10, 11],
[4, 5, 9, 10]
];
const layers = [
{ id: "far", z: -3.2, color: palette.far, pixels: [] },
{ id: "mid", z: 0.0, color: palette.mid, pixels: [] },
{ id: "near", z: 3.2, color: palette.near, pixels: [] }
];
activeRows.forEach((columns, row) => {
columns.forEach((column) => {
let layer;
if (row === 7 || row === 8) {
layer = layers[1];
} else if (column <= 7) {
layer = layers[0];
} else {
layer = layers[2];
}
layer.pixels.push({ row, column });
});
});
const CELL = 0.42;
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const dummy = new THREE.Object3D();
function deterministicRandom(column, row, salt) {
const value = Math.sin(column * 127.1 + row * 311.7 + salt * 74.7) * 43758.5453;
return value - Math.floor(value);
}
layers.forEach((layer, layerIndex) => {
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: layer.color,
emissiveIntensity: 0.075,
roughness: 0.58,
metalness: 0.08
});
const mesh = new THREE.InstancedMesh(
unitBox,
material,
layer.pixels.length
);
mesh.castShadow = true;
mesh.receiveShadow = true;
// Perspective compensation: farther voxels are physically larger,
// while nearer voxels are smaller. From the marked axis they occupy
// exactly the same screen-space positions.
const depthScale = (HOME.radius - layer.z) / HOME.radius;
layer.pixels.forEach(({ row, column }, index) => {
const baseX = (column - 7) * CELL;
const baseY = target.y + (7 - row) * CELL;
dummy.position.set(
baseX * depthScale,
target.y + (baseY - target.y) * depthScale,
layer.z
);
const side = CELL * 0.89 * depthScale;
const depth = CELL * 0.82 * depthScale;
dummy.scale.set(side, side, depth);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
const color = new THREE.Color(layer.color);
const hsl = {};
color.getHSL(hsl);
color.setHSL(
hsl.h + (deterministicRandom(column, row, layerIndex) - 0.5) * 0.012,
hsl.s,
THREE.MathUtils.clamp(
hsl.l + (deterministicRandom(row, column, layerIndex + 8) - 0.5) * 0.07,
0.2,
0.82
)
);
mesh.setColorAt(index, color);
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
scene.add(mesh);
// A colored strip marks each physical depth slice on the stage.
const strip = new THREE.Mesh(
new THREE.BoxGeometry(8.8, 0.025, 0.055),
new THREE.MeshBasicMaterial({
color: layer.color,
transparent: true,
opacity: 0.46
})
);
strip.position.set(0, 0.018, layer.z);
scene.add(strip);
const label = makeLabel(
`${layer.id.toUpperCase()} / Z ${layer.z >= 0 ? "+" : ""}${layer.z.toFixed(1)}`,
`#${layer.color.toString(16).padStart(6, "0")}`
);
label.position.set(-4.25, 0.35, layer.z);
scene.add(label);
});
/* ------------------------------------------------------------------
Fixed 2D output preview
------------------------------------------------------------------ */
const preview = document.querySelector("#preview");
const previewContext = preview.getContext("2d");
const previewSize = 240;
const previewCell = 13;
const previewMargin = (previewSize - 15 * previewCell) / 2;
function drawPreview() {
previewContext.fillStyle = "#08100f";
previewContext.fillRect(0, 0, previewSize, previewSize);
previewContext.strokeStyle = "rgba(180, 210, 199, 0.08)";
previewContext.lineWidth = 1;
for (let i = 0; i <= 15; i++) {
const p = previewMargin + i * previewCell;
previewContext.beginPath();
previewContext.moveTo(p, 0);
previewContext.lineTo(p, previewSize);
previewContext.stroke();
previewContext.beginPath();
previewContext.moveTo(0, p);
previewContext.lineTo(previewSize, p);
previewContext.stroke();
}
layers.forEach((layer) => {
previewContext.fillStyle = `#${layer.color.toString(16).padStart(6, "0")}`;
layer.pixels.forEach(({ row, column }) => {
previewContext.fillRect(
previewMargin + column * previewCell,
previewMargin + row * previewCell,
previewCell - 1,
previewCell - 1
);
});
});
previewContext.strokeStyle = "rgba(232, 238, 233, 0.24)";
previewContext.strokeRect(
previewMargin - 4.5,
previewMargin - 4.5,
15 * previewCell + 8,
15 * previewCell + 8
);
}
drawPreview();
/* ------------------------------------------------------------------
Custom orbit controls
------------------------------------------------------------------ */
let dragging = false;
let pointerId = null;
let lastX = 0;
let lastY = 0;
let resetTween = null;
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
function shortestAngleDifference(from, to) {
return Math.atan2(Math.sin(to - from), Math.cos(to - from));
}
function setCameraFromState(state) {
const sinPhi = Math.sin(state.phi);
camera.position.set(
target.x + state.radius * sinPhi * Math.sin(state.theta),
target.y + state.radius * Math.cos(state.phi),
target.z + state.radius * sinPhi * Math.cos(state.theta)
);
camera.lookAt(target);
}
function cancelTween() {
resetTween = null;
}
function resetView() {
const to = { ...HOME };
if (reducedMotion) {
Object.assign(current, to);
Object.assign(desired, to);
setCameraFromState(current);
return;
}
resetTween = {
start: performance.now(),
duration: 850,
from: { ...current },
to
};
Object.assign(desired, to);
}
canvas.addEventListener("pointerdown", (event) => {
cancelTween();
dragging = true;
pointerId = event.pointerId;
lastX = event.clientX;
lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging || event.pointerId !== pointerId) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
desired.theta -= dx * 0.006;
desired.phi = THREE.MathUtils.clamp(
desired.phi - dy * 0.006,
0.48,
1.48
);
});
function endDrag(event) {
if (event.pointerId !== pointerId) return;
dragging = false;
pointerId = null;
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("lostpointercapture", () => {
dragging = false;
pointerId = null;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cancelTween();
desired.radius = THREE.MathUtils.clamp(
desired.radius * Math.exp(event.deltaY * 0.001),
9,
26
);
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
resetView();
return;
}
cancelTween();
const amount = 0.08;
if (event.key === "ArrowLeft") desired.theta += amount;
if (event.key === "ArrowRight") desired.theta -= amount;
if (event.key === "ArrowUp") desired.phi -= amount;
if (event.key === "ArrowDown") desired.phi += amount;
desired.phi = THREE.MathUtils.clamp(desired.phi, 0.48, 1.48);
});
document.querySelector("#reset").addEventListener("click", resetView);
/* ------------------------------------------------------------------
Readouts and render loop
------------------------------------------------------------------ */
const statusElement = document.querySelector("#status");
const angleElement = document.querySelector("#angle");
const alignmentFill = document.querySelector("#alignment-fill");
const cameraZElement = document.querySelector("#camera-z");
const resetButton = document.querySelector("#reset");
const homeDirection = new THREE.Vector3(0, 0, 1);
const currentDirection = new THREE.Vector3();
function updateReadout() {
currentDirection
.copy(camera.position)
.sub(target)
.normalize();
const angle = Math.acos(
THREE.MathUtils.clamp(currentDirection.dot(homeDirection), -1, 1)
);
const angleDegrees = THREE.MathUtils.radToDeg(angle);
const alignment = Math.max(0, 100 * (1 - angle / (Math.PI / 4)));
const exactMarkedView =
angleDegrees < 0.65 &&
Math.abs(current.radius - HOME.radius) < 0.12 &&
Math.abs(current.phi - HOME.phi) < 0.008;
angleElement.textContent = `${angleDegrees.toFixed(1)}°`;
cameraZElement.textContent = camera.position.z.toFixed(1);
alignmentFill.style.width = `${alignment}%`;
alignmentFill.classList.toggle("locked", angleDegrees < 0.65);
resetButton.classList.toggle("is-locked", exactMarkedView);
if (exactMarkedView) {
statusElement.textContent = "Marked view · locked";
statusElement.classList.add("locked");
} else if (angleDegrees < 0.65) {
statusElement.textContent = "Optical axis · zoomed";
statusElement.classList.add("locked");
} else {
statusElement.textContent = "Off axis · structure exposed";
statusElement.classList.remove("locked");
}
targetFrameMaterial.opacity = angleDegrees < 0.65 ? 0.34 : 0.17;
}
function updateCamera(delta) {
if (resetTween) {
const progress = Math.min(
1,
(performance.now() - resetTween.start) / resetTween.duration
);
const eased = 1 - Math.pow(1 - progress, 3);
current.radius = THREE.MathUtils.lerp(
resetTween.from.radius,
resetTween.to.radius,
eased
);
current.phi = THREE.MathUtils.lerp(
resetTween.from.phi,
resetTween.to.phi,
eased
);
current.theta =
resetTween.from.theta +
shortestAngleDifference(
resetTween.from.theta,
resetTween.to.theta
) * eased;
if (progress >= 1) {
current.theta = resetTween.to.theta;
resetTween = null;
}
} else {
const damping = 1 - Math.pow(0.001, delta);
current.radius = THREE.MathUtils.lerp(
current.radius,
desired.radius,
damping
);
current.phi = THREE.MathUtils.lerp(
current.phi,
desired.phi,
damping
);
current.theta = THREE.MathUtils.lerp(
current.theta,
desired.theta,
damping
);
}
setCameraFromState(current);
}
const clock = new THREE.Clock();
let firstFrame = true;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const time = clock.elapsedTime;
updateCamera(delta);
updateReadout();
const pulse = 1 + Math.sin(time * 1.7) * 0.045;
coralLight.intensity = 13 * pulse;
tealLight.intensity = 12 * (2 - pulse);
markerRing.material.opacity = 0.43 + Math.sin(time * 2.2) * 0.08;
renderer.render(scene, camera);
if (firstFrame) {
firstFrame = false;
setTimeout(() => document.querySelector("#loader").classList.add("hidden"), 180);
}
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
});
setCameraFromState(current);
animate();
</script>
</body>
</html>
```