Prompt specification
Build or customize the Three.js 3D scene "Toy shelf size ordering" 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: Toy shelf size ordering
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/toy-shelf-size-ordering-x0359
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring nesting dolls. Build a shelf with nesting figures, cups, and boxes; users organize each family by capacity while keeping different object types in separate visible groups. Voxel style.
Working Three.js Starter (toy-shelf-size-ordering-x0359):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nest & Sort — Voxel Shelf</title>
<style>
:root {
--ink: #352d2a;
--paper: #fff8e9;
--yellow: #f4c451;
--coral: #df776d;
--teal: #32a89e;
--gold: #d79a38;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e1d3;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 10;
background: var(--paper);
border: 3px solid var(--ink);
box-shadow: 6px 6px 0 var(--ink);
padding: 16px;
}
.intro {
top: 20px;
left: 20px;
width: 335px;
}
.eyebrow {
display: inline-block;
padding: 4px 7px;
background: var(--ink);
color: var(--paper);
font-size: 10px;
font-weight: 800;
letter-spacing: 1.5px;
}
h1 {
margin: 11px 0 4px;
font-size: 39px;
line-height: 0.95;
letter-spacing: -2px;
}
h1 span {
color: var(--coral);
}
.intro p {
margin: 9px 0 13px;
font-size: 12px;
line-height: 1.5;
}
.status-grid {
display: grid;
gap: 7px;
}
.family-row {
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: 8px;
min-height: 27px;
padding: 5px 7px;
border: 2px solid var(--ink);
background: #fffdf5;
font-size: 11px;
font-weight: 800;
}
.family-row .swatch {
width: 10px;
height: 18px;
border: 2px solid var(--ink);
}
.family-row .state {
font-size: 9px;
letter-spacing: 0.5px;
}
.family-row.sorted .state {
color: #18765c;
}
.controls {
top: 20px;
right: 20px;
width: 246px;
}
.controls h2 {
margin: 0 0 11px;
font-size: 12px;
letter-spacing: 1px;
}
button {
width: 100%;
margin: 0 0 9px;
padding: 10px 12px;
border: 2px solid var(--ink);
border-radius: 0;
background: #fffdf5;
color: var(--ink);
box-shadow: 3px 3px 0 var(--ink);
font: inherit;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.5px;
cursor: pointer;
transition: transform 80ms ease, box-shadow 80ms ease;
}
button:hover {
transform: translate(-1px, -1px);
box-shadow: 5px 5px 0 var(--ink);
}
button:active {
transform: translate(3px, 3px);
box-shadow: 0 0 0 var(--ink);
}
button.primary {
background: var(--yellow);
}
button.check {
background: #9edec7;
}
.camera-note {
margin: 4px 0 0;
color: #6d625b;
font-size: 9px;
line-height: 1.55;
}
.legend {
right: 20px;
bottom: 20px;
width: 246px;
}
.legend-title {
margin-bottom: 8px;
font-size: 10px;
font-weight: 900;
letter-spacing: 1px;
}
.capacity-scale {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 5px;
text-align: center;
}
.capacity-cell {
padding: 6px 2px;
border: 2px solid var(--ink);
font-size: 10px;
font-weight: 900;
}
.capacity-cell i {
display: flex;
justify-content: center;
gap: 2px;
height: 9px;
margin-bottom: 5px;
}
.capacity-cell b {
width: 4px;
height: 7px;
background: var(--ink);
}
.hint {
left: 50%;
bottom: 20px;
transform: translateX(-50%);
padding: 10px 14px;
font-size: 10px;
font-weight: 800;
white-space: nowrap;
}
#toast {
position: fixed;
z-index: 30;
top: 21px;
left: 50%;
transform: translate(-50%, -18px);
max-width: min(440px, calc(100vw - 30px));
padding: 11px 15px;
border: 3px solid var(--ink);
background: var(--yellow);
box-shadow: 5px 5px 0 var(--ink);
font-size: 11px;
font-weight: 900;
text-align: center;
opacity: 0;
pointer-events: none;
transition: opacity 160ms ease, transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
.intro {
top: 10px;
left: 10px;
width: calc(100% - 20px);
padding: 11px;
}
h1 {
margin-top: 8px;
font-size: 29px;
}
.intro > p {
display: none;
}
.status-grid {
grid-template-columns: repeat(3, 1fr);
gap: 5px;
margin-top: 9px;
}
.family-row {
grid-template-columns: 8px 1fr;
gap: 5px;
padding: 4px;
font-size: 9px;
}
.family-row .swatch {
width: 7px;
height: 15px;
}
.family-row .state {
grid-column: 1 / -1;
font-size: 8px;
}
.controls {
top: auto;
right: 10px;
bottom: 10px;
width: 174px;
padding: 10px;
}
.controls h2,
.camera-note {
display: none;
}
button {
margin-bottom: 7px;
padding: 8px;
font-size: 9px;
}
.legend {
right: auto;
bottom: 10px;
left: 10px;
width: 154px;
padding: 10px;
}
.hint {
display: none;
}
#toast {
top: 155px;
}
}
@media (max-width: 430px) {
.legend {
display: none;
}
.controls {
width: 100%;
}
}
</style>
</head>
<body>
<canvas
id="scene"
tabindex="0"
aria-label="Interactive voxel shelf. Drag objects within their family bay to arrange them by capacity."
></canvas>
<section class="panel intro">
<div class="eyebrow">SHELF STUDIO / 03 FAMILIES</div>
<h1>NEST <span>&</span> SORT</h1>
<p>
Arrange each family from capacity 1 to 5. Objects may move within
their own colored bay, but never between families.
</p>
<div class="status-grid">
<div class="family-row" data-family="figures">
<span class="swatch" style="background: var(--coral)"></span>
<span>FIGURES</span>
<span class="state">0/5 IN PLACE</span>
</div>
<div class="family-row" data-family="cups">
<span class="swatch" style="background: var(--teal)"></span>
<span>CUPS</span>
<span class="state">0/5 IN PLACE</span>
</div>
<div class="family-row" data-family="boxes">
<span class="swatch" style="background: var(--gold)"></span>
<span>BOXES</span>
<span class="state">0/5 IN PLACE</span>
</div>
</div>
</section>
<section class="panel controls">
<h2>SHELF TOOLS</h2>
<button id="sortAll" class="primary">SORT ALL FAMILIES</button>
<button id="shuffle">SHUFFLE THE SHELF</button>
<button id="checkOrder" class="check">CHECK ORDER</button>
<button id="resetView">RESET CAMERA</button>
<p class="camera-note">
Drag an object to rearrange it.<br />
Drag empty space or right-drag to orbit.<br />
Scroll to zoom. Double-click to reset.
</p>
</section>
<section class="panel legend">
<div class="legend-title">CAPACITY = SIZE + PIPS</div>
<div class="capacity-scale">
<div class="capacity-cell"><i><b></b></i>1</div>
<div class="capacity-cell"><i><b></b><b></b></i>2</div>
<div class="capacity-cell"><i><b></b><b></b><b></b></i>3</div>
<div class="capacity-cell"><i><b></b><b></b><b></b><b></b></i>4</div>
<div class="capacity-cell"><i><b></b><b></b><b></b><b></b><b></b></i>5</div>
</div>
</section>
<div class="panel hint">
DRAG WITHIN A BAY · SMALL → LARGE · CAPACITY 1 → 5
</div>
<div id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const toast = document.querySelector("#toast");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
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;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e1d3);
scene.fog = new THREE.Fog(0xe9e1d3, 20, 44);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
yaw: 0.10,
pitch: 0.31,
radius: window.innerWidth < 760 ? 30 : 17.5,
userZoomed: false,
target: new THREE.Vector3(0, 1.65, 0)
};
scene.add(new THREE.HemisphereLight(0xfff7df, 0x8b796c, 2.2));
const sun = new THREE.DirectionalLight(0xfff1cf, 3.4);
sun.position.set(-7, 13, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -13;
sun.shadow.camera.right = 13;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -7;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbfd8ff, 0.75);
fill.position.set(8, 7, 3);
scene.add(fill);
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function getMaterial(color, roughness = 0.86) {
const key = `${color}-${roughness}`;
if (!materialCache.has(key)) {
materialCache.set(
key,
new THREE.MeshStandardMaterial({
color,
roughness,
metalness: 0,
flatShading: true
})
);
}
return materialCache.get(key);
}
function box(parent, w, h, d, material, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(cubeGeometry, material);
mesh.scale.set(w, h, d);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const M = {
wood: getMaterial(0xa46d4d),
woodDark: getMaterial(0x6f4435),
woodLight: getMaterial(0xc18a61),
dark: getMaterial(0x39302d),
cream: getMaterial(0xfff2d9),
floor: getMaterial(0xffffff),
yellow: new THREE.MeshBasicMaterial({
color: 0xffd84d,
transparent: true,
opacity: 0.9
})
};
const families = {
figures: {
label: "FIGURES",
sign: "FIGURES 1 > 5",
center: -5.35,
panel: 0xefb4a6,
stripe: 0xdf776d,
capacities: [3, 1, 5, 2, 4],
colors: [
0xf8d2bd,
0xf3a58f,
0xe87978,
0xc9586a,
0x93455f
]
},
cups: {
label: "CUPS",
sign: "CUPS 1 > 5",
center: 0,
panel: 0x9bddd3,
stripe: 0x32a89e,
capacities: [4, 2, 5, 1, 3],
colors: [
0xb9eee2,
0x72d4c4,
0x39b9ad,
0x168b91,
0x225b78
]
},
boxes: {
label: "BOXES",
sign: "BOXES 1 > 5",
center: 5.35,
panel: 0xebc674,
stripe: 0xd79a38,
capacities: [2, 5, 3, 4, 1],
colors: [
0xf5df8b,
0xefc45b,
0xd99b37,
0xb8752c,
0x83502e
]
}
};
const BASE_Y = 0.63;
const SLOT_SPACING = 0.91;
function slotX(family, index) {
return family.center + (index - 2) * SLOT_SPACING;
}
// Voxel tiled floor.
const floorTiles = new THREE.InstancedMesh(
cubeGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
flatShading: true
}),
26 * 16
);
const tileMatrix = new THREE.Matrix4();
const tilePosition = new THREE.Vector3();
const tileScale = new THREE.Vector3(1.05, 0.08, 1.05);
const tileQuaternion = new THREE.Quaternion();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let x = 0; x < 26; x++) {
for (let z = 0; z < 16; z++) {
tilePosition.set(
(x - 12.5) * 1.1,
-0.53,
(z - 7.5) * 1.1 - 1.2
);
tileMatrix.compose(tilePosition, tileQuaternion, tileScale);
floorTiles.setMatrixAt(tileIndex, tileMatrix);
const checker = (x + z) % 2;
tileColor.set(checker ? 0xd8cdbd : 0xe4dacb);
floorTiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
floorTiles.receiveShadow = true;
floorTiles.instanceMatrix.needsUpdate = true;
floorTiles.instanceColor.needsUpdate = true;
scene.add(floorTiles);
const backdrop = box(
scene,
42,
14,
0.3,
getMaterial(0xe5dccf),
0,
5.5,
-4.4
);
backdrop.castShadow = false;
// Main voxel shelf.
const shelf = new THREE.Group();
scene.add(shelf);
box(shelf, 16.9, 0.3, 2.7, M.wood, 0, 0.45, 0);
box(shelf, 17.2, 0.27, 2.8, M.woodLight, 0, 3.78, 0);
box(shelf, 16.9, 0.22, 2.7, M.woodDark, 0, 0.25, 0);
for (const x of [-8.25, -2.68, 2.68, 8.25]) {
box(shelf, 0.24, 3.45, 2.58, M.wood, x, 2.02, 0);
box(shelf, 0.36, 0.17, 2.72, M.woodDark, x, 3.61, 0);
}
for (const x of [-7.78, 7.78]) {
box(shelf, 0.45, 0.88, 0.5, M.woodDark, x, -0.02, 0.65);
box(shelf, 0.45, 0.88, 0.5, M.woodDark, x, -0.02, -0.65);
}
// Colored family backboards and floor mats.
for (const family of Object.values(families)) {
box(
shelf,
5.08,
3.02,
0.12,
getMaterial(family.panel),
family.center,
2.12,
-1.16
);
box(
shelf,
5.08,
0.16,
0.15,
getMaterial(family.stripe),
family.center,
3.47,
-1.06
);
box(
shelf,
5.02,
0.07,
2.08,
getMaterial(family.panel),
family.center,
0.64,
0
);
// Small capacity guide marks along the front of each mat.
for (let i = 0; i < 5; i++) {
box(
shelf,
0.68,
0.035,
0.13,
M.cream,
slotX(family, i),
0.705,
0.82
);
}
}
function createSignTexture(text) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 768;
labelCanvas.height = 144;
const context = labelCanvas.getContext("2d");
context.fillStyle = "#fff8e9";
context.fillRect(0, 0, labelCanvas.width, labelCanvas.height);
context.strokeStyle = "#352d2a";
context.lineWidth = 16;
context.strokeRect(8, 8, labelCanvas.width - 16, labelCanvas.height - 16);
context.fillStyle = "#352d2a";
context.font = "900 48px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, labelCanvas.width / 2, labelCanvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
return texture;
}
for (const family of Object.values(families)) {
box(
shelf,
3.55,
0.64,
0.14,
M.woodDark,
family.center,
3.25,
1.38
);
const sign = new THREE.Sprite(
new THREE.SpriteMaterial({
map: createSignTexture(family.sign),
transparent: true,
depthWrite: false
})
);
sign.position.set(family.center, 3.25, 1.48);
sign.scale.set(3.35, 0.63, 1);
scene.add(sign);
}
const items = [];
const orders = {};
const draggableRoots = [];
function addPips(parent, count, options) {
const {
spacing,
size,
x = 0,
y = 0,
z = 0,
material = M.dark
} = options;
for (let i = 0; i < count; i++) {
const offset = (i - (count - 1) / 2) * spacing;
box(
parent,
size,
size,
size * 0.45,
material,
x + offset,
y,
z
);
}
}
function buildDoll(root, capacity, color) {
const s = 0.78 + capacity * 0.1;
const bodyMat = getMaterial(color);
const lightMat = getMaterial(0xffe6c8);
const hairMat = getMaterial(capacity > 3 ? 0x4b3340 : 0x744638);
// Body, torso, head, and hair are stacked cubes.
box(root, 0.74 * s, 0.60 * s, 0.52 * s, bodyMat, 0, 0.30 * s, 0);
box(root, 0.58 * s, 0.38 * s, 0.45 * s, lightMat, 0, 0.79 * s, 0);
box(root, 0.46 * s, 0.42 * s, 0.42 * s, bodyMat, 0, 1.19 * s, 0);
box(root, 0.50 * s, 0.13 * s, 0.45 * s, hairMat, 0, 1.43 * s, -0.01 * s);
// Scarf and face pixels.
box(root, 0.61 * s, 0.08 * s, 0.48 * s, getMaterial(0xf7cf54), 0, 0.99 * s, 0);
box(root, 0.055 * s, 0.055 * s, 0.035 * s, M.dark, -0.10 * s, 1.22 * s, 0.222 * s);
box(root, 0.055 * s, 0.055 * s, 0.035 * s, M.dark, 0.10 * s, 1.22 * s, 0.222 * s);
box(root, 0.09 * s, 0.035 * s, 0.035 * s, getMaterial(0x9d3f4e), 0, 1.10 * s, 0.224 * s);
box(root, 0.055 * s, 0.055 * s, 0.035 * s, getMaterial(0xf19c8f), -0.16 * s, 1.10 * s, 0.222 * s);
box(root, 0.055 * s, 0.055 * s, 0.035 * s, getMaterial(0xf19c8f), 0.16 * s, 1.10 * s, 0.222 * s);
addPips(root, capacity, {
spacing: 0.073 * s,
size: 0.049 * s,
y: 0.22 * s,
z: 0.276 * s
});
return 0.9 * s;
}
function buildCup(root, capacity, color) {
const s = 0.82 + capacity * 0.07;
const h = 0.58 * s + capacity * 0.04;
const w = 0.56 * s;
const d = 0.50 * s;
const wall = 0.075 * s;
const cupMat = getMaterial(color);
// Open-top voxel cup.
box(root, w, 0.08 * s, d, cupMat, 0, 0.04 * s, 0);
box(root, wall, h, d, cupMat, -w / 2 + wall / 2, h / 2, 0);
box(root, wall, h, d, cupMat, w / 2 - wall / 2, h / 2, 0);
box(root, w - wall * 2, h, wall, cupMat, 0, h / 2, -d / 2 + wall / 2);
box(root, w - wall * 2, h, wall, cupMat, 0, h / 2, d / 2 - wall / 2);
// Dark interior floor.
box(
root,
w - wall * 2.2,
0.025 * s,
d - wall * 2.2,
getMaterial(0x244b4d),
0,
0.095 * s,
0
);
// Block handle.
box(root, 0.09 * s, h * 0.62, 0.10 * s, cupMat, w / 2 + 0.11 * s, h * 0.53, 0);
box(root, 0.20 * s, 0.08 * s, 0.10 * s, cupMat, w / 2 + 0.045 * s, h * 0.80, 0);
box(root, 0.20 * s, 0.08 * s, 0.10 * s, cupMat, w / 2 + 0.045 * s, h * 0.26, 0);
addPips(root, capacity, {
spacing: 0.073 * s,
size: 0.049 * s,
y: h * 0.30,
z: d / 2 + 0.025 * s,
material: getMaterial(0x23494d)
});
return w + 0.24 * s;
}
function buildBox(root, capacity, color) {
const s = 0.74 + capacity * 0.08;
const bodyMat = getMaterial(color);
const tapeMat = getMaterial(0xf6e6bd);
box(root, 0.66 * s, 0.62 * s, 0.66 * s, bodyMat, 0, 0.31 * s, 0);
box(root, 0.72 * s, 0.13 * s, 0.72 * s, getMaterial(color, 0.72), 0, 0.685 * s, 0);
// Tape strips.
box(root, 0.105 * s, 0.64 * s, 0.025 * s, tapeMat, 0, 0.31 * s, 0.344 * s);
box(root, 0.105 * s, 0.025 * s, 0.72 * s, tapeMat, 0, 0.762 * s, 0);
addPips(root, capacity, {
spacing: 0.073 * s,
size: 0.052 * s,
y: 0.782 * s,
z: -0.20 * s,
material: getMaterial(0x5f3c27)
});
return 0.82 * s;
}
function createSelectionRing(root, footprint) {
const ring = new THREE.Group();
const width = footprint + 0.16;
box(ring, width, 0.025, 0.035, M.yellow, 0, 0.02, width / 2);
box(ring, width, 0.025, 0.035, M.yellow, 0, 0.02, -width / 2);
box(ring, 0.035, 0.025, width, M.yellow, width / 2, 0.02, 0);
box(ring, 0.035, 0.025, width, M.yellow, -width / 2, 0.02, 0);
ring.visible = false;
root.add(ring);
return ring;
}
function createItem(familyKey, family, capacity) {
const root = new THREE.Group();
const color = family.colors[capacity - 1];
let footprint;
if (familyKey === "figures") {
footprint = buildDoll(root, capacity, color);
} else if (familyKey === "cups") {
footprint = buildCup(root, capacity, color);
} else {
footprint = buildBox(root, capacity, color);
}
const record = {
root,
familyKey,
family,
capacity,
orderIndex: 0,
targetX: 0,
targetY: BASE_Y,
targetZ: 0.06,
ring: null
};
root.userData.record = record;
record.ring = createSelectionRing(root, footprint);
scene.add(root);
draggableRoots.push(root);
items.push(record);
return record;
}
for (const [familyKey, family] of Object.entries(families)) {
orders[familyKey] = family.capacities.map((capacity) =>
createItem(familyKey, family, capacity)
);
}
function applyOrder(familyKey) {
const family = families[familyKey];
orders[familyKey].forEach((record, index) => {
record.orderIndex = index;
record.targetX = slotX(family, index);
});
}
for (const familyKey of Object.keys(families)) {
applyOrder(familyKey);
}
const familyRows = {};
document.querySelectorAll(".family-row").forEach((row) => {
familyRows[row.dataset.family] = row;
});
function familyScore(familyKey) {
return orders[familyKey].reduce(
(score, record, index) => score + (record.capacity === index + 1 ? 1 : 0),
0
);
}
function isSorted(familyKey) {
return familyScore(familyKey) === 5;
}
function updateStatuses() {
for (const familyKey of Object.keys(families)) {
const score = familyScore(familyKey);
const row = familyRows[familyKey];
row.querySelector(".state").textContent =
score === 5 ? "SORTED" : `${score}/5 IN PLACE`;
row.classList.toggle("sorted", score === 5);
}
}
updateStatuses();
let toastTimer;
function showToast(message, duration = 2300) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, duration);
}
// Custom camera controls.
function updateCamera() {
const cosPitch = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x +
cameraState.radius * Math.sin(cameraState.yaw) * cosPitch,
cameraState.target.y + cameraState.radius * Math.sin(cameraState.pitch),
cameraState.target.z +
cameraState.radius * Math.cos(cameraState.yaw) * cosPitch
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.yaw = 0.10;
cameraState.pitch = 0.31;
cameraState.radius = window.innerWidth < 760 ? 30 : 17.5;
cameraState.userZoomed = false;
updateCamera();
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const dragPoint = new THREE.Vector3();
let selectedItem = null;
let dragState = null;
let orbitState = null;
function updatePointer(event) {
const bounds = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
}
function pickItem(event) {
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(draggableRoots, true);
for (const hit of hits) {
let object = hit.object;
while (object && !object.userData.record) {
object = object.parent;
}
if (object?.userData.record) {
return object.userData.record;
}
}
return null;
}
function selectItem(record) {
if (selectedItem?.ring) {
selectedItem.ring.visible = false;
}
selectedItem = record;
if (record?.ring) {
record.ring.visible = true;
}
}
function reorderWithinFamily(record, targetIndex) {
const familyKey = record.familyKey;
const array = orders[familyKey];
const currentIndex = array.indexOf(record);
if (currentIndex === targetIndex) {
return;
}
array.splice(currentIndex, 1);
array.splice(targetIndex, 0, record);
applyOrder(familyKey);
updateStatuses();
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.focus();
const picked = event.button === 0 ? pickItem(event) : null;
if (picked) {
selectItem(picked);
dragState = {
record: picked,
pointerId: event.pointerId,
startClientX: event.clientX,
startClientY: event.clientY,
moved: false
};
picked.targetY = BASE_Y + 0.18;
picked.targetZ = 0.48;
canvas.setPointerCapture(event.pointerId);
} else {
orbitState = {
pointerId: event.pointerId,
lastX: event.clientX,
lastY: event.clientY
};
canvas.setPointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointermove", (event) => {
if (dragState && event.pointerId === dragState.pointerId) {
const dx = event.clientX - dragState.startClientX;
const dy = event.clientY - dragState.startClientY;
if (Math.abs(dx) + Math.abs(dy) > 4) {
dragState.moved = true;
}
updatePointer(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const record = dragState.record;
const family = record.family;
const minX = family.center - 1.94;
const maxX = family.center + 1.94;
const pointerX = THREE.MathUtils.clamp(dragPoint.x, minX, maxX);
const localSlot = (pointerX - family.center) / SLOT_SPACING + 2;
const targetIndex = THREE.MathUtils.clamp(
Math.round(localSlot),
0,
4
);
reorderWithinFamily(record, targetIndex);
record.targetX = pointerX;
}
return;
}
if (orbitState && event.pointerId === orbitState.pointerId) {
const dx = event.clientX - orbitState.lastX;
const dy = event.clientY - orbitState.lastY;
cameraState.yaw -= dx * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.004,
0.10,
0.82
);
orbitState.lastX = event.clientX;
orbitState.lastY = event.clientY;
updateCamera();
}
});
function finishPointer(event) {
if (dragState && event.pointerId === dragState.pointerId) {
const record = dragState.record;
record.targetX = slotX(record.family, record.orderIndex);
record.targetY = BASE_Y;
record.targetZ = 0.06;
if (!dragState.moved) {
showToast(
`${record.family.label}: capacity ${record.capacity} selected.`
);
}
dragState = null;
updateStatuses();
}
if (orbitState && event.pointerId === orbitState.pointerId) {
orbitState = null;
}
}
canvas.addEventListener("pointerup", finishPointer);
canvas.addEventListener("pointercancel", finishPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
11,
36
);
cameraState.userZoomed = true;
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
// Sorting and game feedback.
function sortAllFamilies() {
for (const familyKey of Object.keys(families)) {
orders[familyKey].sort((a, b) => a.capacity - b.capacity);
applyOrder(familyKey);
}
updateStatuses();
showToast("All three families sorted from capacity 1 to 5.");
}
function shuffleFamilies() {
for (const familyKey of Object.keys(families)) {
const array = orders[familyKey];
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
if (array.every((record, index) => record.capacity === index + 1)) {
array.reverse();
}
applyOrder(familyKey);
}
updateStatuses();
showToast("The shelf is scrambled. Each family stays in its own bay.");
}
const confetti = [];
function spawnConfetti() {
const colors = [
0xf4c451,
0xdf776d,
0x32a89e,
0x87516c,
0x65a8db
];
for (let i = 0; i < 80; i++) {
const size = 0.07 + Math.random() * 0.08;
const material = getMaterial(
colors[Math.floor(Math.random() * colors.length)]
);
const mesh = new THREE.Mesh(cubeGeometry, material);
mesh.scale.setScalar(size);
mesh.position.set(
(Math.random() - 0.5) * 10,
4.4 + Math.random() * 1.8,
(Math.random() - 0.5) * 2
);
scene.add(mesh);
confetti.push({
mesh,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 5,
2 + Math.random() * 4,
(Math.random() - 0.5) * 3
),
spin: new THREE.Vector3(
Math.random() * 8,
Math.random() * 8,
Math.random() * 8
)
});
}
}
function checkOrder() {
const incorrectFamily = Object.keys(families).find(
(familyKey) => !isSorted(familyKey)
);
if (!incorrectFamily) {
showToast("Perfect! Every family is organized by capacity.", 3200);
spawnConfetti();
return;
}
const array = orders[incorrectFamily];
const wrongIndex = array.findIndex(
(record, index) => record.capacity !== index + 1
);
const current = array[wrongIndex].capacity;
const expected = wrongIndex + 1;
showToast(
`${families[incorrectFamily].label}: slot ${wrongIndex + 1} needs capacity ${expected}; it currently has ${current}.`,
3100
);
selectItem(array[wrongIndex]);
}
document.querySelector("#sortAll").addEventListener("click", sortAllFamilies);
document.querySelector("#shuffle").addEventListener("click", shuffleFamilies);
document.querySelector("#checkOrder").addEventListener("click", checkOrder);
document.querySelector("#resetView").addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLButtonElement) {
return;
}
const key = event.key.toLowerCase();
if (key === "s") sortAllFamilies();
if (key === "r") shuffleFamilies();
if (key === "c") checkOrder();
});
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
camera.aspect = aspect;
camera.fov = aspect < 0.85 ? 55 : 38;
camera.updateProjectionMatrix();
if (!cameraState.userZoomed) {
cameraState.radius = aspect < 0.85 ? 30 : 17.5;
}
updateCamera();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
const smoothing = 1 - Math.exp(-11 * dt);
for (const record of items) {
record.root.position.x = THREE.MathUtils.lerp(
record.root.position.x,
record.targetX,
smoothing
);
record.root.position.y = THREE.MathUtils.lerp(
record.root.position.y,
record.targetY,
smoothing
);
record.root.position.z = THREE.MathUtils.lerp(
record.root.position.z,
record.targetZ,
smoothing
);
}
if (selectedItem?.ring) {
selectedItem.ring.material = M.yellow;
M.yellow.opacity = 0.68 + Math.sin(clock.elapsedTime * 5) * 0.2;
}
for (let i = confetti.length - 1; i >= 0; i--) {
const piece = confetti[i];
piece.velocity.y -= 7 * dt;
piece.mesh.position.addScaledVector(piece.velocity, dt);
piece.mesh.rotation.x += piece.spin.x * dt;
piece.mesh.rotation.y += piece.spin.y * dt;
piece.mesh.rotation.z += piece.spin.z * dt;
if (piece.mesh.position.y < -1) {
scene.remove(piece.mesh);
confetti.splice(i, 1);
}
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```