Prompt specification
Build or customize the Three.js 3D scene "Miniature Port Event Simulator" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Miniature Port Event Simulator
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/miniature-port-event-simulator-x3575
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows discrete-event timing independent of playback speed. Build an original port game with scheduled ships, finite berths, and cargo events. Drive state from a deterministic event queue while interpolation provides smooth visuals. Voxel style.
Working Three.js Starter (miniature-port-event-simulator-x3575):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cobalt Quay — Voxel Port Simulator</title>
<style>
:root {
--ink: #07141f;
--panel: rgba(8, 25, 37, 0.91);
--panel-solid: #0a2130;
--line: rgba(143, 212, 231, 0.17);
--text: #e6f5f6;
--muted: #86a8b4;
--cyan: #55d7e7;
--lime: #a9ed78;
--amber: #ffbd59;
--red: #ff7272;
--violet: #bc9cff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--ink);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
background:
radial-gradient(circle at 50% 20%, #16364a 0%, #081823 48%, #06111a 100%);
}
button {
font: inherit;
}
#stage, #stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
#stage canvas {
cursor: grab;
touch-action: none;
}
#stage canvas:active { cursor: grabbing; }
.panel {
position: absolute;
z-index: 5;
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.27);
backdrop-filter: blur(14px);
}
.eyebrow {
color: var(--cyan);
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
#topbar {
position: absolute;
z-index: 10;
top: 0;
left: 0;
right: 0;
height: 72px;
padding: 12px 18px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
background: linear-gradient(180deg, rgba(5, 18, 27, 0.97), rgba(5, 18, 27, 0.72));
border-bottom: 1px solid var(--line);
pointer-events: none;
}
#topbar > * { pointer-events: auto; }
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 250px;
}
.brand-icon {
width: 39px;
height: 39px;
position: relative;
background: var(--cyan);
border: 3px solid #173c4a;
box-shadow: 7px 7px 0 rgba(85, 215, 231, 0.18);
}
.brand-icon::before,
.brand-icon::after {
content: "";
position: absolute;
background: #123542;
}
.brand-icon::before {
width: 8px;
height: 25px;
left: 7px;
top: 4px;
}
.brand-icon::after {
width: 21px;
height: 7px;
left: 4px;
top: 8px;
box-shadow: 0 9px 0 #123542, 0 18px 0 #123542;
}
h1 {
margin: 1px 0 0;
font-size: 18px;
line-height: 1;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.brand-sub {
margin-top: 5px;
color: var(--muted);
font: 600 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
.stats {
display: flex;
align-items: center;
gap: 8px;
}
.stat {
min-width: 92px;
padding: 8px 12px;
background: rgba(10, 33, 48, 0.72);
border: 1px solid var(--line);
}
.stat small {
display: block;
margin-bottom: 3px;
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
.stat strong {
font: 800 16px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
color: var(--text);
}
.stat.score strong { color: var(--lime); }
.controls {
display: flex;
align-items: center;
gap: 6px;
}
.control {
height: 36px;
padding: 0 12px;
color: var(--muted);
background: #0b2636;
border: 1px solid var(--line);
cursor: pointer;
font: 800 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
}
.control:hover {
color: white;
border-color: rgba(85, 215, 231, 0.55);
}
.control.active {
color: #06202a;
background: var(--cyan);
border-color: var(--cyan);
}
#pause {
min-width: 84px;
color: var(--text);
}
#manifest {
top: 88px;
left: 18px;
width: 286px;
bottom: 120px;
display: flex;
flex-direction: column;
overflow: hidden;
}
#berths {
top: 88px;
right: 18px;
width: 306px;
bottom: 120px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.panel-head {
padding: 16px 16px 13px;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid var(--line);
}
.panel-head h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.count {
min-width: 24px;
height: 20px;
padding: 0 6px;
display: grid;
place-items: center;
color: var(--cyan);
background: rgba(85, 215, 231, 0.09);
border: 1px solid rgba(85, 215, 231, 0.2);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.panel-scroll {
padding: 10px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #285366 transparent;
}
.ship-card {
position: relative;
margin-bottom: 8px;
padding: 12px;
background: rgba(17, 46, 61, 0.58);
border: 1px solid rgba(139, 207, 222, 0.12);
cursor: pointer;
transition: border-color 120ms, background 120ms, transform 120ms;
}
.ship-card:hover {
background: rgba(24, 61, 77, 0.8);
transform: translateX(2px);
}
.ship-card.selected {
border-color: var(--cyan);
background: rgba(27, 78, 93, 0.75);
box-shadow: inset 4px 0 0 var(--cyan);
}
.ship-card::after {
content: "";
position: absolute;
top: 13px;
right: 13px;
width: 8px;
height: 8px;
background: var(--muted);
}
.ship-card.selected::after {
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.ship-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.ship-name {
font-size: 12px;
font-weight: 850;
letter-spacing: 0.06em;
}
.ship-eta {
color: var(--cyan);
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: nowrap;
}
.ship-meta {
margin-top: 6px;
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
.badge {
padding: 4px 5px;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
border: 1px solid rgba(255, 255, 255, 0.07);
}
.badge.general { color: #b7eaf1; }
.badge.bulk { color: var(--amber); }
.badge.reefer { color: var(--lime); }
.cargo-chips {
margin-top: 9px;
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.cargo-chip {
padding: 4px 5px;
color: #a9c1ca;
background: rgba(0, 0, 0, 0.14);
font: 600 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
.cargo-chip.done { color: var(--lime); }
.cargo-chip.ready { color: var(--amber); }
.cargo-chip.working { color: var(--cyan); }
.cargo-chip.late { color: var(--red); }
.berth-card {
margin-bottom: 10px;
padding: 12px;
background: rgba(17, 46, 61, 0.62);
border: 1px solid rgba(139, 207, 222, 0.12);
}
.berth-title {
display: flex;
align-items: center;
gap: 9px;
}
.berth-code {
width: 34px;
height: 34px;
display: grid;
place-items: center;
color: #06202a;
background: var(--berth-color);
font: 900 15px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.berth-name {
font-size: 11px;
font-weight: 850;
letter-spacing: 0.06em;
}
.berth-state {
margin-top: 3px;
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
.cargo-track {
margin: 11px 0 10px;
display: flex;
gap: 5px;
}
.cargo-dot {
height: 6px;
flex: 1;
background: rgba(255, 255, 255, 0.1);
}
.cargo-dot.future { background: #476471; }
.cargo-dot.ready { background: var(--amber); box-shadow: 0 0 8px rgba(255, 189, 89, 0.45); }
.cargo-dot.working { background: var(--cyan); box-shadow: 0 0 8px rgba(85, 215, 231, 0.55); }
.cargo-dot.done { background: var(--lime); }
.cargo-dot.late { background: var(--red); }
.action {
width: 100%;
height: 34px;
color: var(--text);
background: rgba(85, 215, 231, 0.08);
border: 1px solid rgba(85, 215, 231, 0.23);
cursor: pointer;
font: 850 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.action:hover {
color: #06202a;
background: var(--cyan);
border-color: var(--cyan);
}
.action.work {
color: #1a1200;
background: var(--amber);
border-color: var(--amber);
}
.action.busy {
color: var(--muted);
cursor: wait;
}
#timeline {
left: 322px;
right: 342px;
bottom: 18px;
min-height: 84px;
padding: 11px 14px;
}
.timeline-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 9px;
}
.timeline-note {
color: var(--muted);
font: 700 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
#event-strip {
display: flex;
gap: 7px;
overflow-x: auto;
scrollbar-width: none;
}
.event-chip {
flex: 0 0 auto;
min-width: 115px;
padding: 7px 9px;
background: rgba(0, 0, 0, 0.18);
border-left: 3px solid var(--cyan);
}
.event-chip.deadline { border-left-color: var(--red); }
.event-chip.arrival { border-left-color: var(--amber); }
.event-chip.depart { border-left-color: var(--violet); }
.event-time {
color: var(--muted);
font: 700 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.event-name {
margin-top: 4px;
font-size: 9px;
font-weight: 800;
white-space: nowrap;
}
#log {
position: absolute;
z-index: 4;
left: 18px;
bottom: 18px;
width: 286px;
padding: 9px 11px;
color: var(--muted);
background: rgba(5, 20, 29, 0.77);
border: 1px solid var(--line);
font: 700 9px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
}
#log div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#log div:first-child { color: var(--text); }
#toast {
position: absolute;
z-index: 30;
left: 50%;
top: 88px;
max-width: 520px;
padding: 11px 16px;
color: var(--text);
background: rgba(8, 29, 40, 0.97);
border: 1px solid var(--cyan);
box-shadow: 0 10px 35px rgba(0, 0, 0, 0.3);
transform: translate(-50%, -15px);
opacity: 0;
pointer-events: none;
transition: opacity 160ms, transform 160ms;
font: 750 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.good { border-color: var(--lime); }
#toast.warn { border-color: var(--amber); }
#toast.bad { border-color: var(--red); }
#help {
position: absolute;
z-index: 3;
left: 50%;
bottom: 111px;
transform: translateX(-50%);
padding: 7px 11px;
color: rgba(205, 230, 235, 0.72);
background: rgba(5, 20, 29, 0.56);
border: 1px solid rgba(255, 255, 255, 0.06);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
pointer-events: none;
}
#end-modal {
position: absolute;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: rgba(3, 11, 17, 0.78);
backdrop-filter: blur(8px);
}
#end-modal.hidden { display: none; }
.end-card {
width: min(430px, calc(100% - 32px));
padding: 30px;
background: #0a2231;
border: 1px solid rgba(85, 215, 231, 0.4);
box-shadow: 14px 14px 0 rgba(85, 215, 231, 0.08);
text-align: center;
}
.end-card h2 {
margin: 8px 0 4px;
font-size: 25px;
letter-spacing: 0.08em;
}
.end-card p {
color: var(--muted);
font-size: 12px;
line-height: 1.6;
}
#end-score {
margin: 20px 0;
color: var(--lime);
font: 900 42px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.end-card button {
width: 100%;
height: 42px;
color: #06202a;
background: var(--cyan);
border: 0;
cursor: pointer;
font-weight: 900;
letter-spacing: 0.08em;
}
#loading {
position: absolute;
z-index: 60;
inset: 0;
display: grid;
place-items: center;
color: var(--cyan);
background: #07141f;
font: 800 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
}
@media (max-width: 1000px) {
.stat { min-width: 74px; padding-inline: 8px; }
.brand { min-width: 210px; }
#timeline { display: none; }
#help { bottom: 20px; }
}
@media (max-width: 760px) {
#topbar { height: auto; min-height: 72px; flex-wrap: wrap; }
.brand { min-width: auto; }
.stats { order: 3; width: 100%; }
.stat { flex: 1; }
#manifest, #berths {
top: 126px;
bottom: 52px;
width: calc(50% - 14px);
}
#manifest { left: 8px; }
#berths { right: 8px; }
#log { display: none; }
#help { display: none; }
.ship-card, .berth-card { padding: 9px; }
.ship-name { font-size: 10px; }
.cargo-chips { display: none; }
}
</style>
</head>
<body>
<div id="stage"></div>
<header id="topbar">
<div class="brand">
<div class="brand-icon"></div>
<div>
<div class="eyebrow">Discrete harbor operations</div>
<h1>Cobalt Quay</h1>
<div class="brand-sub">TIDEFORGE TERMINAL // SHIFT 01</div>
</div>
</div>
<div class="stats">
<div class="stat">
<small>Port time</small>
<strong id="clock">08:00</strong>
</div>
<div class="stat score">
<small>Score</small>
<strong id="score">0000</strong>
</div>
<div class="stat">
<small>Loads</small>
<strong id="loads">0</strong>
</div>
</div>
<div class="controls">
<button class="control" id="pause" title="Pause or resume the simulation clock">Ⅱ PAUSE</button>
<button class="control speed active" data-speed="1">1×</button>
<button class="control speed" data-speed="2">2×</button>
<button class="control speed" data-speed="4">4×</button>
</div>
</header>
<section class="panel" id="manifest">
<div class="panel-head">
<div>
<div class="eyebrow">Incoming fleet</div>
<h2>Inbound manifest</h2>
</div>
<div class="count" id="manifest-count">0</div>
</div>
<div class="panel-scroll" id="manifest-list"></div>
</section>
<section class="panel" id="berths">
<div class="panel-head">
<div>
<div class="eyebrow">Finite capacity</div>
<h2>Berth control</h2>
</div>
<div class="count">3</div>
</div>
<div class="panel-scroll" id="berth-list"></div>
</section>
<section class="panel" id="timeline">
<div class="timeline-head">
<div class="eyebrow">Deterministic event queue</div>
<div class="timeline-note">DEADLINES USE SIM TIME — NOT WALL TIME</div>
</div>
<div id="event-strip"></div>
</section>
<div id="log"></div>
<div id="help">SELECT A SHIP → RESERVE A MATCHING BERTH → WORK EACH AMBER CARGO EVENT · KEYS 1 / 2 / 3</div>
<div id="toast"></div>
<div id="end-modal" class="hidden">
<div class="end-card">
<div class="eyebrow">Shift complete</div>
<h2>QUAY CLOSED</h2>
<p id="end-summary"></p>
<div id="end-score">0</div>
<button id="restart">RESTART SHIFT</button>
</div>
</div>
<div id="loading">BUILDING COBALT QUAY…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Deterministic utilities and simulation data
// -------------------------------------------------------------------------
const $ = id => document.getElementById(id);
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const smooth = t => t * t * (3 - 2 * t);
const FIXED_DT = 1 / 30;
const SHIFT_LENGTH = 120;
function mulberry32(seed) {
return function () {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
class EventQueue {
constructor() {
this.heap = [];
this.sequence = 0;
}
schedule(type, at, data = {}) {
const event = { type, at, data, sequence: this.sequence++ };
this.heap.push(event);
let i = this.heap.length - 1;
while (i > 0) {
const parent = (i - 1) >> 1;
if (this.before(this.heap[i], this.heap[parent])) {
[this.heap[i], this.heap[parent]] = [this.heap[parent], this.heap[i]];
i = parent;
} else break;
}
}
before(a, b) {
return a.at < b.at || (a.at === b.at && a.sequence < b.sequence);
}
pop() {
if (!this.heap.length) return null;
const first = this.heap[0];
const last = this.heap.pop();
if (this.heap.length) {
this.heap[0] = last;
let i = 0;
while (true) {
const left = i * 2 + 1;
const right = left + 1;
let smallest = i;
if (left < this.heap.length && this.before(this.heap[left], this.heap[smallest])) smallest = left;
if (right < this.heap.length && this.before(this.heap[right], this.heap[smallest])) smallest = right;
if (smallest === i) break;
[this.heap[i], this.heap[smallest]] = [this.heap[smallest], this.heap[i]];
i = smallest;
}
}
return first;
}
process(now, handler) {
while (this.heap.length && this.heap[0].at <= now + 1e-8) {
handler(this.pop());
}
}
all() {
return [...this.heap].sort((a, b) => this.before(a, b) ? -1 : 1);
}
}
const rng = mulberry32(0xC0BA17);
const visualRng = mulberry32(0x51A9E);
const templates = [
{
name: "MOSS KESTREL", category: "reefer", hull: 0x2b6c68,
lots: [
["Orchard crates", 0x91d878, 2.2, 80],
["Chilled citrus", 0xf3bd55, 2.4, 90],
["Seed drums", 0x8bc9c5, 2.8, 100]
]
},
{
name: "CINDER GULL", category: "bulk", hull: 0x754e42,
lots: [
["Ore voxels", 0x9e7c62, 2.2, 75],
["Grain sacks", 0xd5b668, 2.4, 85],
["Salt blocks", 0xdce5df, 2.8, 95]
]
},
{
name: "PAPER TERN", category: "general", hull: 0x345c7d,
lots: [
["Machinery", 0xe29a55, 2.2, 90],
["Textile bales", 0xc77972, 2.4, 95],
["Solar cells", 0x609fd1, 2.8, 115]
]
},
{
name: "VERDANT LYNX", category: "reefer", hull: 0x3d7253,
lots: [
["Mint leaves", 0x72dca0, 2.2, 85],
["Berry crates", 0xbd6a9f, 2.4, 100],
["Root cells", 0xbaa56f, 2.8, 105]
]
},
{
name: "ORE MANTIS", category: "bulk", hull: 0x65504c,
lots: [
["Iron chunks", 0x9b9690, 2.2, 80],
["Coal sacks", 0x565b63, 2.4, 90],
["Clay blocks", 0xb77d61, 2.8, 100]
]
},
{
name: "COPPER FINCH", category: "general", hull: 0x6d493c,
lots: [
["Wire reels", 0xc88952, 2.2, 90],
["Circuit boxes", 0x75a7bc, 2.4, 105],
["Robot crates", 0x9d8ccc, 2.8, 125]
]
},
{
name: "SALT HARBOR", category: "bulk", hull: 0x526b6d,
lots: [
["Sea salt", 0xdce9e5, 2.2, 85],
["Gravel", 0x9d947f, 2.4, 90],
["Alumina", 0xc2b8a8, 2.8, 110]
]
},
{
name: "AMBER SWIFT", category: "reefer", hull: 0x806037,
lots: [
["Juice drums", 0xe0a646, 2.2, 90],
["Spice crates", 0xcf7257, 2.4, 100],
["Flower boxes", 0xce7eab, 2.8, 115]
]
}
];
const berths = [
{ id: 0, code: "A", name: "General quay", accepts: ["general", "bulk", "reefer"], color: "#55d7e7", x: -7, shipId: null, job: null },
{ id: 1, code: "B", name: "Bulk dock", accepts: ["bulk"], color: "#ffbd59", x: 0, shipId: null, job: null },
{ id: 2, code: "C", name: "Cold store", accepts: ["reefer"], color: "#a9ed78", x: 7, shipId: null, job: null }
];
const queue = new EventQueue();
const ships = [];
const shipById = new Map();
templates.forEach((template, index) => {
const jitter = (rng() - 0.5) * 1.25;
const arrivalAt = 6 + index * 12 + jitter;
const spec = {
...template,
id: index + 1,
arrivalAt,
lane: index % 4,
approach: new THREE.Vector3(-10.5 + (index % 4) * 6.6, 0.08, 11.5 + (index % 2) * 2.2)
};
const ship = {
id: spec.id,
spec,
name: spec.name,
category: spec.category,
status: "upcoming",
assignedBerth: null,
arrivalAt: spec.arrivalAt,
dockAt: null,
approachStart: spec.arrivalAt,
departureAt: null,
departScheduled: false,
completed: 0,
missed: 0,
cargo: spec.lots.map(lot => ({
name: lot[0],
color: lot[1],
duration: lot[2],
reward: lot[3],
status: "locked",
readyAt: null,
deadline: null
})),
position: spec.approach.clone(),
previousPosition: spec.approach.clone(),
dockPosition: new THREE.Vector3(),
exitPosition: new THREE.Vector3()
};
ships.push(ship);
shipById.set(ship.id, ship);
queue.schedule("ARRIVE", ship.arrivalAt, { shipId: ship.id });
});
queue.schedule("SHIFT_END", SHIFT_LENGTH);
let simulationTime = 0;
let accumulator = 0;
let score = 0;
let totalLoads = 0;
let playbackSpeed = 1;
let paused = false;
let ended = false;
let selectedShipId = ships[0].id;
let toastTimer = 0;
let logEntries = [];
// -------------------------------------------------------------------------
// Interface construction
// -------------------------------------------------------------------------
const shipElements = new Map();
const berthElements = new Map();
for (const ship of ships) {
const element = document.createElement("article");
element.className = "ship-card";
element.tabIndex = 0;
element.innerHTML = `
<div class="ship-row">
<div class="ship-name">${ship.name}</div>
<div class="ship-eta"></div>
</div>
<div class="ship-meta">
<span class="badge ${ship.category}">${ship.category}</span>
<span class="ship-status"></span>
</div>
<div class="cargo-chips"></div>
`;
element.addEventListener("click", () => selectShip(ship.id));
element.addEventListener("keydown", event => {
if (event.key === "Enter" || event.key === " ") selectShip(ship.id);
});
$("manifest-list").appendChild(element);
shipElements.set(ship.id, element);
}
for (const berth of berths) {
const element = document.createElement("article");
element.className = "berth-card";
element.style.setProperty("--berth-color", berth.color);
element.innerHTML = `
<div class="berth-title">
<div class="berth-code">${berth.code}</div>
<div>
<div class="berth-name">${berth.name.toUpperCase()}</div>
<div class="berth-state"></div>
</div>
</div>
<div class="cargo-track"></div>
<button class="action"></button>
`;
const button = element.querySelector("button");
button.addEventListener("click", () => berthAction(berth.id));
$("berth-list").appendChild(element);
berthElements.set(berth.id, {
root: element,
state: element.querySelector(".berth-state"),
track: element.querySelector(".cargo-track"),
button
});
}
function selectShip(id) {
const ship = shipById.get(id);
if (!ship || ship.status === "done") return;
selectedShipId = id;
showToast(`${ship.name} selected. Choose a compatible berth.`, "good");
updateUI();
}
function tryReserve(shipId, berthId) {
const ship = shipById.get(shipId);
const berth = berths[berthId];
if (!ship || ship.status === "docked" || ship.status === "departing") {
showToast("That vessel can no longer be reassigned.", "warn");
return;
}
if (ship.assignedBerth !== null) {
showToast(`${ship.name} is already assigned to berth ${berths[ship.assignedBerth].code}.`, "warn");
return;
}
if (berth.shipId !== null) {
showToast(`Berth ${berth.code} is occupied.`, "bad");
return;
}
if (!berth.accepts.includes(ship.category)) {
showToast(`${berth.name} cannot handle ${ship.category} cargo.`, "bad");
return;
}
ship.assignedBerth = berthId;
berth.shipId = ship.id;
ship.departScheduled = false;
ship.dockPosition.set(berth.x, 0.08, 0.25);
ship.exitPosition.set(berth.x, 0.08, 15);
if (ship.status === "waiting") {
ship.status = "inbound";
ship.approachStart = simulationTime;
ship.dockAt = simulationTime + 4.2;
} else {
ship.status = "reserved";
ship.approachStart = ship.arrivalAt;
ship.dockAt = ship.arrivalAt + 4.5;
}
const delays = [0.8, 3.0, 5.2];
ship.cargo = ship.cargo.map((lot, index) => ({
...lot,
status: "future",
readyAt: ship.dockAt + delays[index],
deadline: ship.dockAt + delays[index] + 10
}));
queue.schedule("DOCK", ship.dockAt, { shipId: ship.id });
ship.cargo.forEach((lot, index) => {
queue.schedule("CARGO_READY", lot.readyAt, { shipId: ship.id, lotIndex: index });
queue.schedule("CARGO_DEADLINE", lot.deadline, { shipId: ship.id, lotIndex: index });
});
queue.schedule("BERTH_REVIEW", ship.dockAt + 24, { shipId: ship.id });
score += 10;
addLog(`${ship.name} reserved for berth ${berth.code}.`);
showToast(`${ship.name} assigned to berth ${berth.code}.`, "good");
updateUI();
}
function startCargo(berthId) {
const berth = berths[berthId];
if (!berth.shipId) {
showToast("Select an inbound vessel before reserving a berth.", "warn");
return;
}
if (berth.job) {
showToast(`Crane ${berth.code} is already handling cargo.`, "warn");
return;
}
const ship = shipById.get(berth.shipId);
const lotIndex = ship.cargo.findIndex(lot => lot.status === "ready");
if (lotIndex < 0) {
showToast("No cargo event is ready at this berth.", "warn");
return;
}
const lot = ship.cargo[lotIndex];
lot.status = "working";
berth.job = {
shipId: ship.id,
lotIndex,
startedAt: simulationTime,
endsAt: simulationTime + lot.duration
};
queue.schedule("CARGO_COMPLETE", berth.job.endsAt, {
shipId: ship.id,
lotIndex,
berthId
});
addLog(`Crane ${berth.code}: ${lot.name} handling started.`);
showToast(`Handling ${lot.name}.`, "good");
updateUI();
}
function berthAction(berthId) {
const berth = berths[berthId];
if (!berth.shipId && selectedShipId !== null) {
tryReserve(selectedShipId, berthId);
} else if (berth.shipId) {
startCargo(berthId);
} else {
showToast("Select a vessel from the inbound manifest first.", "warn");
}
}
function scheduleDeparture(ship, delay = 0) {
if (ship.departScheduled) return;
ship.departScheduled = true;
queue.schedule("DEPART", simulationTime + delay, { shipId: ship.id });
}
function allCargoTerminal(ship) {
return ship.cargo.every(lot => lot.status === "done" || lot.status === "late");
}
function handleEvent(event) {
const data = event.data;
switch (event.type) {
case "ARRIVE": {
const ship = shipById.get(data.shipId);
if (ship.status === "upcoming") {
ship.status = ship.assignedBerth !== null ? "inbound" : "waiting";
} else if (ship.status === "reserved") {
ship.status = "inbound";
}
if (ship.assignedBerth === null && ship.status === "waiting") {
queue.schedule("WAIT_PENALTY", simulationTime + 6, { shipId: ship.id });
addLog(`${ship.name} arrived without a berth.`);
} else {
addLog(`${ship.name} entered the approach lane.`);
}
break;
}
case "WAIT_PENALTY": {
const ship = shipById.get(data.shipId);
if (ship.status === "waiting" && ship.assignedBerth === null) {
score -= 15;
addLog(`Queue penalty: ${ship.name} has no berth.`);
queue.schedule("WAIT_PENALTY", simulationTime + 6, { shipId: ship.id });
}
break;
}
case "DOCK": {
const ship = shipById.get(data.shipId);
if (ship.status === "inbound") {
ship.status = "docked";
ship.position.copy(ship.dockPosition);
addLog(`${ship.name} secured at berth ${berths[ship.assignedBerth].code}.`);
showToast(`${ship.name} docked. Watch for amber cargo events.`, "good");
}
break;
}
case "CARGO_READY": {
const ship = shipById.get(data.shipId);
const lot = ship.cargo[data.lotIndex];
if (lot.status === "future") {
lot.status = "ready";
addLog(`${ship.name}: ${lot.name} ready at berth ${berths[ship.assignedBerth].code}.`);
}
break;
}
case "CARGO_DEADLINE": {
const ship = shipById.get(data.shipId);
const lot = ship.cargo[data.lotIndex];
if (["future", "ready", "working"].includes(lot.status)) {
lot.status = "late";
ship.missed++;
score -= 25;
addLog(`Deadline missed: ${lot.name}.`);
showToast(`${lot.name} expired at berth ${berths[ship.assignedBerth].code}.`, "bad");
if (allCargoTerminal(ship)) scheduleDeparture(ship, 0.5);
}
break;
}
case "CARGO_COMPLETE": {
const ship = shipById.get(data.shipId);
const berth = berths[data.berthId];
const lot = ship.cargo[data.lotIndex];
if (berth.job && berth.job.shipId === ship.id && berth.job.lotIndex === data.lotIndex) {
berth.job = null;
}
if (lot.status === "working") {
lot.status = "done";
ship.completed++;
totalLoads++;
const onTime = simulationTime <= lot.deadline;
score += lot.reward + (onTime ? 10 : 0);
addLog(`${lot.name} completed${onTime ? " on time" : " late"}.`);
showToast(`${lot.name} cleared. +${lot.reward + (onTime ? 10 : 0)}`, "good");
}
if (ship.cargo.every(item => item.status === "done")) {
score += 100;
scheduleDeparture(ship, 1.5);
addLog(`${ship.name} manifest complete. +100`);
}
break;
}
case "BERTH_REVIEW": {
const ship = shipById.get(data.shipId);
if (ship.status === "docked" && !allCargoTerminal(ship)) {
scheduleDeparture(ship, 0);
}
break;
}
case "DEPART": {
const ship = shipById.get(data.shipId);
if (ship.status !== "docked") break;
const incomplete = ship.cargo.filter(lot => lot.status !== "done").length;
if (incomplete > 0) {
score -= incomplete * 20;
ship.missed += incomplete;
addLog(`${ship.name} departed with ${incomplete} unresolved lot(s).`);
}
ship.status = "departing";
ship.departureAt = simulationTime;
if (ship.assignedBerth !== null) {
const berth = berths[ship.assignedBerth];
if (berth.shipId === ship.id) berth.shipId = null;
}
ship.assignedBerth = null;
queue.schedule("CLEAR", simulationTime + 5, { shipId: ship.id });
break;
}
case "CLEAR": {
const ship = shipById.get(data.shipId);
ship.status = "done";
break;
}
case "SHIFT_END": {
ended = true;
paused = true;
$("end-summary").textContent =
`You cleared ${totalLoads} cargo lots with ${ships.reduce((sum, ship) => sum + ship.missed, 0)} missed deadlines across a ${SHIFT_LENGTH}-second deterministic shift.`;
$("end-score").textContent = String(score);
$("end-modal").classList.remove("hidden");
$("pause").textContent = "Ⅱ PAUSE";
break;
}
}
}
// -------------------------------------------------------------------------
// Three.js voxel port
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071722);
scene.fog = new THREE.Fog(0x071722, 28, 67);
const renderer = new THREE.WebGLRenderer({ antialias: true, 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.12;
$("stage").appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-20, 20, 15, -15, 0.1, 150);
const cameraTarget = new THREE.Vector3(0, 0, 0.5);
let cameraYaw = 0.68;
let cameraPitch = 0.73;
let cameraZoom = 1;
const cameraDistance = 42;
function updateCamera() {
const aspect = window.innerWidth / window.innerHeight;
const halfHeight = Math.max(13.5, 15 / aspect) / cameraZoom;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * Math.cos(cameraPitch) * cameraDistance,
cameraTarget.y + Math.sin(cameraPitch) * cameraDistance,
cameraTarget.z + Math.cos(cameraYaw) * Math.cos(cameraPitch) * cameraDistance
);
camera.lookAt(cameraTarget);
camera.updateProjectionMatrix();
}
updateCamera();
window.addEventListener("resize", updateCamera);
const hemi = new THREE.HemisphereLight(0xbcefff, 0x17313a, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.1);
sun.position.set(-12, 24, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -24;
sun.shadow.camera.right = 24;
sun.shadow.camera.top = 22;
sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 60;
sun.shadow.bias = -0.0004;
scene.add(sun);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function material(color) {
if (!materialCache.has(color)) {
materialCache.set(color, new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0.02
}));
}
return materialCache.get(color);
}
function box(width, height, depth, color, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(unitBox, material(color));
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Water is made from deterministic square tiles.
box(38, 0.35, 34, 0x0a4055, 0, -0.48, 5);
const tileCountX = 19;
const tileCountZ = 13;
const waterTiles = new THREE.InstancedMesh(
unitBox,
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.72, metalness: 0.06 }),
tileCountX * tileCountZ
);
waterTiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let z = 0; z < tileCountZ; z++) {
for (let x = 0; x < tileCountX; x++) {
const px = (x - (tileCountX - 1) / 2) * 1.75;
const pz = -1.25 + z * 1.75;
dummy.position.set(px, -0.22 + (visualRng() > 0.8 ? 0.025 : 0), pz);
dummy.scale.set(1.69, 0.12, 1.69);
dummy.updateMatrix();
waterTiles.setMatrixAt(tileIndex, dummy.matrix);
tileColor.setHSL(0.53, 0.47, 0.22 + visualRng() * 0.055);
waterTiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
waterTiles.instanceMatrix.needsUpdate = true;
scene.add(waterTiles);
// Main quay and retaining wall.
box(26, 0.9, 7.2, 0x52636a, 0, 0.05, -6.0);
box(26.3, 0.32, 0.35, 0xb2b1a3, 0, 0.18, -2.35);
box(26, 0.16, 0.45, 0xe0c76f, 0, 0.48, -3.25);
// Road and dock markings.
for (let x = -12; x <= 12; x += 2) {
box(0.9, 0.025, 0.12, 0xd7d3bb, x, 0.52, -4.4);
}
for (const berth of berths) {
box(3.4, 0.025, 0.18, 0xf3d267, berth.x, 0.52, -5.2);
}
// Warehouses, roof vents, tanks, and stacked containers.
function createWarehouse(x, width, height, color) {
const group = new THREE.Group();
group.position.set(x, 0.5, -8.0);
scene.add(group);
box(width, height, 2.8, color, 0, height / 2, 0, group);
box(width + 0.25, 0.24, 3.05, 0x233d48, 0, height + 0.12, 0, group);
for (let i = -1; i <= 1; i++) {
box(0.65, 0.65, 0.1, 0x152a35, i * width * 0.25, height * 0.45, 1.43, group);
}
box(0.75, 0.75, 0.75, 0x71808a, width * 0.28, height + 0.6, -0.4, group);
}
createWarehouse(-8.4, 6.8, 2.5, 0x49636c);
createWarehouse(0, 7.6, 2.9, 0x5b6a69);
createWarehouse(8.3, 6.6, 2.4, 0x53616f);
const stackColors = [0x9d624e, 0x477986, 0xb49b52, 0x607557, 0x6b5a78];
for (let stack = 0; stack < 12; stack++) {
const x = -11.5 + stack * 2.05;
const levels = 1 + Math.floor(visualRng() * 3);
for (let level = 0; level < levels; level++) {
box(
1.55, 0.62, 1.0,
stackColors[(stack + level) % stackColors.length],
x, 0.84 + level * 0.66, -7.45
);
}
}
function textSprite(text, color = "#d9f8ff", background = "#0a2634") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
context.fillRect(0, 0, 12, canvas.height);
context.font = "800 48px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 262, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
}));
sprite.scale.set(3.4, 0.85, 1);
return sprite;
}
const hitboxes = [];
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
for (const berth of berths) {
// A narrow finger pier sits beside each ship berth.
box(0.85, 0.48, 6.3, 0x68777a, berth.x + 1.55, 0.13, 0.35);
box(0.95, 0.12, 0.95, 0xe7b94e, berth.x + 1.55, 0.43, -2.55);
const crane = new THREE.Group();
crane.position.set(berth.x + 1.55, 0.45, -2.55);
scene.add(crane);
box(0.9, 0.35, 0.9, 0x293e48, 0, 0.18, 0, crane);
box(0.34, 3.2, 0.34, 0xe1a849, 0, 1.85, 0, crane);
const arm = new THREE.Group();
arm.position.y = 3.15;
crane.add(arm);
box(4.3, 0.25, 0.32, 0xe1a849, -1.6, 0, 0, arm);
box(0.25, 0.25, 2.1, 0xe1a849, -3.55, 0, 0, arm);
box(0.75, 0.65, 0.75, 0x273d48, -0.45, 0.05, 0, arm);
const cable = box(0.055, 1.2, 0.055, 0x1c2930, -2.55, -0.6, 0, arm);
const hook = box(0.3, 0.22, 0.3, 0xd7eef1, -2.55, -1.22, 0, arm);
berth.crane = { group: crane, arm, cable, hook };
const label = textSprite(`${berth.code} · ${berth.name.toUpperCase()}`, "#d8f6fa");
label.position.set(berth.x, 1.05, -3.05);
scene.add(label);
const hitbox = new THREE.Mesh(unitBox, hitMaterial);
hitbox.scale.set(3.8, 2.6, 7.0);
hitbox.position.set(berth.x + 0.45, 1.1, 0.15);
hitbox.userData.berthId = berth.id;
scene.add(hitbox);
hitboxes.push(hitbox);
}
// Dock lamps.
for (const x of [-11, -3.5, 3.5, 11]) {
box(0.13, 3.7, 0.13, 0x354b52, x, 2.35, -4.7);
box(0.75, 0.16, 0.45, 0xcde8e7, x, 4.15, -4.7);
box(0.48, 0.06, 0.28, 0xffedb0, x, 4.03, -4.7);
}
// Channel buoys.
for (let i = 0; i < 8; i++) {
const x = -13.8 + i * 3.9;
box(0.38, 0.38, 0.38, i % 2 ? 0xdd604f : 0xe8c95c, x, 0.08, 8.5);
box(0.13, 0.65, 0.13, 0xe4ece8, x, 0.45, 8.5);
}
// Voxel clouds.
for (let i = 0; i < 6; i++) {
const x = -19 + i * 7.5 + visualRng() * 2;
const y = 8 + visualRng() * 3;
const z = -14 - visualRng() * 5;
box(2.2 + visualRng() * 2, 0.55, 1.0, 0x75909b, x, y, z);
box(1.4, 0.7, 0.9, 0x8ca1aa, x + 0.5, y + 0.45, z);
}
function createShip(ship) {
const group = new THREE.Group();
scene.add(group);
box(1.75, 0.58, 4.15, ship.spec.hull, 0, 0.28, 0, group);
box(1.45, 0.42, 0.8, ship.spec.hull, 0, 0.28, -2.35, group);
box(1.5, 0.16, 3.55, 0x8b9896, 0, 0.63, 0.03, group);
box(1.12, 0.72, 0.82, 0xc6d5d2, 0, 0.96, 1.35, group);
box(1.22, 0.16, 0.9, 0x294a58, 0, 1.38, 1.35, group);
box(0.65, 0.35, 0.06, 0x31586a, 0, 1.02, 0.92, group);
box(0.09, 1.25, 0.09, 0x2b3e48, 0.35, 1.77, 1.4, group);
box(0.46, 0.22, 0.06, 0xeab85b, 0.35, 2.27, 1.4, group);
const cargoMeshes = [];
[-1.2, -0.25, 0.7].forEach((z, index) => {
const cargoMaterial = new THREE.MeshStandardMaterial({
color: ship.spec.lots[index][1],
roughness: 0.8,
emissive: 0x000000
});
const mesh = new THREE.Mesh(unitBox, cargoMaterial);
mesh.scale.set(0.44, 0.44, 0.76);
mesh.position.set(0, 0.94, z);
mesh.castShadow = true;
group.add(mesh);
cargoMeshes.push(mesh);
});
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xffc45a,
emissive: 0x6b3a00,
emissiveIntensity: 0.7,
roughness: 0.5
});
const marker = new THREE.Mesh(unitBox, markerMaterial);
marker.scale.set(0.34, 0.34, 0.34);
marker.position.set(0, 2.65, -0.7);
group.add(marker);
const wake = [];
for (let i = 0; i < 3; i++) {
const foamMaterial = new THREE.MeshBasicMaterial({
color: 0xbce9eb,
transparent: true,
opacity: 0.35 - i * 0.08
});
const mesh = new THREE.Mesh(unitBox, foamMaterial);
mesh.scale.set(1.0 - i * 0.15, 0.025, 0.42);
mesh.position.set(0, -0.08, 2.6 + i * 0.8);
group.add(mesh);
wake.push(mesh);
}
group.position.copy(ship.position);
ship.mesh = group;
ship.cargoMeshes = cargoMeshes;
ship.marker = marker;
ship.wake = wake;
}
ships.forEach(createShip);
const waves = [];
for (let i = 0; i < 14; i++) {
const mesh = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({ color: 0x8ed5dc, transparent: true, opacity: 0.13 })
);
mesh.scale.set(0.8 + visualRng(), 0.015, 0.14);
mesh.position.set(-14 + visualRng() * 28, -0.08, -1 + visualRng() * 17);
scene.add(mesh);
waves.push(mesh);
}
// -------------------------------------------------------------------------
// Simulation stepping and interpolated visuals
// -------------------------------------------------------------------------
function updateShipPositions() {
for (const ship of ships) {
ship.previousPosition.copy(ship.position);
if (ship.status === "upcoming" || ship.status === "reserved" || ship.status === "waiting") {
ship.position.copy(ship.spec.approach);
ship.position.y += Math.sin(simulationTime * 1.35 + ship.id) * 0.025;
} else if (ship.status === "inbound") {
const duration = Math.max(0.001, ship.dockAt - ship.approachStart);
const t = clamp((simulationTime - ship.approachStart) / duration, 0, 1);
ship.position.lerpVectors(ship.spec.approach, ship.dockPosition, smooth(t));
ship.position.y += Math.sin(simulationTime * 1.6 + ship.id) * 0.025;
} else if (ship.status === "docked") {
ship.position.copy(ship.dockPosition);
} else if (ship.status === "departing") {
const t = clamp((simulationTime - ship.departureAt) / 5, 0, 1);
ship.position.lerpVectors(ship.dockPosition, ship.exitPosition, smooth(t));
ship.position.y += Math.sin(simulationTime * 1.6 + ship.id) * 0.02;
} else if (ship.status === "done") {
ship.position.copy(ship.exitPosition);
}
}
}
function stepSimulation(dt) {
simulationTime += dt;
queue.process(simulationTime, handleEvent);
updateShipPositions();
}
function updateScene(alpha) {
for (const ship of ships) {
ship.mesh.position.lerpVectors(ship.previousPosition, ship.position, alpha);
const moving = ship.status === "inbound" || ship.status === "departing";
ship.wake.forEach((wake, index) => {
wake.visible = moving;
wake.position.x = Math.sin(simulationTime * 4 + index) * 0.18;
});
let markerVisible = false;
ship.cargo.forEach((lot, index) => {
const mesh = ship.cargoMeshes[index];
const original = new THREE.Color(ship.spec.lots[index][1]);
if (lot.status === "done") {
mesh.material.color.copy(original).multiplyScalar(0.42);
mesh.material.emissive.setHex(0x143814);
} else if (lot.status === "late") {
mesh.material.color.setHex(0xff725f);
mesh.material.emissive.setHex(0x431009);
} else if (lot.status === "working") {
mesh.material.color.copy(original);
mesh.material.emissive.setHex(0x164d57);
mesh.material.emissiveIntensity = 0.6;
markerVisible = true;
} else if (lot.status === "ready") {
mesh.material.color.copy(original);
mesh.material.emissive.setHex(0x6a3b00);
mesh.material.emissiveIntensity = 0.35;
markerVisible = true;
} else {
mesh.material.color.copy(original).multiplyScalar(0.72);
mesh.material.emissive.setHex(0x000000);
}
});
ship.marker.visible = markerVisible;
ship.marker.rotation.y = simulationTime * 1.8;
ship.marker.position.y = 2.65 + Math.sin(simulationTime * 3.2 + ship.id) * 0.08;
}
for (const berth of berths) {
const crane = berth.crane;
if (berth.job) {
const duration = Math.max(0.01, berth.job.endsAt - berth.job.startedAt);
const progress = clamp((simulationTime - berth.job.startedAt) / duration, 0, 1);
const cycle = Math.sin(progress * Math.PI);
crane.arm.rotation.z = -0.05 + cycle * 0.22;
crane.cable.scale.y = 0.65 + cycle * 0.8;
crane.cable.position.y = -0.55 - cycle * 0.25;
crane.hook.position.y = -1.1 - cycle * 0.42;
} else {
crane.arm.rotation.z = -0.05;
crane.cable.scale.y = 1;
crane.cable.position.y = -0.6;
crane.hook.position.y = -1.22;
}
}
waves.forEach((wave, index) => {
wave.position.z = ((simulationTime * (0.45 + index % 3 * 0.12) + index * 1.37) % 18) - 1;
wave.position.y = -0.08 + Math.sin(simulationTime + index) * 0.012;
});
}
// -------------------------------------------------------------------------
// UI updates, logs, and controls
// -------------------------------------------------------------------------
function formatClock() {
const minutes = 8 * 60 + Math.floor(simulationTime * 2);
const hours = Math.floor(minutes / 60) % 24;
const mins = minutes % 60;
return `${String(hours).padStart(2, "0")}:${String(mins).padStart(2, "0")}`;
}
function statusForShip(ship) {
if (ship.status === "upcoming") return `ETA ${Math.max(0, ship.arrivalAt - simulationTime).toFixed(1)}s`;
if (ship.status === "reserved") return `BERTH ${berths[ship.assignedBerth].code} RESERVED`;
if (ship.status === "inbound") return `DOCK IN ${Math.max(0, ship.dockAt - simulationTime).toFixed(1)}s`;
if (ship.status === "waiting") return "WAITING FOR BERTH";
if (ship.status === "docked") return `${ship.completed}/3 LOADS CLEARED`;
if (ship.status === "departing") return "DEPARTING";
return "COMPLETE";
}
function updateUI() {
$("clock").textContent = formatClock();
$("score").textContent = String(score).padStart(4, "0");
$("loads").textContent = String(totalLoads).padStart(2, "0");
const activeShips = ships.filter(ship => ship.status !== "done");
$("manifest-count").textContent = activeShips.length;
for (const ship of ships) {
const element = shipElements.get(ship.id);
element.classList.toggle("selected", selectedShipId === ship.id);
element.style.opacity = ship.status === "done" ? "0.42" : "1";
element.querySelector(".ship-eta").textContent = statusForShip(ship);
element.querySelector(".ship-status").textContent =
ship.status === "docked" ? `BERTH ${berths[ship.assignedBerth]?.code ?? "—"}` : ship.status.toUpperCase();
element.querySelector(".cargo-chips").innerHTML = ship.cargo.map(lot =>
`<span class="cargo-chip ${lot.status}">${lot.name}</span>`
).join("");
}
for (const berth of berths) {
const ui = berthElements.get(berth.id);
const ship = berth.shipId !== null ? shipById.get(berth.shipId) : null;
const ready = ship && ship.cargo.some(lot => lot.status === "ready");
if (!ship) {
ui.state.textContent = selectedShipId !== null ? "AVAILABLE · SELECT TO RESERVE" : "AVAILABLE";
} else {
ui.state.textContent = `${ship.name} · ${berth.job ? "CRANE ACTIVE" : ready ? "CARGO READY" : "WORKING"}`;
}
ui.track.innerHTML = ship
? ship.cargo.map(lot => `<span class="cargo-dot ${lot.status}"></span>`).join("")
: `<span class="cargo-dot"></span><span class="cargo-dot"></span><span class="cargo-dot"></span>`;
ui.button.className = "action";
if (berth.job) {
const progress = clamp((simulationTime - berth.job.startedAt) / (berth.job.endsAt - berth.job.startedAt), 0, 1);
ui.button.textContent = `HANDLING ${Math.round(progress * 100)}%`;
ui.button.classList.add("busy");
} else if (ready) {
ui.button.textContent = "WORK CARGO";
ui.button.classList.add("work");
} else if (!ship && selectedShipId !== null) {
ui.button.textContent = `RESERVE BERTH ${berth.code}`;
} else if (ship) {
ui.button.textContent = "NO CARGO READY";
ui.button.classList.add("busy");
} else {
ui.button.textContent = "SELECT A VESSEL";
ui.button.classList.add("busy");
}
}
const relevant = queue.all().filter(event =>
event.at > simulationTime - 0.05 &&
["ARRIVE", "DOCK", "CARGO_READY", "CARGO_DEADLINE", "DEPART"].includes(event.type)
).slice(0, 7);
$("event-strip").innerHTML = relevant.map(event => {
let name = event.type.replaceAll("_", " ");
let style = "";
if (event.type === "ARRIVE") {
name = `ARRIVE · ${shipById.get(event.data.shipId)?.name ?? ""}`;
style = "arrival";
} else if (event.type === "DOCK") {
name = `DOCK · BERTH ${berths[shipById.get(event.data.shipId)?.assignedBerth ?? 0].code}`;
} else if (event.type === "CARGO_READY") {
const ship = shipById.get(event.data.shipId);
name = `CARGO · ${ship.cargo[event.data.lotIndex].name}`;
} else if (event.type === "CARGO_DEADLINE") {
const ship = shipById.get(event.data.shipId);
name = `DUE · ${ship.cargo[event.data.lotIndex].name}`;
style = "deadline";
} else if (event.type === "DEPART") {
name = `DEPART · ${shipById.get(event.data.shipId)?.name ?? ""}`;
style = "depart";
}
return `
<div class="event-chip ${style}">
<div class="event-time">+${Math.max(0, event.at - simulationTime).toFixed(1)}s</div>
<div class="event-name">${name}</div>
</div>
`;
}).join("");
$("log").innerHTML = logEntries.slice(-4).map(entry =>
`<div><span style="color:#55d7e7">${entry.time.toFixed(1)}s</span> ${entry.message}</div>`
).join("");
}
function addLog(message) {
logEntries.push({ time: simulationTime, message });
if (logEntries.length > 30) logEntries.shift();
}
function showToast(message, type = "") {
const toast = $("toast");
toast.textContent = message;
toast.className = `show ${type}`;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.className = type;
}, 2800);
}
$("pause").addEventListener("click", () => {
if (ended) return;
paused = !paused;
$("pause").textContent = paused ? "▶ RESUME" : "Ⅱ PAUSE";
showToast(paused ? "Simulation clock paused." : "Simulation clock resumed.");
});
document.querySelectorAll(".speed").forEach(button => {
button.addEventListener("click", () => {
playbackSpeed = Number(button.dataset.speed);
document.querySelectorAll(".speed").forEach(item => item.classList.toggle("active", item === button));
showToast(`Playback ${playbackSpeed}×. Event durations and deadlines remain simulation-locked.`);
});
});
$("restart").addEventListener("click", () => location.reload());
window.addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
$("pause").click();
}
if (["1", "2", "3"].includes(event.key)) {
berthAction(Number(event.key) - 1);
}
if (event.key === "Escape") {
selectedShipId = null;
updateUI();
}
});
// -------------------------------------------------------------------------
// Direct camera controls and 3D berth picking
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let pointerStart = { x: 0, y: 0 };
let lastPointer = { x: 0, y: 0 };
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerStart = { x: event.clientX, y: event.clientY };
lastPointer = { x: event.clientX, y: event.clientY };
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
cameraYaw -= dx * 0.006;
cameraPitch = clamp(cameraPitch + dy * 0.004, 0.34, 1.18);
lastPointer = { x: event.clientX, y: event.clientY };
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
const distance = Math.hypot(event.clientX - pointerStart.x, event.clientY - pointerStart.y);
dragging = false;
if (distance > 6) return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(hitboxes, false);
if (hits.length) berthAction(hits[0].object.userData.berthId);
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraZoom = clamp(cameraZoom * (event.deltaY > 0 ? 0.92 : 1.08), 0.68, 1.75);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let lastUIUpdate = 0;
function animate() {
requestAnimationFrame(animate);
const realDelta = Math.min(clock.getDelta(), 0.08);
if (!paused && !ended) {
accumulator += realDelta * playbackSpeed;
let steps = 0;
while (accumulator >= FIXED_DT && steps < 24) {
stepSimulation(FIXED_DT);
accumulator -= FIXED_DT;
steps++;
}
}
const alpha = accumulator / FIXED_DT;
updateScene(alpha);
renderer.render(scene, camera);
const now = performance.now();
if (now - lastUIUpdate > 100) {
updateUI();
lastUIUpdate = now;
}
}
updateUI();
addLog("Shift systems online. Select an inbound vessel.");
showToast("Select an inbound ship, then reserve a matching berth.", "good");
$("loading").remove();
animate();
</script>
</body>
</html>
```