Prompt specification
Build or customize the Three.js 3D scene "Day-trip packing decision game" 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: Day-trip packing decision game
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/day-trip-packing-decision-game-x0564
Scene Description Prompt:
Create a standalone HTML file using Three.js from cdnjs for a low-poly day-trip packing game. Open a backpack on a bench and place a bottle, jacket, lunch box, notebook, and small activity kit beside it. Each object has a simplified solid footprint and an explicitly symbolic weight. Let users place items inside a bounded bag volume and select an activity schedule that determines which items must be retrieved first. Track occupied space, total symbolic load, and items obstructing the next retrieval. The bag can be cut away during planning, then closed for a side view showing load placement. Reject overlaps rather than shrinking an item to make it fit.
Working Three.js Starter (day-trip-packing-decision-game-x0564):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Pack & Go — Low-Poly Day Trip Packing Game</title>
<style>
:root {
color-scheme: light;
--ink: #183832;
--muted: #667b75;
--paper: #f8fbf9;
--panel: rgba(255, 255, 255, 0.94);
--line: #d8e5df;
--green: #177c68;
--green-dark: #0d5e50;
--mint: #dff3eb;
--amber: #e4a83a;
--red: #cf514d;
--blue: #2b8fc7;
--shadow: 0 16px 42px rgba(26, 66, 56, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e7f0ec;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select,
input {
font: inherit;
}
button {
color: inherit;
}
header {
height: 78px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 12px 22px;
background: rgba(255, 255, 255, 0.9);
border-bottom: 1px solid var(--line);
box-shadow: 0 5px 24px rgba(35, 75, 64, 0.07);
position: relative;
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 44px;
height: 44px;
display: grid;
place-items: center;
flex: 0 0 auto;
border-radius: 14px;
background: var(--green);
color: white;
font-size: 25px;
box-shadow: 0 8px 18px rgba(23, 124, 104, 0.22);
}
.brand h1 {
margin: 0;
font-size: 22px;
line-height: 1.05;
letter-spacing: -0.03em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.view-switch {
display: flex;
align-items: center;
gap: 8px;
padding: 5px;
border: 1px solid var(--line);
border-radius: 13px;
background: #f3f7f5;
}
.view-switch button {
border: 0;
border-radius: 9px;
padding: 9px 13px;
background: transparent;
cursor: pointer;
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
.view-switch button.active {
color: white;
background: var(--green);
box-shadow: 0 4px 10px rgba(23, 124, 104, 0.18);
}
.layout {
height: calc(100vh - 78px);
display: grid;
grid-template-columns: 276px minmax(420px, 1fr) 300px;
min-height: 0;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 16px;
background: var(--paper);
scrollbar-width: thin;
}
aside.left {
border-right: 1px solid var(--line);
}
aside.right {
border-left: 1px solid var(--line);
}
.section {
margin-bottom: 16px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 8px 24px rgba(40, 77, 67, 0.055);
}
.section h2 {
margin: 0 0 12px;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.12em;
color: #4d6861;
}
.section p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.metrics {
display: grid;
gap: 12px;
}
.metric-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.metric-head span {
color: var(--muted);
font-size: 11px;
font-weight: 650;
}
.metric-head strong {
font-size: 14px;
letter-spacing: -0.02em;
}
.bar {
height: 8px;
overflow: hidden;
border-radius: 999px;
background: #e8efec;
}
.bar > i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #42ad91, var(--green));
transition: width 180ms ease;
}
.metric-note {
display: block;
margin-top: 5px;
color: #81918c;
font-size: 10px;
}
.mini-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.mini-metric {
padding: 10px;
border-radius: 12px;
background: #edf5f1;
}
.mini-metric span {
display: block;
color: var(--muted);
font-size: 10px;
}
.mini-metric strong {
display: block;
margin-top: 3px;
font-size: 16px;
}
select {
width: 100%;
border: 1px solid #cadbd4;
border-radius: 10px;
padding: 10px 11px;
color: var(--ink);
background: white;
outline: none;
}
select:focus,
input:focus-visible,
button:focus-visible {
outline: 3px solid rgba(43, 143, 199, 0.25);
outline-offset: 2px;
}
.retrieval-card {
border-left: 4px solid var(--amber);
border-radius: 12px;
padding: 12px;
background: #fff6df;
}
.retrieval-card.blocked {
border-left-color: var(--red);
background: #fff0ee;
}
.retrieval-card.ready {
border-left-color: var(--green);
background: #e9f7f1;
}
.retrieval-card.missing {
border-left-color: var(--amber);
background: #fff6df;
}
.retrieval-card.done {
border-left-color: var(--blue);
background: #edf7fc;
}
.retrieval-card .eyebrow {
margin-bottom: 5px;
color: #8b6a2c;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.retrieval-card h3 {
margin: 0;
font-size: 15px;
}
.retrieval-card p {
margin-top: 6px;
font-size: 11px;
}
.blocker-list {
display: grid;
gap: 5px;
margin: 9px 0 0;
padding: 0;
list-style: none;
}
.blocker-list li {
padding: 6px 8px;
border-radius: 8px;
color: #913b38;
background: rgba(207, 81, 77, 0.09);
font-size: 10px;
font-weight: 750;
}
.order-list,
.inventory {
display: grid;
gap: 7px;
}
.order-item,
.inventory-item {
width: 100%;
display: grid;
align-items: center;
border: 1px solid #dce7e2;
border-radius: 10px;
background: white;
cursor: pointer;
text-align: left;
}
.order-item {
grid-template-columns: 26px 1fr auto;
gap: 8px;
padding: 8px;
}
.order-item:hover,
.inventory-item:hover {
border-color: #94c4b5;
}
.order-number {
width: 25px;
height: 25px;
display: grid;
place-items: center;
border-radius: 8px;
color: #60746e;
background: #edf3f0;
font-size: 10px;
font-weight: 800;
}
.order-item.next {
border-color: #e5b75e;
background: #fff9e9;
}
.order-item.next .order-number {
color: white;
background: var(--amber);
}
.order-item.blocker {
border-color: #e2a19e;
background: #fff3f1;
}
.order-item.retrieved {
opacity: 0.58;
}
.order-copy {
min-width: 0;
}
.order-copy strong,
.inventory-copy strong {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 11px;
}
.order-copy small,
.inventory-copy small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.order-state {
color: var(--muted);
font-size: 8px;
font-weight: 800;
text-transform: uppercase;
}
.selected-title {
display: flex;
align-items: center;
gap: 9px;
}
.swatch {
width: 12px;
height: 12px;
flex: 0 0 auto;
border-radius: 4px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.selected-title strong {
font-size: 14px;
}
.selected-meta {
margin: 8px 0 12px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.range-head {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 7px;
font-size: 10px;
font-weight: 750;
}
input[type="range"] {
width: 100%;
accent-color: var(--green);
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 10px;
}
.btn {
border: 1px solid #cbdcd5;
border-radius: 9px;
padding: 8px 10px;
background: white;
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.btn:hover:not(:disabled) {
border-color: #7eb6a5;
background: #f1f8f5;
}
.btn.primary {
border-color: var(--green);
color: white;
background: var(--green);
}
.btn.primary:hover:not(:disabled) {
background: var(--green-dark);
}
.btn.warning {
border-color: #e1b65c;
color: #765316;
background: #fff7e3;
}
.btn:disabled {
opacity: 0.46;
cursor: not-allowed;
}
.full {
width: 100%;
}
.inventory-item {
grid-template-columns: 12px 1fr auto;
gap: 9px;
padding: 9px;
}
.inventory-item.selected {
border-color: var(--blue);
box-shadow: inset 0 0 0 1px rgba(43, 143, 199, 0.16);
}
.weight-chip {
min-width: 48px;
padding: 5px 6px;
border-radius: 8px;
color: #5c716a;
background: #eef4f1;
text-align: center;
font-size: 8px;
font-weight: 850;
line-height: 1.25;
}
.hint {
margin-top: 10px;
padding: 10px;
border-radius: 10px;
color: #536b64;
background: #edf5f1;
font-size: 10px;
line-height: 1.55;
}
kbd {
padding: 1px 4px;
border: 1px solid #b9cac4;
border-bottom-width: 2px;
border-radius: 4px;
background: white;
font: 700 9px inherit;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #dbe9e5;
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
.stage-overlay {
position: absolute;
inset: 0;
pointer-events: none;
}
.stage-top {
position: absolute;
top: 14px;
left: 14px;
right: 14px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.stage-badge,
.stage-button {
pointer-events: auto;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 10px;
background: rgba(255, 255, 255, 0.84);
box-shadow: 0 6px 20px rgba(30, 67, 58, 0.1);
backdrop-filter: blur(8px);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.stage-badge {
padding: 9px 11px;
color: var(--green-dark);
}
.stage-button {
padding: 9px 11px;
color: var(--ink);
cursor: pointer;
}
.stage-button:disabled {
opacity: 0.55;
}
.stage-help {
position: absolute;
left: 14px;
bottom: 14px;
max-width: 410px;
padding: 9px 12px;
border-radius: 10px;
color: #38554d;
background: rgba(255, 255, 255, 0.8);
box-shadow: 0 6px 20px rgba(30, 67, 58, 0.08);
backdrop-filter: blur(8px);
font-size: 10px;
line-height: 1.5;
}
.dimension-note {
position: absolute;
right: 14px;
bottom: 14px;
padding: 8px 10px;
border-radius: 9px;
color: #526a63;
background: rgba(255, 255, 255, 0.76);
font-size: 9px;
font-weight: 700;
}
#toast {
position: fixed;
left: 50%;
bottom: 25px;
z-index: 50;
max-width: min(520px, calc(100vw - 30px));
padding: 12px 17px;
border-radius: 12px;
color: white;
background: rgba(24, 56, 50, 0.95);
box-shadow: var(--shadow);
font-size: 12px;
font-weight: 650;
line-height: 1.4;
opacity: 0;
transform: translate(-50%, 16px);
transition: opacity 180ms ease, transform 180ms ease;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
background: rgba(135, 48, 45, 0.96);
}
@media (max-width: 1050px) {
.layout {
grid-template-columns: 235px minmax(360px, 1fr) 255px;
}
aside {
padding: 11px;
}
.section {
padding: 12px;
}
}
@media (max-width: 820px) {
html,
body {
height: auto;
overflow: auto;
}
header {
height: auto;
min-height: 78px;
align-items: flex-start;
flex-direction: column;
gap: 10px;
}
.view-switch {
width: 100%;
}
.view-switch button {
flex: 1;
}
.layout {
height: auto;
display: grid;
grid-template-columns: 1fr;
}
#stage {
order: -1;
height: 58vh;
min-height: 420px;
}
aside {
overflow: visible;
border: 0;
border-top: 1px solid var(--line);
}
}
</style>
</head>
<body>
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">▣</div>
<div>
<h1>Pack & Go</h1>
<p>A low-poly day-trip packing and retrieval game</p>
</div>
</div>
<div class="view-switch" aria-label="View mode">
<button id="planBtn" class="active" type="button">Plan / Cutaway</button>
<button id="closedBtn" type="button">Closed Side View</button>
</div>
</header>
<main class="layout">
<aside class="left">
<section class="section">
<h2>Pack Load</h2>
<div class="metrics">
<div>
<div class="metric-head">
<span>Occupied volume</span>
<strong id="volumeValue">0.00 u³</strong>
</div>
<div class="bar"><i id="volumeBar"></i></div>
<small class="metric-note" id="volumeNote">0% of bounded cavity</small>
</div>
<div class="mini-metrics">
<div class="mini-metric">
<span>Symbolic load</span>
<strong id="loadValue">0 / 12</strong>
</div>
<div class="mini-metric">
<span>Floor footprint</span>
<strong id="footprintValue">0%</strong>
</div>
</div>
</div>
</section>
<section class="section">
<h2>Activity Schedule</h2>
<select id="scheduleSelect" aria-label="Activity schedule">
<option value="picnic">Park picnic</option>
<option value="museum">Museum + café</option>
<option value="trail">Trail + transit</option>
</select>
<div id="retrievalOrder" class="order-list" style="margin-top: 12px"></div>
</section>
<section class="section">
<h2>Next Retrieval</h2>
<div id="nextCard" class="retrieval-card missing">
<div class="eyebrow">Required first</div>
<h3 id="nextTitle">Lunch box</h3>
<p id="nextDescription">Pack the first required item.</p>
<ul id="blockerList" class="blocker-list"></ul>
</div>
<div class="button-row">
<button id="retrieveBtn" class="btn primary full" type="button">
Try retrieving lunch box
</button>
</div>
</section>
<section class="section">
<h2>Planning Rules</h2>
<p>
Items keep their exact dimensions. A placement that overlaps another
item is rejected rather than automatically shrinking either object.
</p>
<div class="hint">
Items may be stacked vertically. The next scheduled item is blocked
when another packed item sits directly above its footprint.
</div>
</section>
</aside>
<section id="stage" aria-label="3D packing scene">
<div id="viewport"></div>
<div class="stage-overlay">
<div class="stage-top">
<div id="stageBadge" class="stage-badge">Planning · Bag cutaway</div>
<button id="cutawayBtn" class="stage-button" type="button">
Cutaway: ON
</button>
</div>
<div class="stage-help">
Drag items into the open bag. Use the height slider or
<kbd>Q</kbd>/<kbd>E</kbd> to stage a stack. Drag empty space to orbit;
scroll to zoom.
</div>
<div class="dimension-note">Cavity: 43 × 23 × 42 cm</div>
</div>
</section>
<aside class="right">
<section class="section">
<h2>Selected Object</h2>
<div class="selected-title">
<span id="selectedSwatch" class="swatch"></span>
<strong id="selectedName">Choose an item</strong>
</div>
<div id="selectedMeta" class="selected-meta">
Click a scene object or choose one from the inventory.
</div>
<div class="range-head">
<label for="heightSlider">Placement / stacking height</label>
<span id="heightValue">—</span>
</div>
<input
id="heightSlider"
type="range"
min="0.77"
max="2.70"
step="0.02"
value="0.77"
disabled
/>
<div class="button-row">
<button id="floorBtn" class="btn" type="button" disabled>
Drop to floor
</button>
<button id="benchBtn" class="btn" type="button" disabled>
Return to bench
</button>
</div>
</section>
<section class="section">
<h2>Inventory</h2>
<div id="inventory" class="inventory"></div>
</section>
<section class="section">
<h2>Session</h2>
<button id="resetBtn" class="btn warning full" type="button">
Repack all objects
</button>
<div class="hint">
<strong>Weights are symbolic:</strong> each number is one load symbol,
not a claim about real-world mass. The total shows only the load
currently inside the bag.
</div>
</section>
</aside>
</main>
<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 CFG = {
bagX: -1.5,
bagFloor: 0.84,
bagWidth: 2.15,
bagDepth: 1.16,
bagHeight: 2.05,
benchTop: 0.76,
benchMinX: -3.7,
benchMaxX: 4.65,
benchMinZ: -1.01,
benchMaxZ: 1.01,
loadCapacity: 12
};
CFG.bagLeft = CFG.bagX - CFG.bagWidth / 2;
CFG.bagRight = CFG.bagX + CFG.bagWidth / 2;
CFG.bagTop = CFG.bagFloor + CFG.bagHeight;
const viewport = document.getElementById("viewport");
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe9e5);
scene.fog = new THREE.Fog(0xdbe9e5, 15, 28);
const camera = new THREE.PerspectiveCamera(42, 1, 0.05, 80);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute(
"aria-label",
"Interactive low-poly backpack packing scene"
);
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf4fff9, 0x78958a, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff5dc, 3.2);
sun.position.set(-4, 9, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 7;
sun.shadow.camera.bottom = -7;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 25;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xa9d9eb, 0.85);
fill.position.set(7, 4, -4);
scene.add(fill);
const cameraState = {
target: new THREE.Vector3(0.35, 1.18, 0),
radius: 10.2,
theta: 0.31,
phi: 1.08
};
const desiredCamera = {
target: cameraState.target.clone(),
radius: cameraState.radius,
theta: cameraState.theta,
phi: cameraState.phi
};
function setStandardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0,
...options
});
}
function addBox(parent, width, height, depth, color, x, y, z, material = null) {
const geometry = new THREE.BoxGeometry(width, height, depth);
const mesh = new THREE.Mesh(
geometry,
material || setStandardMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(
parent,
radiusTop,
radiusBottom,
height,
color,
x,
y,
z,
segments = 8
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
radiusTop,
radiusBottom,
height,
segments
),
setStandardMaterial(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Ground and low-poly wooden bench.
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
setStandardMaterial(0xc9d9d2)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.01;
ground.receiveShadow = true;
scene.add(ground);
const bench = new THREE.Group();
scene.add(bench);
const woodColors = [0xb87943, 0xc4874d, 0xb97842, 0xc78a50, 0xb77943];
for (let i = 0; i < 5; i++) {
addBox(
bench,
8.4,
0.18,
0.41,
woodColors[i],
0.47,
CFG.benchTop - 0.09,
-0.88 + i * 0.44
);
}
for (const x of [-3.35, 4.2]) {
for (const z of [-0.76, 0.76]) {
addBox(bench, 0.24, 0.72, 0.24, 0x41665b, x, 0.35, z);
}
}
addBox(bench, 8.0, 0.16, 0.16, 0x476a60, 0.45, 0.27, -0.76);
addBox(bench, 8.0, 0.16, 0.16, 0x476a60, 0.45, 0.27, 0.76);
// A subtle mat distinguishes the staging area.
addBox(
bench,
4.75,
0.025,
1.72,
0x769d8d,
2.46,
CFG.benchTop + 0.008,
0
);
// Backpack shell.
const backpack = new THREE.Group();
backpack.position.x = CFG.bagX;
scene.add(backpack);
const bagFabric = setStandardMaterial(0xd9813f);
const bagDark = setStandardMaterial(0x8d4f29);
const bagTrim = setStandardMaterial(0x284d48);
const rightSideMaterial = setStandardMaterial(0xc96e35, {
transparent: true,
opacity: 0.17,
depthWrite: false,
side: THREE.DoubleSide
});
addBox(
backpack,
2.5,
0.16,
1.5,
0xb96531,
0,
CFG.bagFloor - 0.08,
0,
bagDark
);
addBox(
backpack,
2.5,
CFG.bagHeight,
0.16,
0xc36c32,
0,
CFG.bagFloor + CFG.bagHeight / 2,
-0.69,
bagFabric
);
addBox(
backpack,
0.16,
CFG.bagHeight,
1.48,
0xc97136,
-1.17,
CFG.bagFloor + CFG.bagHeight / 2,
0,
bagFabric
);
const rightWall = addBox(
backpack,
0.16,
CFG.bagHeight,
1.48,
0xc97136,
1.17,
CFG.bagFloor + CFG.bagHeight / 2,
0,
rightSideMaterial
);
const frontPanel = addBox(
backpack,
2.48,
CFG.bagHeight,
0.14,
0xd47b3c,
0,
CFG.bagFloor + CFG.bagHeight / 2,
0.69,
bagFabric
);
frontPanel.visible = false;
const frontPocket = addBox(
backpack,
1.22,
0.66,
0.13,
0xc76732,
0,
CFG.bagFloor + 0.58,
0.81,
bagTrim
);
frontPocket.visible = false;
const frontZipper = addBox(
backpack,
1.65,
0.035,
0.035,
0x263f3b,
0,
CFG.bagFloor + 0.9,
0.79,
bagTrim
);
frontZipper.visible = false;
addBox(
backpack,
2.42,
0.23,
0.15,
0x9b5129,
0,
CFG.bagFloor + 0.115,
0.68,
bagDark
);
// Rear straps.
for (const x of [-0.55, 0.55]) {
const strap = addBox(
backpack,
0.17,
1.78,
0.12,
0x365951,
x,
CFG.bagFloor + 0.95,
-0.82,
bagTrim
);
strap.rotation.x = -0.08;
}
const handle = new THREE.Mesh(
new THREE.TorusGeometry(0.29, 0.065, 6, 12, Math.PI),
setStandardMaterial(0x284d48)
);
handle.position.set(0, CFG.bagTop, -0.05);
handle.castShadow = true;
backpack.add(handle);
// Transparent cavity and wireframe dimensions.
const cavityFill = new THREE.Mesh(
new THREE.BoxGeometry(CFG.bagWidth, CFG.bagHeight, CFG.bagDepth),
new THREE.MeshBasicMaterial({
color: 0x8ee1c7,
transparent: true,
opacity: 0.035,
depthWrite: false
})
);
cavityFill.position.set(
CFG.bagX,
CFG.bagFloor + CFG.bagHeight / 2,
0
);
scene.add(cavityFill);
const cavityWire = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(
CFG.bagWidth,
CFG.bagHeight,
CFG.bagDepth
)
),
new THREE.LineBasicMaterial({
color: 0x70c9ae,
transparent: true,
opacity: 0.7
})
);
cavityWire.position.copy(cavityFill.position);
scene.add(cavityWire);
// A small floor grid makes depth and stacking easier to read.
const gridPoints = [];
for (let x = CFG.bagLeft; x <= CFG.bagRight + 0.001; x += 0.215) {
gridPoints.push(
x,
CFG.bagFloor + 0.007,
-CFG.bagDepth / 2,
x,
CFG.bagFloor + 0.007,
CFG.bagDepth / 2
);
}
for (let z = -CFG.bagDepth / 2; z <= CFG.bagDepth / 2 + 0.001; z += 0.193) {
gridPoints.push(
CFG.bagLeft,
CFG.bagFloor + 0.007,
z,
CFG.bagRight,
CFG.bagFloor + 0.007,
z
);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPoints, 3)
);
scene.add(
new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x9bcaba,
transparent: true,
opacity: 0.4
})
)
);
const schedules = {
picnic: {
label: "Park picnic",
order: ["lunchbox", "bottle", "kit", "jacket", "notebook"]
},
museum: {
label: "Museum + café",
order: ["notebook", "kit", "bottle", "jacket", "lunchbox"]
},
trail: {
label: "Trail + transit",
order: ["bottle", "kit", "notebook", "jacket", "lunchbox"]
}
};
const itemDefinitions = {
bottle: {
name: "Bottle",
weight: 3,
w: 0.48,
d: 0.42,
h: 1.05,
color: 0x3b9cbd,
initialX: 0.48,
initialZ: -0.55
},
jacket: {
name: "Jacket",
weight: 2,
w: 1.1,
d: 0.72,
h: 0.28,
color: 0x718f4f,
initialX: 1.42,
initialZ: 0.36
},
lunchbox: {
name: "Lunch box",
weight: 4,
w: 0.9,
d: 0.64,
h: 0.46,
color: 0xe05b59,
initialX: 2.58,
initialZ: -0.43
},
notebook: {
name: "Notebook",
weight: 1,
w: 0.65,
d: 0.48,
h: 0.18,
color: 0x7259a6,
initialX: 3.64,
initialZ: 0.36
},
kit: {
name: "Activity kit",
weight: 2,
w: 0.72,
d: 0.52,
h: 0.4,
color: 0xe7a33b,
initialX: 3.7,
initialZ: -0.62
}
};
const items = {};
const itemRoots = [];
const retrieved = new Set();
function roundedRectPath(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function createLabel(name, weight, color) {
const canvas = document.createElement("canvas");
canvas.width = 384;
canvas.height = 96;
const ctx = canvas.getContext("2d");
roundedRectPath(ctx, 3, 3, 378, 90, 18);
ctx.fillStyle = "rgba(20, 47, 42, 0.92)";
ctx.fill();
ctx.strokeStyle = "#" + new THREE.Color(color).getHexString();
ctx.lineWidth = 4;
ctx.stroke();
ctx.textAlign = "center";
ctx.fillStyle = "#ffffff";
ctx.font = "800 27px system-ui, sans-serif";
ctx.fillText(name.toUpperCase(), 192, 37);
ctx.fillStyle = "#bcd7cf";
ctx.font = "750 20px system-ui, sans-serif";
ctx.fillText(`WEIGHT: ${weight} SYMBOL${weight === 1 ? "" : "S"}`, 192, 70);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.93, 0.235, 1);
sprite.renderOrder = 20;
return sprite;
}
function buildItemVisual(root, definition) {
const color = definition.color;
const accent = new THREE.Color(color).offsetHSL(0, -0.08, 0.12);
if (definition.name === "Bottle") {
addCylinder(root, 0.22, 0.24, 0.78, color, 0, 0.39, 0, 8);
addCylinder(root, 0.12, 0.16, 0.12, 0x276c7b, 0, 0.84, 0, 8);
addCylinder(root, 0.14, 0.14, 0.1, 0xe7e4cf, 0, 0.95, 0, 8);
addBox(root, 0.25, 0.08, 0.025, 0xe9f2ed, 0, 0.51, 0.232);
}
if (definition.name === "Jacket") {
addBox(root, 1.06, 0.18, 0.68, color, 0, 0.09, 0);
addBox(root, 0.94, 0.08, 0.58, accent.getHex(), 0, 0.21, 0.01);
addBox(root, 0.045, 0.025, 0.61, 0xd9d8bd, -0.38, 0.262, 0);
addBox(root, 0.045, 0.025, 0.61, 0xd9d8bd, 0.38, 0.262, 0);
}
if (definition.name === "Lunch box") {
addBox(root, 0.88, 0.34, 0.6, color, 0, 0.17, 0);
addBox(root, 0.92, 0.1, 0.64, accent.getHex(), 0, 0.39, 0);
addBox(root, 0.16, 0.07, 0.035, 0x7f3938, 0, 0.36, 0.322);
addBox(root, 0.045, 0.12, 0.035, 0xfff0db, -0.24, 0.26, 0.307);
}
if (definition.name === "Notebook") {
addBox(root, 0.59, 0.12, 0.43, 0xf1ead8, 0.025, 0.06, 0);
addBox(root, 0.65, 0.03, 0.48, color, 0, 0.135, 0);
addBox(root, 0.06, 0.18, 0.48, accent.getHex(), -0.295, 0.09, 0);
addBox(root, 0.15, 0.008, 0.035, 0xf3e9a2, 0.08, 0.156, 0.06);
}
if (definition.name === "Activity kit") {
addBox(root, 0.68, 0.26, 0.48, color, 0, 0.13, 0);
addBox(root, 0.72, 0.08, 0.52, accent.getHex(), 0, 0.3, 0);
addBox(root, 0.28, 0.06, 0.1, 0x7b5121, 0, 0.37, 0);
addBox(root, 0.12, 0.04, 0.04, 0xfff1d7, 0, 0.25, 0.252);
}
}
for (const [id, definition] of Object.entries(itemDefinitions)) {
const root = new THREE.Group();
root.userData.itemId = id;
scene.add(root);
root.position.set(
definition.initialX,
CFG.benchTop + 0.01,
definition.initialZ
);
buildItemVisual(root, definition);
const label = createLabel(definition.name, definition.weight, definition.color);
label.position.set(
definition.initialX,
CFG.benchTop + 0.01 + definition.h + 0.19,
definition.initialZ
);
scene.add(label);
const helper = new THREE.BoxHelper(root, 0x2b8fc7);
helper.visible = false;
helper.material.transparent = true;
helper.material.opacity = 0.92;
helper.material.depthTest = false;
helper.renderOrder = 30;
scene.add(helper);
items[id] = {
...definition,
id,
root,
label,
helper,
x: definition.initialX,
z: definition.initialZ,
baseY: CFG.benchTop + 0.01,
inBag: false,
previewBad: false
};
itemRoots.push(root);
}
// Selected footprint visual.
const footprintFill = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
new THREE.MeshBasicMaterial({
color: 0x38a7d4,
transparent: true,
opacity: 0.17,
depthWrite: false,
side: THREE.DoubleSide
})
);
footprintFill.rotation.x = -Math.PI / 2;
footprintFill.visible = false;
scene.add(footprintFill);
const footprintGeometry = new THREE.BufferGeometry();
footprintGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(12), 3)
);
const footprintOutline = new THREE.LineLoop(
footprintGeometry,
new THREE.LineBasicMaterial({
color: 0x2b8fc7,
transparent: true,
opacity: 0.85
})
);
footprintOutline.visible = false;
scene.add(footprintOutline);
let selectedId = null;
let activeSchedule = "picnic";
let viewMode = "plan";
let planCutaway = true;
let drag = null;
let orbit = null;
let heightSnapshot = null;
let toastTimer = null;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const planeHit = new THREE.Vector3();
function syncItem(item) {
item.root.position.set(item.x, item.baseY, item.z);
item.label.position.set(
item.x,
item.baseY + item.h + 0.19,
item.z
);
}
function showToast(message, isError = false) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.toggle("error", isError);
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("show");
}, 2800);
}
function setPointerFromEvent(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);
}
function itemIdFromObject(object) {
let current = object;
while (current) {
if (current.userData.itemId) return current.userData.itemId;
current = current.parent;
}
return null;
}
function horizontalOverlap(a, b) {
return (
Math.min(a.x + a.w / 2, b.x + b.w / 2) -
Math.max(a.x - a.w / 2, b.x - b.w / 2) >
0.012 &&
Math.min(a.z + a.d / 2, b.z + b.d / 2) -
Math.max(a.z - a.d / 2, b.z - b.d / 2) >
0.012
);
}
function solidOverlap(a, b) {
const overlapX =
(a.w + b.w) / 2 - Math.abs(a.x - b.x);
const overlapZ =
(a.d + b.d) / 2 - Math.abs(a.z - b.z);
const overlapY =
(a.h + b.h) / 2 - Math.abs(a.baseY - b.baseY);
return overlapX > 0.012 && overlapZ > 0.012 && overlapY > 0.012;
}
function validatePlacement(id, x, z, baseY, intendedForBag) {
const item = items[id];
if (intendedForBag) {
if (
x - item.w / 2 < CFG.bagLeft - 0.005 ||
x + item.w / 2 > CFG.bagRight + 0.005
) {
return {
ok: false,
reason: "The item extends beyond the left or right side of the bounded cavity."
};
}
if (
z - item.d / 2 < -CFG.bagDepth / 2 - 0.005 ||
z + item.d / 2 > CFG.bagDepth / 2 + 0.005
) {
return {
ok: false,
reason: "The item extends beyond the front or back of the bounded cavity."
};
}
if (baseY < CFG.bagFloor - 0.01) {
return {
ok: false,
reason: "The item must sit above the cavity floor."
};
}
if (baseY + item.h > CFG.bagTop + 0.01) {
return {
ok: false,
reason: "The item is taller than the available cavity height at this position."
};
}
for (const other of Object.values(items)) {
if (other.id === id || !other.inBag || retrieved.has(other.id)) {
continue;
}
if (solidOverlap(item, other)) {
return {
ok: false,
reason: `${item.name} overlaps ${other.name}. Item sizes were not changed.`
};
}
}
return { ok: true };
}
if (
x - item.w / 2 < CFG.benchMinX ||
x + item.w / 2 > CFG.benchMaxX
) {
return {
ok: false,
reason: "That position extends beyond the edge of the bench."
};
}
if (
z - item.d / 2 < CFG.benchMinZ ||
z + item.d / 2 > CFG.benchMaxZ
) {
return {
ok: false,
reason: "That position extends beyond the staging area."
};
}
const effectiveY = CFG.benchTop + 0.01;
for (const other of Object.values(items)) {
if (other.id === id || retrieved.has(other.id)) continue;
if (
horizontalOverlap(item, other) &&
effectiveY < other.baseY + other.h - 0.012 &&
effectiveY + item.h > other.baseY + 0.012
) {
return {
ok: false,
reason: `${item.name} overlaps ${other.name} on the bench.`
};
}
}
return { ok: true };
}
function isBagIntent(x, z) {
return (
Math.abs(x - CFG.bagX) < CFG.bagWidth / 2 + 0.34 &&
Math.abs(z) < CFG.bagDepth / 2 + 0.25
);
}
function getBlockers(targetId) {
const target = items[targetId];
if (!target || !target.inBag) return [];
return Object.values(items).filter((other) => {
if (
other.id === targetId ||
!other.inBag ||
retrieved.has(other.id)
) {
return false;
}
const overlapsAbove =
horizontalOverlap(target, other) &&
other.baseY >= target.baseY + target.h - 0.025;
return overlapsAbove;
});
}
function getRetrievalState() {
const order = schedules[activeSchedule].order;
const targetId = order.find((id) => !retrieved.has(id));
if (!targetId) {
return {
kind: "done",
target: null,
blockers: [],
targetNumber: order.length
};
}
const target = items[targetId];
const blockers = getBlockers(targetId);
return {
kind: !target.inBag ? "missing" : blockers.length ? "blocked" : "ready",
target,
blockers,
targetNumber: order.indexOf(targetId) + 1
};
}
function computeFootprintCoverage() {
const packed = Object.values(items).filter(
(item) => item.inBag && !retrieved.has(item.id)
);
if (!packed.length) return 0;
const nx = 64;
const nz = 36;
const grid = new Uint8Array(nx * nz);
for (const item of packed) {
const minX = Math.max(CFG.bagLeft, item.x - item.w / 2);
const maxX = Math.min(CFG.bagRight, item.x + item.w / 2);
const minZ = Math.max(
-CFG.bagDepth / 2,
item.z - item.d / 2
);
const maxZ = Math.min(
CFG.bagDepth / 2,
item.z + item.d / 2
);
const i0 = Math.max(
0,
Math.floor(((minX - CFG.bagLeft) / CFG.bagWidth) * nx)
);
const i1 = Math.min(
nx - 1,
Math.ceil(((maxX - CFG.bagLeft) / CFG.bagWidth) * nx)
);
const j0 = Math.max(
0,
Math.floor(((minZ + CFG.bagDepth / 2) / CFG.bagDepth) * nz)
);
const j1 = Math.min(
nz - 1,
Math.ceil(((maxZ + CFG.bagDepth / 2) / CFG.bagDepth) * nz)
);
for (let j = j0; j <= j1; j++) {
for (let i = i0; i <= i1; i++) {
grid[j * nx + i] = 1;
}
}
}
let occupied = 0;
for (const cell of grid) occupied += cell;
return occupied / grid.length;
}
function selectItem(id) {
if (!items[id] || retrieved.has(id)) return;
selectedId = id;
updateUI();
}
function updateSelectionPanel() {
const slider = document.getElementById("heightSlider");
const floorBtn = document.getElementById("floorBtn");
const benchBtn = document.getElementById("benchBtn");
const swatch = document.getElementById("selectedSwatch");
const name = document.getElementById("selectedName");
const meta = document.getElementById("selectedMeta");
const heightValue = document.getElementById("heightValue");
const item = selectedId ? items[selectedId] : null;
if (!item) {
swatch.style.background = "#a8b8b2";
name.textContent = "Choose an item";
meta.textContent =
"Click a scene object or choose one from the inventory.";
heightValue.textContent = "—";
slider.disabled = true;
floorBtn.disabled = true;
benchBtn.disabled = true;
return;
}
swatch.style.background =
"#" + new THREE.Color(item.color).getHexString();
name.textContent = item.name;
const cm = (value) => Math.round(value * 20);
meta.innerHTML = `
<strong>${item.weight} symbolic weight${item.weight === 1 ? "" : "s"}</strong><br>
Solid footprint: ${cm(item.w)} × ${cm(item.d)} cm<br>
Height: ${cm(item.h)} cm · ${
item.inBag ? "Inside cavity" : "On bench / staging"
}
`;
slider.disabled = false;
slider.min = CFG.benchTop;
slider.max = CFG.bagTop - item.h;
slider.value = item.baseY;
const heightAboveFloor = Math.max(
0,
Math.round((item.baseY - CFG.bagFloor) * 20)
);
heightValue.textContent = `${heightAboveFloor} cm`;
floorBtn.disabled = !item.inBag;
benchBtn.disabled = !item.inBag;
}
function updateUI() {
const packed = Object.values(items).filter(
(item) => item.inBag && !retrieved.has(item.id)
);
const volume = packed.reduce(
(sum, item) => sum + item.w * item.d * item.h,
0
);
const cavityVolume =
CFG.bagWidth * CFG.bagDepth * CFG.bagHeight;
const volumePercent = (volume / cavityVolume) * 100;
const load = packed.reduce((sum, item) => sum + item.weight, 0);
const footprintPercent = computeFootprintCoverage() * 100;
document.getElementById("volumeValue").textContent =
`${volume.toFixed(2)} u³`;
document.getElementById("volumeBar").style.width =
`${Math.min(100, volumePercent)}%`;
document.getElementById("volumeNote").textContent =
`${Math.round(volumePercent)}% of bounded cavity · ${volume.toFixed(
2
)} / ${cavityVolume.toFixed(2)} u³`;
document.getElementById("loadValue").textContent =
`${load} / ${CFG.loadCapacity}`;
document.getElementById("footprintValue").textContent =
`${Math.round(footprintPercent)}%`;
const state = getRetrievalState();
const nextCard = document.getElementById("nextCard");
const blockerList = document.getElementById("blockerList");
const retrieveBtn = document.getElementById("retrieveBtn");
nextCard.className = `retrieval-card ${state.kind}`;
if (!state.target) {
document.getElementById("nextTitle").textContent =
"All required items retrieved";
document.getElementById("nextDescription").textContent =
"The activity schedule is complete.";
blockerList.innerHTML = "";
retrieveBtn.disabled = true;
retrieveBtn.textContent = "Schedule complete";
} else {
const target = state.target;
document.getElementById("nextTitle").textContent =
`${target.name} · #${state.targetNumber}`;
if (state.kind === "missing") {
document.getElementById("nextDescription").textContent =
`${target.name} is still outside the bag. Pack it before testing retrieval.`;
} else if (state.kind === "blocked") {
document.getElementById("nextDescription").textContent =
"These packed objects obstruct the next retrieval. Move them before lifting it.";
} else {
document.getElementById("nextDescription").textContent =
"No packed item sits above this footprint. It can be retrieved next.";
}
blockerList.innerHTML = state.blockers
.map(
(blocker) =>
`<li>Obstruction: ${blocker.name} (${
blocker.weight
} symbols)</li>`
)
.join("");
retrieveBtn.disabled = viewMode === "closed";
retrieveBtn.textContent = `Try retrieving ${target.name.toLowerCase()}`;
}
const orderElement = document.getElementById("retrievalOrder");
orderElement.innerHTML = schedules[activeSchedule].order
.map((id, index) => {
const item = items[id];
const isTarget = state.target?.id === id;
const isBlocker = state.blockers.some(
(blocker) => blocker.id === id
);
const isRetrieved = retrieved.has(id);
const classes = [
"order-item",
isTarget ? "next" : "",
isBlocker ? "blocker" : "",
isRetrieved ? "retrieved" : ""
]
.filter(Boolean)
.join(" ");
const status = isRetrieved
? "Retrieved"
: isBlocker
? "Blocking"
: item.inBag
? "Packed"
: "Outside";
return `
<button class="${classes}" type="button" data-item="${id}">
<span class="order-number">${index + 1}</span>
<span class="order-copy">
<strong>${item.name}</strong>
<small>${item.weight} weight symbols</small>
</span>
<span class="order-state">${status}</span>
</button>
`;
})
.join("");
const inventoryElement = document.getElementById("inventory");
inventoryElement.innerHTML = Object.values(items)
.map((item) => {
const status = retrieved.has(item.id)
? "Retrieved"
: item.inBag
? "In bag"
: "On bench";
return `
<button
class="inventory-item ${selectedId === item.id ? "selected" : ""}"
type="button"
data-item="${item.id}"
>
<span
class="swatch"
style="background:#${new THREE.Color(item.color).getHexString()}"
></span>
<span class="inventory-copy">
<strong>${item.name}</strong>
<small>${status} · ${Math.round(
item.w * 20
)} × ${Math.round(item.d * 20)} cm</small>
</span>
<span class="weight-chip">${item.weight}<br>SYMBOLS</span>
</button>
`;
})
.join("");
updateSelectionPanel();
updateHighlights();
}
function updateHighlights() {
const state = getRetrievalState();
for (const item of Object.values(items)) {
const isTarget = state.target?.id === item.id;
const isBlocker = state.blockers.some(
(blocker) => blocker.id === item.id
);
const isSelected = selectedId === item.id;
item.helper.visible =
!retrieved.has(item.id) &&
(isTarget || isBlocker || isSelected);
if (isBlocker) {
item.helper.material.color.set(0xcf514d);
} else if (isTarget) {
item.helper.material.color.set(0xe4a83a);
} else {
item.helper.material.color.set(0x2b8fc7);
}
}
const selected = selectedId ? items[selectedId] : null;
footprintFill.visible = Boolean(
selected && !retrieved.has(selected.id)
);
footprintOutline.visible = footprintFill.visible;
if (selected) {
footprintFill.position.set(
selected.x,
selected.baseY + 0.012,
selected.z
);
footprintFill.scale.set(selected.w, selected.d, 1);
const x0 = selected.x - selected.w / 2;
const x1 = selected.x + selected.w / 2;
const z0 = selected.z - selected.d / 2;
const z1 = selected.z + selected.d / 2;
const y = selected.baseY + 0.017;
const positions = footprintGeometry.attributes.position.array;
positions.set(
[x0, y, z0, x1, y, z0, x1, y, z1, x0, y, z1],
0
);
footprintGeometry.attributes.position.needsUpdate = true;
footprintGeometry.computeBoundingSphere();
}
}
function setBagVisibility() {
const closed = viewMode === "closed";
frontPanel.visible = closed || !planCutaway;
frontPocket.visible = closed;
frontZipper.visible = closed;
cavityWire.visible = !closed && planCutaway;
cavityFill.visible = !closed && planCutaway;
if (closed) {
rightSideMaterial.opacity = 0.31;
rightSideMaterial.depthWrite = false;
} else if (planCutaway) {
rightSideMaterial.opacity = 0.16;
rightSideMaterial.depthWrite = false;
} else {
rightSideMaterial.opacity = 0.43;
rightSideMaterial.depthWrite = false;
}
document.getElementById("planBtn").classList.toggle(
"active",
viewMode === "plan"
);
document.getElementById("closedBtn").classList.toggle(
"active",
viewMode === "closed"
);
const cutawayButton = document.getElementById("cutawayBtn");
cutawayButton.disabled = closed;
cutawayButton.textContent = `Cutaway: ${
planCutaway ? "ON" : "OFF"
}`;
document.getElementById("stageBadge").textContent = closed
? "Closed · Translucent side load view"
: planCutaway
? "Planning · Bag cutaway"
: "Planning · Bag shell visible";
}
function setViewMode(mode) {
viewMode = mode;
if (mode === "closed") {
desiredCamera.target.set(CFG.bagX, 1.62, 0);
desiredCamera.radius = 5.0;
desiredCamera.theta = 1.03;
desiredCamera.phi = 1.18;
} else {
desiredCamera.target.set(0.35, 1.18, 0);
desiredCamera.radius = 10.2;
desiredCamera.theta = 0.31;
desiredCamera.phi = 1.08;
}
setBagVisibility();
updateUI();
}
function resetPack() {
retrieved.clear();
selectedId = null;
for (const item of Object.values(items)) {
item.x = item.initialX;
item.z = item.initialZ;
item.baseY = CFG.benchTop + 0.01;
item.inBag = false;
item.previewBad = false;
item.root.visible = true;
item.label.visible = true;
item.helper.visible = false;
syncItem(item);
}
updateUI();
showToast("All objects returned to the bench.");
}
function findFreeBenchSpot(item) {
for (let z = -0.78; z <= 0.79; z += 0.19) {
for (let x = 0.1; x <= 4.45; x += 0.22) {
const result = validatePlacement(
item.id,
x,
z,
CFG.benchTop + 0.01,
false
);
if (result.ok) return { x, z };
}
}
return null;
}
function moveSelectedToBench() {
if (!selectedId) return;
const item = items[selectedId];
const spot = findFreeBenchSpot(item);
if (!spot) {
showToast("There is no free bench position for that item.", true);
return;
}
item.x = spot.x;
item.z = spot.z;
item.baseY = CFG.benchTop + 0.01;
item.inBag = false;
syncItem(item);
updateUI();
showToast(`${item.name} returned to the bench.`);
}
function dropSelectedToFloor() {
if (!selectedId) return;
const item = items[selectedId];
const oldY = item.baseY;
item.baseY = CFG.bagFloor;
const result = validatePlacement(
item.id,
item.x,
item.z,
item.baseY,
true
);
if (!result.ok) {
item.baseY = oldY;
showToast(result.reason, true);
} else {
syncItem(item);
showToast(`${item.name} dropped to the cavity floor.`);
}
updateUI();
}
function adjustSelectedHeight(delta, allowPreview = false) {
if (!selectedId) return;
const item = items[selectedId];
const oldY = item.baseY;
const nextY = THREE.MathUtils.clamp(
item.baseY + delta,
CFG.benchTop,
CFG.bagTop - item.h
);
if (item.inBag && !allowPreview) {
item.baseY = nextY;
const result = validatePlacement(
item.id,
item.x,
item.z,
nextY,
true
);
item.baseY = oldY;
if (!result.ok) {
showToast(result.reason, true);
return;
}
}
item.baseY = nextY;
syncItem(item);
if (drag?.id === item.id) {
drag.planeY = item.baseY;
}
updateUI();
}
function retrieveNext() {
const state = getRetrievalState();
if (!state.target) {
showToast("The schedule is already complete.");
return;
}
if (!state.target.inBag) {
showToast(
`${state.target.name} must be packed before it can be retrieved.`,
true
);
return;
}
if (state.blockers.length) {
const names = state.blockers
.map((item) => item.name)
.join(", ");
showToast(
`Retrieval blocked by ${names}. Move the obstruction first.`,
true
);
return;
}
const item = state.target;
retrieved.add(item.id);
item.inBag = false;
item.root.visible = false;
item.label.visible = false;
item.helper.visible = false;
if (selectedId === item.id) selectedId = null;
updateUI();
showToast(`${item.name} retrieved successfully.`);
}
// Pointer interaction.
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(itemRoots, true);
const hitId = hits.length ? itemIdFromObject(hits[0].object) : null;
if (hitId && viewMode === "plan" && !retrieved.has(hitId)) {
selectItem(hitId);
const item = items[hitId];
dragPlane.set(new THREE.Vector3(0, 1, 0), -item.baseY);
const hit = raycaster.ray.intersectPlane(dragPlane, planeHit);
drag = {
id: hitId,
pointerId: event.pointerId,
planeY: item.baseY,
offsetX: hit ? item.x - hit.x : 0,
offsetZ: hit ? item.z - hit.z : 0,
original: {
x: item.x,
z: item.z,
baseY: item.baseY,
inBag: item.inBag
}
};
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
return;
}
orbit = {
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
theta: desiredCamera.theta,
phi: desiredCamera.phi
};
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (drag && event.pointerId === drag.pointerId) {
const item = items[drag.id];
setPointerFromEvent(event);
dragPlane.set(new THREE.Vector3(0, 1, 0), -drag.planeY);
const hit = raycaster.ray.intersectPlane(dragPlane, planeHit);
if (hit) {
item.x = THREE.MathUtils.clamp(
hit.x + drag.offsetX,
CFG.benchMinX - 0.3,
CFG.benchMaxX + 0.3
);
item.z = THREE.MathUtils.clamp(
hit.z + drag.offsetZ,
CFG.benchMinZ - 0.3,
CFG.benchMaxZ + 0.3
);
}
const intended = isBagIntent(item.x, item.z);
const testY = intended
? item.baseY
: CFG.benchTop + 0.01;
const result = validatePlacement(
item.id,
item.x,
item.z,
testY,
intended
);
item.previewBad = !result.ok;
syncItem(item);
updateHighlights();
event.preventDefault();
return;
}
if (orbit && event.pointerId === orbit.pointerId) {
const dx = event.clientX - orbit.startX;
const dy = event.clientY - orbit.startY;
desiredCamera.theta = orbit.theta - dx * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.005,
0.55,
1.43
);
event.preventDefault();
}
});
function finishDrag(cancelled = false) {
if (!drag) return;
const item = items[drag.id];
const intended = isBagIntent(item.x, item.z);
let finalY = item.baseY;
if (intended) {
if (!drag.original.inBag && finalY < CFG.bagFloor - 0.01) {
finalY = CFG.bagFloor;
}
} else {
finalY = CFG.benchTop + 0.01;
}
const result = validatePlacement(
item.id,
item.x,
item.z,
finalY,
intended
);
if (cancelled || !result.ok) {
item.x = drag.original.x;
item.z = drag.original.z;
item.baseY = drag.original.baseY;
item.inBag = drag.original.inBag;
item.previewBad = false;
syncItem(item);
if (!cancelled) {
showToast(
`Placement rejected. ${result.reason} No item was shrunk.`,
true
);
}
} else {
item.baseY = finalY;
item.inBag = intended;
item.previewBad = false;
syncItem(item);
showToast(
intended
? `${item.name} placed in the bounded cavity.`
: `${item.name} staged on the bench.`
);
}
drag = null;
updateUI();
}
renderer.domElement.addEventListener("pointerup", (event) => {
if (drag && event.pointerId === drag.pointerId) {
finishDrag(false);
}
orbit = null;
});
renderer.domElement.addEventListener("pointercancel", () => {
finishDrag(true);
orbit = null;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius + event.deltaY * 0.006,
3.6,
14
);
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// DOM controls.
document.getElementById("planBtn").addEventListener("click", () => {
planCutaway = true;
setViewMode("plan");
});
document.getElementById("closedBtn").addEventListener("click", () => {
setViewMode("closed");
});
document.getElementById("cutawayBtn").addEventListener("click", () => {
planCutaway = !planCutaway;
setBagVisibility();
});
document.getElementById("scheduleSelect").addEventListener("change", (event) => {
activeSchedule = event.target.value;
updateUI();
showToast(
`${schedules[activeSchedule].label} retrieval order selected.`
);
});
document.getElementById("inventory").addEventListener("click", (event) => {
const button = event.target.closest("[data-item]");
if (button) selectItem(button.dataset.item);
});
document.getElementById("retrievalOrder").addEventListener("click", (event) => {
const button = event.target.closest("[data-item]");
if (button) selectItem(button.dataset.item);
});
const heightSlider = document.getElementById("heightSlider");
heightSlider.addEventListener("focus", () => {
if (!selectedId) return;
heightSnapshot = items[selectedId].baseY;
});
heightSlider.addEventListener("input", () => {
if (!selectedId) return;
const item = items[selectedId];
item.baseY = Number(heightSlider.value);
syncItem(item);
if (item.inBag) {
const result = validatePlacement(
item.id,
item.x,
item.z,
item.baseY,
true
);
item.previewBad = !result.ok;
}
updateUI();
});
heightSlider.addEventListener("change", () => {
if (!selectedId) return;
const item = items[selectedId];
if (item.inBag) {
const result = validatePlacement(
item.id,
item.x,
item.z,
item.baseY,
true
);
if (!result.ok) {
item.baseY = heightSnapshot ?? CFG.bagFloor;
syncItem(item);
showToast(
`Height rejected. ${result.reason} No item was shrunk.`,
true
);
}
}
item.previewBad = false;
heightSnapshot = null;
updateUI();
});
document
.getElementById("floorBtn")
.addEventListener("click", dropSelectedToFloor);
document
.getElementById("benchBtn")
.addEventListener("click", moveSelectedToBench);
document
.getElementById("retrieveBtn")
.addEventListener("click", retrieveNext);
document
.getElementById("resetBtn")
.addEventListener("click", resetPack);
window.addEventListener("keydown", (event) => {
if (
event.target.matches("input, select, textarea, button") ||
!selectedId
) {
return;
}
if (event.code === "KeyQ") {
event.preventDefault();
adjustSelectedHeight(-0.04, Boolean(drag));
}
if (event.code === "KeyE") {
event.preventDefault();
adjustSelectedHeight(0.04, Boolean(drag));
}
});
function resizeRenderer() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(viewport);
resizeRenderer();
setBagVisibility();
updateUI();
let previousTime = performance.now();
function animate(time) {
const dt = Math.min(0.05, (time - previousTime) / 1000);
previousTime = time;
const damping = 1 - Math.exp(-dt * 6);
cameraState.target.lerp(desiredCamera.target, damping);
cameraState.radius +=
(desiredCamera.radius - cameraState.radius) * damping;
cameraState.theta +=
(desiredCamera.theta - cameraState.theta) * damping;
cameraState.phi +=
(desiredCamera.phi - cameraState.phi) * damping;
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
for (const item of Object.values(items)) {
if (item.helper.visible) item.helper.update();
}
updateHighlights();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```