Prompt specification
Build or customize the Three.js 3D scene "Community lending-network simulator" 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: Community lending-network simulator
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/community-lending-network-simulator-x0492
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows three low-poly community book-exchange shelves connected by pedestrian routes. Give each shelf a small canopy, labeled book slots, and a request board showing which titles are wanted there. Users can choose a book and send a carrier along a valid path to another shelf. Preserve the book's identity during the trip and update inventories only when pickup or delivery occurs. A total counter should include books on shelves and books currently being carried. The goal is to satisfy visible requests through transfers, with no new books appearing merely because a destination needs them.
Working Three.js Starter (community-lending-network-simulator-x0492):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Community Book Exchange</title>
<style>
:root {
--ink: #183c37;
--ink-soft: #41635c;
--cream: #fff8e8;
--paper: #fffdf5;
--yellow: #ffd166;
--coral: #ef8354;
--teal: #2a9d8f;
--blue: #4f86c6;
--shadow: 0 14px 40px rgba(24, 60, 55, 0.17);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
background: #dbe9e8;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: rgba(255, 253, 245, 0.94);
border: 1px solid rgba(24, 60, 55, 0.12);
border-radius: 18px;
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.brand {
position: absolute;
top: 18px;
left: 18px;
width: 330px;
padding: 17px 19px;
}
.eyebrow {
margin: 0 0 5px;
color: var(--teal);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.brand p:last-child {
margin: 9px 0 0;
color: var(--ink-soft);
font-size: 12px;
line-height: 1.4;
}
.stats {
position: absolute;
top: 18px;
right: 18px;
display: grid;
grid-template-columns: repeat(4, minmax(78px, 1fr));
gap: 1px;
overflow: hidden;
width: 410px;
background: rgba(24, 60, 55, 0.12);
}
.stat {
min-height: 77px;
padding: 13px 14px;
background: rgba(255, 253, 245, 0.97);
}
.stat:first-child {
background: var(--ink);
color: white;
}
.stat strong {
display: block;
font-size: 25px;
line-height: 1;
letter-spacing: -0.04em;
}
.stat span {
display: block;
margin-top: 7px;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
line-height: 1.25;
text-transform: uppercase;
}
.requests {
position: absolute;
top: 112px;
right: 18px;
width: 410px;
padding: 15px 17px;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.panel-title h2 {
margin: 0;
font-size: 13px;
letter-spacing: 0.02em;
}
.panel-title small {
color: var(--ink-soft);
font-size: 10px;
font-weight: 750;
}
#request-list {
display: grid;
gap: 7px;
}
.request-row {
display: grid;
grid-template-columns: 31px 1fr auto;
align-items: center;
gap: 9px;
min-height: 39px;
padding: 7px 9px;
border-radius: 10px;
background: #f2eee1;
}
.request-row .request-key {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border-radius: 8px;
color: white;
background: var(--teal);
font-size: 12px;
font-weight: 900;
}
.request-row strong {
display: block;
font-size: 11px;
}
.request-row small {
display: block;
margin-top: 2px;
color: var(--ink-soft);
font-size: 9px;
}
.request-badge {
padding: 4px 6px;
border-radius: 999px;
background: #ffe0c7;
color: #9a4826;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.request-badge.done {
background: #d9efe4;
color: #1d6b55;
}
.controls {
position: absolute;
bottom: 18px;
left: 18px;
width: 370px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 17px;
}
.control-label {
display: block;
margin: 0 0 7px;
color: var(--ink-soft);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.source-buttons {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 14px;
}
.source-button {
position: relative;
min-height: 66px;
padding: 8px 7px;
border: 1px solid #d7ddcf;
border-radius: 12px;
background: #f7f4e9;
color: var(--ink);
cursor: pointer;
text-align: left;
transition: 150ms ease;
}
.source-button:hover {
transform: translateY(-1px);
border-color: var(--teal);
}
.source-button.active {
border-color: var(--teal);
background: #dff2e9;
box-shadow: inset 0 0 0 1px var(--teal);
}
.source-button .key {
display: inline-grid;
place-items: center;
width: 21px;
height: 21px;
margin-bottom: 4px;
border-radius: 6px;
color: white;
background: var(--ink);
font-size: 10px;
font-weight: 900;
}
.source-button strong {
display: block;
font-size: 10px;
line-height: 1.15;
}
.source-button small {
display: block;
margin-top: 3px;
color: var(--ink-soft);
font-size: 8px;
}
.book-list {
display: grid;
gap: 6px;
max-height: 188px;
overflow: auto;
margin-bottom: 13px;
padding-right: 2px;
}
.book-option {
display: grid;
grid-template-columns: 10px 1fr auto;
align-items: center;
gap: 9px;
width: 100%;
min-height: 44px;
padding: 8px 10px;
border: 1px solid #dde0d4;
border-radius: 10px;
background: white;
color: var(--ink);
cursor: pointer;
text-align: left;
transition: 140ms ease;
}
.book-option:hover:not(:disabled) {
border-color: var(--teal);
transform: translateX(2px);
}
.book-option.selected {
border-color: var(--teal);
background: #e8f6ef;
box-shadow: inset 3px 0 0 var(--teal);
}
.book-option:disabled {
cursor: not-allowed;
opacity: 0.58;
}
.book-color {
width: 9px;
height: 31px;
border-radius: 4px;
box-shadow: inset -3px 0 rgba(0, 0, 0, 0.13);
}
.book-option strong {
display: block;
font-size: 11px;
line-height: 1.2;
}
.book-option small {
display: block;
margin-top: 3px;
color: var(--ink-soft);
font-size: 8px;
font-weight: 700;
}
.needed {
padding: 4px 6px;
border-radius: 999px;
background: var(--yellow);
color: #654b00;
font-size: 7px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
white-space: nowrap;
}
.needed.pending {
background: #e5e7df;
color: #59635d;
}
.destination-row {
display: grid;
grid-template-columns: 1fr;
gap: 6px;
margin-bottom: 10px;
}
select {
width: 100%;
min-height: 42px;
padding: 8px 34px 8px 11px;
border: 1px solid #ced8cf;
border-radius: 10px;
background: white;
color: var(--ink);
font: inherit;
font-size: 11px;
font-weight: 700;
outline: none;
}
select:focus {
border-color: var(--teal);
box-shadow: 0 0 0 3px rgba(42, 157, 143, 0.13);
}
.match-note {
min-height: 34px;
padding: 8px 10px;
border-radius: 9px;
background: #f0eee5;
color: var(--ink-soft);
font-size: 10px;
line-height: 1.35;
}
.match-note.good {
background: #dff2e9;
color: #17664f;
font-weight: 750;
}
.route-box {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 10px 0;
padding: 10px 11px;
border: 1px dashed #bfcabe;
border-radius: 10px;
background: #faf8ee;
}
#route-line {
font-size: 11px;
font-weight: 850;
}
#route-distance {
color: var(--ink-soft);
font-size: 9px;
white-space: nowrap;
}
.primary-button {
width: 100%;
min-height: 45px;
border: 0;
border-radius: 11px;
background: var(--ink);
color: white;
font: inherit;
font-size: 12px;
font-weight: 850;
cursor: pointer;
transition: 150ms ease;
}
.primary-button:hover:not(:disabled) {
background: var(--teal);
transform: translateY(-1px);
}
.primary-button:disabled {
cursor: not-allowed;
opacity: 0.42;
}
.status {
min-height: 48px;
margin-top: 10px;
padding: 9px 10px;
border-radius: 10px;
background: #edf0e9;
color: var(--ink-soft);
font-size: 10px;
line-height: 1.35;
}
.status.good {
background: #dff2e9;
color: #17664f;
}
.status.warn {
background: #ffe5d5;
color: #91431f;
}
.help {
position: absolute;
right: 18px;
bottom: 18px;
width: 410px;
padding: 13px 15px;
color: var(--ink-soft);
font-size: 10px;
line-height: 1.5;
}
.help strong {
color: var(--ink);
}
.help button {
float: right;
margin-left: 12px;
padding: 5px 8px;
border: 1px solid #cbd6cd;
border-radius: 7px;
background: white;
color: var(--ink);
font: inherit;
font-size: 9px;
font-weight: 800;
cursor: pointer;
}
@media (max-width: 900px) {
.brand {
width: 285px;
}
.stats {
width: 350px;
grid-template-columns: repeat(2, 1fr);
}
.requests {
top: 186px;
width: 350px;
}
.help {
width: 350px;
}
}
@media (max-width: 650px) {
.brand {
top: 9px;
left: 9px;
width: 235px;
padding: 12px 14px;
}
.brand h1 {
font-size: 19px;
}
.brand p:last-child {
display: none;
}
.stats {
top: 9px;
right: 9px;
width: 142px;
grid-template-columns: repeat(2, 1fr);
}
.stat {
min-height: 55px;
padding: 9px;
}
.stat strong {
font-size: 18px;
}
.stat span {
margin-top: 4px;
font-size: 7px;
}
.requests {
display: none;
}
.controls {
left: 9px;
bottom: 9px;
width: calc(100% - 18px);
max-height: 55vh;
padding: 13px;
}
.help {
display: none;
}
.book-list {
max-height: 130px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<header class="brand panel">
<p class="eyebrow">Neighborhood Commons</p>
<h1>Community Book Exchange</h1>
<p>
Choose an existing title and send a carrier along the pedestrian network.
Books keep their ID from shelf to shelf.
</p>
</header>
<section class="stats panel" aria-label="Book totals">
<div class="stat">
<strong id="stat-total">0</strong>
<span>Total<br>shelf + carried</span>
</div>
<div class="stat">
<strong id="stat-shelf">0</strong>
<span>On<br>shelves</span>
</div>
<div class="stat">
<strong id="stat-carried">0</strong>
<span>Currently<br>carried</span>
</div>
<div class="stat">
<strong id="stat-fulfilled">0</strong>
<span>Requests<br>satisfied</span>
</div>
</section>
<section class="requests panel">
<div class="panel-title">
<h2>Visible requests</h2>
<small>Existing titles only</small>
</div>
<div id="request-list"></div>
</section>
<section class="controls panel">
<p class="control-label">1 · Choose a source shelf</p>
<div id="source-buttons" class="source-buttons"></div>
<p class="control-label">2 · Choose one existing book</p>
<div id="book-list" class="book-list"></div>
<div class="destination-row">
<label class="control-label" for="destination">3 · Choose a destination shelf</label>
<select id="destination"></select>
</div>
<div id="match-note" class="match-note"></div>
<div class="route-box">
<span id="route-line"></span>
<span id="route-distance"></span>
</div>
<button id="send-button" class="primary-button" type="button">
Send carrier with selected book
</button>
<div id="status" class="status" role="status" aria-live="polite">
Select a book to begin.
</div>
</section>
<aside class="help panel">
<button id="reset-view" type="button">Reset view</button>
<strong>Controls:</strong> drag to orbit, scroll to zoom, and click a 3D book to
select it. The highlighted line is a valid pedestrian route.
<br><strong>Integrity:</strong> the catalog contains <span id="catalog-total">0</span>
fixed book IDs. A request never creates stock; only an existing book can satisfy it.
</aside>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Fixed catalog: requests can be satisfied only by moving one of these IDs.
// -------------------------------------------------------------------------
const CAPACITY = 6;
const requests = [
{ id: "REQ-A", shelfId: "A", title: "Tide Atlas", status: "open", fulfilledBy: null },
{ id: "REQ-B", shelfId: "B", title: "Moon Garden", status: "open", fulfilledBy: null },
{ id: "REQ-C", shelfId: "C", title: "Paper Lanterns", status: "open", fulfilledBy: null }
];
const rawBooks = [
{ id: "BK-01", title: "Paper Lanterns", author: "Mina Park", color: 0xef8354, shelfId: "A" },
{ id: "BK-02", title: "River Notes", author: "Ada Bell", color: 0x4f86c6, shelfId: "A" },
{ id: "BK-03", title: "Seed Keeper", author: "Noor Fields", color: 0x79b99a, shelfId: "A" },
{ id: "BK-04", title: "Small Hours", author: "Ivo Hart", color: 0x9b6bc3, shelfId: "A" },
{ id: "BK-05", title: "Tide Atlas", author: "Rae Sol", color: 0x3aa6a0, shelfId: "B" },
{ id: "BK-06", title: "City of Branches", author: "June Kim", color: 0xe9a23b, shelfId: "B" },
{ id: "BK-07", title: "Moss & Moon", author: "Tess Avery", color: 0x708f4f, shelfId: "B" },
{ id: "BK-08", title: "Atlas of Rain", author: "Luca West", color: 0x5b76bd, shelfId: "B" },
{ id: "BK-09", title: "Moon Garden", author: "Anika Noor", color: 0x8867ad, shelfId: "C" },
{ id: "BK-10", title: "Lantern Fox", author: "Sam Alder", color: 0xe76f51, shelfId: "C" },
{ id: "BK-11", title: "Quiet Orbit", author: "Nora Vale", color: 0x4f9da2, shelfId: "C" },
{ id: "BK-12", title: "The Copper Map", author: "Eden Lake", color: 0xb47b42, shelfId: "C" }
];
const books = rawBooks.map((book) => ({
...book,
status: "shelf",
slotIndex: null,
locked: false,
mesh: null,
coverMaterial: null
}));
const shelfDefinitions = [
{
id: "A",
name: "Cedar Commons",
position: new THREE.Vector3(-7, 0, 2),
front: new THREE.Vector3(0.42, 0, 0.91),
color: 0x2a9d8f
},
{
id: "B",
name: "Riverside Hub",
position: new THREE.Vector3(0, 0, -6),
front: new THREE.Vector3(0, 0, 1),
color: 0xef8354
},
{
id: "C",
name: "Market Nook",
position: new THREE.Vector3(7, 0, 2),
front: new THREE.Vector3(-0.42, 0, 0.91),
color: 0xe9a23b
}
];
const shelfIds = shelfDefinitions.map((shelf) => shelf.id);
const shelfMap = new Map();
// The route graph is intentionally not a complete triangle. A to C must
// pass through Riverside Hub, proving that transfers follow graph edges.
const graph = {
A: ["B"],
B: ["A", "C"],
C: ["B"]
};
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D community book exchange with three shelves and pedestrian routes."
);
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce9e9);
scene.fog = new THREE.Fog(0xdce9e9, 24, 43);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const orbit = {
theta: 0.34,
phi: 1.03,
radius: 22,
target: new THREE.Vector3(0, 1.35, 0)
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xeaf8ff, 0x7e956f, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d3, 2.6);
sun.position.set(-8, 16, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 42;
sun.shadow.bias = -0.0008;
scene.add(sun);
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0,
flatShading: true,
...options
});
}
function addBox(parent, width, height, depth, x, y, z, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function createCanvasTexture(width, height, draw) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
draw(context, canvas);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
return { canvas, context, texture };
}
function wrapText(context, text, maximumWidth) {
const words = text.split(" ");
const lines = [];
let line = "";
for (const word of words) {
const test = line ? `${line} ${word}` : word;
if (context.measureText(test).width > maximumWidth && line) {
lines.push(line);
line = word;
} else {
line = test;
}
}
if (line) lines.push(line);
return lines;
}
function hexColor(number) {
return `#${number.toString(16).padStart(6, "0")}`;
}
// -------------------------------------------------------------------------
// World, walkways, and low-poly decorations
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(31, 25),
standardMaterial(0xa9c68d)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.055;
ground.receiveShadow = true;
scene.add(ground);
const plaza = new THREE.Mesh(
new THREE.CircleGeometry(4.8, 32),
standardMaterial(0xc8d5aa)
);
plaza.rotation.x = -Math.PI / 2;
plaza.position.y = -0.035;
plaza.receiveShadow = true;
scene.add(plaza);
const routeHighlightGroup = new THREE.Group();
scene.add(routeHighlightGroup);
const routeHighlightMaterial = new THREE.MeshBasicMaterial({
color: 0xffc857
});
function makeTree(x, z, scale, crownColor) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.15, 0.22, 1.6, 5),
standardMaterial(0x79563d)
);
trunk.position.y = 0.8;
trunk.castShadow = true;
tree.add(trunk);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.05, 0),
standardMaterial(crownColor)
);
crown.position.y = 2.05;
crown.scale.set(1, 1.12, 1);
crown.castShadow = true;
tree.add(crown);
scene.add(tree);
}
[
[-12, 7, 1.1, 0x4f8d68],
[-10, -7, 0.9, 0x6f9f62],
[-5, -10, 1.15, 0x3e7d61],
[5, -10, 1.05, 0x598c58],
[11, -6, 1.12, 0x4e8366],
[12, 7, 0.92, 0x6d965a],
[-12, 0, 0.78, 0x739a5d]
].forEach((values) => makeTree(...values));
function makeBench(x, z, rotation = 0) {
const bench = new THREE.Group();
bench.position.set(x, 0, z);
bench.rotation.y = rotation;
const wood = standardMaterial(0x9a6644);
const metal = standardMaterial(0x42534e);
addBox(bench, 1.8, 0.13, 0.5, 0, 0.55, 0, wood);
addBox(bench, 1.8, 0.55, 0.12, 0, 0.88, -0.2, wood);
addBox(bench, 0.13, 0.55, 0.42, -0.66, 0.28, 0, metal);
addBox(bench, 0.13, 0.55, 0.42, 0.66, 0.28, 0, metal);
scene.add(bench);
}
makeBench(-9.5, -3.6, 0.8);
makeBench(9.4, -3.4, -0.8);
function addRock(x, z, scale, color) {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(scale, 0),
standardMaterial(color)
);
rock.position.set(x, scale * 0.55, z);
rock.rotation.set(0.3, x, 0.15);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
addRock(-10.7, 4.2, 0.46, 0x9ba7a0);
addRock(10.6, 4.3, 0.52, 0x9ba7a0);
addRock(-3.2, -9.1, 0.34, 0xa6afa5);
addRock(3.5, -9.2, 0.4, 0xa6afa5);
// -------------------------------------------------------------------------
// Shelves
// -------------------------------------------------------------------------
const pickables = [];
function createShelf(definition) {
const shelf = {
...definition,
group: new THREE.Group(),
slots: Array(CAPACITY).fill(null),
reserved: 0
};
shelf.group.position.copy(definition.position);
shelf.group.rotation.y = Math.atan2(definition.front.x, definition.front.z);
scene.add(shelf.group);
const front = definition.front.clone().normalize();
shelf.approach = definition.position.clone().addScaledVector(front, 2.7);
shelf.approach.y = 0.05;
const frameMaterial = standardMaterial(0xf2e7ce);
const frameDarkMaterial = standardMaterial(0x36574f);
const roofMaterial = standardMaterial(definition.color);
const backMaterial = standardMaterial(0xe7ddc5);
addBox(
shelf.group,
4.55,
0.22,
1.45,
0,
0.12,
0,
frameDarkMaterial
);
addBox(
shelf.group,
4.35,
2.85,
0.16,
0,
1.83,
-0.59,
backMaterial
);
addBox(shelf.group, 0.16, 3.05, 1.1, -2.12, 1.82, 0, frameMaterial);
addBox(shelf.group, 0.16, 3.05, 1.1, 2.12, 1.82, 0, frameMaterial);
[-0.7, 0.7].forEach((x) => {
addBox(shelf.group, 0.11, 2.62, 1.02, x, 1.82, -0.03, frameMaterial);
});
[0.55, 1.85, 3.14].forEach((y) => {
addBox(shelf.group, 4.25, 0.11, 1.12, 0, y, 0, frameMaterial);
});
// Four-sided low-poly canopy.
const canopy = new THREE.Mesh(
new THREE.ConeGeometry(3.05, 0.85, 4),
roofMaterial
);
canopy.position.set(0, 3.94, -0.05);
canopy.rotation.y = Math.PI / 4;
canopy.scale.z = 0.56;
canopy.castShadow = true;
canopy.receiveShadow = true;
shelf.group.add(canopy);
addBox(
shelf.group,
4.48,
0.2,
0.12,
0,
3.56,
0.84,
roofMaterial
);
// Shelf sign.
const sign = createCanvasTexture(1024, 230, (context) => {
context.fillStyle = hexColor(definition.color);
context.fillRect(0, 0, 1024, 230);
context.fillStyle = "#fff9e9";
context.textAlign = "center";
context.font = "900 62px system-ui";
context.fillText(definition.name, 512, 92, 920);
context.font = "800 30px system-ui";
context.fillText("COMMUNITY BOOK EXCHANGE", 512, 151);
context.fillStyle = "rgba(255,255,255,0.28)";
context.fillRect(155, 183, 714, 8);
});
const signPlane = new THREE.Mesh(
new THREE.PlaneGeometry(3.75, 0.84),
new THREE.MeshBasicMaterial({
map: sign.texture,
side: THREE.DoubleSide
})
);
signPlane.position.set(0, 3.35, 0.91);
shelf.group.add(signPlane);
// Six individually labeled book slots.
shelf.slotLabels = [];
for (let index = 0; index < CAPACITY; index += 1) {
const row = Math.floor(index / 3);
const column = index % 3;
const x = [-1.38, 0, 1.38][column];
const y = [0.48, 1.78][row];
const label = createCanvasTexture(512, 104, () => {});
const labelPlane = new THREE.Mesh(
new THREE.PlaneGeometry(1.27, 0.255),
new THREE.MeshBasicMaterial({
map: label.texture,
side: THREE.DoubleSide
})
);
labelPlane.position.set(x, y, 0.89);
shelf.group.add(labelPlane);
shelf.slotLabels.push({
canvas: label.canvas,
context: label.context,
texture: label.texture,
plane: labelPlane
});
}
// Request board.
const board = createCanvasTexture(640, 900, () => {});
const boardGroup = new THREE.Group();
boardGroup.position.set(3.18, 1.83, 0.02);
shelf.group.add(boardGroup);
addBox(
boardGroup,
1.82,
2.48,
0.14,
0,
0,
0,
frameDarkMaterial
);
const boardPlane = new THREE.Mesh(
new THREE.PlaneGeometry(1.64, 2.3),
new THREE.MeshBasicMaterial({
map: board.texture,
side: THREE.DoubleSide
})
);
boardPlane.position.z = 0.078;
boardPlane.userData.requestShelf = shelf.id;
boardGroup.add(boardPlane);
pickables.push(boardPlane);
addBox(boardGroup, 0.11, 1.0, 0.11, -0.64, -1.53, 0, frameDarkMaterial);
addBox(boardGroup, 0.11, 1.0, 0.11, 0.64, -1.53, 0, frameDarkMaterial);
shelf.board = board;
shelfMap.set(shelf.id, shelf);
return shelf;
}
shelfDefinitions.forEach(createShelf);
function updateSlotLabel(shelf, index) {
const label = shelf.slotLabels[index];
const context = label.context;
const bookId = shelf.slots[index];
const book = books.find((item) => item.id === bookId);
context.clearRect(0, 0, label.canvas.width, label.canvas.height);
context.fillStyle = book ? "#fff9e9" : "#e4e4d8";
context.fillRect(0, 0, 512, 104);
context.strokeStyle = book ? "#c8b98f" : "#b8bcae";
context.lineWidth = 5;
context.strokeRect(3, 3, 506, 98);
context.textAlign = "left";
context.fillStyle = "#24443e";
context.font = "900 31px system-ui";
if (book) {
context.fillText(book.title, 16, 42, 410);
context.fillStyle = "#748078";
context.font = "800 18px system-ui";
context.fillText(book.id, 16, 78);
context.textAlign = "right";
context.fillText("SHELF SLOT", 495, 78);
} else {
context.fillText(`SLOT ${String(index + 1).padStart(2, "0")} · OPEN`, 16, 45);
context.fillStyle = "#879087";
context.font = "700 18px system-ui";
context.fillText("Awaiting an existing title", 16, 79);
}
label.texture.needsUpdate = true;
}
function redrawRequestBoard(shelf) {
const context = shelf.board.context;
const request = requests.find((item) => item.shelfId === shelf.id);
context.clearRect(0, 0, 640, 900);
context.fillStyle = "#183c37";
context.fillRect(0, 0, 640, 900);
context.fillStyle = "#fff5dc";
context.textAlign = "center";
context.font = "900 49px system-ui";
context.fillText("REQUEST BOARD", 320, 78);
context.fillStyle = "#ffd166";
context.fillRect(74, 108, 492, 7);
context.fillStyle = "#b9d9ca";
context.font = "750 27px system-ui";
context.fillText(shelf.name, 320, 158, 560);
context.strokeStyle = "rgba(255,255,255,0.18)";
context.lineWidth = 3;
context.strokeRect(34, 194, 572, 602);
if (request.status === "open") {
context.fillStyle = "#ef8354";
context.beginPath();
context.roundRect(170, 231, 300, 65, 32);
context.fill();
context.fillStyle = "#183c37";
context.font = "900 28px system-ui";
context.fillText("TITLE WANTED", 320, 273);
context.fillStyle = "#fff9e9";
context.font = "900 57px system-ui";
const lines = wrapText(context, request.title, 510);
const startY = 390 - (lines.length - 1) * 27;
lines.forEach((line, index) => {
context.fillText(line, 320, startY + index * 66);
});
context.fillStyle = "#b9d9ca";
context.font = "650 25px system-ui";
context.fillText("Bring an existing copy", 320, 605);
context.fillText("Requests never create new books.", 320, 650);
} else {
context.fillStyle = "#78c7a2";
context.beginPath();
context.arc(320, 393, 94, 0, Math.PI * 2);
context.fill();
context.fillStyle = "#183c37";
context.font = "900 94px system-ui";
context.fillText("✓", 320, 426);
context.fillStyle = "#fff9e9";
context.font = "900 37px system-ui";
context.fillText("REQUEST SATISFIED", 320, 566, 540);
context.fillStyle = "#b9d9ca";
context.font = "650 24px system-ui";
context.fillText(`Delivered by ${request.fulfilledBy}`, 320, 625);
}
context.fillStyle = "#84a99d";
context.font = "800 20px system-ui";
context.fillText(`FIXED CATALOG · ${books.length} UNIQUE BOOK IDS`, 320, 848);
shelf.board.texture.needsUpdate = true;
}
for (const shelf of shelfMap.values()) {
for (let index = 0; index < CAPACITY; index += 1) {
updateSlotLabel(shelf, index);
}
redrawRequestBoard(shelf);
}
// -------------------------------------------------------------------------
// Pedestrian routes
// -------------------------------------------------------------------------
const walkwayMaterial = standardMaterial(0xd9c49c);
const walkwayBorderMaterial = standardMaterial(0xead9b8);
const pavingMaterial = standardMaterial(0xcbb58b);
const zAxis = new THREE.Vector3(0, 0, 1);
function addWalkway(startShelf, endShelf) {
const start = startShelf.approach.clone();
const end = endShelf.approach.clone();
start.y = 0;
end.y = 0;
const direction = end.clone().sub(start);
const length = direction.length();
const midpoint = start.clone().add(end).multiplyScalar(0.5);
const rotation = new THREE.Quaternion().setFromUnitVectors(
zAxis,
direction.clone().normalize()
);
const border = new THREE.Mesh(
new THREE.BoxGeometry(1.65, 0.045, length),
walkwayBorderMaterial
);
border.position.set(midpoint.x, 0.005, midpoint.z);
border.quaternion.copy(rotation);
border.receiveShadow = true;
scene.add(border);
const path = new THREE.Mesh(
new THREE.BoxGeometry(1.32, 0.075, length),
walkwayMaterial
);
path.position.set(midpoint.x, 0.035, midpoint.z);
path.quaternion.copy(rotation);
path.receiveShadow = true;
scene.add(path);
const paverCount = Math.max(3, Math.floor(length / 1.35));
for (let index = 0; index < paverCount; index += 1) {
const t = (index + 0.5) / paverCount;
const point = start.clone().lerp(end, t);
const paver = new THREE.Mesh(
new THREE.BoxGeometry(0.43, 0.035, 0.57),
pavingMaterial
);
paver.position.set(point.x, 0.087, point.z);
paver.quaternion.copy(rotation);
paver.receiveShadow = true;
scene.add(paver);
}
}
addWalkway(shelfMap.get("A"), shelfMap.get("B"));
addWalkway(shelfMap.get("B"), shelfMap.get("C"));
for (const shelf of shelfMap.values()) {
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(0.94, 0.94, 0.08, 16),
walkwayMaterial
);
pad.position.set(shelf.approach.x, 0.04, shelf.approach.z);
pad.receiveShadow = true;
scene.add(pad);
}
// -------------------------------------------------------------------------
// Books: each book owns one persistent mesh and one persistent ID.
// -------------------------------------------------------------------------
function positionBookInSlot(book, shelf, slotIndex) {
const row = Math.floor(slotIndex / 3);
const column = slotIndex % 3;
book.mesh.position.set(
[-1.38, 0, 1.38][column],
[0.98, 2.28][row],
0.16
);
book.mesh.rotation.set(0, 0, 0);
book.mesh.scale.setScalar(1);
}
function createBookMesh(book) {
const group = new THREE.Group();
group.name = book.id;
const coverMaterial = standardMaterial(book.color);
const cover = new THREE.Mesh(
new THREE.BoxGeometry(0.46, 0.72, 0.42),
coverMaterial
);
cover.castShadow = true;
cover.receiveShadow = true;
group.add(cover);
const pageMaterial = standardMaterial(0xfff3d5);
const pageEdge = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.61, 0.405),
pageMaterial
);
pageEdge.position.x = 0.245;
pageEdge.castShadow = true;
group.add(pageEdge);
const spine = createCanvasTexture(512, 210, (context) => {
context.fillStyle = hexColor(book.color);
context.fillRect(0, 0, 512, 210);
context.fillStyle = "rgba(255,255,255,0.84)";
context.fillRect(30, 27, 452, 4);
context.fillRect(30, 177, 452, 4);
context.textAlign = "center";
context.fillStyle = "#fffdf3";
context.font = "900 31px system-ui";
context.fillText(book.title, 256, 103, 450);
context.font = "900 28px system-ui";
context.fillText(book.id, 256, 151);
});
const spinePlane = new THREE.Mesh(
new THREE.PlaneGeometry(0.39, 0.16),
new THREE.MeshBasicMaterial({
map: spine.texture,
side: THREE.DoubleSide
})
);
spinePlane.position.set(-0.015, 0.1, 0.216);
group.add(spinePlane);
group.traverse((object) => {
object.userData.bookId = book.id;
});
pickables.push(cover, spinePlane);
book.mesh = group;
book.coverMaterial = coverMaterial;
}
const initialSlots = [0, 1, 3, 4];
for (const shelf of shelfMap.values()) {
const shelfBooks = books.filter((book) => book.shelfId === shelf.id);
shelfBooks.forEach((book, index) => {
const slotIndex = initialSlots[index];
book.slotIndex = slotIndex;
shelf.slots[slotIndex] = book.id;
createBookMesh(book);
shelf.group.add(book.mesh);
positionBookInSlot(book, shelf, slotIndex);
updateSlotLabel(shelf, slotIndex);
});
}
// -------------------------------------------------------------------------
// Routing and transfer state
// -------------------------------------------------------------------------
function findPath(startId, endId) {
const distances = {};
const previous = {};
const visited = new Set();
for (const id of shelfIds) distances[id] = Infinity;
distances[startId] = 0;
while (true) {
let current = null;
let smallest = Infinity;
for (const id of shelfIds) {
if (!visited.has(id) && distances[id] < smallest) {
smallest = distances[id];
current = id;
}
}
if (current === null || current === endId) break;
visited.add(current);
for (const neighbor of graph[current]) {
const candidate = distances[current] + 1;
if (candidate < distances[neighbor]) {
distances[neighbor] = candidate;
previous[neighbor] = current;
}
}
}
if (!Number.isFinite(distances[endId])) return null;
const path = [endId];
while (path[0] !== startId) {
path.unshift(previous[path[0]]);
}
return path;
}
function routePoints(path) {
return path.map((id) => shelfMap.get(id).approach.clone());
}
function routeDistance(path) {
const points = routePoints(path);
let distance = 0;
for (let index = 1; index < points.length; index += 1) {
distance += points[index - 1].distanceTo(points[index]);
}
return distance;
}
function updateRouteHighlight() {
for (const child of [...routeHighlightGroup.children]) {
routeHighlightGroup.remove(child);
child.geometry.dispose();
}
const path = findPath(sourceShelfId, destinationShelfId);
if (!path) return;
const points = routePoints(path);
for (let index = 1; index < points.length; index += 1) {
const start = points[index - 1];
const end = points[index];
const direction = end.clone().sub(start);
const length = direction.length();
const segment = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 0.045, length),
routeHighlightMaterial
);
segment.position.copy(start).add(end).multiplyScalar(0.5);
segment.position.y = 0.15;
segment.quaternion.setFromUnitVectors(
zAxis,
direction.clone().normalize()
);
routeHighlightGroup.add(segment);
}
}
let sourceShelfId = "A";
let destinationShelfId = "C";
let selectedBookId = null;
const transfers = [];
function getSelectedBook() {
return books.find((book) => book.id === selectedBookId) || null;
}
function setStatus(message, tone = "") {
const status = document.getElementById("status");
status.textContent = message;
status.className = `status ${tone}`.trim();
}
function otherShelves() {
return shelfIds.filter((id) => id !== sourceShelfId);
}
function chooseDestinationForBook(book) {
if (!book) {
if (destinationShelfId === sourceShelfId) {
destinationShelfId = otherShelves()[0];
}
return;
}
const matchingRequest = requests.find(
(request) =>
request.status === "open" &&
request.shelfId !== sourceShelfId &&
request.title === book.title
);
if (matchingRequest) {
destinationShelfId = matchingRequest.shelfId;
} else if (destinationShelfId === sourceShelfId) {
destinationShelfId = otherShelves()[0];
}
}
function selectBook(bookId) {
const book = books.find((item) => item.id === bookId);
if (!book || book.locked || book.status !== "shelf") return;
sourceShelfId = book.shelfId;
selectedBookId = book.id;
chooseDestinationForBook(book);
refreshUI();
const request = requests.find(
(item) =>
item.status === "open" &&
item.shelfId === destinationShelfId &&
item.title === book.title
);
if (request) {
setStatus(
`${book.id} is wanted at ${destinationShelfId}. The route preview is valid and ready.`,
"good"
);
} else {
setStatus(`${book.id} selected. Choose a destination shelf.`);
}
}
function selectSource(shelfId) {
sourceShelfId = shelfId;
const firstAvailable = books.find(
(book) => book.shelfId === shelfId && !book.locked
);
selectedBookId = firstAvailable ? firstAvailable.id : null;
chooseDestinationForBook(firstAvailable);
refreshUI();
}
function createCarrier(transferNumber) {
const group = new THREE.Group();
const carrierColors = [0xef8354, 0x4f86c6, 0x2a9d8f, 0xe9a23b];
const bodyMaterial = standardMaterial(
carrierColors[transferNumber % carrierColors.length]
);
const darkMaterial = standardMaterial(0x304b45);
const skinMaterial = standardMaterial(0xd99b72);
const hatMaterial = standardMaterial(0xffd166);
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.24, 0.3, 0.68, 6),
bodyMaterial
);
body.position.y = 0.98;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.24, 1),
skinMaterial
);
head.position.y = 1.52;
head.castShadow = true;
group.add(head);
const hat = new THREE.Mesh(
new THREE.ConeGeometry(0.3, 0.19, 6),
hatMaterial
);
hat.position.y = 1.78;
hat.castShadow = true;
group.add(hat);
const legPivots = [];
for (const side of [-1, 1]) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.14, 0.64, 0);
const leg = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.1, 0.48, 5),
darkMaterial
);
leg.position.y = -0.24;
leg.castShadow = true;
pivot.add(leg);
group.add(pivot);
legPivots.push(pivot);
}
const armPivots = [];
for (const side of [-1, 1]) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.31, 1.2, 0);
const arm = new THREE.Mesh(
new THREE.CylinderGeometry(0.065, 0.075, 0.48, 5),
skinMaterial
);
arm.position.y = -0.23;
arm.castShadow = true;
pivot.add(arm);
group.add(pivot);
armPivots.push(pivot);
}
const satchel = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.29, 0.16),
hatMaterial
);
satchel.position.set(-0.36, 0.82, -0.05);
satchel.castShadow = true;
group.add(satchel);
const heldAnchor = new THREE.Object3D();
heldAnchor.position.set(0.39, 1.03, 0.28);
group.add(heldAnchor);
scene.add(group);
return {
group,
heldAnchor,
legPivots,
armPivots,
walkTime: 0
};
}
function sendTransfer() {
const book = getSelectedBook();
if (!book || book.status !== "shelf" || book.locked) {
setStatus("Choose one unlocked book from the source shelf.", "warn");
return;
}
if (!otherShelves().includes(destinationShelfId)) {
setStatus("The destination must be a different shelf.", "warn");
return;
}
const path = findPath(sourceShelfId, destinationShelfId);
if (!path) {
setStatus("No valid pedestrian route connects those shelves.", "warn");
return;
}
const destination = shelfMap.get(destinationShelfId);
const occupied = destination.slots.filter(Boolean).length;
if (occupied + destination.reserved >= CAPACITY) {
setStatus(
`${destinationShelfId} has no free slot for this delivery. ` +
"Wait for an incoming carrier or choose another shelf.",
"warn"
);
return;
}
const carrier = createCarrier(transfers.length);
carrier.group.position.copy(shelfMap.get(sourceShelfId).approach);
const transfer = {
id: `TR-${String(transfers.length + 1).padStart(2, "0")}`,
book,
source: shelfMap.get(sourceShelfId),
destination,
path,
points: routePoints(path),
carrier,
phase: "pickup",
timer: 0,
segment: 0,
progress: 0,
completed: false
};
transfers.push(transfer);
// A lock prevents the same shelf copy from being dispatched twice.
// This does not alter the shelf inventory or any counter.
book.locked = true;
destination.reserved += 1;
refreshUI();
setStatus(
`Carrier dispatched for ${book.id}. The book remains on ${sourceShelfId} ` +
"until pickup is completed.",
"good"
);
}
function pickupBook(transfer) {
const book = transfer.book;
const source = transfer.source;
if (book.slotIndex !== null) {
source.slots[book.slotIndex] = null;
updateSlotLabel(source, book.slotIndex);
}
// The only inventory change at pickup: shelf -> carried.
book.shelfId = null;
book.slotIndex = null;
book.status = "carried";
source.group.remove(book.mesh);
transfer.carrier.heldAnchor.add(book.mesh);
book.mesh.position.set(0, 0, 0);
book.mesh.rotation.set(0, 0, 0);
book.mesh.scale.setScalar(0.88);
if (selectedBookId === book.id) selectedBookId = null;
transfer.phase = "travel";
transfer.segment = 0;
transfer.progress = 0;
refreshUI();
setStatus(
`${book.id} picked up at ${source.id}. Shelf count decreased by one; ` +
"carried count increased by one.",
"good"
);
}
function deliverBook(transfer) {
const book = transfer.book;
const destination = transfer.destination;
const slotIndex = destination.slots.findIndex((slot) => slot === null);
if (slotIndex < 0) {
// Reservation logic prevents this, but no book is ever destroyed.
setStatus(
`Delivery to ${destination.id} was deferred because its slots are occupied.`,
"warn"
);
return false;
}
// The only inventory change at delivery: carried -> destination shelf.
book.status = "shelf";
book.shelfId = destination.id;
book.slotIndex = slotIndex;
destination.slots[slotIndex] = book.id;
book.locked = false;
transfer.carrier.heldAnchor.remove(book.mesh);
destination.group.add(book.mesh);
positionBookInSlot(book, destination, slotIndex);
updateSlotLabel(destination, slotIndex);
destination.reserved = Math.max(0, destination.reserved - 1);
const matchingRequest = requests.find(
(request) =>
request.shelfId === destination.id &&
request.status === "open" &&
request.title === book.title
);
if (matchingRequest) {
matchingRequest.status = "fulfilled";
matchingRequest.fulfilledBy = book.id;
}
redrawRequestBoard(destination);
refreshUI();
if (matchingRequest) {
setStatus(
`${book.id} delivered to ${destination.id}. The request for ` +
`"${matchingRequest.title}" is now satisfied.`,
"good"
);
} else {
setStatus(
`${book.id} delivered to ${destination.id}. The book keeps the same ID, ` +
"and the total inventory is unchanged.",
"good"
);
}
transfer.completed = true;
scene.remove(transfer.carrier.group);
return true;
}
function updateTransfers(delta) {
for (let index = transfers.length - 1; index >= 0; index -= 1) {
const transfer = transfers[index];
if (transfer.phase === "pickup") {
transfer.timer += delta;
transfer.carrier.group.position.y =
transfer.source.approach.y + Math.sin(transfer.timer * 3) * 0.015;
if (transfer.timer >= 0.85) {
pickupBook(transfer);
}
continue;
}
if (transfer.phase !== "travel") continue;
const start = transfer.points[transfer.segment];
const end = transfer.points[transfer.segment + 1];
const segmentLength = start.distanceTo(end);
const speed = 3.35;
transfer.progress += (speed * delta) / segmentLength;
transfer.carrier.walkTime += delta * speed * 3.6;
const direction = end.clone().sub(start).normalize();
transfer.carrier.group.rotation.y = Math.atan2(direction.x, direction.z);
const swing = Math.sin(transfer.carrier.walkTime) * 0.55;
transfer.carrier.legPivots[0].rotation.x = swing;
transfer.carrier.legPivots[1].rotation.x = -swing;
transfer.carrier.armPivots[0].rotation.x = -swing * 0.75;
transfer.carrier.armPivots[1].rotation.x = swing * 0.75;
transfer.carrier.group.position.lerpVectors(
start,
end,
Math.min(transfer.progress, 1)
);
transfer.carrier.group.position.y =
0.05 + Math.abs(Math.sin(transfer.carrier.walkTime)) * 0.025;
if (transfer.progress >= 1) {
transfer.carrier.group.position.copy(end);
if (transfer.segment >= transfer.points.length - 2) {
const delivered = deliverBook(transfer);
if (delivered) transfers.splice(index, 1);
} else {
transfer.segment += 1;
transfer.progress = 0;
}
}
}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const sourceButtonsElement = document.getElementById("source-buttons");
const bookListElement = document.getElementById("book-list");
const destinationElement = document.getElementById("destination");
const matchNoteElement = document.getElementById("match-note");
const routeLineElement = document.getElementById("route-line");
const routeDistanceElement = document.getElementById("route-distance");
const sendButtonElement = document.getElementById("send-button");
const requestListElement = document.getElementById("request-list");
function refreshUI() {
const shelfCount = books.filter((book) => book.status === "shelf").length;
const carriedCount = books.filter((book) => book.status === "carried").length;
const totalCount = shelfCount + carriedCount;
const fulfilledCount = requests.filter(
(request) => request.status === "fulfilled"
).length;
document.getElementById("stat-total").textContent = totalCount;
document.getElementById("stat-shelf").textContent = shelfCount;
document.getElementById("stat-carried").textContent = carriedCount;
document.getElementById("stat-fulfilled").textContent = fulfilledCount;
document.getElementById("catalog-total").textContent = books.length;
const selected = getSelectedBook();
if (selected && selected.shelfId !== sourceShelfId) {
selectedBookId = null;
}
if (!otherShelves().includes(destinationShelfId)) {
destinationShelfId = otherShelves()[0];
}
// Source shelf buttons.
sourceButtonsElement.innerHTML = "";
for (const shelf of shelfMap.values()) {
const count = shelf.slots.filter(Boolean).length;
const button = document.createElement("button");
button.type = "button";
button.className = `source-button${
shelf.id === sourceShelfId ? " active" : ""
}`;
button.innerHTML = `
<span class="key">${shelf.id}</span>
<strong>${shelf.name}</strong>
<small>${count} book${count === 1 ? "" : "s"}</small>
`;
button.addEventListener("click", () => selectSource(shelf.id));
sourceButtonsElement.appendChild(button);
}
// Inventory list.
bookListElement.innerHTML = "";
const sourceBooks = books
.filter((book) => book.shelfId === sourceShelfId && book.status === "shelf")
.sort((a, b) => a.slotIndex - b.slotIndex);
if (sourceBooks.length === 0) {
const empty = document.createElement("div");
empty.className = "match-note";
empty.textContent = "No books are currently on this shelf.";
bookListElement.appendChild(empty);
}
for (const book of sourceBooks) {
const request = requests.find(
(item) =>
item.status === "open" &&
item.shelfId !== sourceShelfId &&
item.title === book.title
);
const button = document.createElement("button");
button.type = "button";
button.className = `book-option${
selectedBookId === book.id ? " selected" : ""
}`;
button.disabled = book.locked;
const badge = book.locked
? '<span class="needed pending">Pickup pending</span>'
: request
? `<span class="needed">Wanted at ${request.shelfId}</span>`
: "";
button.innerHTML = `
<span class="book-color" style="background:${hexColor(book.color)}"></span>
<span>
<strong>${book.title}</strong>
<small>${book.id} · ${book.author}</small>
</span>
${badge}
`;
button.title = book.locked
? "A carrier has already been dispatched for this copy."
: `Select ${book.title}`;
button.addEventListener("click", () => selectBook(book.id));
bookListElement.appendChild(button);
}
// Destination options.
destinationElement.innerHTML = "";
for (const id of otherShelves()) {
const shelf = shelfMap.get(id);
const request = requests.find((item) => item.shelfId === id);
const occupied = shelf.slots.filter(Boolean).length;
const reserved = occupied + shelf.reserved;
const option = document.createElement("option");
option.value = id;
const requestText =
request.status === "open"
? `wants ${request.title}`
: "request satisfied";
option.textContent =
`${id} · ${shelf.name} — ${requestText} (${reserved}/${CAPACITY})`;
destinationElement.appendChild(option);
}
destinationElement.value = destinationShelfId;
// Request matching note.
const current = getSelectedBook();
const targetRequest = requests.find(
(item) => item.shelfId === destinationShelfId
);
if (!current) {
matchNoteElement.className = "match-note";
matchNoteElement.textContent =
"Choose an existing title. The inventory updates only after pickup or delivery.";
} else if (
targetRequest.status === "open" &&
current.title === targetRequest.title
) {
matchNoteElement.className = "match-note good";
matchNoteElement.textContent =
`Requested-title match: ${destinationShelfId} wants "${current.title}".`;
} else if (targetRequest.status === "open") {
matchNoteElement.className = "match-note";
matchNoteElement.textContent =
`${destinationShelfId} currently wants "${targetRequest.title}". ` +
`This delivery would not satisfy that request.`;
} else {
matchNoteElement.className = "match-note";
matchNoteElement.textContent =
`${destinationShelfId}'s visible request is already satisfied.`;
}
// Route preview.
const path = findPath(sourceShelfId, destinationShelfId);
if (path) {
routeLineElement.textContent = path.join(" → ");
routeDistanceElement.textContent =
`${routeDistance(path).toFixed(1)} scene units`;
} else {
routeLineElement.textContent = "No valid route";
routeDistanceElement.textContent = "";
}
const destinationShelf = shelfMap.get(destinationShelfId);
const hasCapacity =
destinationShelf.slots.filter(Boolean).length +
destinationShelf.reserved <
CAPACITY;
sendButtonElement.disabled =
!current ||
current.locked ||
current.status !== "shelf" ||
!path ||
!hasCapacity;
// Physical request list mirror.
requestListElement.innerHTML = "";
for (const request of requests) {
const shelf = shelfMap.get(request.shelfId);
const row = document.createElement("div");
row.className = "request-row";
row.innerHTML = `
<span class="request-key">${shelf.id}</span>
<span>
<strong>${request.title}</strong>
<small>${shelf.name}${
request.status === "fulfilled"
? ` · fulfilled by ${request.fulfilledBy}`
: ""
}</small>
</span>
<span class="request-badge ${
request.status === "fulfilled" ? "done" : ""
}">${request.status === "fulfilled" ? "Satisfied" : "Wanted"}</span>
`;
requestListElement.appendChild(row);
}
// Highlight selected physical books.
for (const book of books) {
if (!book.coverMaterial) continue;
const isSelected = book.id === selectedBookId;
book.coverMaterial.emissive.setHex(isSelected ? 0x4a3510 : 0x000000);
book.coverMaterial.emissiveIntensity = isSelected ? 0.38 : 0;
}
updateRouteHighlight();
}
destinationElement.addEventListener("change", () => {
destinationShelfId = destinationElement.value;
refreshUI();
});
sendButtonElement.addEventListener("click", sendTransfer);
// -------------------------------------------------------------------------
// Direct camera controls and 3D picking
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const activePointers = new Map();
let pointerStart = null;
let dragged = false;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (activePointers.size === 1) {
pointerStart = {
id: event.pointerId,
x: event.clientX,
y: event.clientY
};
dragged = false;
}
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = activePointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointerStart && pointerStart.id === event.pointerId) {
const totalDistance = Math.hypot(
event.clientX - pointerStart.x,
event.clientY - pointerStart.y
);
if (totalDistance > 5) dragged = true;
}
if (activePointers.size === 1) {
orbit.theta -= dx * 0.005;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.005,
0.48,
1.36
);
updateCamera();
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
activePointers.delete(event.pointerId);
if (
pointerStart &&
pointerStart.id === event.pointerId &&
!dragged
) {
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);
const intersections = raycaster.intersectObjects(pickables, true);
if (intersections.length > 0) {
let object = intersections[0].object;
while (object) {
if (object.userData.bookId) {
selectBook(object.userData.bookId);
break;
}
if (object.userData.requestShelf) {
const shelfId = object.userData.requestShelf;
if (shelfId !== sourceShelfId) {
destinationShelfId = shelfId;
refreshUI();
setStatus(
`Destination changed to ${shelfId}. Review the route and send the carrier.`
);
}
break;
}
object = object.parent;
}
}
}
if (activePointers.size === 0) pointerStart = null;
});
renderer.domElement.addEventListener("pointercancel", (event) => {
activePointers.delete(event.pointerId);
pointerStart = null;
dragged = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
11,
31
);
updateCamera();
},
{ passive: false }
);
document.getElementById("reset-view").addEventListener("click", () => {
orbit.theta = 0.34;
orbit.phi = 1.03;
orbit.radius = 22;
orbit.target.set(0, 1.35, 0);
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
const firstBook = books.find(
(book) => book.shelfId === sourceShelfId && !book.locked
);
selectedBookId = firstBook.id;
chooseDestinationForBook(firstBook);
refreshUI();
setStatus(
`${firstBook.id} is selected. Paper Lanterns is wanted at Market Nook; ` +
"the valid route passes through Riverside Hub.",
"good"
);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
updateTransfers(delta);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```