Prompt specification
Build or customize the Three.js 3D scene "Harvest logistics scheduling game" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Harvest logistics scheduling game
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/harvest-logistics-scheduling-game-x1076
Scene Description Prompt:
Make a low-poly toy orchard scheduling game with fictional picking rates, limited carts, and fruit inventories conserved throughout delivery. Three.js from cdnjs, one HTML file.
Working Three.js Starter (harvest-logistics-scheduling-game-x1076):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pocket Orchard</title>
<style>
:root {
--ink: #26343a;
--muted: #65777d;
--cream: #fffaf0;
--panel: rgba(255, 252, 242, 0.94);
--line: rgba(55, 74, 77, 0.14);
--green: #4f8d68;
--green-dark: #2f684d;
--sun: #ee6554;
--moon: #e6bd3e;
--star: #8b65c8;
--shadow: 0 14px 35px rgba(49, 70, 72, 0.17);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #cfe8ed;
font-family: ui-rounded, "Avenir Next", "Segoe UI", sans-serif;
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 12px;
left: 14px;
right: 14px;
height: 66px;
display: flex;
align-items: center;
gap: 14px;
padding: 10px 14px;
border: 1px solid rgba(255,255,255,.7);
border-radius: 18px;
background: rgba(255, 252, 242, .91);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.brand {
display: flex;
align-items: center;
gap: 10px;
min-width: 210px;
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
border-radius: 13px;
color: white;
background: var(--green);
font-size: 23px;
box-shadow: inset 0 -4px 0 rgba(0,0,0,.12);
}
.brand h1 {
margin: 0;
font-size: 20px;
letter-spacing: -.5px;
}
.brand small {
display: block;
margin-top: 1px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: .8px;
text-transform: uppercase;
}
.top-stat {
min-width: 92px;
padding-left: 14px;
border-left: 1px solid var(--line);
}
.top-stat span {
display: block;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .8px;
text-transform: uppercase;
}
.top-stat strong {
display: block;
margin-top: 2px;
font-size: 18px;
font-variant-numeric: tabular-nums;
}
.ledger {
flex: 1;
max-width: 520px;
min-width: 220px;
}
.ledger-title {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 6px;
font-size: 11px;
font-weight: 800;
}
#ledgerText { color: var(--muted); }
.ledger-bar {
height: 11px;
display: flex;
overflow: hidden;
border: 2px solid rgba(40,60,60,.12);
border-radius: 999px;
background: #e8ece6;
}
.ledger-bar i {
display: block;
height: 100%;
transition: width .2s ease;
}
#segTree { background: #77aa73; }
#segBasket { background: #f0a34a; }
#segPacked { background: #7f91c8; }
#segCart { background: #d47b9b; }
#segDelivered { background: #4b9b8f; }
.camera-buttons {
display: flex;
gap: 7px;
}
.small-button {
border: 1px solid var(--line);
border-radius: 11px;
padding: 8px 10px;
color: var(--ink);
background: rgba(255,255,255,.74);
cursor: pointer;
font-size: 11px;
font-weight: 800;
}
.small-button:hover { background: white; }
.panel {
position: fixed;
z-index: 9;
top: 90px;
bottom: 48px;
width: 304px;
overflow: auto;
padding: 15px;
border: 1px solid rgba(255,255,255,.8);
border-radius: 20px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(13px);
scrollbar-width: thin;
}
#leftPanel { left: 14px; }
#rightPanel { right: 14px; width: 326px; }
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 1px 0 9px;
font-size: 12px;
font-weight: 900;
letter-spacing: .65px;
text-transform: uppercase;
}
.panel-title .pill {
padding: 4px 7px;
border-radius: 999px;
color: var(--green-dark);
background: #e5f2e7;
font-size: 10px;
letter-spacing: 0;
text-transform: none;
}
.section {
margin-bottom: 17px;
}
.workers {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.worker {
position: relative;
min-height: 58px;
padding: 8px;
text-align: left;
border: 1px solid var(--line);
border-radius: 12px;
color: var(--ink);
background: rgba(255,255,255,.72);
cursor: pointer;
transition: .15s ease;
}
.worker:hover { transform: translateY(-1px); }
.worker.selected {
border-color: var(--green);
background: #eef8ec;
box-shadow: 0 0 0 2px rgba(79,141,104,.13);
}
.worker.busy { opacity: .72; }
.worker strong {
display: block;
font-size: 12px;
}
.worker small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.worker b {
position: absolute;
top: 8px;
right: 8px;
width: 8px;
height: 8px;
border-radius: 50%;
background: #72b985;
}
.worker.busy b { background: #f0a34a; }
.crop-card {
margin-bottom: 8px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,.7);
}
.crop-head {
display: flex;
align-items: center;
gap: 8px;
}
.fruit-dot {
flex: 0 0 auto;
width: 13px;
height: 13px;
border-radius: 45% 55% 48% 52%;
box-shadow: inset -2px -2px 0 rgba(0,0,0,.1);
}
.crop-head strong { font-size: 13px; }
.crop-meta {
display: flex;
justify-content: space-between;
gap: 8px;
margin: 6px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.assign-button, .send-button {
width: 100%;
padding: 7px 9px;
border: 0;
border-radius: 9px;
color: white;
background: var(--green);
cursor: pointer;
font-size: 11px;
font-weight: 900;
box-shadow: inset 0 -3px 0 rgba(0,0,0,.12);
}
.assign-button:hover, .send-button:hover:not(:disabled) {
background: var(--green-dark);
}
.ticket {
margin-bottom: 8px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,.72);
}
.ticket.done {
border-color: rgba(79,141,104,.35);
background: #eff8ed;
}
.ticket.late { border-color: rgba(220,100,75,.35); }
.ticket-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 900;
}
.ticket-head time {
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.progress {
height: 7px;
margin-top: 8px;
overflow: hidden;
border-radius: 999px;
background: #e5e9e3;
}
.progress > i {
display: block;
height: 100%;
border-radius: inherit;
background: var(--green);
transition: width .2s ease;
}
.ticket-foot {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.stock-list {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
}
.stock-item {
padding: 8px 4px;
border: 1px solid var(--line);
border-radius: 11px;
text-align: center;
background: rgba(255,255,255,.7);
}
.stock-item strong {
display: block;
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.stock-item span {
color: var(--muted);
font-size: 9px;
font-weight: 800;
}
.cart-card {
margin-bottom: 8px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255,255,255,.72);
}
.cart-head {
display: flex;
justify-content: space-between;
gap: 8px;
font-size: 12px;
font-weight: 900;
}
.cart-status {
margin: 4px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.send-button:disabled {
color: #899391;
background: #dfe5df;
cursor: not-allowed;
box-shadow: none;
}
.hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 10px;
transform: translateX(-50%);
max-width: calc(100vw - 700px);
padding: 8px 13px;
border: 1px solid rgba(255,255,255,.7);
border-radius: 999px;
color: #4e6267;
background: rgba(255,252,242,.84);
box-shadow: 0 7px 20px rgba(50,70,70,.12);
font-size: 10px;
font-weight: 750;
text-align: center;
pointer-events: none;
}
.modal {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
padding: 20px;
background: rgba(44, 67, 68, .28);
backdrop-filter: blur(7px);
}
.modal.hidden { display: none; }
.modal-card {
width: min(520px, 100%);
padding: 28px;
border: 1px solid rgba(255,255,255,.9);
border-radius: 25px;
background: var(--cream);
box-shadow: 0 28px 80px rgba(34,53,54,.28);
}
.modal-card h2 {
margin: 7px 0 8px;
font-size: clamp(28px, 5vw, 42px);
line-height: 1;
letter-spacing: -1.7px;
}
.modal-card p {
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
.eyebrow {
display: inline-block;
padding: 5px 9px;
border-radius: 999px;
color: var(--green-dark);
background: #e2f0df;
font-size: 10px;
font-weight: 900;
letter-spacing: .8px;
text-transform: uppercase;
}
.steps {
display: grid;
gap: 8px;
margin: 18px 0;
}
.step {
display: flex;
gap: 10px;
align-items: center;
padding: 9px 11px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255,255,255,.64);
font-size: 12px;
font-weight: 700;
}
.step b {
display: grid;
place-items: 0;
place-items: center;
flex: 0 0 25px;
height: 25px;
border-radius: 8px;
color: white;
background: var(--green);
font-size: 11px;
}
.primary {
width: 100%;
padding: 13px 16px;
border: 0;
border-radius: 13px;
color: white;
background: var(--green);
cursor: pointer;
font-weight: 900;
box-shadow: inset 0 -4px 0 rgba(0,0,0,.14);
}
.primary:hover { background: var(--green-dark); }
.end-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin: 20px 0;
}
.end-stat {
padding: 13px 8px;
border: 1px solid var(--line);
border-radius: 13px;
text-align: center;
background: white;
}
.end-stat strong {
display: block;
font-size: 23px;
}
.end-stat span {
color: var(--muted);
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
}
#toast {
position: fixed;
z-index: 50;
left: 50%;
top: 86px;
transform: translate(-50%, -15px);
max-width: 420px;
padding: 10px 15px;
border-radius: 999px;
color: white;
background: rgba(39,55,58,.94);
box-shadow: var(--shadow);
font-size: 12px;
font-weight: 800;
opacity: 0;
pointer-events: none;
transition: .2s ease;
text-align: center;
}
#toast.show {
transform: translate(-50%, 0);
opacity: 1;
}
@media (max-width: 900px) {
.topbar { gap: 8px; padding: 8px 10px; }
.brand { min-width: 170px; }
.brand h1 { font-size: 17px; }
.top-stat { min-width: 72px; padding-left: 9px; }
.ledger { min-width: 160px; }
.panel { width: 270px; padding: 11px; }
#rightPanel { width: 285px; }
.hint { display: none; }
}
@media (max-width: 680px) {
.topbar { height: 58px; }
.brand-mark { width: 34px; height: 34px; font-size: 18px; }
.brand { min-width: 145px; }
.brand small, .ledger-title, .camera-buttons { display: none; }
.ledger { min-width: 80px; }
.top-stat { min-width: 66px; }
.top-stat strong { font-size: 15px; }
.panel {
top: 78px;
bottom: 8px;
width: calc(50vw - 11px);
border-radius: 15px;
}
#leftPanel { left: 7px; }
#rightPanel { right: 7px; }
.workers { grid-template-columns: 1fr; }
.worker { min-height: 48px; }
.panel-title { font-size: 10px; }
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<header class="topbar">
<div class="brand">
<div class="brand-mark">♣</div>
<div>
<h1>Pocket Orchard</h1>
<small>Toy harvest scheduler</small>
</div>
</div>
<div class="top-stat">
<span>Shift closes</span>
<strong id="shiftTime">5:00</strong>
</div>
<div class="top-stat">
<span>Tickets</span>
<strong id="ticketCount">0 / 3</strong>
</div>
<div class="ledger">
<div class="ledger-title">
<span>Fruit conservation ledger</span>
<span id="ledgerText">510 / 510 accounted</span>
</div>
<div class="ledger-bar" id="ledgerBar">
<i id="segTree"></i>
<i id="segBasket"></i>
<i id="segPacked"></i>
<i id="segCart"></i>
<i id="segDelivered"></i>
</div>
</div>
<div class="camera-buttons">
<button class="small-button" id="resetCam">Reset view</button>
</div>
</header>
<aside class="panel" id="leftPanel">
<section class="section">
<div class="panel-title">
Pickers
<span class="pill">Select, then assign</span>
</div>
<div class="workers" id="workerList"></div>
</section>
<section class="section">
<div class="panel-title">
Orchard rows
<span class="pill">Fictional rates</span>
</div>
<div id="cropList"></div>
</section>
<section class="section">
<div class="panel-title">How packing works</div>
<div class="step">
<b>1</b>
<span>Each picker carries 24 fruit back to the packing shed.</span>
</div>
<div class="step" style="margin-top:7px">
<b>2</b>
<span>Dispatch a cart to carry packed fruit to the market.</span>
</div>
</section>
</aside>
<aside class="panel" id="rightPanel">
<section class="section">
<div class="panel-title">
Market tickets
<span class="pill">Auto-prioritized</span>
</div>
<div id="ticketList"></div>
</section>
<section class="section">
<div class="panel-title">Packed inventory</div>
<div class="stock-list" id="packedList"></div>
</section>
<section class="section">
<div class="panel-title">
Delivery carts
<span class="pill">3 available</span>
</div>
<div id="cartList"></div>
</section>
</aside>
<div class="hint">Drag to orbit · Shift/right-drag to pan · Scroll to zoom · Click a tree row to assign</div>
<div id="toast"></div>
<div class="modal" id="intro">
<div class="modal-card">
<span class="eyebrow">A five-minute toy shift</span>
<h2>Pocket Orchard</h2>
<p>
Schedule your little pickers, fill market tickets, and send the harvest
into town before the closing bell.
</p>
<div class="steps">
<div class="step"><b>1</b><span>Select a picker, then assign them to an orchard row.</span></div>
<div class="step"><b>2</b><span>Wait for fruit to return to the packing shed.</span></div>
<div class="step"><b>3</b><span>Load one of three limited carts and deliver it.</span></div>
</div>
<p style="font-size:12px">
Every picked fruit moves from tree → basket → packing shed → cart → market.
The conservation ledger proves that no fruit is created or lost.
</p>
<button class="primary" id="startBtn">Open the orchard</button>
</div>
</div>
<div class="modal hidden" id="endOverlay">
<div class="modal-card">
<span class="eyebrow">Shift complete</span>
<h2 id="endTitle">A fruitful day!</h2>
<p id="endCopy"></p>
<div class="end-stats" id="endStats"></div>
<button class="primary" id="restartBtn">Play another shift</button>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const SHIFT_DURATION = 300;
const BASKET_CAPACITY = 24;
const CART_CAPACITY = 70;
const crops = [
{
id: "sun",
name: "Sun apples",
short: "Sun",
color: 0xee6554,
css: "#ee6554",
initial: 180,
x: -6.2,
z: -2.25,
label: "SUN APPLES"
},
{
id: "moon",
name: "Moon pears",
short: "Moon",
color: 0xe6bd3e,
css: "#e6bd3e",
initial: 150,
x: 0,
z: -2.25,
label: "MOON PEARS"
},
{
id: "star",
name: "Star figs",
short: "Star",
color: 0x8b65c8,
css: "#8b65c8",
initial: 180,
x: 6.2,
z: -2.25,
label: "STAR FIGS"
}
];
const cropMap = Object.fromEntries(crops.map(c => [c.id, c]));
const workers = [
{ id: "pip", name: "Pip", rate: 54, specialty: "sun", color: 0xe76f51, x: -5.4, z: 4.1 },
{ id: "mox", name: "Mox", rate: 42, specialty: "moon", color: 0x5f91c5, x: -4.7, z: 4.5 },
{ id: "twig", name: "Twig", rate: 66, specialty: "star", color: 0x9168c4, x: -4.0, z: 4.1 },
{ id: "clove", name: "Clove", rate: 60, specialty: "sun", color: 0xe1b83e, x: -3.3, z: 4.5 }
];
const tickets = [
{ id: "sun", name: "Sun Pie Co.", need: 48, due: 150, fulfilled: false, coins: 96 },
{ id: "moon", name: "Moon Tea Cart", need: 40, due: 220, fulfilled: false, coins: 80 },
{ id: "star", name: "Star Preserves", need: 48, due: 285, fulfilled: false, coins: 96 }
];
const INITIAL_TOTAL = crops.reduce((sum, c) => sum + c.initial, 0);
const state = {
running: false,
elapsed: 0,
timeLeft: SHIFT_DURATION,
coins: 0,
selectedWorker: "pip",
selectedCrop: "sun",
ledgerOk: true,
ended: false,
ledger: Object.fromEntries(crops.map(c => [
c.id,
{ tree: c.initial, basket: 0, packed: 0, cart: 0, delivered: 0 }
]))
};
const carts = Array.from({ length: 3 }, (_, index) => ({
index,
state: "idle",
cargo: { sun: 0, moon: 0, star: 0 },
start: new THREE.Vector3(-3.9 + index * 2.25, 0, 5.75),
position: new THREE.Vector3(),
outboundPath: null,
returnPath: null,
progress: 0,
wheelSpin: 0
}));
// ---------- Three.js scene ----------
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xcfe8ed);
scene.fog = new THREE.Fog(0xcfe8ed, 27, 55);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const controls = {
target: new THREE.Vector3(0, 0.4, 0.2),
yaw: 0.58,
pitch: 0.78,
radius: 27
};
function updateCamera() {
const s = Math.sin(controls.pitch);
camera.position.set(
controls.target.x + controls.radius * s * Math.sin(controls.yaw),
controls.target.y + controls.radius * Math.cos(controls.pitch),
controls.target.z + controls.radius * s * Math.cos(controls.yaw)
);
camera.lookAt(controls.target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xeafaff, 0x6e8258, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff4d7, 3.2);
sun.position.set(-9, 18, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 17;
sun.shadow.camera.bottom = -17;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0005;
scene.add(sun);
const mat = (color, extra = {}) => new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
flatShading: true,
...extra
});
const materials = {
ground: mat(0x91b77a),
soil: mat(0x9b7352),
soilEdge: mat(0x76553f),
path: mat(0xd8c49d),
wood: mat(0x9a683f),
woodLight: mat(0xc4935b),
woodDark: mat(0x69462f),
trunk: mat(0x765139),
leafA: mat(0x5f985f),
leafB: mat(0x75a866),
leafC: mat(0x4f8659),
cream: mat(0xfff3d5),
roof: mat(0xb95f4c),
teal: mat(0x4b8c87),
pink: mat(0xd47a91),
metal: mat(0x59676a, { metalness: 0.25, roughness: 0.5 }),
black: mat(0x344247)
};
const fruitMaterials = Object.fromEntries(
crops.map(c => [c.id, mat(c.color)])
);
const world = new THREE.Group();
scene.add(world);
function addBox(parent, size, position, material, cast = true, receive = 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 = cast;
mesh.receiveShadow = receive;
parent.add(mesh);
return mesh;
}
function addCylinder(parent, radiusTop, radiusBottom, height, position, material, segments = 8) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function createLabel(text, background = "#fff3d5", foreground = "#33484a", width = 3.2) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, 512, 128);
ctx.strokeStyle = "rgba(40,60,60,.18)";
ctx.lineWidth = 8;
ctx.strokeRect(4, 4, 504, 120);
ctx.fillStyle = foreground;
ctx.font = "900 48px sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 67);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
}));
sprite.scale.set(width, width * 0.25, 1);
return sprite;
}
// Ground and paths.
addBox(world, [29, 0.55, 20], [0, -0.36, 0.5], materials.ground, false, true);
addBox(world, [24, 0.10, 1.8], [0, 0.01, 4.75], materials.path, false, true);
addBox(world, [2.0, 0.11, 9.0], [9.0, 0.015, 1.0], materials.path, false, true);
addBox(world, [19, 0.10, 0.75], [0.5, 0.02, -5.1], materials.path, false, true);
// Low fence along the back.
const fenceGroup = new THREE.Group();
world.add(fenceGroup);
for (let x = -9; x <= 9; x += 1.5) {
addBox(fenceGroup, [0.17, 1.0, 0.17], [x, 0.5, -5.35], materials.woodLight);
}
addBox(fenceGroup, [18.2, 0.13, 0.13], [0, 0.68, -5.35], materials.woodLight);
addBox(fenceGroup, [18.2, 0.13, 0.13], [0, 0.30, -5.35], materials.woodLight);
// Tree creation.
const fruitOffsets = [
[0.74, 0.18, 0.36],
[-0.70, 0.13, 0.38],
[0.32, -0.20, 0.76],
[-0.38, -0.24, 0.71],
[0.66, 0.63, -0.25],
[-0.63, 0.57, -0.36],
[0.08, 0.43, 0.91],
[-0.05, 0.86, -0.67],
[0.92, -0.05, -0.25],
[-0.90, -0.08, -0.22],
[0.15, -0.44, 0.68],
[-0.14, -0.43, -0.69]
];
function createTree(parent, localX, localZ, crop, variation = 0) {
const group = new THREE.Group();
group.position.set(localX, 0, localZ);
group.rotation.y = variation * 0.7;
parent.add(group);
addCylinder(group, 0.18, 0.25, 1.55, [0, 0.78, 0], materials.trunk, 6);
const canopy1 = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.05, 1),
variation % 2 ? materials.leafB : materials.leafA
);
canopy1.position.set(0, 2.0, 0);
canopy1.scale.set(1.0, 1.08, 0.93);
canopy1.castShadow = true;
canopy1.receiveShadow = true;
group.add(canopy1);
const canopy2 = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.72, 0),
variation % 2 ? materials.leafC : materials.leafB
);
canopy2.position.set(0.60, 1.72, 0.18);
canopy2.castShadow = true;
group.add(canopy2);
const canopy3 = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.67, 0),
materials.leafC
);
canopy3.position.set(-0.58, 1.78, -0.12);
canopy3.castShadow = true;
group.add(canopy3);
const fruits = [];
fruitOffsets.forEach(offset => {
const fruit = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.14, 0),
fruitMaterials[crop.id]
);
fruit.position.set(offset[0], 1.65 + offset[1], offset[2]);
fruit.castShadow = true;
group.add(fruit);
fruits.push(fruit);
});
return { group, fruits };
}
const patchHits = [];
const patchVisuals = {};
crops.forEach((crop, cropIndex) => {
const group = new THREE.Group();
group.position.set(crop.x, 0, crop.z);
world.add(group);
addBox(group, [4.85, 0.22, 4.35], [0, 0.03, 0], materials.soil);
addBox(group, [5.05, 0.14, 0.22], [0, 0.15, -2.12], materials.soilEdge);
addBox(group, [5.05, 0.14, 0.22], [0, 0.15, 2.12], materials.soilEdge);
addBox(group, [0.22, 0.14, 4.35], [-2.40, 0.15, 0], materials.soilEdge);
addBox(group, [0.22, 0.14, 4.35], [2.40, 0.15, 0], materials.soilEdge);
const treePositions = [
[-1.25, -0.70],
[0.95, -0.92],
[0.05, 1.05]
];
const trees = treePositions.map((p, i) => createTree(group, p[0], p[1], crop, i + cropIndex));
const label = createLabel(crop.label, crop.id === "sun" ? "#f8dfcf" : crop.id === "moon" ? "#f7edbd" : "#e8dcf5", "#354345", 3.4);
label.position.set(0, 3.65, -0.25);
group.add(label);
const ring = new THREE.Mesh(
new THREE.RingGeometry(2.47, 2.62, 40),
new THREE.MeshBasicMaterial({
color: crop.color,
transparent: true,
opacity: 0.72,
side: THREE.DoubleSide,
depthWrite: false
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(crop.x, 0.19, crop.z);
scene.add(ring);
const hit = new THREE.Mesh(
new THREE.BoxGeometry(4.9, 3.4, 4.4),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
})
);
hit.position.set(crop.x, 1.6, crop.z);
hit.userData.cropId = crop.id;
scene.add(hit);
patchHits.push(hit);
patchVisuals[crop.id] = {
group,
trees,
ring,
assigned: []
};
});
// Packing shed.
const shed = new THREE.Group();
shed.position.set(-8.0, 0, 6.0);
world.add(shed);
addBox(shed, [3.4, 0.25, 2.6], [0, 0.05, 0], materials.woodLight);
addBox(shed, [3.0, 2.2, 2.25], [0, 1.25, 0], materials.cream);
addBox(shed, [3.65, 0.35, 2.65], [0, 2.55, 0], materials.roof);
addBox(shed, [1.15, 1.45, 0.12], [0, 0.95, 1.16], materials.woodDark);
addBox(shed, [0.92, 0.78, 0.12], [-0.85, 1.55, 1.17], materials.teal);
addBox(shed, [0.92, 0.78, 0.12], [0.85, 1.55, 1.17], materials.teal);
const shedLabel = createLabel("PACKING SHED", "#fff3d5", "#425653", 3.5);
shedLabel.position.set(0, 2.95, 0.2);
shed.add(shedLabel);
// Packed fruit crates.
const packedVisual = new THREE.Group();
packedVisual.position.set(-7.15, 0, 4.35);
world.add(packedVisual);
const packedCrates = [];
for (let i = 0; i < 12; i++) {
const crate = new THREE.Group();
crate.position.set((i % 4) * 0.34 - 0.5, 0.05 + Math.floor(i / 4) * 0.24, 0);
packedVisual.add(crate);
addBox(crate, [0.28, 0.16, 0.25], [0, 0, 0], materials.woodLight);
const fruit = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.095, 0),
fruitMaterials.sun
);
fruit.position.y = 0.13;
crate.add(fruit);
packedCrates.push({ crate, fruit });
}
// Market stall.
const market = new THREE.Group();
market.position.set(9.15, 0, 5.65);
world.add(market);
addBox(market, [4.1, 0.25, 2.8], [0, 0.02, 0], materials.path);
addBox(market, [3.2, 1.25, 1.1], [0, 0.75, -0.25], materials.cream);
addBox(market, [3.6, 0.18, 1.45], [0, 1.48, 0], materials.woodLight);
for (const x of [-1.55, 1.55]) {
addBox(market, [0.16, 2.65, 0.16], [x, 1.3, -0.35], materials.wood);
}
for (let i = 0; i < 6; i++) {
const awningMat = i % 2 === 0 ? materials.roof : materials.cream;
addBox(
market,
[0.64, 0.15, 2.1],
[-1.6 + i * 0.64, 2.62, 0.15],
awningMat
);
}
const marketLabel = createLabel("MARKET", "#f7dfcf", "#4b4c3d", 3.0);
marketLabel.position.set(0, 3.22, 0);
market.add(marketLabel);
// Worker models.
function createWorker(worker) {
const group = new THREE.Group();
group.position.set(worker.x, 0, worker.z);
scene.add(group);
const shirt = mat(worker.color);
const skin = mat(0xf0c69d);
addCylinder(group, 0.18, 0.22, 0.52, [0, 0.68, 0], shirt, 7);
const head = new THREE.Mesh(new THREE.IcosahedronGeometry(0.23, 1), skin);
head.position.y = 1.12;
head.castShadow = true;
group.add(head);
addCylinder(group, 0.28, 0.28, 0.10, [0, 1.33, 0], materials.woodLight, 10);
const brim = addCylinder(group, 0.33, 0.33, 0.055, [0, 1.29, 0], materials.woodLight, 10);
brim.castShadow = true;
const armLeft = addCylinder(group, 0.065, 0.065, 0.48, [-0.27, 0.73, 0], shirt, 6);
const armRight = addCylinder(group, 0.065, 0.065, 0.48, [0.27, 0.73, 0], shirt, 6);
armLeft.rotation.z = -0.18;
armRight.rotation.z = 0.18;
addBox(group, [0.18, 0.28, 0.26], [-0.11, 0.18, 0], materials.black);
addBox(group, [0.18, 0.28, 0.26], [0.11, 0.18, 0], materials.black);
const basket = new THREE.Group();
basket.position.set(0, 0.50, 0.40);
group.add(basket);
addBox(basket, [0.40, 0.25, 0.28], [0, 0, 0], materials.woodLight);
const basketFruits = [];
for (let i = 0; i < 3; i++) {
const fruit = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.085, 0),
fruitMaterials.sun
);
fruit.position.set((i - 1) * 0.10, 0.16, 0);
basket.add(fruit);
basketFruits.push(fruit);
}
worker.group = group;
worker.armLeft = armLeft;
worker.armRight = armRight;
worker.basket = basket;
worker.basketFruits = basketFruits;
worker.state = "idle";
worker.basketCount = 0;
worker.basketCrop = null;
worker.patch = null;
worker.target = null;
worker.pickAccumulator = 0;
worker.walkPhase = 0;
}
workers.forEach(createWorker);
const workerRing = new THREE.Mesh(
new THREE.RingGeometry(0.36, 0.46, 28),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.9,
side: THREE.DoubleSide,
depthWrite: false
})
);
workerRing.rotation.x = -Math.PI / 2;
scene.add(workerRing);
// Cart models.
function createCart(cart) {
const group = new THREE.Group();
group.position.copy(cart.start);
scene.add(group);
addBox(group, [1.22, 0.16, 0.84], [0, 0.42, 0], materials.wood);
addBox(group, [1.14, 0.48, 0.10], [0, 0.68, -0.36], materials.woodLight);
addBox(group, [0.10, 0.48, 0.72], [-0.54, 0.68, 0], materials.woodLight);
addBox(group, [0.10, 0.48, 0.72], [0.54, 0.68, 0], materials.woodLight);
for (const x of [-0.56, 0.56]) {
for (const z of [-0.29, 0.29]) {
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.20, 0.20, 0.11, 10),
materials.black
);
wheel.rotation.z = Math.PI / 2;
wheel.position.set(x, 0.22, z);
wheel.castShadow = true;
group.add(wheel);
cart.wheels = cart.wheels || [];
cart.wheels.push(wheel);
}
}
addBox(group, [0.10, 0.10, 1.2], [-0.38, 0.62, 0.92], materials.woodDark);
addBox(group, [0.10, 0.10, 1.2], [0.38, 0.62, 0.92], materials.woodDark);
const cargoMeshes = [];
for (let i = 0; i < 12; i++) {
const fruit = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.105, 0),
fruitMaterials.sun
);
fruit.position.set(
(i % 4) * 0.22 - 0.33,
0.67 + Math.floor(i / 4) * 0.12,
i % 2 ? -0.13 : 0.13
);
fruit.castShadow = true;
group.add(fruit);
cargoMeshes.push(fruit);
}
cart.group = group;
cart.cargoMeshes = cargoMeshes;
}
carts.forEach(createCart);
// ---------- Exact inventory ledger ----------
function moveFruit(cropId, amount, from, to) {
if (amount <= 0) return;
const row = state.ledger[cropId];
if (row[from] < amount) {
state.ledgerOk = false;
console.error(`Ledger underflow: ${cropId}, ${from} → ${to}`);
return;
}
row[from] -= amount;
row[to] += amount;
checkLedger();
}
function checkLedger() {
let total = 0;
for (const crop of crops) {
const row = state.ledger[crop.id];
total += row.tree + row.basket + row.packed + row.cart + row.delivered;
}
if (total !== INITIAL_TOTAL) {
state.ledgerOk = false;
console.error(`Conservation failure: expected ${INITIAL_TOTAL}, found ${total}`);
}
}
function stageTotal(stage) {
return crops.reduce((sum, crop) => sum + state.ledger[crop.id][stage], 0);
}
// ---------- Scheduling ----------
function selectWorker(id) {
state.selectedWorker = id;
updateUI();
}
function effectiveRate(worker, cropId) {
return worker.rate * (worker.specialty === cropId ? 1.25 : 1);
}
function assignWorker(cropId) {
if (!state.running) {
toast("Start the shift before assigning pickers.");
return;
}
state.selectedCrop = cropId;
let worker = workers.find(w => w.id === state.selectedWorker);
if (!worker || worker.state !== "idle") {
worker = workers.find(w => w.state === "idle");
if (worker) state.selectedWorker = worker.id;
}
if (!worker) {
toast("Every picker is busy. Wait for one to return.");
return;
}
const visual = patchVisuals[cropId];
if (state.ledger[cropId].tree <= 0) {
toast("That row has been picked clean.");
return;
}
if (visual.assigned.length >= 2) {
toast("This row already has two pickers.");
return;
}
if (visual.assigned.includes(worker.id)) {
toast(`${worker.name} is already assigned to this row.`);
return;
}
const treeIndex = visual.trees.findIndex((_, index) =>
!visual.assigned.some(id => workers.find(w => w.id === id)?.targetTree === index)
);
const tree = visual.trees[treeIndex >= 0 ? treeIndex : 0];
const worldTreePosition = new THREE.Vector3();
tree.group.getWorldPosition(worldTreePosition);
worker.state = "toTree";
worker.patch = cropId;
worker.targetTree = treeIndex >= 0 ? treeIndex : 0;
worker.target = worldTreePosition.clone();
worker.basketCrop = cropId;
worker.pickAccumulator = 0;
visual.assigned.push(worker.id);
toast(`${worker.name} is heading to ${cropMap[cropId].name}.`);
updateUI();
}
function moveWorkerTowards(worker, target, speed, dt) {
const dx = target.x - worker.group.position.x;
const dz = target.z - worker.group.position.z;
const distance = Math.hypot(dx, dz);
if (distance < 0.10) return true;
const step = Math.min(distance, speed * dt);
worker.group.position.x += dx / distance * step;
worker.group.position.z += dz / distance * step;
worker.group.rotation.y = Math.atan2(dx, dz);
worker.walkPhase += dt * 10;
worker.group.position.y = Math.abs(Math.sin(worker.walkPhase)) * 0.055;
worker.armLeft.rotation.x = Math.sin(worker.walkPhase) * 0.55;
worker.armRight.rotation.x = -Math.sin(worker.walkPhase) * 0.55;
return false;
}
function updateWorkers(dt) {
for (const worker of workers) {
if (worker.state === "toTree") {
if (moveWorkerTowards(worker, worker.target, 3.2, dt)) {
worker.state = "picking";
}
} else if (worker.state === "picking") {
const cropId = worker.patch;
const rate = effectiveRate(worker, cropId);
worker.pickAccumulator += rate / 60 * dt;
let amount = Math.floor(worker.pickAccumulator);
worker.pickAccumulator -= amount;
const available = Math.min(
amount,
BASKET_CAPACITY - worker.basketCount,
state.ledger[cropId].tree
);
for (let i = 0; i < available; i++) {
moveFruit(cropId, 1, "tree", "basket");
worker.basketCount++;
}
worker.walkPhase += dt * 8;
worker.group.position.y = Math.abs(Math.sin(worker.walkPhase)) * 0.025;
worker.armLeft.rotation.x = -0.8 + Math.sin(worker.walkPhase) * 0.45;
worker.armRight.rotation.x = -0.8 - Math.sin(worker.walkPhase) * 0.45;
if (
worker.basketCount >= BASKET_CAPACITY ||
state.ledger[cropId].tree <= 0
) {
const packIndex = workers.indexOf(worker);
worker.state = "toPack";
worker.target = new THREE.Vector3(
-7.05 + (packIndex % 4) * 0.40,
0,
3.75
);
}
} else if (worker.state === "toPack") {
if (moveWorkerTowards(worker, worker.target, 3.2, dt)) {
const cropId = worker.patch;
while (worker.basketCount > 0) {
moveFruit(cropId, 1, "basket", "packed");
worker.basketCount--;
}
patchVisuals[cropId].assigned =
patchVisuals[cropId].assigned.filter(id => id !== worker.id);
worker.state = "idle";
worker.patch = null;
worker.basketCrop = null;
worker.target = null;
worker.group.position.y = 0;
worker.armLeft.rotation.x = 0;
worker.armRight.rotation.x = 0;
}
}
}
}
// ---------- Cart loading and delivery ----------
function outstandingFor(cropId) {
const ticket = tickets.find(t => t.id === cropId);
return Math.max(
0,
ticket.need -
state.ledger[cropId].delivered -
state.ledger[cropId].cart
);
}
function availableToLoad() {
return crops.reduce((sum, crop) => {
return sum + Math.min(
state.ledger[crop.id].packed,
outstandingFor(crop.id)
);
}, 0);
}
function sendCart(index) {
if (!state.running) {
toast("Start the shift before dispatching a cart.");
return;
}
const cart = carts[index];
if (cart.state !== "idle") {
toast("That cart is already on the road.");
return;
}
let capacity = CART_CAPACITY;
let loaded = 0;
while (capacity > 0) {
const candidates = crops
.filter(crop =>
state.ledger[crop.id].packed > 0 &&
outstandingFor(crop.id) > 0
)
.sort((a, b) => outstandingFor(b.id) - outstandingFor(a.id));
if (!candidates.length) break;
const crop = candidates[0];
const amount = Math.min(
capacity,
state.ledger[crop.id].packed,
outstandingFor(crop.id)
);
for (let i = 0; i < amount; i++) {
moveFruit(crop.id, 1, "packed", "cart");
cart.cargo[crop.id]++;
loaded++;
}
capacity -= amount;
}
if (loaded === 0) {
toast("There is no packed fruit ready for an outstanding ticket.");
return;
}
cart.state = "toMarket";
cart.progress = 0;
const start = cart.group.position.clone();
cart.outboundPath = [
start,
new THREE.Vector3(3.25, 0, 5.75),
new THREE.Vector3(6.8, 0, 5.75),
new THREE.Vector3(8.45, 0, 5.65)
];
toast(`Cart ${index + 1} loaded with ${loaded} fruit.`);
updateUI();
}
function samplePath(points, t) {
const segments = [];
let totalLength = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
segments.push({ a: points[i], b: points[i + 1], length });
totalLength += length;
}
let remaining = THREE.MathUtils.clamp(t, 0, 1) * totalLength;
for (const segment of segments) {
if (remaining <= segment.length) {
const alpha = segment.length ? remaining / segment.length : 0;
return segment.a.clone().lerp(segment.b, alpha);
}
remaining -= segment.length;
}
return points[points.length - 1].clone();
}
function deliverCart(cart) {
for (const crop of crops) {
const amount = cart.cargo[crop.id];
for (let i = 0; i < amount; i++) {
moveFruit(crop.id, 1, "cart", "delivered");
cart.cargo[crop.id]--;
}
}
for (const ticket of tickets) {
if (
!ticket.fulfilled &&
state.ledger[ticket.id].delivered >= ticket.need &&
state.elapsed <= ticket.due
) {
ticket.fulfilled = true;
state.coins += ticket.coins;
toast(`${ticket.name} is complete! +${ticket.coins} coins`);
}
}
cart.state = "returning";
cart.progress = 0;
cart.returnPath = [
new THREE.Vector3(8.45, 0, 5.65),
new THREE.Vector3(5.0, 0, 5.75),
cart.start.clone()
];
}
function updateCarts(dt) {
for (const cart of carts) {
if (cart.state === "toMarket") {
cart.progress += dt / 9.5;
const previous = cart.group.position.clone();
cart.group.position.copy(samplePath(cart.outboundPath, cart.progress));
const dx = cart.group.position.x - previous.x;
const dz = cart.group.position.z - previous.z;
if (Math.abs(dx) + Math.abs(dz) > 0.0001) {
cart.group.rotation.y = Math.atan2(dx, dz);
}
const distance = Math.hypot(dx, dz);
cart.wheelSpin += distance / 0.20;
if (cart.wheels) {
cart.wheels.forEach(wheel => wheel.rotation.x = cart.wheelSpin);
}
if (cart.progress >= 1) {
deliverCart(cart);
}
} else if (cart.state === "returning") {
cart.progress += dt / 9.5;
const previous = cart.group.position.clone();
cart.group.position.copy(samplePath(cart.returnPath, cart.progress));
const dx = cart.group.position.x - previous.x;
const dz = cart.group.position.z - previous.z;
if (Math.abs(dx) + Math.abs(dz) > 0.0001) {
cart.group.rotation.y = Math.atan2(dx, dz);
}
const distance = Math.hypot(dx, dz);
cart.wheelSpin += distance / 0.20;
if (cart.wheels) {
cart.wheels.forEach(wheel => wheel.rotation.x = cart.wheelSpin);
}
if (cart.progress >= 1) {
cart.state = "idle";
cart.group.position.copy(cart.start);
cart.progress = 0;
}
}
}
}
// ---------- Visual synchronization ----------
function updateTreeVisuals() {
for (const crop of crops) {
const visual = patchVisuals[crop.id];
const amount = state.ledger[crop.id].tree;
const totalSlots = Math.min(36, Math.ceil(amount / 10));
visual.trees.forEach((tree, treeIndex) => {
const start = Math.floor(treeIndex * totalSlots / 3);
const end = Math.floor((treeIndex + 1) * totalSlots / 3);
const visible = end - start;
tree.fruits.forEach((fruit, fruitIndex) => {
fruit.visible = fruitIndex < visible;
});
});
visual.ring.material.opacity =
state.selectedCrop === crop.id ? 0.85 : 0.18;
}
}
function updateWorkerVisuals() {
for (const worker of workers) {
const selected = state.selectedWorker === worker.id;
workerRing.position.set(
worker.group.position.x,
0.20,
worker.group.position.z
);
workerRing.visible = selected;
workerRing.material.opacity = 0.55 + Math.sin(performance.now() * 0.004) * 0.2;
worker.basket.visible = worker.basketCount > 0;
worker.basketFruits.forEach((fruit, index) => {
fruit.visible = index < Math.min(3, worker.basketCount);
fruit.material = fruitMaterials[worker.basketCrop || "sun"];
});
}
}
function updatePackedVisuals() {
const packedFruit = [];
for (const crop of crops) {
for (let i = 0; i < state.ledger[crop.id].packed; i++) {
packedFruit.push(crop.id);
}
}
packedCrates.forEach((entry, index) => {
entry.crate.visible = index < Math.ceil(packedFruit.length / 3);
if (index < packedFruit.length) {
entry.fruit.material = fruitMaterials[packedFruit[index]];
}
});
}
function updateCartVisuals() {
for (const cart of carts) {
const cargo = [];
for (const crop of crops) {
for (let i = 0; i < cart.cargo[crop.id]; i++) cargo.push(crop.id);
}
cart.cargoMeshes.forEach((mesh, index) => {
mesh.visible = index < cargo.length;
if (index < cargo.length) {
mesh.material = fruitMaterials[cargo[index]];
}
});
}
}
// ---------- UI ----------
let toastTimer;
function toast(message) {
$("toast").textContent = message;
$("toast").classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => $("toast").classList.remove("show"), 2200);
}
function formatTime(seconds) {
seconds = Math.max(0, Math.ceil(seconds));
const minutes = Math.floor(seconds / 60);
return `${minutes}:${String(seconds % 60).padStart(2, "0")}`;
}
function renderWorkers() {
$("workerList").innerHTML = workers.map(worker => {
const status = worker.state === "idle"
? "Ready"
: worker.state === "picking"
? "Picking"
: worker.state === "toPack"
? "Packing"
: "Walking";
return `
<button class="worker ${state.selectedWorker === worker.id ? "selected" : ""} ${worker.state !== "idle" ? "busy" : ""}"
data-worker="${worker.id}">
<b></b>
<strong>${worker.name}</strong>
<small>${worker.rate}/min · ${status}</small>
</button>
`;
}).join("");
}
function renderCrops() {
$("cropList").innerHTML = crops.map(crop => {
const visual = patchVisuals[crop.id];
const bestWorkers = workers
.filter(worker => worker.specialty === crop.id)
.map(worker => `${worker.name} ${Math.round(effectiveRate(worker, crop.id))}/min`)
.join(" · ");
return `
<article class="crop-card">
<div class="crop-head">
<span class="fruit-dot" style="background:${crop.css}"></span>
<strong>${crop.name}</strong>
</div>
<div class="crop-meta">
<span>${state.ledger[crop.id].tree} on trees</span>
<span>${visual.assigned.length}/2 pickers</span>
</div>
<div class="crop-meta" style="margin-top:-4px">
<span>${bestWorkers}</span>
</div>
<button class="assign-button" data-assign="${crop.id}">
Send selected picker
</button>
</article>
`;
}).join("");
}
function renderTickets() {
$("ticketList").innerHTML = tickets.map(ticket => {
const delivered = state.ledger[ticket.id].delivered;
const remaining = ticket.due - state.elapsed;
const late = !ticket.fulfilled && remaining <= 0;
const status = ticket.fulfilled
? "Delivered"
: late
? "Expired"
: `${formatTime(remaining)} left`;
return `
<div class="ticket ${ticket.fulfilled ? "done" : ""} ${late ? "late" : ""}">
<div class="ticket-head">
<span>${ticket.name}</span>
<time>${status}</time>
</div>
<div class="progress">
<i style="width:${Math.min(100, delivered / ticket.need * 100)}%;background:${cropMap[ticket.id].css}"></i>
</div>
<div class="ticket-foot">
<span>${cropMap[ticket.id].name}</span>
<span>${delivered} / ${ticket.need}</span>
</div>
</div>
`;
}).join("");
}
function renderPacked() {
$("packedList").innerHTML = crops.map(crop => `
<div class="stock-item">
<strong style="color:${crop.css}">${state.ledger[crop.id].packed}</strong>
<span>${crop.short}</span>
</div>
`).join("");
}
function renderCarts() {
const loadable = availableToLoad();
$("cartList").innerHTML = carts.map(cart => {
const cargoCount = cart.cargo.sun + cart.cargo.moon + cart.cargo.star;
const status = cart.state === "idle"
? "At the packing shed"
: cart.state === "toMarket"
? "Rolling to the market"
: "Returning empty";
const disabled = cart.state !== "idle" || loadable <= 0;
return `
<div class="cart-card">
<div class="cart-head">
<span>Cart ${cart.index + 1}</span>
<span>${cargoCount}/${CART_CAPACITY}</span>
</div>
<div class="cart-status">${status}</div>
<button class="send-button" data-send="${cart.index}" ${disabled ? "disabled" : ""}>
${cart.state === "idle" ? "Load & send" : "On the road"}
</button>
</div>
`;
}).join("");
}
function updateLedgerUI() {
const tree = stageTotal("tree");
const basket = stageTotal("basket");
const packed = stageTotal("packed");
const cart = stageTotal("cart");
const delivered = stageTotal("delivered");
const total = tree + basket + packed + cart + delivered;
$("segTree").style.width = `${tree / total * 100}%`;
$("segBasket").style.width = `${basket / total * 100}%`;
$("segPacked").style.width = `${packed / total * 100}%`;
$("segCart").style.width = `${cart / total * 100}%`;
$("segDelivered").style.width = `${delivered / total * 100}%`;
$("ledgerText").textContent =
`${total} / ${INITIAL_TOTAL} accounted${state.ledgerOk ? " · conserved" : " · ERROR"}`;
$("ledgerText").style.color = state.ledgerOk ? "" : "#c53e38";
}
function updateUI() {
$("shiftTime").textContent = formatTime(state.timeLeft);
$("ticketCount").textContent = `${tickets.filter(t => t.fulfilled).length} / ${tickets.length}`;
renderWorkers();
renderCrops();
renderTickets();
renderPacked();
renderCarts();
updateLedgerUI();
updateTreeVisuals();
updatePackedVisuals();
updateCartVisuals();
}
$("workerList").addEventListener("click", event => {
const button = event.target.closest("[data-worker]");
if (button) selectWorker(button.dataset.worker);
});
$("cropList").addEventListener("click", event => {
const button = event.target.closest("[data-assign]");
if (button) assignWorker(button.dataset.assign);
});
$("cartList").addEventListener("click", event => {
const button = event.target.closest("[data-send]");
if (button) sendCart(Number(button.dataset.send));
});
$("startBtn").addEventListener("click", () => {
state.running = true;
$("intro").classList.add("hidden");
toast("Shift started. Assign Pip to the Sun apples!");
});
$("restartBtn").addEventListener("click", () => location.reload());
$("resetCam").addEventListener("click", () => {
controls.target.set(0, 0.4, 0.2);
controls.yaw = 0.58;
controls.pitch = 0.78;
controls.radius = 27;
updateCamera();
});
// ---------- Direct camera controls ----------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let drag = null;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
drag = {
id: event.pointerId,
button: event.button,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false
};
});
canvas.addEventListener("pointermove", event => {
if (!drag || drag.id !== event.pointerId) return;
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
if (Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > 5) {
drag.moved = true;
}
if (drag.button === 2 || event.shiftKey) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = camera.getWorldDirection(new THREE.Vector3());
forward.y = 0;
forward.normalize();
const scale = controls.radius * 0.0014;
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(forward, dy * scale);
} else {
controls.yaw -= dx * 0.006;
controls.pitch = THREE.MathUtils.clamp(controls.pitch + dy * 0.004, 0.38, 1.22);
}
drag.lastX = event.clientX;
drag.lastY = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", event => {
if (!drag || drag.id !== event.pointerId) return;
if (!drag.moved && drag.button === 0) {
const rect = canvas.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 hits = raycaster.intersectObjects(patchHits, false);
if (hits.length) {
assignWorker(hits[0].object.userData.cropId);
}
}
drag = null;
});
canvas.addEventListener("pointercancel", () => drag = null);
canvas.addEventListener("wheel", event => {
event.preventDefault();
controls.radius = THREE.MathUtils.clamp(
controls.radius + event.deltaY * 0.018,
15,
39
);
updateCamera();
}, { passive: false });
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// ---------- End of shift ----------
function endGame() {
if (state.ended) return;
state.ended = true;
state.running = false;
const completed = tickets.filter(t => t.fulfilled).length;
const delivered = stageTotal("delivered");
$("endTitle").textContent =
completed === tickets.length ? "A fruitful day!" :
completed > 0 ? "A good harvest." : "The bell rang.";
$("endCopy").textContent =
completed === tickets.length
? "Every market ticket arrived on time. The little orchard is delighted."
: "The market stalls are closing, but your carefully conserved fruit is safe. Try assigning balanced teams and dispatching carts as soon as fruit is packed.";
$("endStats").innerHTML = `
<div class="end-stat"><strong>${completed}/3</strong><span>Tickets</span></div>
<div class="end-stat"><strong>${delivered}</strong><span>Delivered</span></div>
<div class="end-stat"><strong>${state.coins}</strong><span>Coins</span></div>
`;
$("endOverlay").classList.remove("hidden");
updateUI();
}
// ---------- Animation loop ----------
const clock = new THREE.Clock();
let uiAccumulator = 0;
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
if (state.running) {
state.elapsed = Math.min(SHIFT_DURATION, state.elapsed + dt);
state.timeLeft = SHIFT_DURATION - state.elapsed;
updateWorkers(dt);
updateCarts(dt);
if (state.elapsed >= SHIFT_DURATION) {
endGame();
}
}
updateWorkerVisuals();
updateTreeVisuals();
updatePackedVisuals();
updateCartVisuals();
uiAccumulator += dt;
if (uiAccumulator >= 0.16) {
uiAccumulator = 0;
updateUI();
}
renderer.render(scene, camera);
}
updateUI();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```