Prompt specification
Build or customize the Three.js 3D scene "Crane Availability and Berth-Window Terminal" 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: Crane Availability and Berth-Window Terminal
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/crane-availability-and-berth-window-terminal-x2123
Scene Description Prompt:
Crane availability and berth-window terminal. Build an original compact port with two berths, one shared crane, and tracked containers. Combine synthetic docking windows with crane service times, showing waiting ships and blocked transfers without inventing capacity. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (crane-availability-and-berth-window-terminal-x2123):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QUAY/7 — Crane & Berth Terminal</title>
<style>
:root {
--bg: #071219;
--panel: #0d1c25;
--panel-2: #102630;
--line: #24414d;
--muted: #78939f;
--text: #e5f0f2;
--cyan: #58d6d0;
--blue: #68aef2;
--amber: #f4bd62;
--red: #ff6d6d;
--green: #72dda4;
--purple: #b39bff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
font-size: 13px;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#app {
height: 100vh;
display: grid;
grid-template-rows: 66px minmax(0, 1fr) 210px;
}
header {
display: flex;
align-items: center;
gap: 22px;
padding: 0 18px;
background: #09161e;
border-bottom: 1px solid var(--line);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 11px;
min-width: 226px;
}
.brand-mark {
width: 34px;
height: 34px;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 2px;
transform: rotate(-4deg);
}
.brand-mark i {
display: block;
background: var(--cyan);
border-radius: 1px;
}
.brand-mark i:nth-child(1),
.brand-mark i:nth-child(3),
.brand-mark i:nth-child(8) {
opacity: .35;
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(5),
.brand-mark i:nth-child(7),
.brand-mark i:nth-child(9) {
opacity: .72;
}
.brand-title {
font-weight: 850;
font-size: 16px;
letter-spacing: .12em;
}
.brand-sub {
margin-top: 2px;
color: var(--muted);
font-size: 10px;
letter-spacing: .13em;
text-transform: uppercase;
}
.clock-block {
padding-right: 21px;
border-right: 1px solid var(--line);
}
.clock {
font-size: 23px;
font-weight: 800;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.clock-label {
margin-top: 5px;
color: var(--muted);
font-size: 9px;
letter-spacing: .12em;
text-transform: uppercase;
}
.metrics {
display: flex;
align-items: center;
gap: 9px;
flex: 1;
min-width: 0;
}
.metric {
min-width: 112px;
padding: 8px 11px;
background: #0d1d26;
border: 1px solid var(--line);
border-radius: 6px;
}
.metric-value {
font-size: 15px;
font-weight: 800;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.metric-label {
margin-top: 3px;
color: var(--muted);
font-size: 9px;
letter-spacing: .1em;
text-transform: uppercase;
}
.metric.alert .metric-value {
color: var(--red);
}
.metric.good .metric-value {
color: var(--green);
}
header .header-note {
color: var(--muted);
font-size: 10px;
line-height: 1.45;
text-align: right;
max-width: 170px;
}
main {
position: relative;
min-height: 0;
display: grid;
grid-template-columns: 282px minmax(360px, 1fr) 306px;
background: #08151c;
}
aside {
min-height: 0;
overflow: auto;
background: var(--panel);
scrollbar-width: thin;
scrollbar-color: #34515d transparent;
z-index: 10;
}
#leftPanel {
border-right: 1px solid var(--line);
}
#rightPanel {
border-left: 1px solid var(--line);
}
.section {
padding: 15px;
border-bottom: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: #b9cdd3;
font-size: 10px;
font-weight: 800;
letter-spacing: .14em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted);
font-weight: 600;
letter-spacing: .04em;
}
.berth-card {
margin-bottom: 10px;
padding: 12px;
background: #10242d;
border: 1px solid #28444f;
border-radius: 7px;
}
.berth-card:last-child {
margin-bottom: 0;
}
.berth-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.berth-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 15px;
font-weight: 850;
}
.berth-dot {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 12px #58d6d044;
}
.berth-dot.b {
background: var(--blue);
box-shadow: 0 0 12px #68aef244;
}
.berth-status {
color: var(--muted);
font-size: 10px;
}
.berth-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 11px 0;
}
.berth-stat {
padding: 7px 8px;
background: #0b1b23;
border-radius: 4px;
}
.berth-stat strong {
display: block;
font-size: 11px;
margin-bottom: 3px;
}
.berth-stat small {
color: var(--muted);
font-size: 9px;
letter-spacing: .05em;
text-transform: uppercase;
}
.window-list {
color: var(--muted);
font-size: 10px;
line-height: 1.65;
}
.window-list b {
color: #bed1d7;
font-weight: 650;
}
.mini-button {
width: 100%;
margin-top: 9px;
padding: 7px 8px;
border: 1px solid #36545f;
border-radius: 4px;
background: #142a33;
color: #cce0e4;
cursor: pointer;
font-size: 10px;
font-weight: 700;
}
.mini-button:hover:not(:disabled) {
background: #1b3843;
border-color: var(--cyan);
}
.mini-button:disabled {
opacity: .35;
cursor: default;
}
.ship-list {
display: grid;
gap: 8px;
}
.ship-card {
display: grid;
grid-template-columns: 1fr auto;
gap: 5px 10px;
padding: 9px 10px;
background: #0b1b23;
border: 1px solid #203b46;
border-radius: 5px;
}
.ship-name {
font-size: 11px;
font-weight: 800;
letter-spacing: .03em;
}
.ship-meta {
grid-column: 1 / -1;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
.badge {
align-self: start;
padding: 3px 5px;
border-radius: 3px;
background: #243741;
color: #b9cbd1;
font-size: 8px;
font-weight: 850;
letter-spacing: .06em;
text-transform: uppercase;
white-space: nowrap;
}
.badge.cyan {
background: #163e41;
color: var(--cyan);
}
.badge.blue {
background: #19344e;
color: var(--blue);
}
.badge.amber {
background: #49391d;
color: var(--amber);
}
.badge.red {
background: #49252a;
color: var(--red);
}
.badge.green {
background: #173d2e;
color: var(--green);
}
.badge.purple {
background: #342a4d;
color: var(--purple);
}
.badge.gray {
background: #26343a;
color: #91a4aa;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #9bc6ce;
}
#scene {
position: absolute;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
}
.scene-top {
position: absolute;
top: 13px;
left: 14px;
right: 14px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
z-index: 5;
}
.model-note {
max-width: 290px;
padding: 9px 11px;
background: #081920d9;
border: 1px solid #33515c;
border-radius: 5px;
backdrop-filter: blur(7px);
}
.model-note strong {
display: block;
color: var(--cyan);
font-size: 9px;
letter-spacing: .13em;
text-transform: uppercase;
margin-bottom: 4px;
}
.model-note span {
color: #aec3ca;
font-size: 9px;
line-height: 1.5;
}
.camera-tools {
display: flex;
gap: 6px;
pointer-events: auto;
}
.camera-tools button {
padding: 8px 10px;
border: 1px solid #42616b;
border-radius: 5px;
background: #0a1c24dc;
color: #d7e8eb;
cursor: pointer;
font-size: 9px;
font-weight: 750;
text-transform: uppercase;
letter-spacing: .08em;
}
.camera-tools button:hover {
border-color: var(--cyan);
}
.camera-help {
position: absolute;
left: 14px;
bottom: 14px;
padding: 7px 9px;
background: #071820c9;
border: 1px solid #294651;
border-radius: 4px;
color: #afc5cc;
font-size: 9px;
pointer-events: none;
z-index: 5;
}
#labels {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
z-index: 4;
}
.world-label {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -100%);
padding: 5px 7px;
border: 1px solid #52727b;
border-radius: 3px;
background: #071820e8;
color: #e2eff1;
box-shadow: 0 3px 10px #00101555;
font-size: 8px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
white-space: nowrap;
}
.world-label.waiting {
border-color: #d8a957;
color: #ffd98f;
}
.world-label.docked {
border-color: #50c8c2;
color: #8bf1ec;
}
.world-label.crane {
border-color: #a990f5;
color: #d4c6ff;
}
.capacity-card {
padding: 12px;
background: #10242d;
border: 1px solid #28444f;
border-radius: 6px;
}
.capacity-number {
display: flex;
align-items: baseline;
gap: 7px;
}
.capacity-number strong {
font-size: 26px;
line-height: 1;
}
.capacity-number span {
color: var(--muted);
font-size: 10px;
}
.capacity-bar {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
margin: 12px 0 9px;
}
.capacity-bar i {
height: 7px;
border-radius: 2px;
background: #263d46;
}
.capacity-bar i.occupied {
background: var(--cyan);
}
.capacity-note {
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.ledger {
display: grid;
gap: 7px;
}
.ledger-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 4px 8px;
padding: 8px 9px;
background: #0b1b23;
border: 1px solid #203a45;
border-radius: 4px;
}
.ledger-id {
font-size: 10px;
font-weight: 800;
letter-spacing: .03em;
}
.ledger-route {
grid-column: 1 / -1;
color: var(--muted);
font-size: 9px;
}
.ledger-reason {
grid-column: 1 / -1;
color: #91aab2;
font-size: 9px;
line-height: 1.35;
}
.ledger-reason.blocked {
color: #ff9c9c;
}
.ledger-service {
color: var(--muted);
font-size: 8px;
}
.empty {
padding: 16px 8px;
color: var(--muted);
font-size: 10px;
text-align: center;
}
footer {
display: grid;
grid-template-columns: 272px minmax(380px, 1fr) 310px;
min-height: 0;
background: #09161e;
border-top: 1px solid var(--line);
z-index: 20;
}
.controls {
padding: 15px;
border-right: 1px solid var(--line);
}
.control-row {
display: flex;
align-items: center;
gap: 7px;
}
.control-button {
min-width: 40px;
height: 35px;
padding: 0 11px;
border: 1px solid #35545f;
border-radius: 5px;
background: #112630;
color: #d8e9ec;
cursor: pointer;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: .06em;
}
.control-button.primary {
min-width: 88px;
color: #052025;
background: var(--cyan);
border-color: var(--cyan);
}
.control-button:hover {
filter: brightness(1.12);
}
.speed-group {
display: flex;
gap: 4px;
margin-top: 12px;
}
.speed-group button {
flex: 1;
padding: 6px;
border: 1px solid #2b4954;
border-radius: 4px;
background: transparent;
color: var(--muted);
cursor: pointer;
font-size: 9px;
font-weight: 750;
}
.speed-group button.active {
color: var(--cyan);
border-color: var(--cyan);
background: #102b31;
}
.control-note {
margin-top: 13px;
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.timeline-panel {
min-width: 0;
padding: 13px 16px 10px;
border-right: 1px solid var(--line);
}
.timeline-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
}
.timeline-head strong {
font-size: 10px;
letter-spacing: .12em;
text-transform: uppercase;
}
.timeline-legend {
display: flex;
gap: 12px;
color: var(--muted);
font-size: 8px;
text-transform: uppercase;
letter-spacing: .05em;
}
.timeline-legend span {
display: flex;
align-items: center;
gap: 4px;
}
.timeline-legend i {
width: 9px;
height: 6px;
display: inline-block;
background: #49616a;
}
.timeline-legend i.actual {
background: var(--cyan);
}
.timeline-legend i.crane {
background: var(--purple);
}
.timeline-body {
position: relative;
}
.timeline-axis {
height: 17px;
margin-left: 44px;
position: relative;
color: #6f8b95;
font-size: 8px;
}
.timeline-axis span {
position: absolute;
transform: translateX(-50%);
white-space: nowrap;
}
.timeline-row {
display: grid;
grid-template-columns: 36px 1fr;
align-items: center;
gap: 8px;
height: 36px;
}
.timeline-row-label {
color: #9bb2ba;
font-size: 9px;
font-weight: 850;
text-align: right;
}
.timeline-track {
position: relative;
height: 23px;
background:
repeating-linear-gradient(
90deg,
#10242d 0,
#10242d calc(20% - 1px),
#28404a calc(20% - 1px),
#28404a 20%
);
border: 1px solid #223d47;
border-radius: 3px;
overflow: hidden;
}
.timeline-window,
.timeline-service,
.timeline-crane {
position: absolute;
top: 4px;
bottom: 4px;
border-radius: 2px;
}
.timeline-window {
background: #3a525c;
border: 1px dashed #6d8790;
}
.timeline-service {
background: #55c9c3;
opacity: .9;
}
.timeline-crane {
background: #9e8bea;
opacity: .9;
}
.timeline-now {
position: absolute;
top: 0;
bottom: 0;
width: 1px;
background: #fff;
box-shadow: 0 0 7px #fff;
z-index: 4;
}
.activity-panel {
min-width: 0;
padding: 13px 15px;
}
.activity-list {
display: grid;
gap: 6px;
max-height: 155px;
overflow: auto;
scrollbar-width: thin;
}
.activity-row {
display: grid;
grid-template-columns: 43px 1fr;
gap: 8px;
color: #a8bec5;
font-size: 9px;
line-height: 1.35;
}
.activity-time {
color: #66858f;
font-variant-numeric: tabular-nums;
}
.activity-row.warning .activity-text {
color: #ffc27f;
}
.activity-row.error .activity-text {
color: #ff9494;
}
.activity-row.good .activity-text {
color: #8de3b3;
}
@media (max-width: 1120px) {
main {
grid-template-columns: 248px minmax(330px, 1fr) 270px;
}
footer {
grid-template-columns: 248px minmax(330px, 1fr) 270px;
}
.metric {
min-width: 95px;
}
.metric:nth-child(4),
header .header-note {
display: none;
}
}
@media (max-width: 880px) {
#app {
grid-template-rows: 60px minmax(0, 1fr) 195px;
}
main {
display: block;
}
#viewport {
width: 100%;
height: 100%;
}
aside {
position: absolute;
top: 8px;
bottom: 8px;
width: 250px;
border: 1px solid var(--line);
border-radius: 7px;
box-shadow: 0 10px 30px #0005;
}
#leftPanel {
left: 8px;
}
#rightPanel {
right: 8px;
}
footer {
grid-template-columns: 210px 1fr;
}
.activity-panel {
display: none;
}
.metrics .metric:nth-child(n+3) {
display: none;
}
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<div>
<div class="brand-title">QUAY/7</div>
<div class="brand-sub">Shared crane terminal</div>
</div>
</div>
<div class="clock-block">
<div class="clock" id="clock">06:00</div>
<div class="clock-label">Synthetic terminal clock</div>
</div>
<div class="metrics">
<div class="metric">
<div class="metric-value" id="metricCrane">IDLE · A</div>
<div class="metric-label">Shared crane</div>
</div>
<div class="metric">
<div class="metric-value" id="metricBerths">0 / 2</div>
<div class="metric-label">Berths occupied</div>
</div>
<div class="metric" id="metricWaitingCard">
<div class="metric-value" id="metricWaiting">0</div>
<div class="metric-label">Waiting ships</div>
</div>
<div class="metric" id="metricBlockedCard">
<div class="metric-value" id="metricBlocked">0</div>
<div class="metric-label">Blocked transfers</div>
</div>
<div class="metric good">
<div class="metric-value" id="metricSlots">0 / 4</div>
<div class="metric-label">Handoff slots used</div>
</div>
</div>
<div class="header-note">
One crane. Two berths.<br>
No downstream yard inventory modeled.
</div>
</header>
<main>
<aside id="leftPanel">
<section class="section">
<div class="section-title">
<span>Berth windows</span>
<span>Synthetic schedule</span>
</div>
<div id="berthCards"></div>
</section>
<section class="section">
<div class="section-title">
<span>Vessel queue</span>
<span id="vesselCount">0 vessels</span>
</div>
<div class="ship-list" id="shipList"></div>
</section>
</aside>
<section id="viewport">
<div id="scene"></div>
<div class="scene-top">
<div class="model-note">
<strong>Constrained terminal model</strong>
<span>
2 berths · 1 shared crane · 4 explicit handoff slots.
Container inventory is not created outside the modeled pads.
</span>
</div>
<div class="camera-tools">
<button id="cameraReset" type="button">Reset view</button>
</div>
</div>
<div id="labels"></div>
<div class="camera-help">
Drag: orbit · Shift/right-drag: pan · Wheel: zoom
</div>
</section>
<aside id="rightPanel">
<section class="section">
<div class="section-title">
<span>Explicit capacity</span>
<span>Handoff pads</span>
</div>
<div class="capacity-card">
<div class="capacity-number">
<strong id="capacityUsed">0 / 4</strong>
<span>slots occupied</span>
</div>
<div class="capacity-bar" id="capacityBar">
<i></i><i></i><i></i><i></i>
</div>
<div class="capacity-note">
Each berth has exactly two visible transfer pads. When both are
occupied, further lifts are blocked until a pad is removed.
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Transfer ledger</span>
<span id="transferCount">0 tracked</span>
</div>
<div class="ledger" id="transferLedger"></div>
</section>
</aside>
</main>
<footer>
<section class="controls">
<div class="control-row">
<button class="control-button primary" id="playButton" type="button">
Pause
</button>
<button class="control-button" id="resetButton" type="button">
Reset
</button>
</div>
<div class="speed-group" id="speedGroup">
<button data-speed="1" type="button">1×</button>
<button data-speed="4" class="active" type="button">4×</button>
<button data-speed="12" type="button">12×</button>
</div>
<div class="control-note">
Simulation minutes advance at the selected rate. Crane travel time
and each lift's service time are explicit in the model.
</div>
</section>
<section class="timeline-panel">
<div class="timeline-head">
<strong>Terminal timeline</strong>
<div class="timeline-legend">
<span><i></i> window</span>
<span><i class="actual"></i> vessel</span>
<span><i class="crane"></i> crane</span>
</div>
</div>
<div class="timeline-body">
<div class="timeline-axis" id="timelineAxis"></div>
<div id="timelineRows"></div>
</div>
</section>
<section class="activity-panel">
<div class="section-title">
<span>Event stream</span>
<span>Live</span>
</div>
<div class="activity-list" id="activityLog"></div>
</section>
</footer>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const START_MINUTE = 360;
const HORIZON_END = 900;
const berths = {
A: {
id: "A",
x: -9,
windows: [
{ id: "A1", start: 370, end: 500 },
{ id: "A2", start: 530, end: 680 }
],
occupant: null,
slots: []
},
B: {
id: "B",
x: 9,
windows: [
{ id: "B1", start: 390, end: 545 },
{ id: "B2", start: 585, end: 800 }
],
occupant: null,
slots: []
}
};
const shipBlueprints = [
{
id: "NOVA",
name: "NORTHERN STAR",
berth: "A",
arrival: 360,
services: [7, 8, 6],
hull: 0x26495e,
accent: 0xf3b85c
},
{
id: "KITE",
name: "KESTREL",
berth: "B",
arrival: 380,
services: [8, 7, 8],
hull: 0x2d5960,
accent: 0x74d7d0
},
{
id: "COBALT",
name: "COBALT",
berth: "A",
arrival: 445,
services: [6, 7, 6],
hull: 0x334a68,
accent: 0x8aaef3
},
{
id: "MISTRAL",
name: "MISTRAL",
berth: "B",
arrival: 520,
services: [7, 8, 7],
hull: 0x5a465e,
accent: 0xe597bd
},
{
id: "EMBER",
name: "EMBER",
berth: "A",
arrival: 525,
services: [6, 8, 7],
hull: 0x704b3d,
accent: 0xff9d67
},
{
id: "LARK",
name: "LARK",
berth: "B",
arrival: 600,
services: [7, 7, 8],
hull: 0x365a43,
accent: 0xa4df85
}
];
const containerColors = [
0xe46b4f,
0x4eb5a8,
0x6d91d6,
0xe0ad4d,
0x8b72bd,
0x65b96b
];
const stateLabels = {
scheduled: "Scheduled",
waiting_window: "Window wait",
waiting_berth: "Berth occupied",
docked: "Docked",
en_route: "Crane en route",
in_transfer: "In transfer",
staged: "Staged",
blocked_window: "Window blocked",
blocked_capacity: "Pad blocked",
cleared: "Cleared",
departed: "Departed"
};
const stateClasses = {
scheduled: "gray",
waiting_window: "amber",
waiting_berth: "amber",
docked: "cyan",
en_route: "purple",
in_transfer: "green",
staged: "green",
blocked_window: "red",
blocked_capacity: "red",
cleared: "gray",
departed: "gray"
};
const ships = shipBlueprints.map((blueprint, shipIndex) => {
const ship = {
...blueprint,
index: shipIndex,
status: "scheduled",
arrivedAt: null,
dockAt: null,
completeAt: null,
dockWindowIndex: null,
transfers: [],
group: null,
cargoMeshes: [],
targetPosition: new THREE.Vector3()
};
ship.transfers = blueprint.services.map((service, transferIndex) => ({
id: `${blueprint.id}-${String(transferIndex + 1).padStart(2, "0")}`,
code: `MSCU ${204810 + shipIndex * 13 + transferIndex}`,
shipId: ship.id,
shipName: ship.name,
berthId: blueprint.berth,
service,
state: "scheduled",
reason: "Awaiting vessel arrival",
slot: null,
sourceX: [-0.8, 1.1, 3.0][transferIndex],
color: containerColors[(shipIndex + transferIndex) % containerColors.length]
}));
return ship;
});
let simulationMinute = START_MINUTE;
let playing = true;
let speed = 4;
let events = [];
let craneJobs = [];
const crane = {
state: "idle",
x: berths.A.x,
job: null
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9bc6ce);
scene.fog = new THREE.Fog(0x9bc6ce, 48, 92);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
document.getElementById("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 150);
const hemisphere = new THREE.HemisphereLight(0xdff8ff, 0x34484d, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0d2, 3.1);
sun.position.set(-18, 34, 25);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -38;
sun.shadow.camera.right = 38;
sun.shadow.camera.top = 32;
sun.shadow.camera.bottom = -32;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 90;
sun.shadow.bias = -0.0004;
scene.add(sun);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x1a2f38,
transparent: true,
opacity: 0.42
});
function material(color) {
const key = String(color);
if (!materialCache.has(key)) {
materialCache.set(
key,
new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.05,
flatShading: true
})
);
}
return materialCache.get(key);
}
function box(
width,
height,
depth,
color,
x,
y,
z,
parent = scene,
withEdges = false
) {
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);
if (withEdges) {
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(unitBox),
edgeMaterial
);
mesh.add(edges);
}
return mesh;
}
function createVoxelTerrain() {
const dummy = new THREE.Object3D();
const waterGeometry = new THREE.BoxGeometry(1, 1, 1);
const waterMaterial = new THREE.MeshStandardMaterial({
roughness: 0.6,
metalness: 0.03,
vertexColors: true
});
const waterColumns = 31;
const waterRows = 15;
const water = new THREE.InstancedMesh(
waterGeometry,
waterMaterial,
waterColumns * waterRows
);
let waterIndex = 0;
for (let ix = 0; ix < waterColumns; ix++) {
for (let iz = 0; iz < waterRows; iz++) {
const x = -30 + ix * 2;
const z = 1 + iz * 2;
dummy.position.set(x, -0.18, z);
dummy.scale.set(1.94, 0.34, 1.94);
dummy.updateMatrix();
water.setMatrixAt(waterIndex, dummy.matrix);
const wave =
0.5 +
0.5 * Math.sin(ix * 1.81 + iz * 0.73) +
((ix + iz) % 3) * 0.025;
water.setColorAt(
waterIndex,
new THREE.Color().setHSL(
0.53,
0.37,
0.39 + Math.min(wave, 1) * 0.07
)
);
waterIndex++;
}
}
water.receiveShadow = true;
scene.add(water);
const landGeometry = new THREE.BoxGeometry(1, 1, 1);
const landMaterial = new THREE.MeshStandardMaterial({
roughness: 0.92,
metalness: 0.02,
vertexColors: true
});
const landColumns = 27;
const landRows = 8;
const land = new THREE.InstancedMesh(
landGeometry,
landMaterial,
landColumns * landRows
);
let landIndex = 0;
for (let ix = 0; ix < landColumns; ix++) {
for (let iz = 0; iz < landRows; iz++) {
const x = -26 + ix * 2;
const z = -16 + iz * 2;
dummy.position.set(x, 0.44, z);
dummy.scale.set(1.93, 0.9, 1.93);
dummy.updateMatrix();
land.setMatrixAt(landIndex, dummy.matrix);
const shade = 0.18 + ((ix * 7 + iz * 3) % 5) * 0.009;
land.setColorAt(
landIndex,
new THREE.Color().setHSL(0.54, 0.12, shade)
);
landIndex++;
}
}
land.receiveShadow = true;
land.castShadow = true;
scene.add(land);
// Quay face, rails, safety markings, and lane markings.
for (let x = -25; x <= 25; x += 2) {
box(1.92, 1.25, 0.5, 0x405760, x, 0.25, -1.05, scene, true);
if (x % 4 === 0) {
box(1.1, 0.06, 0.28, 0xe7b84e, x, 1.01, -1.47, scene);
}
}
box(46, 0.16, 0.14, 0x1d3038, 0, 1.02, -6.0, scene);
box(46, 0.16, 0.14, 0x1d3038, 0, 1.02, -2.0, scene);
for (let x = -22; x <= 22; x += 4) {
box(1.7, 0.04, 0.12, 0xb89a51, x, 1.02, -9.1, scene);
}
// Voxel terminal building.
box(10, 4.3, 5.8, 0x526d77, 0, 3.05, -12.0, scene, true);
box(11, 0.55, 6.6, 0x263e49, 0, 5.42, -12.0, scene, true);
box(9.5, 0.45, 5.4, 0x344f5a, 0, 5.88, -12.0, scene, true);
for (let x = -3.5; x <= 3.5; x += 1.75) {
box(1.0, 1.0, 0.08, 0x8bc9d1, x, 2.2, -9.05, scene);
}
box(2.0, 2.7, 0.12, 0x253d47, 0, 2.25, -9.02, scene);
box(2.4, 0.28, 1.0, 0xd39a43, 0, 3.85, -8.8, scene);
// Small operations block.
box(5, 2.6, 4.2, 0x687a7d, -19, 2.2, -12.0, scene, true);
box(5.5, 0.4, 4.7, 0x2c424b, -19, 3.7, -12.0, scene, true);
box(1.0, 0.9, 0.08, 0x9ed8dc, -19, 2.1, -9.85, scene);
// Bollards and beacons.
for (const berth of Object.values(berths)) {
for (const dx of [-4.5, 4.5]) {
box(0.42, 0.6, 0.42, 0x233942, berth.x + dx, 1.2, -1.65, scene);
box(0.54, 0.15, 0.54, 0xd0a84f, berth.x + dx, 1.56, -1.65, scene);
}
box(11, 0.06, 1.25, 0x315661, berth.x, 0.95, -3.5, scene);
box(11, 0.06, 0.16, 0x65c9c6, berth.x, 1.0, -2.9, scene);
}
}
function createPads() {
for (const berth of Object.values(berths)) {
for (let index = 0; index < 2; index++) {
const offset = index === 0 ? -1.08 : 1.08;
const x = berth.x + offset;
const z = -4.35;
box(2.0, 0.08, 1.4, 0x162e38, x, 0.98, z, scene, true);
box(2.0, 0.06, 0.08, 0x5c777e, x, 1.04, z - 0.66, scene);
box(2.0, 0.06, 0.08, 0x5c777e, x, 1.04, z + 0.66, scene);
box(0.08, 0.06, 1.4, 0x5c777e, x - 0.96, 1.04, z, scene);
box(0.08, 0.06, 1.4, 0x5c777e, x + 0.96, 1.04, z, scene);
const delivered = box(
1.82,
1.12,
1.08,
0xffffff,
x,
1.62,
z,
scene,
true
);
delivered.material = delivered.material.clone();
delivered.visible = false;
berth.slots.push({
x,
z,
occupiedBy: null,
transferId: null,
mesh: delivered
});
}
}
}
function createShip(ship) {
const group = new THREE.Group();
group.visible = false;
scene.add(group);
box(7.6, 0.62, 2.5, ship.hull, 0, 0.55, 0, group, true);
box(7.8, 0.18, 2.6, 0x71868b, 0, 0.94, 0, group, true);
// Stepped bow.
box(0.8, 0.52, 2.0, ship.hull, 4.1, 0.57, 0, group, true);
box(0.6, 0.38, 1.25, ship.hull, 4.7, 0.54, 0, group, true);
// Aft superstructure.
box(1.35, 1.65, 1.95, 0xd6d8d1, -3.0, 1.82, 0, group, true);
box(1.55, 0.28, 2.1, ship.accent, -3.0, 2.78, 0, group, true);
box(0.42, 1.05, 0.48, 0x334c58, -3.3, 3.38, 0, group, true);
box(0.28, 0.3, 1.9, 0x263f4b, -3.0, 2.12, 0, group);
// Tracked source containers.
ship.transfers.forEach((transfer, index) => {
const container = box(
1.72,
1.08,
1.06,
transfer.color,
transfer.sourceX,
1.63,
0,
group,
true
);
ship.cargoMeshes.push(container);
});
ship.group = group;
}
function createCrane() {
const root = new THREE.Group();
root.position.x = crane.x;
scene.add(root);
const yellow = 0xe6ad3e;
const dark = 0x263f49;
for (const x of [-2.8, 2.8]) {
for (const z of [-6, -2]) {
box(0.48, 7.65, 0.48, yellow, x, 4.78, z, root, true);
box(0.9, 0.42, 0.9, dark, x, 1.18, z, root, true);
}
}
for (const z of [-6, -2]) {
box(6.2, 0.5, 0.55, yellow, 0, 8.48, z, root, true);
}
box(0.48, 0.55, 12.5, yellow, -1.0, 8.48, 0, root, true);
box(0.48, 0.55, 12.5, yellow, 1.0, 8.48, 0, root, true);
box(2.5, 0.32, 0.65, dark, 0, 8.42, 6.0, root, true);
// Voxel machinery house.
box(1.75, 1.1, 1.7, 0x3c5660, 2.0, 9.18, -4.6, root, true);
box(1.45, 0.35, 1.45, dark, 2.0, 9.88, -4.6, root);
const trolley = new THREE.Group();
trolley.position.set(0, 8.12, 0);
root.add(trolley);
box(2.7, 0.36, 1.05, dark, 0, 0, 0, trolley, true);
box(0.85, 0.65, 0.85, 0x8bc8cd, 1.45, -0.28, 0, trolley, true);
const cable = box(0.055, 1, 0.055, 0x20343c, 0, -0.3, 0, trolley);
const spreader = box(1.85, 0.13, 1.15, yellow, 0, -0.8, 0, trolley, true);
const held = box(1.72, 1.08, 1.06, 0xffffff, 0, -1.45, 0, trolley, true);
held.material = held.material.clone();
held.visible = false;
root.userData.trolley = trolley;
root.userData.cable = cable;
root.userData.spreader = spreader;
root.userData.held = held;
return root;
}
createVoxelTerrain();
createPads();
ships.forEach(createShip);
const craneRoot = createCrane();
class CameraRig {
constructor() {
this.target = new THREE.Vector3(0, 1.5, 2.5);
this.radius = 43;
this.theta = 0.73;
this.phi = 0.86;
this.dragging = false;
this.lastX = 0;
this.lastY = 0;
this.mode = "orbit";
const canvas = renderer.domElement;
canvas.addEventListener("pointerdown", (event) => {
this.dragging = true;
this.lastX = event.clientX;
this.lastY = event.clientY;
this.mode = event.shiftKey || event.button === 2 ? "pan" : "orbit";
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!this.dragging) return;
const dx = event.clientX - this.lastX;
const dy = event.clientY - this.lastY;
this.lastX = event.clientX;
this.lastY = event.clientY;
if (this.mode === "orbit") {
this.theta -= dx * 0.006;
this.phi = THREE.MathUtils.clamp(this.phi + dy * 0.005, 0.28, 1.28);
} else {
const scale = this.radius * 0.0014;
this.target.x -= dx * scale;
this.target.z -= dy * scale;
this.target.x = THREE.MathUtils.clamp(this.target.x, -22, 22);
this.target.z = THREE.MathUtils.clamp(this.target.z, -12, 20);
}
});
const stop = () => {
this.dragging = false;
};
canvas.addEventListener("pointerup", stop);
canvas.addEventListener("pointercancel", stop);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
this.radius = THREE.MathUtils.clamp(
this.radius * Math.exp(event.deltaY * 0.001),
24,
68
);
},
{ passive: false }
);
this.update();
}
reset() {
this.target.set(0, 1.5, 2.5);
this.radius = 43;
this.theta = 0.73;
this.phi = 0.86;
this.update();
}
update() {
const horizontal = Math.sin(this.phi) * this.radius;
camera.position.set(
this.target.x + horizontal * Math.sin(this.theta),
this.target.y + Math.cos(this.phi) * this.radius,
this.target.z + horizontal * Math.cos(this.theta)
);
camera.lookAt(this.target);
}
}
const cameraRig = new CameraRig();
function formatTime(minute) {
const normalized = ((minute % 1440) + 1440) % 1440;
const hours = Math.floor(normalized / 60);
const minutes = Math.floor(normalized % 60);
return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
function windowAt(berthId, minute) {
return (
berths[berthId].windows.find(
(window) => minute >= window.start && minute <= window.end
) || null
);
}
function nextWindow(berthId, minute) {
return (
berths[berthId].windows.find((window) => window.end > minute) || null
);
}
function logEvent(message, type = "normal") {
events.unshift({
time: simulationMinute,
message,
type
});
if (events.length > 40) events.length = 40;
}
function allTransfers() {
return ships.flatMap((ship) => ship.transfers);
}
function transferById(id) {
return allTransfers().find((transfer) => transfer.id === id);
}
function activeJobForShip(shipId) {
return crane.job && crane.job.ship.id === shipId ? crane.job : null;
}
function occupiedSlots() {
return Object.values(berths).reduce(
(sum, berth) =>
sum + berth.slots.filter((slot) => slot.occupiedBy).length,
0
);
}
function waitingShipCount() {
return ships.filter((ship) =>
["waiting_window", "waiting_berth"].includes(ship.status)
).length;
}
function blockedTransferCount() {
return allTransfers().filter((transfer) =>
["blocked_window", "blocked_capacity"].includes(transfer.state)
).length;
}
function dockShip(ship, window) {
const berth = berths[ship.berth];
ship.status = "docked";
ship.dockAt = simulationMinute;
ship.dockWindowIndex = berth.windows.indexOf(window);
berth.occupant = ship.id;
ship.transfers.forEach((transfer) => {
transfer.state = "waiting_crane";
transfer.reason = "Waiting for the shared crane";
});
logEvent(
`${ship.name} docked at berth ${ship.berth}; ${ship.services.length} lifts queued.`,
"good"
);
}
function completeShip(ship) {
if (ship.status === "departed") return;
ship.status = "departed";
ship.completeAt = simulationMinute;
berths[ship.berth].occupant = null;
logEvent(
`${ship.name} completed modeled service and departed berth ${ship.berth}.`,
"good"
);
}
function blockShipForWindow(ship) {
const pending = ship.transfers.filter((transfer) =>
["waiting_crane", "blocked_capacity"].includes(transfer.state)
);
pending.forEach((transfer) => {
transfer.state = "blocked_window";
transfer.reason = "Docking window closed before crane service";
});
ship.status = "window_closed";
logEvent(
`${ship.name}: ${pending.length} transfer(s) blocked by docking-window close.`,
"error"
);
if (!activeJobForShip(ship.id)) {
berths[ship.berth].occupant = null;
}
}
function updateShips() {
ships.forEach((ship) => {
if (ship.status === "scheduled" && simulationMinute >= ship.arrival) {
ship.status = "waiting_window";
ship.arrivedAt = simulationMinute;
logEvent(`${ship.name} arrived and is awaiting berth eligibility.`);
}
if (["waiting_window", "waiting_berth"].includes(ship.status)) {
const window = windowAt(ship.berth, simulationMinute);
const berth = berths[ship.berth];
if (!window) {
ship.status = "waiting_window";
} else if (berth.occupant) {
ship.status = "waiting_berth";
} else {
dockShip(ship, window);
}
}
if (ship.status === "docked") {
const window = berths[ship.berth].windows[ship.dockWindowIndex];
if (simulationMinute > window.end) {
blockShipForWindow(ship);
}
}
const delivered = ship.transfers.every((transfer) =>
["staged", "cleared"].includes(transfer.state)
);
if (
delivered &&
["docked", "window_closed"].includes(ship.status)
) {
completeShip(ship);
}
});
}
function updateClosedShips() {
ships.forEach((ship) => {
if (ship.status !== "window_closed") return;
const job = activeJobForShip(ship.id);
if (!job) {
berths[ship.berth].occupant = null;
}
});
}
function selectCraneJob() {
if (crane.job) return;
const dockedShips = ships
.filter((ship) => ship.status === "docked")
.sort((a, b) => a.dockAt - b.dockAt);
for (const ship of dockedShips) {
const berth = berths[ship.berth];
if (!windowAt(ship.berth, simulationMinute)) continue;
for (const transfer of ship.transfers) {
if (!["waiting_crane", "blocked_capacity"].includes(transfer.state)) {
continue;
}
const slot = berth.slots.find(
(candidate) =>
!candidate.occupiedBy && !candidate.transferId
);
if (!slot) {
if (transfer.state !== "blocked_capacity") {
transfer.state = "blocked_capacity";
transfer.reason =
`Handoff pads full (${berth.slots.length}/${berth.slots.length}); remove a staged box`;
logEvent(
`${transfer.code} blocked: berth ${ship.berth} handoff pads are full.`,
"error"
);
}
continue;
}
slot.transferId = transfer.id;
slot.occupiedBy = transfer.id;
transfer.slot = slot;
transfer.state = "en_route";
transfer.reason = `Crane travelling to berth ${ship.berth}`;
const targetX = berth.x;
const travelDuration =
Math.abs(targetX - crane.x) < 0.1 ? 0.8 : 4;
crane.job = {
ship,
transfer,
berth,
slot,
phase: "travel",
travelElapsed: 0,
travelDuration,
workElapsed: 0,
startX: crane.x,
targetX,
timelineStart: simulationMinute
};
crane.state = "moving";
craneJobs.push({
start: simulationMinute,
end: null,
berth: ship.berth,
ship: ship.name
});
logEvent(
`Shared crane committed to ${ship.name} at berth ${ship.berth}.`,
"normal"
);
return;
}
}
}
function updateCrane(dt) {
if (!crane.job) {
crane.state = "idle";
return;
}
const job = crane.job;
if (job.phase === "travel") {
job.travelElapsed += dt;
const progress = Math.min(
job.travelElapsed / job.travelDuration,
1
);
const eased = progress * progress * (3 - 2 * progress);
crane.x = THREE.MathUtils.lerp(
job.startX,
job.targetX,
eased
);
if (progress >= 1) {
crane.x = job.targetX;
job.phase = "work";
job.workElapsed = 0;
crane.state = "working";
job.transfer.state = "in_transfer";
job.transfer.reason = `Crane serving berth ${job.berth.id}`;
job.ship.cargoMeshes[
job.ship.transfers.indexOf(job.transfer)
].visible = false;
}
return;
}
job.workElapsed += dt;
job.transfer.progress = Math.min(
job.workElapsed / job.transfer.service,
1
);
if (job.workElapsed >= job.transfer.service) {
const transfer = job.transfer;
const slot = job.slot;
slot.mesh.visible = true;
slot.mesh.material.color.setHex(transfer.color);
transfer.state = "staged";
transfer.reason = `Staged in handoff slot ${job.berth.id}${
job.berth.slots.indexOf(slot) + 1
}`;
craneJobs[craneJobs.length - 1].end = simulationMinute;
logEvent(
`${transfer.code} staged at berth ${job.berth.id}; service ${transfer.service}m complete.`,
"good"
);
crane.job = null;
crane.state = "idle";
}
}
function clearBerthPads(berthId) {
const berth = berths[berthId];
let removed = 0;
berth.slots.forEach((slot) => {
if (!slot.occupiedBy) return;
const transfer = transferById(slot.occupiedBy);
if (!transfer || transfer.state !== "staged") return;
transfer.state = "cleared";
transfer.reason = "Removed from modeled handoff pad";
slot.mesh.visible = false;
slot.occupiedBy = null;
slot.transferId = null;
removed++;
});
if (removed) {
logEvent(
`Removed ${removed} container(s) from berth ${berthId} handoff pads; no downstream stock assumed.`,
"normal"
);
}
}
function resetSimulation() {
simulationMinute = START_MINUTE;
events = [];
craneJobs = [];
crane.state = "idle";
crane.x = berths.A.x;
crane.job = null;
Object.values(berths).forEach((berth) => {
berth.occupant = null;
berth.slots.forEach((slot) => {
slot.occupiedBy = null;
slot.transferId = null;
slot.mesh.visible = false;
});
});
ships.forEach((ship) => {
ship.status = "scheduled";
ship.arrivedAt = null;
ship.dockAt = null;
ship.completeAt = null;
ship.dockWindowIndex = null;
ship.group.visible = false;
ship.group.position.set(0, 0, 24);
ship.cargoMeshes.forEach((mesh) => {
mesh.visible = true;
});
ship.transfers.forEach((transfer) => {
transfer.state = "scheduled";
transfer.reason = "Awaiting vessel arrival";
transfer.slot = null;
transfer.progress = 0;
});
});
logEvent(
"Synthetic schedule loaded: 2 berths, 1 shared crane, 4 explicit handoff slots.",
"normal"
);
updateUI();
}
function simulate(dt) {
if (!playing) return;
simulationMinute += dt;
updateShips();
updateClosedShips();
updateCrane(dt);
selectCraneJob();
}
function waitingPosition(index) {
const positions = [
{ x: -20, z: 11 },
{ x: 0, z: 13 },
{ x: 20, z: 11 },
{ x: -10, z: 19 },
{ x: 10, z: 19 }
];
return positions[index % positions.length];
}
function updateShipVisuals(dt) {
const waitingShips = ships.filter((ship) =>
["waiting_window", "waiting_berth"].includes(ship.status)
);
ships.forEach((ship) => {
if (ship.status === "scheduled") {
ship.group.visible = false;
return;
}
ship.group.visible = true;
if (["docked", "window_closed"].includes(ship.status)) {
ship.targetPosition.set(berths[ship.berth].x, 0, 4.15);
} else if (ship.status === "departed") {
ship.targetPosition.set(36, 0, 14);
if (ship.group.position.x > 32) ship.group.visible = false;
} else {
const index = waitingShips.indexOf(ship);
const position = waitingPosition(Math.max(index, 0));
ship.targetPosition.set(position.x, 0, position.z);
}
const smoothing = 1 - Math.exp(-Math.max(dt, 0.001) * 3.5);
ship.group.position.lerp(ship.targetPosition, smoothing);
const desiredRotation =
ship.status === "departed" ? -0.08 : 0;
ship.group.rotation.y = THREE.MathUtils.lerp(
ship.group.rotation.y,
desiredRotation,
smoothing
);
});
}
function setCraneVisual() {
const trolley = craneRoot.userData.trolley;
const cable = craneRoot.userData.cable;
const spreader = craneRoot.userData.spreader;
const held = craneRoot.userData.held;
craneRoot.position.x = crane.x;
trolley.position.set(0, 8.12, -0.8);
cable.scale.set(0.055, 0.2, 0.055);
cable.position.set(0, -0.28, 0);
spreader.position.set(0, -0.38, 0);
held.visible = false;
const job = crane.job;
if (!job) return;
if (job.phase === "travel") {
return;
}
const p = job.transfer.progress;
const sourceX = job.transfer.sourceX;
const padX = job.slot.x - job.berth.x;
const sourceZ = 4.15;
const padZ = job.slot.z;
let x = sourceX;
let z = sourceZ;
let length = 0.2;
let showHeld = false;
if (p < 0.14) {
const u = p / 0.14;
length = THREE.MathUtils.lerp(0.2, 5.2, u);
} else if (p < 0.28) {
const u = (p - 0.14) / 0.14;
length = THREE.MathUtils.lerp(5.2, 0.2, u);
showHeld = u > 0.25;
} else if (p < 0.5) {
const u = (p - 0.28) / 0.22;
x = THREE.MathUtils.lerp(sourceX, padX, u);
z = THREE.MathUtils.lerp(sourceZ, padZ, u);
showHeld = true;
} else if (p < 0.68) {
const u = (p - 0.5) / 0.18;
x = padX;
z = padZ;
length = THREE.MathUtils.lerp(0.2, 5.7, u);
showHeld = true;
} else if (p < 0.76) {
x = padX;
z = padZ;
length = 5.7;
showHeld = true;
} else if (p < 0.9) {
const u = (p - 0.76) / 0.14;
x = padX;
z = padZ;
length = THREE.MathUtils.lerp(5.7, 0.2, u);
showHeld = false;
} else {
x = padX;
z = padZ;
length = 0.2;
showHeld = false;
}
trolley.position.set(x, 8.12, z);
cable.scale.set(0.055, length, 0.055);
cable.position.set(0, -0.28 - length / 2, 0);
spreader.position.set(0, -0.35 - length, 0);
held.position.set(0, -0.95 - length, 0);
held.visible = showHeld;
if (showHeld) {
held.material.color.setHex(job.transfer.color);
}
if (p > 0.72) {
job.slot.mesh.visible = true;
job.slot.mesh.material.color.setHex(job.transfer.color);
}
}
const worldLabels = [];
function rebuildWorldLabels() {
worldLabels.length = 0;
const layer = document.getElementById("labels");
layer.innerHTML = "";
Object.values(berths).forEach((berth) => {
const occupied = berth.occupant
? ships.find((ship) => ship.id === berth.occupant)
: null;
const text = occupied
? `BERTH ${berth.id} · ${occupied.name}`
: `BERTH ${berth.id} · ${windowAt(berth.id, simulationMinute) ? "OPEN" : "CLOSED"}`;
const element = document.createElement("div");
element.className = `world-label ${occupied ? "docked" : ""}`;
element.textContent = text;
layer.appendChild(element);
worldLabels.push({
element,
position: new THREE.Vector3(berth.x, 2.0, -1.3)
});
});
ships.forEach((ship) => {
if (!["waiting_window", "waiting_berth", "docked"].includes(ship.status)) {
return;
}
const element = document.createElement("div");
element.className = `world-label ${
ship.status === "docked" ? "docked" : "waiting"
}`;
element.textContent =
ship.status === "docked"
? `${ship.name} · DOCKED`
: `${ship.name} · WAITING`;
layer.appendChild(element);
worldLabels.push({
element,
position: new THREE.Vector3()
});
worldLabels[worldLabels.length - 1].ship = ship;
});
const craneLabel = document.createElement("div");
craneLabel.className = "world-label crane";
craneLabel.textContent =
crane.job && crane.state === "moving"
? `SHARED CRANE → ${crane.job.berth.id}`
: crane.job
? `SHARED CRANE · ${crane.job.ship.name}`
: "SHARED CRANE · IDLE";
layer.appendChild(craneLabel);
worldLabels.push({
element: craneLabel,
position: new THREE.Vector3(crane.x, 10.2, 0)
});
}
function updateProjectedLabels() {
const width = renderer.domElement.clientWidth;
const height = renderer.domElement.clientHeight;
worldLabels.forEach((label) => {
const position = label.ship
? label.ship.group.position.clone().add(new THREE.Vector3(0, 4.4, 0))
: label.position;
const projected = position.project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
label.element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
label.element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
});
}
function renderBerthCards() {
const container = document.getElementById("berthCards");
container.innerHTML = Object.values(berths)
.map((berth) => {
const occupant = berth.occupant
? ships.find((ship) => ship.id === berth.occupant)
: null;
const activeWindow = windowAt(berth.id, simulationMinute);
const next = nextWindow(berth.id, simulationMinute);
const staged = berth.slots.filter((slot) => slot.occupiedBy).length;
const windowText = berth.windows
.map(
(window) =>
`<b>${formatTime(window.start)}–${formatTime(window.end)}</b>`
)
.join(" / ");
const status = occupant
? `Occupied · ${occupant.name}`
: activeWindow
? "Open · no vessel"
: "Closed";
return `
<div class="berth-card">
<div class="berth-head">
<div class="berth-name">
<i class="berth-dot ${berth.id === "B" ? "b" : ""}"></i>
BERTH ${berth.id}
</div>
<div class="berth-status">${status}</div>
</div>
<div class="berth-grid">
<div class="berth-stat">
<strong>${activeWindow ? activeWindow.id : "—"}</strong>
<small>Current window</small>
</div>
<div class="berth-stat">
<strong>${staged} / 2</strong>
<small>Handoff pads</small>
</div>
</div>
<div class="window-list">
Windows: ${windowText}<br>
${next ? `Next eligible: ${formatTime(next.start)}` : "No further window"}
</div>
<button
class="mini-button"
data-clear="${berth.id}"
${staged ? "" : "disabled"}
type="button"
>
Remove staged boxes from pads
</button>
</div>
`;
})
.join("");
}
function renderShipList() {
const container = document.getElementById("shipList");
document.getElementById("vesselCount").textContent = `${ships.length} vessels`;
container.innerHTML = ships
.map((ship) => {
const status = stateLabels[ship.status] || ship.status;
const badgeClass =
ship.status === "window_closed"
? "red"
: stateClasses[ship.status] || "gray";
const totalService = ship.services.reduce((a, b) => a + b, 0);
const done = ship.transfers.filter((transfer) =>
["staged", "cleared"].includes(transfer.state)
).length;
return `
<div class="ship-card">
<div class="ship-name">${ship.name}</div>
<div class="badge ${badgeClass}">${status}</div>
<div class="ship-meta">
Berth ${ship.berth} · Arrival ${formatTime(ship.arrival)} ·
${totalService}m crane service · ${done}/${ship.transfers.length} lifts
</div>
</div>
`;
})
.join("");
}
function renderTransferLedger() {
const transfers = allTransfers();
const container = document.getElementById("transferLedger");
document.getElementById("transferCount").textContent =
`${transfers.length} tracked`;
container.innerHTML = transfers
.map((transfer) => {
const badgeClass =
transfer.state === "window_closed" ||
transfer.state === "blocked_capacity"
? "red"
: stateClasses[transfer.state] || "gray";
const blocked = [
"blocked_window",
"blocked_capacity"
].includes(transfer.state);
return `
<div class="ledger-row">
<div class="ledger-id">${transfer.code}</div>
<div class="badge ${badgeClass}">
${stateLabels[transfer.state] || transfer.state}
</div>
<div class="ledger-route">
${transfer.shipName} → BERTH ${transfer.berthId}
</div>
<div class="ledger-reason ${blocked ? "blocked" : ""}">
${transfer.reason}
</div>
<div class="ledger-service">${transfer.service}m service</div>
</div>
`;
})
.join("");
}
function renderTimeline() {
const axis = document.getElementById("timelineAxis");
const rows = document.getElementById("timelineRows");
const span = HORIZON_END - START_MINUTE;
const percentage = (minute) =>
THREE.MathUtils.clamp((minute - START_MINUTE) / span, 0, 1) * 100;
axis.innerHTML = "";
for (let minute = START_MINUTE; minute <= HORIZON_END; minute += 120) {
const element = document.createElement("span");
element.style.left = `${percentage(minute)}%`;
element.textContent = formatTime(minute);
axis.appendChild(element);
}
let html = "";
for (const berth of Object.values(berths)) {
const windows = berth.windows
.map(
(window) => `
<div
class="timeline-window"
style="left:${percentage(window.start)}%;width:${
percentage(window.end) - percentage(window.start)
}%"
title="Window ${window.id}"
></div>
`
)
.join("");
const services = ships
.filter((ship) => ship.berth === berth.id && ship.dockAt !== null)
.map((ship) => {
const end = ship.completeAt ?? simulationMinute;
return `
<div
class="timeline-service"
style="left:${percentage(ship.dockAt)}%;width:${
percentage(end) - percentage(ship.dockAt)
}%"
title="${ship.name}: ${formatTime(ship.dockAt)}–${formatTime(end)}"
></div>
`;
})
.join("");
html += `
<div class="timeline-row">
<div class="timeline-row-label">BERTH ${berth.id}</div>
<div class="timeline-track">
${windows}
${services}
<div class="timeline-now" style="left:${percentage(simulationMinute)}%"></div>
</div>
</div>
`;
}
const craneBlocks = craneJobs
.map((job) => {
const end = job.end ?? simulationMinute;
return `
<div
class="timeline-crane"
style="left:${percentage(job.start)}%;width:${
percentage(end) - percentage(job.start)
}%"
title="Crane: ${job.ship} at berth ${job.berth}"
></div>
`;
})
.join("");
html += `
<div class="timeline-row">
<div class="timeline-row-label">CRANE</div>
<div class="timeline-track">
${craneBlocks}
<div class="timeline-now" style="left:${percentage(simulationMinute)}%"></div>
</div>
</div>
`;
rows.innerHTML = html;
}
function renderActivity() {
const container = document.getElementById("activityLog");
container.innerHTML = events
.slice(0, 12)
.map(
(event) => `
<div class="activity-row ${event.type}">
<div class="activity-time">${formatTime(event.time)}</div>
<div class="activity-text">${event.message}</div>
</div>
`
)
.join("");
}
function updateUI() {
document.getElementById("clock").textContent = formatTime(simulationMinute);
const craneText = crane.job
? crane.state === "moving"
? `→ ${crane.job.berth.id}`
: crane.job.ship.name
: `IDLE · ${crane.x < 0 ? "A" : "B"}`;
document.getElementById("metricCrane").textContent = craneText;
const occupied = Object.values(berths).filter(
(berth) => berth.occupant
).length;
document.getElementById("metricBerths").textContent = `${occupied} / 2`;
const waiting = waitingShipCount();
const blocked = blockedTransferCount();
const used = occupiedSlots();
document.getElementById("metricWaiting").textContent = waiting;
document.getElementById("metricBlocked").textContent = blocked;
document.getElementById("metricSlots").textContent = `${used} / 4`;
document.getElementById("capacityUsed").textContent = `${used} / 4`;
document
.getElementById("metricWaitingCard")
.classList.toggle("alert", waiting > 0);
document
.getElementById("metricBlockedCard")
.classList.toggle("alert", blocked > 0);
const capacityCells = document.querySelectorAll(
"#capacityBar i"
);
capacityCells.forEach((cell, index) => {
cell.classList.toggle("occupied", index < used);
});
renderBerthCards();
renderShipList();
renderTransferLedger();
renderTimeline();
renderActivity();
rebuildWorldLabels();
}
document.getElementById("leftPanel").addEventListener("click", (event) => {
const button = event.target.closest("[data-clear]");
if (!button) return;
clearBerthPads(button.dataset.clear);
updateUI();
});
document.getElementById("playButton").addEventListener("click", () => {
playing = !playing;
document.getElementById("playButton").textContent = playing
? "Pause"
: "Play";
});
document.getElementById("resetButton").addEventListener("click", () => {
playing = true;
document.getElementById("playButton").textContent = "Pause";
resetSimulation();
});
document.getElementById("speedGroup").addEventListener("click", (event) => {
const button = event.target.closest("[data-speed]");
if (!button) return;
speed = Number(button.dataset.speed);
document.querySelectorAll("#speedGroup button").forEach((candidate) => {
candidate.classList.toggle("active", candidate === button);
});
});
document.getElementById("cameraReset").addEventListener("click", () => {
cameraRig.reset();
});
function resize() {
const viewport = document.getElementById("viewport");
const width = viewport.clientWidth;
const height = viewport.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(
document.getElementById("viewport")
);
resetSimulation();
resize();
let previousTime = performance.now();
let uiAccumulator = 0;
function frame(now) {
const realDt = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
simulate(realDt * speed);
updateShipVisuals(realDt * Math.min(speed, 5));
setCraneVisual();
cameraRig.update();
updateProjectedLabels();
uiAccumulator += realDt;
if (uiAccumulator >= 0.2) {
uiAccumulator = 0;
updateUI();
}
renderer.render(scene, camera);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>
</html>
```