Prompt specification
Build or customize the Three.js 3D scene "Storage-capacity planning puzzle" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Storage-capacity planning puzzle
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/storage-capacity-planning-puzzle-x1068
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows grain storage. Create several bins and incoming fictional harvest batches; users allocate compatible storage space and schedule discharge while capacity and inventory constraints remain visibly conserved. Low-poly.
Working Three.js Starter (storage-capacity-planning-puzzle-x1068):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grainline — Cooperative Storage</title>
<style>
:root {
--paper: #f3efe5;
--panel: #fffdf8;
--ink: #17352b;
--muted: #708078;
--line: #ded8c9;
--green: #315e48;
--green-soft: #dce9df;
--gold: #d4a63d;
--orange: #d87832;
--blue: #567c91;
--danger: #a84e3c;
--shadow: 0 12px 34px rgba(25, 45, 35, 0.12);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
height: 100%;
overflow: hidden;
background: var(--paper);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input, select { font: inherit; }
button { cursor: pointer; }
button:disabled { cursor: not-allowed; opacity: 0.45; }
.app {
display: grid;
grid-template-rows: 70px minmax(0, 1fr);
height: 100%;
}
header {
z-index: 20;
display: flex;
align-items: center;
gap: 24px;
padding: 0 22px;
background: rgba(255, 253, 248, 0.96);
border-bottom: 1px solid var(--line);
box-shadow: 0 2px 16px rgba(27, 49, 39, 0.05);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 245px;
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
overflow: hidden;
border-radius: 11px;
background: var(--ink);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
left: 8px;
width: 22px;
height: 5px;
border-radius: 1px;
background: var(--gold);
transform: skewX(-18deg);
}
.brand-mark::before { top: 11px; }
.brand-mark::after { top: 22px; background: #83a16c; }
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1.05;
letter-spacing: -0.02em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.header-metrics {
display: flex;
align-items: center;
gap: 26px;
margin-left: auto;
}
.header-metric {
display: flex;
flex-direction: column;
gap: 2px;
}
.header-metric span {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.header-metric strong {
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.header-actions {
display: flex;
gap: 8px;
padding-left: 18px;
border-left: 1px solid var(--line);
}
.small-button {
min-height: 35px;
padding: 0 12px;
color: var(--ink);
font-size: 12px;
font-weight: 800;
border: 1px solid var(--line);
border-radius: 9px;
background: #fff;
}
.small-button:hover:not(:disabled) {
border-color: #aeb9af;
background: #f6f8f3;
}
.small-button.active {
color: #fff;
border-color: var(--green);
background: var(--green);
}
.workspace {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
min-height: 0;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #e8e5d9;
}
#grainCanvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#grainCanvas:active { cursor: grabbing; }
#labelLayer {
position: absolute;
inset: 0;
z-index: 4;
overflow: hidden;
pointer-events: none;
}
.scene-heading {
position: absolute;
z-index: 6;
top: 20px;
left: 20px;
max-width: 300px;
padding: 13px 15px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 13px;
background: rgba(255, 253, 248, 0.88);
box-shadow: var(--shadow);
backdrop-filter: blur(9px);
pointer-events: none;
}
.eyebrow {
margin: 0 0 5px;
color: var(--green);
font-size: 10px;
font-weight:900;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.scene-heading h2 {
margin: 0;
font-size: 19px;
letter-spacing: -0.025em;
}
.scene-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.scene-badge {
position: absolute;
z-index: 6;
top: 20px;
right: 20px;
display: flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
color: var(--ink);
font-size: 11px;
font-weight: 800;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 999px;
background: rgba(255, 253, 248, 0.9);
box-shadow: 0 6px 18px rgba(30, 52, 42, 0.09);
pointer-events: none;
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #4f9365;
box-shadow: 0 0 0 4px rgba(79, 147, 101, 0.14);
}
.bin-label {
position: absolute;
min-width: 88px;
padding: 7px 9px;
color: var(--ink);
border: 1px solid rgba(255, 255, 255, 0.85);
border-radius: 9px;
background: rgba(255, 253, 248, 0.91);
box-shadow: 0 7px 18px rgba(24, 43, 33, 0.13);
transform: translate(-50%, -100%);
backdrop-filter: blur(7px);
}
.bin-label::after {
content: "";
position: absolute;
left: 50%;
top: 100%;
width: 1px;
height: 17px;
background: rgba(36, 60, 48, 0.32);
}
.bin-label strong,
.bin-label span {
display: block;
white-space: nowrap;
}
.bin-label strong {
font-size: 11px;
letter-spacing: 0.02em;
}
.bin-label span {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.label-meter {
height: 3px;
margin-top: 5px;
overflow: hidden;
border-radius: 3px;
background: #e5e2d8;
}
.label-meter i {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--green);
transition: width 300ms ease;
}
.ledger {
position: absolute;
z-index: 7;
left: 18px;
right: 18px;
bottom: 18px;
display: grid;
grid-template-columns: minmax(250px, 1.2fr) minmax(320px, 1fr);
gap: 18px;
align-items: center;
padding: 13px 16px;
border: 1px solid rgba(255, 255, 255, 0.76);
border-radius: 14px;
background: rgba(255, 253, 248, 0.93);
box-shadow: var(--shadow);
backdrop-filter: blur(10px);
pointer-events: none;
}
.ledger-title {
margin-bottom: 7px;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.04em;
}
.ledger-bar {
display: flex;
height: 9px;
overflow: hidden;
border-radius: 999px;
background: #e5e1d6;
}
.ledger-bar span {
display: block;
height: 100%;
transition: width 350ms ease;
}
#ledgerPending { background: var(--gold); }
#ledgerStored { background: var(--green); }
#ledgerDispatched { background: var(--blue); }
.ledger-legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.ledger-legend i {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 4px;
border-radius: 2px;
}
.equation {
text-align: right;
}
.equation strong {
display: block;
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.equation span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.sidebar {
z-index: 10;
min-height: 0;
overflow-y: auto;
padding: 18px;
border-left: 1px solid var(--line);
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #c9c4b6 transparent;
}
.section {
padding-bottom: 18px;
margin-bottom: 18px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
padding-bottom: 4px;
margin-bottom: 0;
border-bottom: 0;
}
.section-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.section-head h3 {
margin: 0;
font-size: 15px;
letter-spacing: -0.015em;
}
.section-head p {
margin: 3px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.count-pill {
min-width: 25px;
padding: 4px 7px;
text-align: center;
color: var(--green);
font-size: 10px;
font-weight: 900;
border-radius: 999px;
background: var(--green-soft);
}
.batch-list {
display: grid;
gap: 8px;
}
.batch-card {
width: 100%;
padding: 11px;
text-align: left;
color: var(--ink);
border: 1px solid var(--line);
border-radius: 11px;
background: #fff;
transition: 150ms ease;
}
.batch-card:hover {
transform: translateY(-1px);
border-color: #b7c1b8;
box-shadow: 0 6px 16px rgba(34, 57, 46, 0.07);
}
.batch-card.active {
border-color: var(--green);
box-shadow: inset 3px 0 0 var(--green);
background: #fbfdf8;
}
.batch-card.closed {
opacity: 0.57;
background: #f7f5ef;
}
.batch-top,
.batch-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.batch-code {
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
}
.batch-type {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 850;
}
.grain-dot {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--grain);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--grain) 20%, transparent);
}
.batch-bottom {
margin-top: 8px;
}
.batch-bottom strong {
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.batch-bottom span {
color: var(--muted);
font-size: 9px;
font-weight: 750;
}
.thin-progress {
height: 3px;
margin-top: 7px;
overflow: hidden;
border-radius: 5px;
background: #ece8de;
}
.thin-progress i {
display: block;
height: 100%;
border-radius: inherit;
background: var(--green);
}
.allocation-box {
margin-top: 10px;
padding: 12px;
border: 1px solid #cfd9cf;
border-radius: 11px;
background: #f4f8f2;
}
.allocation-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
font-size: 11px;
font-weight: 900;
}
.allocation-title span:last-child {
color: var(--muted);
font-size: 9px;
}
.field {
margin-bottom: 9px;
}
.field label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.07em;
text-transform: uppercase;
}
select,
input[type="number"] {
width: 100%;
height: 37px;
padding: 0 10px;
color: var(--ink);
border: 1px solid #cfd2c9;
border-radius: 8px;
outline: none;
background: #fff;
font-size: 12px;
}
select:focus,
input[type="number"]:focus {
border-color: var(--green);
box-shadow: 0 0 0 3px rgba(49, 94, 72, 0.11);
}
.field-row {
display: grid;
grid-template-columns: 1fr 92px;
gap: 9px;
}
.primary-button,
.secondary-button {
width: 100%;
min-height: 38px;
padding: 0 12px;
border-radius: 8px;
font-size: 11px;
font-weight: 900;
}
.primary-button {
color: #fff;
border: 1px solid var(--green);
background: var(--green);
}
.primary-button:hover:not(:disabled) { background: #264d3b; }
.secondary-button {
color: var(--ink);
border: 1px solid #bfc9c1;
background: #fff;
}
.secondary-button:hover:not(:disabled) { background: #f0f5ef; }
.hint {
margin: 8px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.hint strong { color: var(--ink); }
.bin-list {
display: grid;
gap: 7px;
}
.bin-row {
width: 100%;
padding: 10px 11px;
text-align: left;
color: var(--ink);
border: 1px solid var(--line);
border-radius: 10px;
background: #fff;
transition: 150ms ease;
}
.bin-row:hover { border-color: #afbeb2; }
.bin-row.active {
border-color: var(--green);
background: #f7faf6;
box-shadow: inset 3px 0 0 var(--green);
}
.bin-row-top,
.bin-row-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.bin-row-top strong {
font-size: 12px;
}
.bin-row-top span {
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.bin-row-bottom {
margin-top: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
}
.capacity-track {
position: relative;
height: 6px;
margin-top: 7px;
overflow: hidden;
border-radius: 5px;
background: #e8e4d9;
}
.capacity-fill,
.capacity-reserved {
position: absolute;
inset: 0 auto 0 0;
border-radius: inherit;
transition: width 300ms ease;
}
.capacity-fill { background: #73957a; }
.capacity-reserved {
background: repeating-linear-gradient(
-45deg,
rgba(216, 120, 50, 0.88),
rgba(216, 120, 50, 0.88) 4px,
rgba(247, 177, 111, 0.9) 4px,
rgba(247, 177, 111, 0.9) 8px
);
}
.discharge-box {
margin-top: 10px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: #f8f6f0;
}
.discharge-top {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
font-size: 11px;
font-weight: 900;
}
.discharge-top span:last-child {
color: var(--muted);
font-size: 9px;
}
.dispatch-list {
display: grid;
gap: 8px;
}
.dispatch-card {
padding: 10px;
border: 1px solid #d9d4c7;
border-radius: 10px;
background: #fff;
}
.dispatch-top,
.dispatch-bottom {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.dispatch-top strong { font-size: 11px; }
.dispatch-top span {
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.dispatch-bottom {
margin-top: 7px;
}
.dispatch-bottom small {
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.dispatch-bottom button {
padding: 4px 8px;
color: var(--green);
font-size: 9px;
font-weight: 900;
border: 1px solid #b8c9bb;
border-radius: 6px;
background: #f3f8f3;
}
.dispatch-progress {
height: 3px;
margin-top: 8px;
overflow: hidden;
border-radius: 4px;
background: #e9e5dc;
}
.dispatch-progress i {
display: block;
width: 0;
height: 100%;
background: var(--orange);
}
.empty {
padding: 13px;
text-align: center;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
border: 1px dashed #d3cec1;
border-radius: 10px;
background: #faf8f2;
}
.toast {
position: fixed;
z-index: 100;
left: 50%;
bottom: 26px;
max-width: min(420px, calc(100vw - 30px));
padding: 11px 15px;
color: #fff;
font-size: 11px;
font-weight: 800;
text-align: center;
border-radius: 9px;
background: #1e4032;
box-shadow: 0 12px 30px rgba(20, 40, 31, 0.25);
transform: translate(-50%, 25px);
opacity: 0;
pointer-events: none;
transition: 200ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
html, body { overflow: auto; }
.app { height: auto; min-height: 100vh; }
header { position: sticky; top: 0; }
.header-metric:nth-child(2) { display: none; }
.workspace { grid-template-columns: 1fr; }
#viewport { height: 58vh; min-height: 430px; }
.sidebar { overflow: visible; border-left: 0; border-top: 1px solid var(--line); }
.ledger { grid-template-columns: 1fr; gap: 9px; }
.equation { text-align: left; }
.scene-badge { display: none; }
}
@media (max-width: 600px) {
header { gap: 10px; padding: 0 12px; }
.brand { min-width: 0; }
.brand p { display: none; }
.brand h1 { font-size: 15px; }
.brand-mark { width: 32px; height: 32px; }
.header-metrics { gap: 10px; }
.header-metric span { font-size: 8px; }
.header-metric strong { font-size: 14px; }
.header-actions { padding-left: 8px; }
#resetBtn { display: none; }
.scene-heading { top: 12px; left: 12px; }
.ledger { left: 10px; right: 10px; bottom: 10px; }
.bin-label { min-width: 70px; padding: 5px 7px; }
.bin-label span { font-size: 8px; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Grainline</h1>
<p>Cooperative storage</p>
</div>
</div>
<div class="header-metrics">
<div class="header-metric">
<span>On site</span>
<strong id="headerOnSite">—</strong>
</div>
<div class="header-metric">
<span>Incoming</span>
<strong id="headerPending">—</strong>
</div>
<div class="header-metric">
<span>Scheduled</span>
<strong id="headerReserved">—</strong>
</div>
</div>
<div class="header-actions">
<button class="small-button active" id="pauseBtn">Auto-dispatch on</button>
<button class="small-button" id="resetBtn">Reset</button>
</div>
</header>
<main class="workspace">
<section id="viewport" aria-label="Interactive low-poly grain storage yard">
<canvas id="grainCanvas"></canvas>
<div id="labelLayer"></div>
<div class="scene-heading">
<p class="eyebrow">Fictional harvest network</p>
<h2>North Yard</h2>
<p>Drag to orbit · Scroll to zoom · Select a silo</p>
</div>
<div class="scene-badge">
<span class="live-dot"></span>
Inventory ledger live
</div>
<div class="ledger">
<div>
<div class="ledger-title">Conservation ledger · all grain accounted for</div>
<div class="ledger-bar">
<span id="ledgerPending"></span>
<span id="ledgerStored"></span>
<span id="ledgerDispatched"></span>
</div>
<div class="ledger-legend">
<span><i style="background:var(--gold)"></i>Pending <b id="legendPending"></b></span>
<span><i style="background:var(--green)"></i>Stored <b id="legendStored"></b></span>
<span><i style="background:var(--blue)"></i>Dispatched <b id="legendDispatched"></b></span>
</div>
</div>
<div class="equation">
<strong id="ledgerEquation">—</strong>
<span id="ledgerNote">Scheduled grain remains included in stored inventory.</span>
</div>
</div>
</section>
<aside class="sidebar" aria-label="Storage operations">
<section class="section">
<div class="section-head">
<div>
<h3>Incoming harvest</h3>
<p>Select a batch, then allocate compatible space.</p>
</div>
<span class="count-pill" id="pendingBatchCount">4</span>
</div>
<div class="batch-list" id="batchList"></div>
<div id="allocationPanel"></div>
</section>
<section class="section">
<div class="section-head">
<div>
<h3>Storage bins</h3>
<p>Physical inventory and scheduled load-outs.</p>
</div>
<span class="count-pill" id="totalCapacity">450</span>
</div>
<div class="bin-list" id="binList"></div>
<div id="dischargePanel"></div>
</section>
<section class="section">
<div class="section-head">
<div>
<h3>Dispatch queue</h3>
<p>Scheduled trucks depart automatically after 12 seconds.</p>
</div>
<span class="count-pill" id="queueCount">0</span>
</div>
<div class="dispatch-list" id="dispatchQueue"></div>
</section>
</aside>
</main>
</div>
<div class="toast" 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 $ = (selector) => document.querySelector(selector);
const formatT = (value) => Number(value).toLocaleString(undefined, {
maximumFractionDigits: 1
});
const GRAIN = {
wheat: { label: "Wheat", color: 0xd4a43c, css: "#d4a43c" },
corn: { label: "Corn", color: 0xdf8131, css: "#df8131" },
barley: { label: "Barley", color: 0xb3a05b, css: "#b3a05b" },
soy: { label: "Soy", color: 0x78984f, css: "#78984f" }
};
const bins = [
{
id: "A-01",
name: "Silo 01",
capacity: 120,
inventory: 64,
initial: 64,
accepts: ["wheat", "barley"],
position: [-5.1, 0, -2.15],
body: 0xd8d2bd,
accent: 0x4c745e
},
{
id: "A-02",
name: "Silo 02",
capacity: 140,
inventory: 72,
initial: 72,
accepts: ["corn"],
position: [-1.7, 0, -2.15],
body: 0xd9caaa,
accent: 0x8b7042
},
{
id: "A-03",
name: "Silo 03",
capacity: 100,
inventory: 35,
initial: 35,
accepts: ["barley", "wheat"],
position: [1.7, 0, -2.15],
body: 0xc9cfbd,
accent: 0x607c6d
},
{
id: "A-04",
name: "Silo 04",
capacity: 90,
inventory: 28,
initial: 28,
accepts: ["soy"],
position: [5.1, 0, -2.15],
body: 0xcbc2b1,
accent: 0x776a50
}
];
const batches = [
{
id: "HR-101",
farm: "Meadow Run",
type: "wheat",
original: 38,
remaining: 38,
position: [-4.8, 0, 3.25]
},
{
id: "HR-102",
farm: "Goldfork Farm",
type: "corn",
original: 51,
remaining: 51,
position: [-1.6, 0, 3.25]
},
{
id: "HR-103",
farm: "Stonehill Co-op",
type: "barley",
original: 42,
remaining: 42,
position: [1.6, 0, 3.25]
},
{
id: "HR-104",
farm: "Riverbend Fields",
type: "soy",
original: 31,
remaining: 31,
position: [4.8, 0, 3.25]
}
];
const INITIAL_TOTAL =
bins.reduce((sum, bin) => sum + bin.inventory, 0) +
batches.reduce((sum, batch) => sum + batch.original, 0);
let selectedBatchId = "HR-101";
let selectedBinId = "A-01";
let targetBinId = "A-01";
let dispatched = 0;
let dispatchSequence = 0;
let dispatchPaused = false;
let effects = [];
const dispatches = [];
const viewport = $("#viewport");
const canvas = $("#grainCanvas");
const labelLayer = $("#labelLayer");
const toast = $("#toast");
let toastTimer;
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
// -----------------------------------------------------------------------
// Three.js scene
// -----------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8e5d9);
scene.fog = new THREE.Fog(0xe8e5d9, 24, 43);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const hemisphere = new THREE.HemisphereLight(0xfbf8ec, 0x6a786d, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2cf, 3.1);
sun.position.set(7, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0008;
scene.add(sun);
const fillLight = new THREE.DirectionalLight(0xb8d0d0, 0.65);
fillLight.position.set(-8, 5, -7);
scene.add(fillLight);
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0,
flatShading: true,
...options
});
}
function addBox(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(30, 22),
standardMaterial(0xc9c9b8)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.1;
ground.receiveShadow = true;
scene.add(ground);
const yardPad = addBox(
scene,
[16.2, 0.16, 7.3],
[0, 0.0, -1.3],
standardMaterial(0xd8d4c5),
false
);
const road = addBox(
scene,
[23, 0.07, 2.25],
[0, 0.03, 4.65],
standardMaterial(0x8d9388),
false
);
const roadEdgeMaterial = standardMaterial(0xe2ddca, { flatShading: true });
for (let x = -10.5; x <= 10.5; x += 2.4) {
addBox(
scene,
[1.25, 0.025, 0.08],
[x, 0.09, 4.65],
roadEdgeMaterial,
false
);
}
// Low-poly trees around the perimeter.
function createTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.16, 1.1, 7),
standardMaterial(0x705843)
);
trunk.position.y = 0.55;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.7, 1.65, 7),
standardMaterial(0x54765b)
);
crown.position.y = 1.65;
crown.castShadow = true;
group.add(crown);
scene.add(group);
}
[
[-8.7, -4.6, 1.15], [-8.1, 1.2, 0.85], [-8.3, 6.6, 1.0],
[8.4, -4.6, 1.0], [8.6, 0.8, 0.8], [8.1, 6.7, 1.12],
[-5.8, -6.1, 0.85], [0, -6.3, 0.95], [5.8, -6.0, 0.8]
].forEach(([x, z, s]) => createTree(x, z, s));
// Small yard office.
const office = new THREE.Group();
office.position.set(7.8, 0, -1.45);
addBox(office, [1.65, 1.45, 1.8], [0, 0.73, 0], standardMaterial(0xc9c1ad));
const officeRoof = new THREE.Mesh(
new THREE.ConeGeometry(1.42, 0.72, 4),
standardMaterial(0x536b5c)
);
officeRoof.rotation.y = Math.PI / 4;
officeRoof.position.y = 1.8;
officeRoof.castShadow = true;
office.add(officeRoof);
addBox(office, [0.55, 0.85, 0.06], [0, 0.43, 0.93], standardMaterial(0x536d70));
scene.add(office);
const binVisuals = new Map();
const binMeshes = [];
function createBin(bin) {
const group = new THREE.Group();
group.position.set(...bin.position);
const body = new THREE.Mesh(
new THREE.CylinderGeometry(1.43, 1.43, 2.8, 12, 1, false),
standardMaterial(bin.body)
);
body.position.y = 1.4;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(1.54, 0.9, 12),
standardMaterial(bin.accent)
);
roof.position.y = 3.25;
roof.castShadow = true;
group.add(roof);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(1.53, 1.58, 0.18, 12),
standardMaterial(0x8f9487)
);
base.position.y = 0.09;
base.castShadow = true;
group.add(base);
const bandMaterial = standardMaterial(bin.accent, { roughness: 0.72 });
[0.64, 2.22].forEach((y) => {
const band = new THREE.Mesh(
new THREE.TorusGeometry(1.45, 0.055, 5, 12),
bandMaterial
);
band.rotation.x = Math.PI / 2;
band.position.y = y;
band.castShadow = true;
group.add(band);
});
const door = addBox(
group,
[0.72, 0.75, 0.08],
[0, 0.53, 1.43],
standardMaterial(0x6b766d)
);
const track = addBox(
group,
[0.29, 1.9, 0.09],
[0.72, 1.45, 1.45],
standardMaterial(0x5f695f)
);
const fill = addBox(
group,
[0.19, 1, 0.11],
[0.72, 1, 1.51],
standardMaterial(GRAIN[bin.accepts[0]].color, {
emissive: GRAIN[bin.accepts[0]].color,
emissiveIntensity: 0.06
})
);
const vent = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.48, 8),
standardMaterial(0x778077)
);
vent.position.set(-0.25, 3.85, 0);
vent.castShadow = true;
group.add(vent);
const ring = new THREE.Mesh(
new THREE.RingGeometry(1.58, 1.7, 32),
new THREE.MeshBasicMaterial({
color: 0x315e48,
transparent: true,
opacity: 0.76,
side: THREE.DoubleSide
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.12;
group.add(ring);
group.traverse((object) => {
if (object.isMesh && object !== ring) {
object.userData.binId = bin.id;
binMeshes.push(object);
}
});
scene.add(group);
binVisuals.set(bin.id, { group, fill, ring });
}
bins.forEach(createBin);
function createTruck(color) {
const group = new THREE.Group();
const trailer = addBox(
group,
[1.65, 0.72, 0.95],
[-0.34, 0.72, 0],
standardMaterial(color)
);
const trailerTop = addBox(
group,
[1.55, 0.09, 0.86],
[-0.34, 1.12, 0],
standardMaterial(0xe1d6b8)
);
const cab = addBox(
group,
[0.68, 0.73, 0.9],
[0.82, 0.66, 0],
standardMaterial(0xe7e1cf)
);
addBox(
group,
[0.07, 0.36, 0.72],
[1.17, 0.8, 0],
standardMaterial(0x526d72, { roughness: 0.42 })
);
const wheelMaterial = standardMaterial(0x333c38);
[-0.78, 0.7].forEach((x) => {
[-0.51, 0.51].forEach((z) => {
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.23, 0.23, 0.17, 10),
wheelMaterial
);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.28, z);
wheel.castShadow = true;
group.add(wheel);
});
});
const cargo = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.34, 0),
standardMaterial(color)
);
cargo.position.set(-0.35, 1.35, 0);
cargo.scale.set(1.2, 0.55, 0.8);
cargo.castShadow = true;
group.add(cargo);
group.userData.cargo = cargo;
group.scale.setScalar(0.88);
return group;
}
batches.forEach((batch) => {
const truck = createTruck(GRAIN[batch.type].color);
truck.position.set(...batch.position);
scene.add(truck);
batch.truck = truck;
});
// DOM labels above each bin.
const binLabels = new Map();
bins.forEach((bin) => {
const label = document.createElement("div");
label.className = "bin-label";
label.dataset.labelBin = bin.id;
label.innerHTML = `
<strong>${bin.id}</strong>
<span></span>
<div class="label-meter"><i></i></div>
`;
labelLayer.appendChild(label);
binLabels.set(bin.id, label);
});
// -----------------------------------------------------------------------
// Direct camera controls — no addons or examples are imported.
// -----------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0.85, 0.25),
radius: 19,
targetRadius: 19,
theta: 0.66,
targetTheta: 0.66,
phi: 1.02,
targetPhi: 1.02
};
let firstResize = true;
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();
if (firstResize) {
const radius = camera.aspect < 1.05 ? 24 : 19;
cameraState.radius = cameraState.targetRadius = radius;
firstResize = false;
}
}
new ResizeObserver(resizeRenderer).observe(viewport);
resizeRenderer();
function updateCamera() {
cameraState.radius += (cameraState.targetRadius - cameraState.radius) * 0.1;
cameraState.theta += (cameraState.targetTheta - cameraState.theta) * 0.1;
cameraState.phi += (cameraState.targetPhi - cameraState.phi) * 0.1;
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);
}
const pointer = {
down: false,
moved: false,
x: 0,
y: 0
};
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointer.down = true;
pointer.moved = false;
pointer.x = event.clientX;
pointer.y = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!pointer.down) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
if (Math.abs(dx) + Math.abs(dy) > 4) pointer.moved = true;
cameraState.targetTheta -= dx * 0.006;
cameraState.targetPhi = THREE.MathUtils.clamp(
cameraState.targetPhi + dy * 0.0045,
0.48,
1.35
);
pointer.x = event.clientX;
pointer.y = event.clientY;
});
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
canvas.addEventListener("pointerup", (event) => {
pointer.down = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (!pointer.moved) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hit = raycaster.intersectObjects(binMeshes, false)[0];
if (hit?.object.userData.binId) {
selectedBinId = hit.object.userData.binId;
renderAll();
}
}
});
canvas.addEventListener("pointercancel", () => { pointer.down = false; });
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius + event.deltaY * 0.012,
10,
29
);
}, { passive: false });
// -----------------------------------------------------------------------
// Inventory model and UI
// -----------------------------------------------------------------------
const pendingTotal = () => batches.reduce((sum, batch) => sum + batch.remaining, 0);
const storedTotal = () => bins.reduce((sum, bin) => sum + bin.inventory, 0);
const activeDispatches = () => dispatches.filter((dispatch) => dispatch.status !== "completed");
const reservedFor = (binId) => activeDispatches()
.filter((dispatch) => dispatch.binId === binId)
.reduce((sum, dispatch) => sum + dispatch.quantity, 0);
const compatibleBins = (batch) => bins.filter((bin) => bin.accepts.includes(batch.type));
function eligibleTargets(batch) {
return compatibleBins(batch)
.map((bin) => ({
bin,
free: Math.max(0, bin.capacity - bin.inventory),
amount: Math.min(batch.remaining, Math.max(0, bin.capacity - bin.inventory))
}))
.filter((target) => target.amount > 0);
}
function renderHeader() {
const pending = pendingTotal();
const stored = storedTotal();
const reserved = activeDispatches().reduce((sum, dispatch) => sum + dispatch.quantity, 0);
$("#headerOnSite").textContent = `${formatT(pending + stored)} t`;
$("#headerPending").textContent = `${formatT(pending)} t`;
$("#headerReserved").textContent = `${formatT(reserved)} t`;
$("#pauseBtn").textContent = dispatchPaused ? "Auto-dispatch paused" : "Auto-dispatch on";
$("#pauseBtn").classList.toggle("active", !dispatchPaused);
}
function renderBatches() {
const container = $("#batchList");
const pendingBatches = batches.filter((batch) => batch.remaining > 0);
$("#pendingBatchCount").textContent = pendingBatches.length;
container.innerHTML = batches.map((batch) => {
const allocated = batch.original - batch.remaining;
const percent = (allocated / batch.original) * 100;
const selected = selectedBatchId === batch.id;
const closed = batch.remaining === 0;
return `
<button
class="batch-card ${selected ? "active" : ""} ${closed ? "closed" : ""}"
data-batch-id="${batch.id}"
>
<div class="batch-top">
<span class="batch-code">${batch.id} · ${batch.farm}</span>
<span class="batch-type">
<i class="grain-dot" style="--grain:${GRAIN[batch.type].css}"></i>
${GRAIN[batch.type].label}
</span>
</div>
<div class="batch-bottom">
<strong>${formatT(batch.remaining)} t pending</strong>
<span>${closed ? "Allocated" : `${formatT(batch.original)} t received`}</span>
</div>
<div class="thin-progress">
<i style="width:${percent}%"></i>
</div>
</button>
`;
}).join("");
}
function renderAllocation() {
const panel = $("#allocationPanel");
const batch = batches.find((item) => item.id === selectedBatchId);
if (!batch || batch.remaining <= 0) {
panel.innerHTML = `
<div class="allocation-box">
<div class="allocation-title">
<span>Allocate incoming grain</span>
<span>Select a batch above</span>
</div>
<div class="hint">Choose an incoming harvest batch to allocate compatible storage.</div>
</div>
`;
return;
}
const eligible = eligibleTargets(batch);
const selectedStillEligible = eligible.some((target) => target.bin.id === targetBinId);
if (!selectedStillEligible) {
targetBinId = eligible[0]?.bin.id || null;
}
const options = bins.map((bin) => {
const compatible = bin.accepts.includes(batch.type);
const free = Math.max(0, bin.capacity - bin.inventory);
if (!compatible) {
return `<option disabled value="${bin.id}">${bin.id} — incompatible grain</option>`;
}
if (free <= 0) {
return `<option disabled value="${bin.id}">${bin.id} — capacity full</option>`;
}
return `<option value="${bin.id}" ${targetBinId === bin.id ? "selected" : ""}>
${bin.id} · ${formatT(free)} t free
</option>`;
}).join("");
const target = eligible.find((item) => item.bin.id === targetBinId);
const maximum = target?.amount || 0;
const compatibleNames = compatibleBins(batch).map((bin) => bin.id).join(", ");
panel.innerHTML = `
<div class="allocation-box">
<div class="allocation-title">
<span>Allocate ${batch.id}</span>
<span>${formatT(batch.remaining)} t still pending</span>
</div>
<div class="field">
<label for="targetBin">Target bin</label>
<select id="targetBin">
${options}
</select>
</div>
<div class="field-row">
<div class="field">
<label for="allocAmount">Quantity</label>
<input id="allocAmount" type="number" min="1" max="${maximum}" step="1" value="${maximum}" />
</div>
<button class="primary-button" id="allocateBtn" ${maximum <= 0 ? "disabled" : ""}>
Allocate ${formatT(maximum)} t
</button>
</div>
<p class="hint">
Compatible bins: <strong>${compatibleNames}</strong>.
The quantity cannot exceed either the pending batch or free physical capacity.
</p>
</div>
`;
$("#targetBin").addEventListener("change", (event) => {
targetBinId = event.target.value;
const next = eligibleTargets(batch).find((item) => item.bin.id === targetBinId);
const nextMax = next?.amount || 0;
$("#allocAmount").max = nextMax;
$("#allocAmount").value = nextMax;
updateAllocationButton();
});
$("#allocAmount").addEventListener("input", updateAllocationButton);
$("#allocateBtn").addEventListener("click", allocateSelectedBatch);
}
function updateAllocationButton() {
const input = $("#allocAmount");
const button = $("#allocateBtn");
if (!input || !button) return;
const amount = Number(input.value);
const maximum = Number(input.max);
button.textContent = `Allocate ${formatT(Math.max(0, amount))} t`;
button.disabled = !Number.isFinite(amount) || amount <= 0 || amount > maximum;
}
function renderBinList() {
const container = $("#binList");
const totalCapacity = bins.reduce((sum, bin) => sum + bin.capacity, 0);
$("#totalCapacity").textContent = `${totalCapacity} t`;
container.innerHTML = bins.map((bin) => {
const reserved = reservedFor(bin.id);
const inventoryPercent = (bin.inventory / bin.capacity) * 100;
const reservedPercent = (reserved / bin.capacity) * 100;
const accepted = bin.accepts.map((type) => GRAIN[type].label).join(" / ");
const free = bin.capacity - bin.inventory;
return `
<button class="bin-row ${selectedBinId === bin.id ? "active" : ""}" data-bin-id="${bin.id}">
<div class="bin-row-top">
<strong>${bin.id} · ${bin.name}</strong>
<span>${accepted}</span>
</div>
<div class="bin-row-bottom">
<span>${formatT(bin.inventory)} / ${formatT(bin.capacity)} t stored</span>
<span>${formatT(free)} t free${reserved ? ` · ${formatT(reserved)} t reserved` : ""}</span>
</div>
<div class="capacity-track">
<i class="capacity-fill" style="width:${inventoryPercent}%"></i>
<i class="capacity-reserved" style="width:${reservedPercent}%"></i>
</div>
</button>
`;
}).join("");
}
function renderDischargePanel() {
const panel = $("#dischargePanel");
const bin = bins.find((item) => item.id === selectedBinId);
if (!bin) {
panel.innerHTML = "";
return;
}
const reserved = reservedFor(bin.id);
const available = Math.max(0, bin.inventory - reserved);
panel.innerHTML = `
<div class="discharge-box">
<div class="discharge-top">
<span>Schedule discharge · ${bin.id}</span>
<span>${formatT(available)} t schedulable</span>
</div>
<div class="field-row">
<div class="field">
<label for="dischargeAmount">Load-out quantity</label>
<input
id="dischargeAmount"
type="number"
min="1"
max="${available}"
step="1"
value="${available}"
${available <= 0 ? "disabled" : ""}
/>
</div>
<button class="secondary-button" id="scheduleBtn" ${available <= 0 ? "disabled" : ""}>
Schedule truck
</button>
</div>
<p class="hint">
<strong>${formatT(bin.inventory)} t</strong> remains physically stored.
<strong>${formatT(reserved)} t</strong> is already reserved, so only
<strong>${formatT(available)} t</strong> may be newly scheduled.
</p>
</div>
`;
$("#scheduleBtn").addEventListener("click", scheduleDischarge);
}
function renderQueue() {
const container = $("#dispatchQueue");
const active = activeDispatches();
$("#queueCount").textContent = active.length;
if (!active.length) {
container.innerHTML = `
<div class="empty">
No trucks scheduled. Select a bin and reserve a load-out quantity.
</div>
`;
return;
}
container.innerHTML = active.map((dispatch) => {
const bin = bins.find((item) => item.id === dispatch.binId);
return `
<div class="dispatch-card">
<div class="dispatch-top">
<strong>${dispatch.id} · ${formatT(dispatch.quantity)} t</strong>
<span>${bin.name}</span>
</div>
<div class="dispatch-bottom">
<small data-countdown="${dispatch.id}">Scheduled</small>
${dispatch.status === "scheduled"
? `<button data-release-id="${dispatch.id}">Send now</button>`
: `<span class="route-status">Rolling out</span>`}
</div>
<div class="dispatch-progress" data-progress-box="${dispatch.id}">
<i data-progress="${dispatch.id}"></i>
</div>
</div>
`;
}).join("");
updateQueueTimers();
}
function updateQueueTimers() {
const now = performance.now();
activeDispatches().forEach((dispatch) => {
const countdown = document.querySelector(`[data-countdown="${dispatch.id}"]`);
const progress = document.querySelector(`[data-progress="${dispatch.id}"]`);
if (!countdown || !progress) return;
if (dispatch.status === "scheduled") {
const seconds = Math.max(0, Math.ceil((dispatch.dueAt - now) / 1000));
countdown.textContent = dispatchPaused
? `Paused · ${seconds}s`
: `Due in ${seconds}s`;
const ratio = THREE.MathUtils.clamp(1 - (dispatch.dueAt - now) / 12000, 0, 1);
progress.style.width = `${ratio * 100}%`;
} else {
countdown.textContent = "Truck en route";
progress.style.width = "100%";
}
});
}
function renderLedger() {
const pending = pendingTotal();
const stored = storedTotal();
const reserved = activeDispatches().reduce((sum, dispatch) => sum + dispatch.quantity, 0);
const total = pending + stored + dispatched;
$("#ledgerPending").style.width = `${(pending / total) * 100}%`;
$("#ledgerStored").style.width = `${(stored / total) * 100}%`;
$("#ledgerDispatched").style.width = `${(dispatched / total) * 100}%`;
$("#legendPending").textContent = `${formatT(pending)} t`;
$("#legendStored").textContent = `${formatT(stored)} t`;
$("#legendDispatched").textContent = `${formatT(dispatched)} t`;
$("#ledgerEquation").textContent =
`${formatT(pending)} + ${formatT(stored)} + ${formatT(dispatched)} = ${formatT(total)} t`;
$("#ledgerNote").textContent =
`${formatT(reserved)} t scheduled is a subset of stored inventory; no grain is double-counted.`;
}
function updateSceneState() {
bins.forEach((bin) => {
const visual = binVisuals.get(bin.id);
const ratio = THREE.MathUtils.clamp(bin.inventory / bin.capacity, 0, 1);
const height = 1.88 * ratio;
visual.fill.scale.y = Math.max(0.001, height);
visual.fill.position.y = 0.51 + height / 2;
visual.ring.visible = selectedBinId === bin.id;
const label = binLabels.get(bin.id);
label.querySelector("span").textContent = `${formatT(bin.inventory)} / ${formatT(bin.capacity)} t`;
label.querySelector(".label-meter i").style.width = `${ratio * 100}%`;
});
batches.forEach((batch) => {
const ratio = batch.remaining / batch.original;
batch.truck.userData.cargo.visible = batch.remaining > 0;
batch.truck.userData.cargo.scale.y = 0.25 + ratio * 0.45;
});
}
function renderAll() {
renderHeader();
renderBatches();
renderAllocation();
renderBinList();
renderDischargePanel();
renderQueue();
renderLedger();
updateSceneState();
}
// -----------------------------------------------------------------------
// Conservation-safe operations
// -----------------------------------------------------------------------
function allocateSelectedBatch() {
const batch = batches.find((item) => item.id === selectedBatchId);
const bin = bins.find((item) => item.id === targetBinId);
const input = $("#allocAmount");
const quantity = Number(input?.value);
if (!batch || !bin || !Number.isFinite(quantity) || quantity <= 0) {
showToast("Enter a valid allocation quantity.");
return;
}
if (!bin.accepts.includes(batch.type)) {
showToast(`${bin.id} cannot store ${GRAIN[batch.type].label.toLowerCase()}.`);
return;
}
const free = bin.capacity - bin.inventory;
if (quantity > batch.remaining) {
showToast("Allocation exceeds the unallocated harvest batch.");
return;
}
if (quantity > free) {
showToast(`${bin.id} has only ${formatT(free)} t of free capacity.`);
return;
}
batch.remaining -= quantity;
bin.inventory += quantity;
animateAllocation(batch, bin, quantity);
if (batch.remaining <= 0.0001) {
const nextBatch = batches.find((item) => item.remaining > 0);
selectedBatchId = nextBatch?.id || null;
targetBinId = nextBatch
? eligibleTargets(nextBatch)[0]?.bin.id || null
: null;
}
renderAll();
showToast(`${formatT(quantity)} t allocated to ${bin.id}. Ledger remains balanced.`);
}
function scheduleDischarge() {
const bin = bins.find((item) => item.id === selectedBinId);
const input = $("#dischargeAmount");
const quantity = Number(input?.value);
if (!bin || !Number.isFinite(quantity) || quantity <= 0) {
showToast("Enter a valid discharge quantity.");
return;
}
const reserved = reservedFor(bin.id);
const available = bin.inventory - reserved;
if (quantity > available) {
showToast(`Only ${formatT(available)} t can be newly scheduled from ${bin.id}.`);
return;
}
dispatchSequence += 1;
dispatches.push({
id: `TR-${String(dispatchSequence).padStart(2, "0")}`,
binId: bin.id,
quantity,
status: "scheduled",
dueAt: performance.now() + 12000,
startedAt: null
});
renderAll();
showToast(`${formatT(quantity)} t reserved for dispatch from ${bin.id}.`);
}
function releaseDispatch(id, automatic = false) {
const dispatch = dispatches.find((item) => item.id === id);
if (!dispatch || dispatch.status !== "scheduled") return;
const bin = bins.find((item) => item.id === dispatch.binId);
if (!bin || bin.inventory < dispatch.quantity) {
dispatch.status = "completed";
renderAll();
showToast("Dispatch cancelled: inventory was no longer available.");
return;
}
dispatch.status = "enroute";
dispatch.startedAt = performance.now();
animateDispatchTruck(dispatch, bin);
renderAll();
if (!automatic) {
showToast(`${dispatch.id} released from ${bin.id}.`);
}
}
function completeDispatch(id) {
const dispatch = dispatches.find((item) => item.id === id);
if (!dispatch || dispatch.status === "completed") return;
const bin = bins.find((item) => item.id === dispatch.binId);
if (!bin || bin.inventory < dispatch.quantity) {
dispatch.status = "completed";
renderAll();
showToast("A dispatch could not be completed. Inventory was conserved.");
return;
}
bin.inventory -= dispatch.quantity;
dispatched += dispatch.quantity;
dispatch.status = "completed";
renderAll();
showToast(`${formatT(dispatch.quantity)} t departed ${bin.id}. Inventory transferred, not lost.`);
}
// -----------------------------------------------------------------------
// Scene animation effects
// -----------------------------------------------------------------------
function animateAllocation(batch, bin, quantity) {
const material = standardMaterial(GRAIN[batch.type].color, {
emissive: GRAIN[batch.type].color,
emissiveIntensity: 0.2
});
const mesh = new THREE.Mesh(
new THREE.OctahedronGeometry(0.22 + Math.min(0.12, quantity / 500), 0),
material
);
const from = batch.truck.position.clone();
from.y = 1.4;
const to = new THREE.Vector3(bin.position[0], 2.1, bin.position[2]);
mesh.position.copy(from);
scene.add(mesh);
effects.push({
type: "allocation",
mesh,
from,
to,
started: performance.now(),
duration: 1050
});
const pulse = new THREE.Mesh(
new THREE.RingGeometry(1.1, 1.23, 24),
new THREE.MeshBasicMaterial({
color: GRAIN[batch.type].color,
transparent: true,
opacity: 0.8,
side: THREE.DoubleSide
})
);
pulse.rotation.x = -Math.PI / 2;
pulse.position.set(bin.position[0], 0.14, bin.position[2]);
scene.add(pulse);
effects.push({
type: "pulse",
mesh: pulse,
started: performance.now(),
duration: 850
});
}
function animateDispatchTruck(dispatch, bin) {
const truck = createTruck(0x607d69);
const start = new THREE.Vector3(bin.position[0], 0, -0.35);
const first = new THREE.Vector3(bin.position[0], 0, 2.65);
const exit = new THREE.Vector3(9.5, 0, 4.75);
truck.position.copy(start);
scene.add(truck);
effects.push({
type: "truck",
mesh: truck,
start,
first,
exit,
started: performance.now(),
duration: 2800
});
setTimeout(() => completeDispatch(dispatch.id), 2850);
}
function updateEffects(now) {
effects = effects.filter((effect) => {
const t = THREE.MathUtils.clamp((now - effect.started) / effect.duration, 0, 1);
if (effect.type === "allocation") {
effect.mesh.position.lerpVectors(effect.from, effect.to, t);
effect.mesh.position.y += Math.sin(t * Math.PI) * 2.1;
effect.mesh.rotation.x += 0.08;
effect.mesh.rotation.y += 0.11;
effect.mesh.scale.setScalar(1 + Math.sin(t * Math.PI) * 0.35);
}
if (effect.type === "pulse") {
effect.mesh.scale.setScalar(1 + t * 1.5);
effect.mesh.material.opacity = (1 - t) * 0.8;
}
if (effect.type === "truck") {
if (t < 0.48) {
const local = t / 0.48;
effect.mesh.position.lerpVectors(effect.start, effect.first, local);
effect.mesh.rotation.y = -Math.PI / 2;
} else {
const local = (t - 0.48) / 0.52;
effect.mesh.position.lerpVectors(effect.first, effect.exit, local);
const dx = effect.exit.x - effect.first.x;
const dz = effect.exit.z - effect.first.z;
effect.mesh.rotation.y = -Math.atan2(dz, dx);
}
}
if (t >= 1) {
scene.remove(effect.mesh);
effect.mesh.geometry?.dispose?.();
if (Array.isArray(effect.mesh.material)) {
effect.mesh.material.forEach((material) => material.dispose());
} else {
effect.mesh.material?.dispose?.();
}
return false;
}
return true;
});
}
const labelPosition = new THREE.Vector3();
function updateLabels() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
bins.forEach((bin) => {
labelPosition.set(bin.position[0], 4.25, bin.position[2]).project(camera);
const x = (labelPosition.x * 0.5 + 0.5) * width;
const y = (-labelPosition.y * 0.5 + 0.5) * height;
const label = binLabels.get(bin.id);
label.style.left = `${x}px`;
label.style.top = `${y}px`;
label.style.visibility = labelPosition.z > 1 ? "hidden" : "visible";
});
}
// -----------------------------------------------------------------------
// Events
// -----------------------------------------------------------------------
$("#batchList").addEventListener("click", (event) => {
const card = event.target.closest("[data-batch-id]");
if (!card) return;
selectedBatchId = card.dataset.batchId;
const batch = batches.find((item) => item.id === selectedBatchId);
targetBinId = eligibleTargets(batch)[0]?.bin.id || null;
renderAll();
});
$("#binList").addEventListener("click", (event) => {
const row = event.target.closest("[data-bin-id]");
if (!row) return;
selectedBinId = row.dataset.binId;
renderAll();
});
$("#dispatchQueue").addEventListener("click", (event) => {
const button = event.target.closest("[data-release-id]");
if (!button) return;
releaseDispatch(button.dataset.releaseId);
});
$("#pauseBtn").addEventListener("click", () => {
dispatchPaused = !dispatchPaused;
renderHeader();
updateQueueTimers();
showToast(dispatchPaused
? "Automatic dispatch paused. Scheduled loads remain reserved."
: "Automatic dispatch resumed.");
});
$("#resetBtn").addEventListener("click", () => {
bins.forEach((bin) => { bin.inventory = bin.initial; });
batches.forEach((batch) => { batch.remaining = batch.original; });
dispatches.length = 0;
dispatched = 0;
dispatchSequence = 0;
dispatchPaused = false;
effects.forEach((effect) => scene.remove(effect.mesh));
effects = [];
selectedBatchId = "HR-101";
selectedBinId = "A-01";
targetBinId = "A-01";
renderAll();
showToast("Demo reset. All inventory and scheduled loads restored.");
});
// -----------------------------------------------------------------------
// Animation loop
// -----------------------------------------------------------------------
let lastQueueUpdate = 0;
function animate(now) {
requestAnimationFrame(animate);
updateCamera();
updateEffects(now);
if (!dispatchPaused) {
const due = dispatches.find((dispatch) =>
dispatch.status === "scheduled" && dispatch.dueAt <= now
);
if (due) releaseDispatch(due.id, true);
}
if (now - lastQueueUpdate > 250) {
updateQueueTimers();
lastQueueUpdate = now;
}
updateLabels();
renderer.render(scene, camera);
}
renderAll();
requestAnimationFrame(animate);
</script>
</body>
</html>
```