Prompt specification
Build or customize the Three.js 3D scene "Sandwich exploded stack" 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: Sandwich exploded stack
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/sandwich-exploded-stack-x0149
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing sandwich layers. Separate bread, cheese, tomato, and leaf layers vertically above a plate; align their footprints so the intended assembled order is obvious from one view. Voxel style.
Working Three.js Starter (sandwich-exploded-stack-x0149):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sandwich Stack — Voxel Study</title>
<style>
:root {
--ink: #21362e;
--muted: #6f786f;
--paper: #efe8da;
--label-width: 154px;
--label-right: 28px;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage,
#stage canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#stage canvas {
display: block;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
z-index: 5;
pointer-events: none;
}
#intro {
top: 30px;
left: 32px;
max-width: 320px;
}
.eyebrow {
margin-bottom: 9px;
color: #8b744e;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(30px, 4vw, 54px);
font-weight: 850;
line-height: 0.92;
letter-spacing: -0.055em;
}
#intro p {
max-width: 245px;
margin: 14px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
#order {
bottom: 28px;
left: 32px;
padding: 12px 14px 11px;
border: 1px solid rgba(33, 54, 46, 0.12);
border-radius: 10px;
background: rgba(255, 252, 245, 0.62);
box-shadow: 0 8px 30px rgba(56, 47, 32, 0.06);
backdrop-filter: blur(9px);
}
#order span {
display: block;
margin-bottom: 6px;
color: #8b744e;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.2em;
}
#order strong {
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
}
#order i {
padding: 0 4px;
color: #ad9366;
font-style: normal;
}
#hint {
right: 28px;
bottom: 32px;
color: rgba(33, 54, 46, 0.58);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#reset {
position: fixed;
right: 28px;
bottom: 58px;
z-index: 8;
padding: 8px 12px;
border: 1px solid rgba(33, 54, 46, 0.17);
border-radius: 8px;
background: rgba(255, 252, 245, 0.78);
color: var(--ink);
font: inherit;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
cursor: pointer;
backdrop-filter: blur(9px);
transition:
background 160ms ease,
transform 160ms ease;
}
#reset:hover {
background: #fffdf7;
transform: translateY(-2px);
}
#reset:active {
transform: translateY(0);
}
#leaders {
position: fixed;
inset: 0;
z-index: 3;
width: 100%;
height: 100%;
overflow: visible;
pointer-events: none;
}
#labels {
position: fixed;
inset: 0;
z-index: 4;
pointer-events: none;
}
.label {
position: absolute;
right: var(--label-right);
display: flex;
align-items: center;
width: var(--label-width);
min-height: 38px;
padding: 8px 10px;
border: 1px solid rgba(33, 54, 46, 0.11);
border-radius: 8px;
background: rgba(255, 252, 245, 0.78);
box-shadow: 0 8px 24px rgba(56, 47, 32, 0.05);
transform: translateY(-50%);
backdrop-filter: blur(8px);
}
.label .number {
width: 23px;
color: #9a927f;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.06em;
}
.label .swatch {
width: 7px;
height: 25px;
margin-right: 9px;
border-radius: 2px;
background: var(--swatch);
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06);
}
.label .name {
font-size: 9px;
font-weight: 850;
letter-spacing: 0.09em;
white-space: nowrap;
}
@media (max-width: 760px) {
:root {
--label-width: 126px;
--label-right: 14px;
}
#intro {
top: 20px;
left: 20px;
}
#intro p,
#leaders,
.label,
#hint {
display: none;
}
#order {
bottom: 18px;
left: 20px;
}
#reset {
right: 16px;
bottom: 18px;
}
}
</style>
</head>
<body>
<main id="stage" aria-label="Interactive exploded voxel sandwich"></main>
<header id="intro" class="hud">
<div class="eyebrow">Exploded assembly · voxel study</div>
<h1>THE<br />SANDWICH<br />STACK</h1>
<p>
Bread, leaf, tomato and cheese separated into a perfectly aligned
assembly.
</p>
</header>
<aside id="order" class="hud">
<span>Assembly order</span>
<strong>
BREAD <i>→</i> LEAF <i>→</i> TOMATO <i>→</i> CHEESE <i>→</i> BREAD
</strong>
</aside>
<svg id="leaders" aria-hidden="true"></svg>
<div id="labels" aria-hidden="true"></div>
<button id="reset" type="button">Reset view</button>
<div id="hint" class="hud">Drag to orbit · Scroll to zoom · Double-click to reset</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 stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xefe8da);
scene.fog = new THREE.Fog(0xefe8da, 19, 38);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
100
);
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;
renderer.domElement.setAttribute(
"aria-label",
"Drag to orbit an exploded voxel sandwich"
);
stage.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xfff6df,
0x78918e,
2.15
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffefd0, 3.4);
keyLight.position.set(-6, 12, 8);
keyLight.target.position.set(0, 2.5, 0);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 32;
keyLight.shadow.bias = -0.00045;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight, keyLight.target);
const fillLight = new THREE.DirectionalLight(0xbdd7df, 1.15);
fillLight.position.set(7, 7, -8);
scene.add(fillLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0xeee6d6,
roughness: 1,
metalness: 0,
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.055;
ground.receiveShadow = true;
scene.add(ground);
// -------------------------------------------------------------------------
// Small utilities
// -------------------------------------------------------------------------
function hash(x, z, salt = 0) {
let n =
Math.imul(x + 101, 374761393) ^
Math.imul(z + 57, 668265263) ^
Math.imul(salt + 13, 2246822519);
n = Math.imul(n ^ (n >>> 13), 1274126177);
return ((n ^ (n >>> 16)) >>> 0) / 4294967295;
}
function insideRoundedRect(x, z, halfX, halfZ, radius) {
const dx = Math.max(Math.abs(x) - (halfX - radius), 0);
const dz = Math.max(Math.abs(z) - (halfZ - radius), 0);
return dx * dx + dz * dz <= radius * radius;
}
function createVoxelMesh(items, options = {}) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material =
options.material ||
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: options.roughness ?? 0.78,
metalness: 0,
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
items.length
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
items.forEach((item, index) => {
dummy.position.set(item.x, item.y, item.z);
dummy.scale.set(item.sx, item.sy, item.sz);
dummy.rotation.set(0, item.rotY || 0, 0);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
mesh.setColorAt(index, color.set(item.color));
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
scene.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Dimensions and layer heights
// -------------------------------------------------------------------------
const VOXEL = 0.24;
const BREAD_THICKNESS = 0.22;
const BASE_Y = 0.38;
const LEAF_Y = 2.02;
const TOMATO_Y = 3.66;
const CHEESE_Y = 5.30;
const TOP_Y = 6.94;
// -------------------------------------------------------------------------
// Voxel plate
// -------------------------------------------------------------------------
const plateItems = [];
const plateCell = 0.25;
for (let ix = -14; ix <= 14; ix++) {
for (let iz = -14; iz <= 14; iz++) {
const radius = Math.hypot(ix, iz);
if (radius > 14.1) continue;
const isRim = radius > 12.35;
const variation = hash(ix, iz, 4);
plateItems.push({
x: ix * plateCell,
y: 0.075 + (variation - 0.5) * 0.012,
z: iz * plateCell,
sx: 0.242,
sy: 0.15,
sz: 0.242,
color: isRim
? variation > 0.5
? "#8da7a5"
: "#829c9a"
: variation > 0.78
? "#e5ece8"
: "#d6e2de",
});
}
}
createVoxelMesh(plateItems, { roughness: 0.62 });
// -------------------------------------------------------------------------
// Bread slices
// -------------------------------------------------------------------------
const breadCells = new Set();
for (let ix = -9; ix <= 9; ix++) {
for (let iz = -6; iz <= 6; iz++) {
if (insideRoundedRect(ix, iz, 9.45, 6.45, 2.35)) {
breadCells.add(`${ix},${iz}`);
}
}
}
function breadItems(y, salt) {
const items = [];
for (const key of breadCells) {
const [ix, iz] = key.split(",").map(Number);
const isEdge =
!breadCells.has(`${ix + 1},${iz}`) ||
!breadCells.has(`${ix - 1},${iz}`) ||
!breadCells.has(`${ix},${iz + 1}`) ||
!breadCells.has(`${ix},${iz - 1}`);
const variation = hash(ix, iz, salt);
const crumbColors = ["#f2ca80", "#f6d38f", "#edbd70"];
const crustColors = ["#c87532", "#d1843a", "#bd682d"];
items.push({
x: ix * VOXEL,
y,
z: iz * VOXEL,
sx: VOXEL * 0.94,
sy: BREAD_THICKNESS,
sz: VOXEL * 0.94,
color: isEdge
? crustColors[Math.floor(variation * crustColors.length)]
: crumbColors[Math.floor(variation * crumbColors.length)],
});
}
return items;
}
createVoxelMesh(breadItems(BASE_Y, 1));
createVoxelMesh(breadItems(TOP_Y, 2));
// Sesame seeds on the upper bread.
const sesameItems = [];
for (const key of breadCells) {
const [ix, iz] = key.split(",").map(Number);
const isEdge =
!breadCells.has(`${ix + 1},${iz}`) ||
!breadCells.has(`${ix - 1},${iz}`) ||
!breadCells.has(`${ix},${iz + 1}`) ||
!breadCells.has(`${ix},${iz - 1}`);
if (
!isEdge &&
Math.abs(iz) <= 5 &&
hash(ix, iz, 12) > 0.955
) {
sesameItems.push({
x: ix * VOXEL,
y: TOP_Y + BREAD_THICKNESS * 0.5 + 0.025,
z: iz * VOXEL,
sx: 0.055,
sy: 0.045,
sz: 0.145,
rotY: hash(ix, iz, 14) > 0.5 ? 0 : Math.PI / 2,
color: hash(ix, iz, 15) > 0.5 ? "#fff0bd" : "#f8df9f",
});
}
}
createVoxelMesh(sesameItems);
// -------------------------------------------------------------------------
// Ruffled leaf layer
// -------------------------------------------------------------------------
const leafItems = [];
for (let ix = -10; ix <= 10; ix++) {
for (let iz = -6; iz <= 6; iz++) {
const edgeX = 9.35 + 0.72 * Math.sin(iz * 1.2 + 0.4);
const edgeZ = 6.25 + 0.58 * Math.cos(ix * 0.82);
const ellipse =
(Math.abs(ix) / 10.6) ** 2 +
(Math.abs(iz) / 7.25) ** 2 <
1.12;
if (Math.abs(ix) > edgeX || Math.abs(iz) > edgeZ || !ellipse) {
continue;
}
const nearEdge =
Math.abs(ix) > edgeX - 1.2 || Math.abs(iz) > edgeZ - 1.1;
if (nearEdge && hash(ix, iz, 20) < 0.24) continue;
const variation = hash(ix, iz, 21);
let color;
if (iz === 0) {
color = variation > 0.5 ? "#8ac65b" : "#79b34d";
} else if (nearEdge) {
color = variation > 0.5 ? "#34793a" : "#2e6e35";
} else {
color = variation > 0.7
? "#5da84a"
: variation > 0.3
? "#4e9841"
: "#438a3c";
}
leafItems.push({
x: ix * VOXEL,
y: LEAF_Y,
z: iz * VOXEL,
sx: VOXEL * 0.95,
sy: 0.21,
sz: VOXEL * 0.95,
color,
});
}
}
createVoxelMesh(leafItems);
// Slightly raised central leaf vein.
const veinItems = [];
for (let ix = -6; ix <= 6; ix++) {
veinItems.push({
x: ix * VOXEL,
y: LEAF_Y + 0.13,
z: 0,
sx: 0.17,
sy: 0.065,
sz: 0.105,
color: ix % 2 === 0 ? "#9ad267" : "#86c458",
});
}
createVoxelMesh(veinItems);
// -------------------------------------------------------------------------
// Overlapping tomato slices
// -------------------------------------------------------------------------
const tomatoCenters = [
{ x: -2.65, z: 0.05 },
{ x: 0, z: -0.1 },
{ x: 2.65, z: 0.08 },
];
const tomatoItems = [];
for (let ix = -8; ix <= 8; ix++) {
for (let iz = -5; iz <= 5; iz++) {
let bestRatio = Infinity;
for (const center of tomatoCenters) {
const dx = (ix - center.x) / 5.15;
const dz = (iz - center.z) / 4.55;
bestRatio = Math.min(bestRatio, Math.hypot(dx, dz));
}
if (bestRatio > 1) continue;
const variation = hash(ix, iz, 30);
let color;
if (bestRatio > 0.78) {
color = variation > 0.5 ? "#ad302f" : "#bd3531";
} else if (bestRatio < 0.25) {
color = variation > 0.5 ? "#ef7154" : "#e96348";
} else {
color = variation > 0.62
? "#e3543f"
: variation > 0.3
? "#d94738"
: "#cf4034";
}
tomatoItems.push({
x: ix * VOXEL,
y: TOMATO_Y,
z: iz * VOXEL,
sx: VOXEL * 0.95,
sy: 0.22,
sz: VOXEL * 0.95,
color,
});
}
}
createVoxelMesh(tomatoItems);
const tomatoSeeds = [];
tomatoCenters.forEach((center, sliceIndex) => {
for (let i = 0; i < 7; i++) {
const angle = (i / 7) * Math.PI * 2 + sliceIndex * 0.31;
const radius = 1.9 + hash(i, sliceIndex, 40) * 0.55;
tomatoSeeds.push({
x: (center.x + Math.cos(angle) * radius) * VOXEL,
y: TOMATO_Y + 0.145,
z: (center.z + Math.sin(angle) * radius * 0.8) * VOXEL,
sx: 0.075,
sy: 0.06,
sz: 0.095,
rotY: angle,
color: i % 3 === 0 ? "#ffd27a" : "#ffe3a0",
});
}
});
createVoxelMesh(tomatoSeeds);
// -------------------------------------------------------------------------
// Cheese layer with clipped corners and a few square holes
// -------------------------------------------------------------------------
const cheeseHoles = new Set([
"3,1",
"-4,-2",
"1,4",
"-1,-4",
"6,-1",
]);
const cheeseItems = [];
for (let ix = -9; ix <= 9; ix++) {
for (let iz = -6; iz <= 6; iz++) {
if (Math.abs(ix) + Math.abs(iz) > 13) continue;
if (cheeseHoles.has(`${ix},${iz}`)) continue;
const variation = hash(ix, iz, 50);
cheeseItems.push({
x: ix * VOXEL,
y: CHEESE_Y,
z: iz * VOXEL,
sx: VOXEL * 0.96,
sy: 0.2,
sz: VOXEL * 0.96,
color: variation > 0.76
? "#ffda57"
: variation > 0.3
? "#f6ca38"
: "#efbd2f",
});
}
}
createVoxelMesh(cheeseItems, { roughness: 0.64 });
// -------------------------------------------------------------------------
// Subtle central alignment guide
// -------------------------------------------------------------------------
const guideItems = [];
for (let y = 0.58; y < TOP_Y; y += 0.29) {
guideItems.push({
x: 0,
y,
z: 0,
sx: 0.035,
sy: 0.075,
sz: 0.035,
color: "#b99b61",
});
}
createVoxelMesh(guideItems, {
material: new THREE.MeshBasicMaterial({
color: 0xb99b61,
transparent: true,
opacity: 0.38,
depthWrite: false,
}),
castShadow: false,
receiveShadow: false,
});
// -------------------------------------------------------------------------
// Labels and projected leader lines
// -------------------------------------------------------------------------
const labelDefinitions = [
{
id: "top",
number: "05",
name: "TOP BREAD",
color: "#d1843a",
y: TOP_Y,
halfWidth: 2.25,
},
{
id: "cheese",
number: "04",
name: "CHEESE",
color: "#f1c334",
y: CHEESE_Y,
halfWidth: 2.25,
},
{
id: "tomato",
number: "03",
name: "TOMATO",
color: "#d94738",
y: TOMATO_Y,
halfWidth: 1.85,
},
{
id: "leaf",
number: "02",
name: "LEAF",
color: "#4e9841",
y: LEAF_Y,
halfWidth: 2.35,
},
{
id: "base",
number: "01",
name: "BASE BREAD",
color: "#d1843a",
y: BASE_Y,
halfWidth: 2.25,
},
];
const labelsElement = document.getElementById("labels");
const leadersElement = document.getElementById("leaders");
const svgNamespace = "http://www.w3.org/2000/svg";
labelDefinitions.forEach((definition) => {
const label = document.createElement("div");
label.className = "label";
label.id = `label-${definition.id}`;
label.style.setProperty("--swatch", definition.color);
label.style.top = "50%";
label.innerHTML = `
<span class="number">${definition.number}</span>
<span class="swatch"></span>
<span class="name">${definition.name}</span>
`;
labelsElement.appendChild(label);
const path = document.createElementNS(svgNamespace, "path");
path.setAttribute("fill", "none");
path.setAttribute("stroke", definition.color);
path.setAttribute("stroke-width", "1.25");
path.setAttribute("stroke-linecap", "round");
path.setAttribute("opacity", "0.54");
const dot = document.createElementNS(svgNamespace, "circle");
dot.setAttribute("r", "3");
dot.setAttribute("fill", definition.color);
dot.setAttribute("opacity", "0.72");
leadersElement.appendChild(path);
leadersElement.appendChild(dot);
definition.element = label;
definition.path = path;
definition.dot = dot;
});
// -------------------------------------------------------------------------
// Custom camera controls — no addon imports
// -------------------------------------------------------------------------
const target = new THREE.Vector3(0, 3.15, 0);
const defaultView = {
theta: 0.22,
phi: 1.22,
radius: 14.8,
};
let theta = defaultView.theta;
let phi = defaultView.phi;
let radius = defaultView.radius;
function updateCamera() {
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
function resetView() {
theta = defaultView.theta;
phi = defaultView.phi;
radius = defaultView.radius;
}
const pointers = new Map();
let previousPinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
});
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
previousPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
});
if (pointers.size === 1) {
theta -= dx * 0.006;
phi = THREE.MathUtils.clamp(phi + dy * 0.005, 0.42, 1.48);
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (previousPinchDistance > 0) {
radius = THREE.MathUtils.clamp(
radius * (previousPinchDistance / distance),
9.5,
23
);
}
previousPinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
previousPinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
radius = THREE.MathUtils.clamp(
radius * Math.exp(event.deltaY * 0.001),
9.5,
23
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetView);
document.getElementById("reset").addEventListener("click", resetView);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetView();
if (event.key === "ArrowLeft") theta -= 0.08;
if (event.key === "ArrowRight") theta += 0.08;
if (event.key === "ArrowUp") phi -= 0.05;
if (event.key === "ArrowDown") phi += 0.05;
if (event.key === "+" || event.key === "=") {
radius = Math.max(9.5, radius - 0.6);
}
if (event.key === "-" || event.key === "_") {
radius = Math.min(23, radius + 0.6);
}
phi = THREE.MathUtils.clamp(phi, 0.42, 1.48);
});
// -------------------------------------------------------------------------
// Responsive resizing and label projection
// -------------------------------------------------------------------------
const projectionA = new THREE.Vector3();
const projectionB = new THREE.Vector3();
function projectToScreen(worldPosition, output) {
output.copy(worldPosition).project(camera);
return {
x: (output.x * 0.5 + 0.5) * window.innerWidth,
y: (-output.y * 0.5 + 0.5) * window.innerHeight,
};
}
function updateLabels() {
if (window.innerWidth <= 760) return;
const mobileLabel = window.innerWidth < 1000;
const labelWidth = mobileLabel ? 126 : 154;
const labelRight = mobileLabel ? 16 : 28;
const labelLeft = window.innerWidth - labelRight - labelWidth;
labelDefinitions.forEach((definition) => {
projectionA.set(definition.halfWidth, definition.y, 0.1);
projectionB.set(-definition.halfWidth, definition.y, 0.1);
const pointA = projectToScreen(projectionA, new THREE.Vector3());
const pointB = projectToScreen(projectionB, new THREE.Vector3());
const anchor = pointA.x >= pointB.x ? pointA : pointB;
const labelY = THREE.MathUtils.clamp(
anchor.y,
40,
window.innerHeight - 40
);
definition.element.style.top = `${labelY}px`;
definition.path.setAttribute(
"d",
`M ${anchor.x} ${anchor.y} L ${labelLeft - 12} ${labelY}`
);
definition.dot.setAttribute("cx", anchor.x);
definition.dot.setAttribute("cy", anchor.y);
});
}
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = width / height;
camera.fov = width / height < 0.8 ? 50 : 40;
camera.updateProjectionMatrix();
leadersElement.setAttribute("viewBox", `0 0 ${width} ${height}`);
}
window.addEventListener("resize", onResize);
onResize();
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
function animate() {
requestAnimationFrame(animate);
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```