Prompt specification
Build or customize the Three.js 3D scene "Packing-order geometry 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: Packing-order geometry puzzle
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/packing-order-geometry-puzzle-x0576
Scene Description Prompt:
Pack rigid low-poly clothing bundles into a suitcase; a transparent lid reveals collisions and gaps. Three.js from cdnjs, one HTML file.
Working Three.js Starter (packing-order-geometry-puzzle-x0576):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PackLab — Rigid Clothing Packing</title>
<style>
:root {
--ink: #172229;
--muted: #66747b;
--paper: rgba(250, 249, 244, 0.88);
--line: rgba(23, 34, 41, 0.12);
--accent: #16a39a;
--danger: #ed5964;
--warning: #e5a743;
--shadow: 0 16px 50px rgba(26, 36, 42, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e6dd;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
button {
font: inherit;
}
.hud {
position: fixed;
inset: 0;
z-index: 10;
pointer-events: none;
}
.panel {
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.7);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(130%);
-webkit-backdrop-filter: blur(18px) saturate(130%);
}
.brand {
position: absolute;
top: 26px;
left: 28px;
width: min(370px, calc(100vw - 56px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 12px;
color: var(--accent);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 24px;
height: 2px;
content: "";
background: var(--accent);
}
h1 {
max-width: 340px;
margin: 0;
font-size: clamp(28px, 3.3vw, 48px);
font-weight: 750;
letter-spacing: -0.055em;
line-height: 0.98;
}
.subtitle {
max-width: 330px;
margin: 13px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.stats {
position: absolute;
top: 26px;
right: 28px;
width: 265px;
padding: 16px;
border-radius: 18px;
pointer-events: auto;
}
.stats-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
}
.stats-title {
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.status {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 0 4px rgba(22, 163, 154, 0.12);
}
.status.conflict .status-dot {
background: var(--danger);
box-shadow: 0 0 0 4px rgba(237, 89, 100, 0.13);
}
.stat-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.stat {
padding: 11px 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.42);
}
.stat-value {
display: block;
margin-bottom: 3px;
font-size: 21px;
font-weight: 760;
letter-spacing: -0.04em;
}
.stat-label {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 13px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 8px;
height: 8px;
border-radius: 2px;
}
.swatch.red {
background: var(--danger);
}
.swatch.amber {
background: var(--warning);
}
.swatch.teal {
background: var(--accent);
}
.selection {
position: absolute;
left: 28px;
bottom: 28px;
width: min(330px, calc(100vw - 56px));
padding: 14px 16px;
border-radius: 15px;
pointer-events: none;
}
.selection-label {
margin-bottom: 5px;
color: var(--accent);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.selection-name {
font-size: 16px;
font-weight: 750;
letter-spacing: -0.025em;
}
.selection-meta {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.toolbar {
position: absolute;
bottom: 28px;
left: 50%;
display: flex;
gap: 7px;
padding: 7px;
border-radius: 17px;
transform: translateX(-50%);
pointer-events: auto;
}
.tool {
min-height: 39px;
padding: 0 15px;
border: 0;
border-radius: 11px;
background: transparent;
color: var(--ink);
cursor: pointer;
font-size: 12px;
font-weight: 720;
white-space: nowrap;
transition:
transform 150ms ease,
background 150ms ease,
color 150ms ease;
}
.tool:hover {
background: rgba(23, 34, 41, 0.07);
transform: translateY(-1px);
}
.tool.primary {
background: var(--ink);
color: white;
}
.tool.primary:hover {
background: #263940;
}
.tool.active {
background: rgba(22, 163, 154, 0.13);
color: #087d76;
}
.help {
position: absolute;
right: 28px;
bottom: 30px;
color: rgba(23, 34, 41, 0.6);
font-size: 10px;
font-weight: 650;
line-height: 1.6;
text-align: right;
pointer-events: none;
}
.loading {
position: fixed;
inset: 0;
z-index: 30;
display: grid;
place-items: center;
background: #e9e6dd;
color: var(--muted);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
.loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 880px) {
.brand {
top: 18px;
left: 18px;
}
.stats {
top: 18px;
right: 18px;
width: 235px;
}
h1 {
font-size: 31px;
}
.subtitle {
display: none;
}
.selection {
left: 18px;
bottom: 82px;
}
.toolbar {
bottom: 18px;
}
.help {
display: none;
}
}
@media (max-width: 620px) {
.brand {
width: calc(100vw - 36px);
}
h1 {
max-width: 230px;
font-size: 27px;
}
.stats {
top: auto;
right: 18px;
bottom: 82px;
width: 220px;
}
.selection {
display: none;
}
.toolbar {
width: calc(100vw - 24px);
justify-content: center;
overflow-x: auto;
}
.tool {
padding: 0 11px;
font-size: 11px;
}
}
</style>
</head>
<body>
<div id="loading" class="loading">Preparing suitcase…</div>
<div class="hud">
<header class="brand">
<div class="eyebrow">PackLab / Rigid Mode</div>
<h1>Make every centimeter work.</h1>
<p class="subtitle">
Drag rigid clothing bundles into the case. The transparent lid exposes
collisions, unused footprint, and inefficient packing in real time.
</p>
</header>
<aside class="stats panel">
<div class="stats-head">
<div class="stats-title">Packing analysis</div>
<div id="status" class="status conflict">
<span class="status-dot"></span>
<span id="statusText">Checking layout</span>
</div>
</div>
<div class="stat-grid">
<div class="stat">
<span id="coverageValue" class="stat-value">0%</span>
<span class="stat-label">Coverage</span>
</div>
<div class="stat">
<span id="gapValue" class="stat-value">0%</span>
<span class="stat-label">Gap</span>
</div>
<div class="stat">
<span id="collisionValue" class="stat-value">0</span>
<span class="stat-label">Collisions</span>
</div>
</div>
<div class="legend">
<span><i class="swatch red"></i>Overlap</span>
<span><i class="swatch amber"></i>Unused floor</span>
<span><i class="swatch teal"></i>Selected</span>
</div>
</aside>
<div class="selection panel">
<div class="selection-label">Current bundle</div>
<div id="selectionName" class="selection-name">Grab a clothing bundle</div>
<div id="selectionMeta" class="selection-meta">
Drag to pack · drag empty space to orbit
</div>
</div>
<nav class="toolbar panel" aria-label="Packing tools">
<button id="autoPack" class="tool primary" type="button">
Auto-pack
</button>
<button id="toggleLid" class="tool" type="button">Close lid</button>
<button id="resetLayout" class="tool" type="button">Reset</button>
<button id="toggleHeatmap" class="tool active" type="button">
Gap map
</button>
</nav>
<div class="help">
Drag bundle — reposition<br />
Drag empty space — orbit<br />
Wheel — zoom · Right-drag — pan
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const loading = document.getElementById("loading");
const statusEl = document.getElementById("status");
const statusText = document.getElementById("statusText");
const coverageValue = document.getElementById("coverageValue");
const gapValue = document.getElementById("gapValue");
const collisionValue = document.getElementById("collisionValue");
const selectionName = document.getElementById("selectionName");
const selectionMeta = document.getElementById("selectionMeta");
const autoPackButton = document.getElementById("autoPack");
const resetButton = document.getElementById("resetLayout");
const lidButton = document.getElementById("toggleLid");
const heatmapButton = document.getElementById("toggleHeatmap");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e6dd);
scene.fog = new THREE.Fog(0xe9e6dd, 24, 48);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance",
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
document.body.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
target: new THREE.Vector3(0, 0.45, 0),
radius: 17.2,
theta: 0.43,
phi: 0.83,
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
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();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xfffcf3, 0x778187, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff5df, 3.2);
keyLight.position.set(-8, 15, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 14;
keyLight.shadow.camera.bottom = -14;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xb9e9ed, 1.15);
fillLight.position.set(10, 8, -9);
scene.add(fillLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshStandardMaterial({
color: 0xe6e1d7,
roughness: 1,
metalness: 0,
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.29;
floor.receiveShadow = true;
scene.add(floor);
const floorGrid = new THREE.GridHelper(42, 42, 0xc8c3b8, 0xd7d2c8);
floorGrid.position.y = -0.282;
floorGrid.material.transparent = true;
floorGrid.material.opacity = 0.32;
scene.add(floorGrid);
const CASE = {
innerHalfWidth: 5.2,
innerHalfDepth: 3.5,
floorY: 0.38,
};
function makeBox(width, height, depth, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const shellMaterial = new THREE.MeshStandardMaterial({
color: 0x25343a,
roughness: 0.72,
metalness: 0.08,
flatShading: true,
});
const liningMaterial = new THREE.MeshStandardMaterial({
color: 0xb9ad94,
roughness: 0.95,
metalness: 0,
flatShading: true,
});
const accentMaterial = new THREE.MeshStandardMaterial({
color: 0xe16b4d,
roughness: 0.65,
metalness: 0.04,
flatShading: true,
});
// Suitcase shell and lining.
makeBox(11.65, 0.52, 8.15, shellMaterial, 0, 0, 0);
makeBox(10.55, 0.14, 7.15, liningMaterial, 0, 0.3, 0);
makeBox(0.38, 1.45, 7.85, shellMaterial, -5.55, 0.94, 0);
makeBox(0.38, 1.45, 7.85, shellMaterial, 5.55, 0.94, 0);
makeBox(10.75, 1.45, 0.38, shellMaterial, 0, 0.94, -3.78);
makeBox(10.75, 1.45, 0.38, shellMaterial, 0, 0.94, 3.78);
// Corner protectors.
for (const x of [-5.55, 5.55]) {
for (const z of [-3.78, 3.78]) {
makeBox(0.48, 1.53, 0.48, accentMaterial, x, 0.95, z);
}
}
// Front handle.
makeBox(0.26, 0.25, 0.34, shellMaterial, -1.15, 0.95, 4.04);
makeBox(0.26, 0.25, 0.34, shellMaterial, 1.15, 0.95, 4.04);
makeBox(2.55, 0.24, 0.28, shellMaterial, 0, 0.95, 4.13);
// Transparent hinged lid.
const lidPivot = new THREE.Group();
lidPivot.position.set(0, 1.72, -3.65);
scene.add(lidPivot);
const lidMaterial = new THREE.MeshPhysicalMaterial({
color: 0xb8e5e4,
transparent: true,
opacity: 0.14,
roughness: 0.12,
metalness: 0,
clearcoat: 1,
clearcoatRoughness: 0.08,
side: THREE.DoubleSide,
depthWrite: false,
});
const lidPanel = new THREE.Mesh(
new THREE.BoxGeometry(10.78, 0.055, 7.32),
lidMaterial
);
lidPanel.position.set(0, 0, 3.65);
lidPanel.castShadow = false;
lidPanel.receiveShadow = false;
lidPivot.add(lidPanel);
makeBox(
0.18,
0.13,
7.45,
shellMaterial,
-5.48,
0,
3.65,
lidPivot
);
makeBox(
0.18,
0.13,
7.45,
shellMaterial,
5.48,
0,
3.65,
lidPivot
);
makeBox(
11.12,
0.13,
0.18,
shellMaterial,
0,
0,
0.02,
lidPivot
);
makeBox(
11.12,
0.13,
0.18,
shellMaterial,
0,
0,
7.28,
lidPivot
);
const hingeMaterial = new THREE.MeshStandardMaterial({
color: 0x9ca6a6,
roughness: 0.35,
metalness: 0.65,
flatShading: true,
});
for (const x of [-3.8, 3.8]) {
const hinge = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 1.25, 10),
hingeMaterial
);
hinge.rotation.z = Math.PI / 2;
hinge.position.set(x, 0, 0);
hinge.castShadow = true;
lidPivot.add(hinge);
}
let lidOpen = true;
let lidTargetAngle = -0.62;
lidPivot.rotation.x = lidTargetAngle;
const definitions = [
{
id: "rose",
name: "Rose tee",
category: "Folded shirt",
w: 3.6,
d: 2.8,
h: 1.15,
color: 0xd96c75,
accent: 0xf7b1ae,
x: -3.3,
z: -2.0,
},
{
id: "indigo",
name: "Indigo chinos",
category: "Folded trousers",
w: 3.0,
d: 2.4,
h: 1.05,
color: 0x405c78,
accent: 0x91abc0,
x: -0.6,
z: -1.7,
},
{
id: "sage",
name: "Sage knit",
category: "Folded sweater",
w: 2.8,
d: 2.0,
h: 0.9,
color: 0x879a72,
accent: 0xc1d0aa,
x: 2.2,
z: -1.8,
},
{
id: "cloud",
name: "Cloud hoodie",
category: "Folded hoodie",
w: 3.4,
d: 2.6,
h: 1.22,
color: 0xd7d9d5,
accent: 0xf4f1e7,
x: -3.3,
z: 0.7,
},
{
id: "ochre",
name: "Ochre crew",
category: "Folded sweatshirt",
w: 3.2,
d: 1.9,
h: 1.0,
color: 0xd3a03b,
accent: 0xf1d16c,
x: 0.2,
z: 0.2,
},
{
id: "stone",
name: "Stone shorts",
category: "Folded shorts",
w: 2.6,
d: 1.8,
h: 0.9,
color: 0x8b8980,
accent: 0xc0bdb1,
x: 2.0,
z: 0.4,
},
{
id: "sea",
name: "Sea towel",
category: "Compact towel",
w: 2.2,
d: 1.2,
h: 0.7,
color: 0x4d9a9a,
accent: 0x9fd0cb,
x: -1.2,
z: -0.1,
},
{
id: "graphite",
name: "Graphite socks",
category: "Rolled accessory",
w: 2.2,
d: 1.1,
h: 0.65,
color: 0x4f5356,
accent: 0x8f9698,
x: -3.4,
z: 2.5,
},
{
id: "ivory",
name: "Ivory tee",
category: "Folded shirt",
w: 1.9,
d: 1.2,
h: 0.72,
color: 0xe9dfc9,
accent: 0xfff7e5,
x: 1.0,
z: 0.1,
},
];
function createBundleGeometry(width, depth, height) {
const cut = Math.min(0.2, width * 0.075, depth * 0.075);
const halfW = width / 2;
const halfD = depth / 2;
const shape = new THREE.Shape();
shape.moveTo(-halfW + cut, -halfD);
shape.lineTo(halfW - cut, -halfD);
shape.lineTo(halfW, -halfD + cut);
shape.lineTo(halfW, halfD - cut);
shape.lineTo(halfW - cut, halfD);
shape.lineTo(-halfW + cut, halfD);
shape.lineTo(-halfW, halfD - cut);
shape.lineTo(-halfW, -halfD + cut);
shape.closePath();
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: height,
steps: 1,
bevelEnabled: true,
bevelSegments: 1,
bevelSize: 0.055,
bevelThickness: 0.045,
curveSegments: 1,
});
geometry.rotateX(-Math.PI / 2);
geometry.computeBoundingBox();
const sourceHeight =
geometry.boundingBox.max.y - geometry.boundingBox.min.y;
geometry.scale(1, height / sourceHeight, 1);
geometry.computeBoundingBox();
geometry.translate(0, -geometry.boundingBox.min.y, 0);
geometry.computeVertexNormals();
return geometry;
}
const items = [];
const hitMeshes = [];
for (const definition of definitions) {
const root = new THREE.Group();
root.position.set(definition.x, CASE.floorY, definition.z);
scene.add(root);
const material = new THREE.MeshStandardMaterial({
color: definition.color,
roughness: 0.88,
metalness: 0,
flatShading: true,
});
const body = new THREE.Mesh(
createBundleGeometry(definition.w, definition.d, definition.h),
material
);
body.castShadow = true;
body.receiveShadow = true;
root.add(body);
const baseColor = new THREE.Color(definition.color);
const panelMaterial = new THREE.MeshStandardMaterial({
color: baseColor.clone().offsetHSL(0, 0.015, 0.075),
roughness: 0.92,
flatShading: true,
});
const seamMaterial = new THREE.MeshStandardMaterial({
color: baseColor.clone().offsetHSL(0, 0.02, -0.16),
roughness: 0.95,
flatShading: true,
});
const accentMaterialLocal = new THREE.MeshStandardMaterial({
color: definition.accent,
roughness: 0.82,
flatShading: true,
});
const panelWidth = Math.max(0.25, (definition.w - 0.18) * 0.5);
const panelDepth = definition.d * 0.8;
for (const side of [-1, 1]) {
const panel = new THREE.Mesh(
new THREE.BoxGeometry(panelWidth, 0.035, panelDepth),
panelMaterial
);
panel.position.set(
side * definition.w * 0.245,
definition.h + 0.022,
0
);
panel.castShadow = true;
panel.receiveShadow = true;
root.add(panel);
}
const seam = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.045, panelDepth * 0.94),
seamMaterial
);
seam.position.set(0, definition.h + 0.032, 0);
root.add(seam);
const strap = new THREE.Mesh(
new THREE.BoxGeometry(definition.w * 0.76, 0.042, 0.095),
accentMaterialLocal
);
strap.position.set(0, definition.h + 0.058, -definition.d * 0.29);
root.add(strap);
const tag = new THREE.Mesh(
new THREE.BoxGeometry(
Math.min(0.32, definition.w * 0.18),
0.045,
Math.min(0.22, definition.d * 0.2)
),
accentMaterialLocal
);
tag.position.set(
definition.w * 0.29,
definition.h + 0.06,
definition.d * 0.26
);
root.add(tag);
const helper = new THREE.Box3Helper(new THREE.Box3(), 0xed5964);
helper.material.depthTest = false;
helper.material.transparent = true;
helper.material.opacity = 0.9;
helper.renderOrder = 12;
helper.visible = false;
scene.add(helper);
const item = {
...definition,
root,
body,
material,
helper,
colliding: false,
outOfBounds: false,
};
body.userData.item = item;
items.push(item);
hitMeshes.push(body);
}
const selectionHelper = new THREE.Box3Helper(
new THREE.Box3(),
0x16a39a
);
selectionHelper.material.depthTest = false;
selectionHelper.material.transparent = true;
selectionHelper.material.opacity = 0.95;
selectionHelper.renderOrder = 13;
selectionHelper.visible = false;
scene.add(selectionHelper);
// Shared collision footprint markers.
const collisionGeometry = new THREE.BoxGeometry(1, 1, 1);
const collisionMaterial = new THREE.MeshBasicMaterial({
color: 0xed5964,
transparent: true,
opacity: 0.34,
depthWrite: false,
depthTest: false,
});
const collisionMarkers = Array.from({ length: 40 }, () => {
const marker = new THREE.Mesh(collisionGeometry, collisionMaterial);
marker.visible = false;
marker.renderOrder = 10;
scene.add(marker);
return marker;
});
// Grid-based empty-footprint heatmap.
const heatmapStep = 0.25;
const heatmapColumns = Math.round(
(CASE.innerHalfWidth * 2) / heatmapStep
);
const heatmapRows = Math.round(
(CASE.innerHalfDepth * 2) / heatmapStep
);
const heatmapGeometry = new THREE.PlaneGeometry(
heatmapStep * 0.88,
heatmapStep * 0.88
);
const heatmapMaterial = new THREE.MeshBasicMaterial({
color: 0xe5a743,
transparent: true,
opacity: 0.24,
depthWrite: false,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: -1,
});
const heatmap = new THREE.InstancedMesh(
heatmapGeometry,
heatmapMaterial,
heatmapColumns * heatmapRows
);
heatmap.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
heatmap.frustumCulled = false;
scene.add(heatmap);
let heatmapVisible = true;
let selectedItem = null;
let statusOverride = "";
let activeTween = null;
const dummy = new THREE.Object3D();
function itemBounds(item) {
return {
minX: item.root.position.x - item.w / 2,
maxX: item.root.position.x + item.w / 2,
minZ: item.root.position.z - item.d / 2,
maxZ: item.root.position.z + item.d / 2,
};
}
function updateHeatmap() {
let index = 0;
for (let row = 0; row < heatmapRows; row++) {
for (let column = 0; column < heatmapColumns; column++) {
const x =
-CASE.innerHalfWidth +
(column + 0.5) * heatmapStep;
const z =
-CASE.innerHalfDepth +
(row + 0.5) * heatmapStep;
let covered = false;
for (const item of items) {
const bounds = itemBounds(item);
if (
x >= bounds.minX &&
x <= bounds.maxX &&
z >= bounds.minZ &&
z <= bounds.maxZ
) {
covered = true;
break;
}
}
if (!covered) {
dummy.position.set(x, 0.377, z);
dummy.rotation.set(-Math.PI / 2, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
heatmap.setMatrixAt(index, dummy.matrix);
index++;
}
}
}
heatmap.count = index;
heatmap.instanceMatrix.needsUpdate = true;
heatmap.visible = heatmapVisible;
}
function updateHelper(helper, root, visible) {
helper.visible = visible;
if (!visible) return;
root.updateMatrixWorld(true);
helper.box.setFromObject(root);
helper.updateMatrixWorld(true);
}
function updateDiagnostics() {
let collisionCount = 0;
let markerIndex = 0;
for (const item of items) {
item.colliding = false;
item.outOfBounds = false;
const bounds = itemBounds(item);
item.outOfBounds =
bounds.minX < -CASE.innerHalfWidth - 0.025 ||
bounds.maxX > CASE.innerHalfWidth + 0.025 ||
bounds.minZ < -CASE.innerHalfDepth - 0.025 ||
bounds.maxZ > CASE.innerHalfDepth + 0.025;
}
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
const a = itemBounds(items[i]);
const b = itemBounds(items[j]);
const overlapX =
Math.min(a.maxX, b.maxX) - Math.max(a.minX, b.minX);
const overlapZ =
Math.min(a.maxZ, b.maxZ) - Math.max(a.minZ, b.minZ);
if (overlapX > 0.045 && overlapZ > 0.045) {
collisionCount++;
items[i].colliding = true;
items[j].colliding = true;
if (markerIndex < collisionMarkers.length) {
const marker = collisionMarkers[markerIndex++];
marker.visible = true;
marker.position.set(
(Math.max(a.minX, b.minX) +
Math.min(a.maxX, b.maxX)) /
2,
1.69,
(Math.max(a.minZ, b.minZ) +
Math.min(a.maxZ, b.maxZ)) /
2
);
marker.scale.set(overlapX, 0.035, overlapZ);
}
}
}
}
for (let i = markerIndex; i < collisionMarkers.length; i++) {
collisionMarkers[i].visible = false;
}
let occupiedCells = 0;
const totalCells = heatmapColumns * heatmapRows;
for (let row = 0; row < heatmapRows; row++) {
for (let column = 0; column < heatmapColumns; column++) {
const x =
-CASE.innerHalfWidth +
(column + 0.5) * heatmapStep;
const z =
-CASE.innerHalfDepth +
(row + 0.5) * heatmapStep;
for (const item of items) {
const bounds = itemBounds(item);
if (
x >= bounds.minX &&
x <= bounds.maxX &&
z >= bounds.minZ &&
z <= bounds.maxZ
) {
occupiedCells++;
break;
}
}
}
}
const coverage = (occupiedCells / totalCells) * 100;
const gap = Math.max(0, 100 - coverage);
coverageValue.textContent = `${Math.round(coverage)}%`;
gapValue.textContent = `${Math.round(gap)}%`;
collisionValue.textContent = String(collisionCount);
statusEl.classList.toggle("conflict", collisionCount > 0);
if (statusOverride) {
statusText.textContent = statusOverride;
} else if (collisionCount > 0) {
statusText.textContent = `${collisionCount} overlap${
collisionCount === 1 ? "" : "s"
} detected`;
} else {
statusText.textContent = "No collisions detected";
}
for (const item of items) {
item.material.emissive.set(
item.colliding
? 0x7c1620
: item.outOfBounds
? 0x7c4910
: 0x000000
);
item.material.emissiveIntensity =
item.colliding || item.outOfBounds ? 0.42 : 0;
const helperColor = item.colliding
? 0xed5964
: item.outOfBounds
? 0xe5a743
: 0x16a39a;
item.helper.material.color.set(helperColor);
updateHelper(
item.helper,
item.root,
item.colliding || item.outOfBounds
);
}
updateHelper(
selectionHelper,
selectedItem?.root,
Boolean(selectedItem)
);
updateHeatmap();
}
function selectItem(item) {
selectedItem = item;
if (!item) {
selectionName.textContent = "Grab a clothing bundle";
selectionMeta.textContent =
"Drag to pack · drag empty space to orbit";
selectionHelper.visible = false;
return;
}
selectionName.textContent = item.name;
selectionMeta.textContent =
`${item.category} · ${item.w.toFixed(1)} × ${item.d.toFixed(
1
)} footprint · ${item.h.toFixed(1)} high`;
}
const initialLayout = new Map(
definitions.map((definition) => [
definition.id,
{
x: definition.x,
z: definition.z,
},
])
);
// A non-overlapping rigid layout, arranged in lower-left rows.
const packedLowerLeft = {
rose: [0, 0],
indigo: [3.6, 0],
sage: [6.6, 0],
cloud: [0, 2.8],
ochre: [3.4, 2.8],
stone: [6.6, 2.0],
sea: [3.4, 4.7],
graphite: [0, 5.4],
ivory: [6.6, 3.8],
};
const packedLayout = new Map();
for (const item of items) {
const [left, front] = packedLowerLeft[item.id];
packedLayout.set(item.id, {
x:
-CASE.innerHalfWidth +
left +
item.w / 2,
z:
-CASE.innerHalfDepth +
front +
item.d / 2,
});
}
function startTween(layout, message) {
activeTween = {
start: performance.now(),
duration: 760,
entries: items.map((item, index) => ({
item,
delay: index * 32,
fromX: item.root.position.x,
fromZ: item.root.position.z,
toX: layout.get(item.id).x,
toZ: layout.get(item.id).z,
})),
};
statusOverride = message;
statusText.textContent = message;
}
function cancelTween() {
activeTween = null;
statusOverride = "";
}
autoPackButton.addEventListener("click", () => {
startTween(packedLayout, "Arranging clean layout…");
});
resetButton.addEventListener("click", () => {
startTween(initialLayout, "Restoring trial layout…");
});
lidButton.addEventListener("click", () => {
lidOpen = !lidOpen;
lidTargetAngle = lidOpen ? -0.62 : -0.025;
lidButton.textContent = lidOpen ? "Close lid" : "Open lid";
});
heatmapButton.addEventListener("click", () => {
heatmapVisible = !heatmapVisible;
heatmap.visible = heatmapVisible;
heatmapButton.classList.toggle("active", heatmapVisible);
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLButtonElement) return;
if (event.code === "Space") {
event.preventDefault();
startTween(packedLayout, "Arranging clean layout…");
} else if (event.key.toLowerCase() === "l") {
lidButton.click();
} else if (event.key.toLowerCase() === "r") {
startTween(initialLayout, "Restoring trial layout…");
} else if (event.key.toLowerCase() === "g") {
heatmapButton.click();
}
});
// Custom orbit, pan, zoom, and item dragging.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const dragPoint = new THREE.Vector3();
const dragOffset = new THREE.Vector2();
let pointerMode = null;
let draggedItem = null;
let lastPointerX = 0;
let lastPointerY = 0;
function updatePointer(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;
raycaster.setFromCamera(pointer, camera);
}
renderer.domElement.addEventListener(
"pointerdown",
(event) => {
updatePointer(event);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
const hits = raycaster.intersectObjects(hitMeshes, false);
if (event.button === 0 && hits.length > 0) {
const item = hits[0].object.userData.item;
cancelTween();
selectItem(item);
dragPlane.set(
new THREE.Vector3(0, 1, 0),
-item.root.position.y
);
raycaster.ray.intersectPlane(dragPlane, dragPoint);
dragOffset.set(
item.root.position.x - dragPoint.x,
item.root.position.z - dragPoint.z
);
draggedItem = item;
pointerMode = "drag";
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
event.preventDefault();
return;
}
if (event.button === 2 || event.button === 1 || event.shiftKey) {
pointerMode = "pan";
} else {
pointerMode = "orbit";
}
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
},
{ passive: false }
);
renderer.domElement.addEventListener("pointermove", (event) => {
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (pointerMode === "drag" && draggedItem) {
updatePointer(event);
raycaster.ray.intersectPlane(dragPlane, dragPoint);
draggedItem.root.position.x = THREE.MathUtils.clamp(
dragPoint.x + dragOffset.x,
-6.2,
6.2
);
draggedItem.root.position.z = THREE.MathUtils.clamp(
dragPoint.z + dragOffset.y,
-4.7,
4.7
);
updateDiagnostics();
return;
}
if (pointerMode === "orbit") {
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.005,
0.26,
1.35
);
updateCamera();
} else if (pointerMode === "pan") {
const right = new THREE.Vector3();
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
right.setFromMatrixColumn(camera.matrixWorld, 0);
right.y = 0;
right.normalize();
forward.y = 0;
forward.normalize();
const scale = cameraState.radius / renderer.domElement.clientHeight;
cameraState.target.addScaledVector(
right,
-deltaX * scale
);
cameraState.target.addScaledVector(
forward,
deltaY * scale
);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-8,
8
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-8,
8
);
updateCamera();
} else {
updatePointer(event);
const hits = raycaster.intersectObjects(hitMeshes, false);
renderer.domElement.style.cursor = hits.length ? "grab" : "default";
}
});
function endPointer(event) {
pointerMode = null;
draggedItem = null;
renderer.domElement.style.cursor = "default";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
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.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10.5,
27
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
updateDiagnostics();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
lidPivot.rotation.x = THREE.MathUtils.lerp(
lidPivot.rotation.x,
lidTargetAngle,
1 - Math.exp(-7 * delta)
);
if (activeTween) {
const elapsed = performance.now() - activeTween.start;
let complete = true;
for (const entry of activeTween.entries) {
const progress = THREE.MathUtils.clamp(
(elapsed - entry.delay) / activeTween.duration,
0,
1
);
const eased = 1 - Math.pow(1 - progress, 3);
entry.item.root.position.x = THREE.MathUtils.lerp(
entry.fromX,
entry.toX,
eased
);
entry.item.root.position.z = THREE.MathUtils.lerp(
entry.fromZ,
entry.toZ,
eased
);
if (progress < 1) complete = false;
}
updateDiagnostics();
if (complete) {
activeTween = null;
statusOverride = "";
updateDiagnostics();
}
}
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(() => {
loading.classList.add("hidden");
setTimeout(() => loading.remove(), 400);
});
</script>
</body>
</html>
```