Prompt specification
Build or customize the Three.js 3D scene "Reservation Deadlock at a Junction" 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: Reservation Deadlock at a Junction
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/reservation-deadlock-at-a-junction-x2128
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows railway block occupancy and train exclusion. Create a bounded railway puzzle with conflicting reservations. Show the deadlock and let users alter the reservation order while preserving the declared track-exclusion rules. Low-poly.
Working Three.js Starter (reservation-deadlock-at-a-junction-x2128):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Railway Block — Deadlock Lab</title>
<style>
:root {
--bg: #07111f;
--panel: #0b1727;
--panel-2: #101f32;
--line: rgba(151, 181, 209, 0.16);
--text: #eaf4fb;
--muted: #8198aa;
--cyan: #55d8ff;
--green: #62e6ae;
--red: #ff6474;
--amber: #ffb454;
--purple: #aa91ff;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button { font: inherit; }
#app {
width: 100vw;
height: 100vh;
display: grid;
grid-template-columns: 320px minmax(0, 1fr);
grid-template-rows: 72px minmax(0, 1fr) 250px;
background:
radial-gradient(circle at 72% 20%, rgba(30, 93, 124, 0.14), transparent 34%),
var(--bg);
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
border-bottom: 1px solid var(--line);
background: rgba(7, 17, 31, 0.88);
backdrop-filter: blur(16px);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 36px;
height: 36px;
display: grid;
place-items: center;
border: 1px solid rgba(85, 216, 255, 0.38);
border-radius: 9px;
color: var(--cyan);
background: rgba(85, 216, 255, 0.07);
box-shadow: inset 0 0 18px rgba(85, 216, 255, 0.06);
}
.brand-mark svg { width: 23px; height: 23px; }
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.15;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.header-right {
display: flex;
align-items: center;
gap: 18px;
flex-shrink: 0;
}
.network-code {
color: var(--muted);
font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
text-align: right;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.status-badge {
min-width: 116px;
padding: 10px 13px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
color: var(--muted);
font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.12em;
text-align: center;
text-transform: uppercase;
}
.status-badge.running {
color: var(--cyan);
border-color: rgba(85, 216, 255, 0.35);
background: rgba(85, 216, 255, 0.08);
}
.status-badge.deadlock {
color: var(--red);
border-color: rgba(255, 100, 116, 0.42);
background: rgba(255, 100, 116, 0.09);
animation: alarm 1.7s ease-in-out infinite;
}
.status-badge.success {
color: var(--green);
border-color: rgba(98, 230, 174, 0.38);
background: rgba(98, 230, 174, 0.08);
}
@keyframes alarm {
50% { box-shadow: 0 0 24px rgba(255, 100, 116, 0.12); }
}
aside {
grid-column: 1;
grid-row: 2 / 4;
min-height: 0;
overflow-y: auto;
border-right: 1px solid var(--line);
background: rgba(9, 21, 36, 0.9);
scrollbar-width: thin;
scrollbar-color: #294158 transparent;
}
.side-section {
padding: 20px;
border-bottom: 1px solid var(--line);
}
.eyebrow {
margin: 0 0 10px;
color: var(--cyan);
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.side-section h2 {
margin: 0 0 10px;
font-size: 17px;
line-height: 1.25;
letter-spacing: -0.02em;
}
.side-section p {
margin: 0;
color: #a9bdca;
font-size: 12px;
line-height: 1.6;
}
.route-map {
margin-top: 16px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(0, 0, 0, 0.13);
}
.route-map svg {
display: block;
width: 100%;
height: auto;
}
.rule {
display: grid;
grid-template-columns: 38px 1fr;
gap: 9px;
margin-top: 14px;
}
.rule-code {
color: var(--cyan);
font: 700 10px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.rule strong {
display: block;
margin-bottom: 3px;
color: #dceaf3;
font-size: 11px;
letter-spacing: 0.03em;
text-transform: uppercase;
}
.rule p {
font-size: 11px;
line-height: 1.45;
}
.diagnosis {
padding: 14px;
border: 1px solid var(--line);
border-left: 3px solid var(--muted);
border-radius: 8px;
background: rgba(255, 255, 255, 0.025);
}
.diagnosis.deadlock {
border-left-color: var(--red);
background: rgba(255, 100, 116, 0.055);
}
.diagnosis.success {
border-left-color: var(--green);
background: rgba(98, 230, 174, 0.05);
}
.diagnosis.running {
border-left-color: var(--cyan);
}
.diagnosis h3 {
margin: 0 0 7px;
font-size: 13px;
}
.diagnosis p {
font-size: 11px;
line-height: 1.55;
}
.train-list {
display: grid;
gap: 8px;
}
.train-row {
display: grid;
grid-template-columns: 8px 1fr auto;
align-items: center;
gap: 10px;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.022);
}
.train-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--train-color);
box-shadow: 0 0 12px color-mix(in srgb, var(--train-color) 55%, transparent);
}
.train-name {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.train-route {
margin-top: 3px;
color: var(--muted);
font: 10px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.train-state {
color: var(--muted);
font: 9px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
text-align: right;
text-transform: uppercase;
}
#viewport {
grid-column: 2;
grid-row: 2;
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 45%, rgba(30, 78, 102, 0.18), transparent 45%),
#07111f;
}
#viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
#viewport canvas:active { cursor: grabbing; }
.view-chrome {
position: absolute;
inset: 0;
z-index: 3;
pointer-events: none;
}
.view-title {
position: absolute;
top: 20px;
left: 22px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(7, 17, 31, 0.72);
backdrop-filter: blur(10px);
}
.view-title strong {
display: block;
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.view-title span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
}
.camera-hint {
position: absolute;
right: 18px;
bottom: 16px;
color: rgba(185, 207, 220, 0.58);
font: 9px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.04em;
text-align: right;
text-transform: uppercase;
}
#labels {
position: absolute;
inset: 0;
z-index: 2;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
top: 0;
left: 0;
white-space: nowrap;
will-change: transform;
}
.block-label {
min-width: 88px;
padding: 6px 9px;
border: 1px solid rgba(150, 187, 211, 0.26);
border-radius: 7px;
background: rgba(6, 17, 29, 0.88);
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.22);
text-align: center;
}
.block-label strong {
display: block;
color: #dceaf3;
font: 800 12px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.block-label span {
display: block;
margin-top: 4px;
color: var(--muted);
font: 8px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.block-label.occupied {
border-color: color-mix(in srgb, var(--owner-color) 65%, transparent);
}
.block-label.occupied span { color: var(--owner-color); }
.train-label {
padding: 4px 7px;
border: 1px solid color-mix(in srgb, var(--train-color) 55%, transparent);
border-radius: 5px;
background: rgba(7, 17, 31, 0.9);
color: var(--train-color);
font: 800 8px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
box-shadow: 0 5px 16px rgba(0, 0, 0, 0.25);
}
#queuePanel {
grid-column: 2;
grid-row: 3;
min-width: 0;
min-height: 0;
overflow: hidden;
border-top: 1px solid var(--line);
background: rgba(9, 21, 36, 0.94);
}
.queue-header {
height: 60px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
padding: 0 18px;
border-bottom: 1px solid var(--line);
}
.queue-heading {
min-width: 0;
}
.queue-heading strong {
display: block;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.queue-heading span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.actions {
display: flex;
align-items: center;
gap: 7px;
flex-shrink: 0;
}
.button {
padding: 8px 10px;
border: 1px solid rgba(151, 181, 209, 0.2);
border-radius: 7px;
background: rgba(255, 255, 255, 0.035);
color: #bfd0dc;
cursor: pointer;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.045em;
text-transform: uppercase;
transition: border-color 150ms, color 150ms, background 150ms, transform 150ms;
}
.button:hover:not(:disabled) {
border-color: rgba(85, 216, 255, 0.45);
color: var(--text);
background: rgba(85, 216, 255, 0.08);
transform: translateY(-1px);
}
.button.primary {
border-color: rgba(85, 216, 255, 0.42);
background: rgba(85, 216, 255, 0.1);
color: var(--cyan);
}
.button.danger {
color: #ff9aa5;
}
.button.success {
color: var(--green);
}
.button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
#queueList {
height: calc(100% - 60px);
display: flex;
align-items: stretch;
gap: 10px;
overflow-x: auto;
overflow-y: hidden;
padding: 14px 18px 18px;
scrollbar-width: thin;
scrollbar-color: #294158 transparent;
}
.request-card {
position: relative;
flex: 0 0 205px;
display: grid;
grid-template-rows: auto auto 1fr auto;
padding: 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: linear-gradient(145deg, rgba(255,255,255,0.035), rgba(255,255,255,0.012));
cursor: grab;
user-select: none;
transition: border-color 150ms, background 150ms, transform 150ms, opacity 150ms;
}
.request-card:hover { transform: translateY(-2px); }
.request-card.dragging { opacity: 0.35; cursor: grabbing; }
.request-card.drag-over { border-color: var(--cyan); background: rgba(85, 216, 255, 0.07); }
.request-card.granted {
border-color: color-mix(in srgb, var(--train-color) 46%, transparent);
background: color-mix(in srgb, var(--train-color) 7%, transparent);
}
.request-card.blocked {
border-color: rgba(255, 100, 116, 0.52);
background: rgba(255, 100, 116, 0.065);
}
.request-card.processing {
border-color: rgba(85, 216, 255, 0.55);
box-shadow: 0 0 18px rgba(85, 216, 255, 0.08);
}
.request-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.request-number {
color: var(--muted);
font: 9px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.request-state {
color: var(--muted);
font: 8px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.granted .request-state { color: var(--green); }
.blocked .request-state { color: var(--red); }
.processing .request-state { color: var(--cyan); }
.request-main {
display: flex;
align-items: center;
gap: 9px;
margin-top: 13px;
}
.train-chip {
width: 28px;
height: 28px;
display: grid;
place-items: center;
flex-shrink: 0;
border-radius: 7px;
background: color-mix(in srgb, var(--train-color) 16%, transparent);
color: var(--train-color);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.request-main strong {
display: block;
font-size: 11px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.request-main span {
display: block;
margin-top: 4px;
color: var(--muted);
font: 9px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.request-detail {
align-self: end;
min-height: 29px;
margin-top: 12px;
color: #839aaa;
font-size: 10px;
line-height: 1.4;
}
.blocked .request-detail { color: #ff9aa5; }
.granted .request-detail { color: #9adfc6; }
.request-actions {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 10px;
padding-top: 9px;
border-top: 1px solid var(--line);
}
.move-button {
width: 25px;
height: 22px;
border: 1px solid var(--line);
border-radius: 5px;
background: rgba(255,255,255,0.025);
color: var(--muted);
cursor: pointer;
line-height: 1;
}
.move-button:hover:not(:disabled) { color: var(--cyan); border-color: rgba(85,216,255,.4); }
.move-button:disabled { opacity: .25; cursor: default; }
.drag-mark {
color: #5f7688;
font: 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.12em;
}
@media (max-width: 980px) {
html, body { overflow: auto; }
#app {
height: auto;
min-height: 100vh;
display: flex;
flex-direction: column;
}
header { min-height: 68px; }
aside {
order: 3;
border-right: 0;
border-top: 1px solid var(--line);
overflow: visible;
}
#viewport { order: 1; height: 58vh; min-height: 420px; }
#queuePanel { order: 2; height: 250px; border-left: 0; }
.network-code { display: none; }
}
@media (max-width: 620px) {
header { padding: 0 14px; }
.brand p { display: none; }
.brand h1 { font-size: 12px; }
.status-badge { min-width: 94px; padding: 9px; font-size: 9px; }
.queue-header { height: auto; min-height: 88px; align-items: flex-start; padding: 12px; flex-direction: column; }
#queueList { height: calc(100% - 88px); }
.actions { width: 100%; overflow-x: auto; }
.button { white-space: nowrap; }
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M7 3h10a3 3 0 0 1 3 3v9a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4V6a3 3 0 0 1 3-3Z"/>
<path d="M8 7h8M8 12h8M9 19l-2 3M15 19l2 3M7 16h10"/>
<circle cx="8.5" cy="16" r="1" fill="currentColor" stroke="none"/>
<circle cx="15.5" cy="16" r="1" fill="currentColor" stroke="none"/>
</svg>
</div>
<div>
<h1>Deadlock Lab / Triangle Yard</h1>
<p>Railway block occupancy & train exclusion</p>
</div>
</div>
<div class="header-right">
<div class="network-code">
NET-03 / 3 EXCLUSIVE BLOCKS<br>
HOLDOUT WAIT ENABLED
</div>
<div id="statusBadge" class="status-badge" aria-live="polite">Ready</div>
</div>
</header>
<aside>
<section class="side-section">
<p class="eyebrow">Puzzle objective</p>
<h2>Break the circular wait.</h2>
<p>
Three trains need to cross the same bounded triangle. The default queue reserves
every entry block before any train can request its continuation, creating a deadlock.
Reorder the reservation requests without violating the exclusion rules.
</p>
<div class="route-map" aria-label="Diagram of the triangle railway">
<svg viewBox="0 0 260 130">
<path d="M48 92 L130 24 L214 92 Z" fill="none" stroke="#29465d" stroke-width="12" stroke-linejoin="round"/>
<path d="M48 92 L130 24" fill="none" stroke="#ffb454" stroke-width="3" opacity=".85"/>
<path d="M130 24 L214 92" fill="none" stroke="#49d8c5" stroke-width="3" opacity=".85"/>
<path d="M214 92 L48 92" fill="none" stroke="#aa91ff" stroke-width="3" opacity=".85"/>
<g fill="#0b1727" stroke="#91adbf" stroke-width="2">
<circle cx="48" cy="92" r="10"/>
<circle cx="130" cy="24" r="10"/>
<circle cx="214" cy="92" r="10"/>
</g>
<g font-family="monospace" font-size="11" font-weight="700" text-anchor="middle">
<text x="48" y="96" fill="#eaf4fb">A</text>
<text x="130" y="28" fill="#eaf4fb">B</text>
<text x="214" y="96" fill="#eaf4fb">C</text>
</g>
<g font-family="monospace" font-size="9" text-anchor="middle">
<text x="85" y="48" fill="#ffb454">T1</text>
<text x="177" y="49" fill="#49d8c5">T2</text>
<text x="132" y="116" fill="#aa91ff">T3</text>
</g>
</svg>
</div>
</section>
<section class="side-section">
<p class="eyebrow">Declared exclusion rules</p>
<div class="rule">
<div class="rule-code">EX-01</div>
<div>
<strong>Exclusive block</strong>
<p>Blocks A, B, and C may each contain no more than one train.</p>
</div>
</div>
<div class="rule">
<div class="rule-code">EX-02</div>
<div>
<strong>Ordered route</strong>
<p>A train may reserve only the next ungranted block on its declared route.</p>
</div>
</div>
<div class="rule">
<div class="rule-code">EX-03</div>
<div>
<strong>Hold and wait</strong>
<p>A train keeps its current block while waiting for its next reservation.</p>
</div>
</div>
<div class="rule">
<div class="rule-code">EX-04</div>
<div>
<strong>Physical clearance</strong>
<p>A block is released only after the train body clears it toward its exit.</p>
</div>
</div>
</section>
<section class="side-section">
<p class="eyebrow">Dispatcher diagnosis</p>
<div id="diagnosis" class="diagnosis" aria-live="polite">
<h3 id="diagnosisTitle">Preparing simulation</h3>
<p id="diagnosisText">The default request sequence will be dispatched automatically.</p>
</div>
</section>
<section class="side-section">
<p class="eyebrow">Train roster</p>
<div id="trainList" class="train-list"></div>
</section>
</aside>
<section id="viewport" aria-label="Interactive 3D railway scene">
<div id="labels"></div>
<div class="view-chrome">
<div class="view-title">
<strong>Triangle Yard / Exclusions Active</strong>
<span>One train maximum per colored block</span>
</div>
<div class="camera-hint">
Drag to orbit · wheel to zoom<br>
Shift-drag to pan · double-click to reset view
</div>
</div>
</section>
<section id="queuePanel">
<div class="queue-header">
<div class="queue-heading">
<strong>Reservation request queue</strong>
<span>Drag cards or use arrows to change global dispatch order.</span>
</div>
<div class="actions">
<button id="resetBtn" class="button" title="Reset the simulation while keeping this order">Reset</button>
<button id="stepBtn" class="button">Step</button>
<button id="deadlockBtn" class="button danger">Deadlock preset</button>
<button id="safeBtn" class="button success">Safe order</button>
<button id="runBtn" class="button primary">Apply & run</button>
</div>
</div>
<div id="queueList"></div>
</section>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const viewport = $("#viewport");
const labelsLayer = $("#labels");
const queueList = $("#queueList");
const trainList = $("#trainList");
const statusBadge = $("#statusBadge");
const diagnosis = $("#diagnosis");
const diagnosisTitle = $("#diagnosisTitle");
const diagnosisText = $("#diagnosisText");
const TRACK_Y = 0.34;
const nodes = {
n0: new THREE.Vector3(-5, TRACK_Y, -1.3),
n1: new THREE.Vector3(0, TRACK_Y, 4.7),
n2: new THREE.Vector3(5, TRACK_Y, -1.3)
};
const blocks = {
A: { from: "n0", to: "n1", empty: 0x163d50 },
B: { from: "n1", to: "n2", empty: 0x17394b },
C: { from: "n2", to: "n0", empty: 0x15344a }
};
function outward(node, toward, amount) {
return node.clone().add(node.clone().sub(toward).normalize().multiplyScalar(amount));
}
const trainDefs = {
t1: {
id: "t1",
code: "T1",
name: "Cinder",
color: "#ffb454",
colorInt: 0xffb454,
route: ["A", "B"],
start: outward(nodes.n0, nodes.n1, 2.35),
exit: outward(nodes.n2, nodes.n1, 2.35)
},
t2: {
id: "t2",
code: "T2",
name: "Mica",
color: "#49d8c5",
colorInt: 0x49d8c5,
route: ["B", "C"],
start: outward(nodes.n1, nodes.n2, 2.35),
exit: outward(nodes.n0, nodes.n2, 2.35)
},
t3: {
id: "t3",
code: "T3",
name: "Vela",
color: "#aa91ff",
colorInt: 0xaa91ff,
route: ["C", "A"],
start: outward(nodes.n2, nodes.n0, 2.35),
exit: outward(nodes.n1, nodes.n0, 2.35)
}
};
const requests = {
r1: { id: "r1", train: "t1", block: "A", routeIndex: 0 },
r2: { id: "r2", train: "t2", block: "B", routeIndex: 0 },
r3: { id: "r3", train: "t3", block: "C", routeIndex: 0 },
r4: { id: "r4", train: "t1", block: "B", routeIndex: 1 },
r5: { id: "r5", train: "t2", block: "C", routeIndex: 1 },
r6: { id: "r6", train: "t3", block: "A", routeIndex: 1 }
};
const deadlockOrder = ["r1", "r2", "r3", "r4", "r5", "r6"];
const safeOrder = ["r1", "r4", "r2", "r5", "r3", "r6"];
let queueOrder = [...deadlockOrder];
let occupancy = {};
let running = false;
let queueIndex = 0;
let draggedId = null;
let outcome = "idle";
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 18, 34);
const camera = new THREE.OrthographicCamera(-10, 10, 8, -8, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.domElement.setAttribute("aria-label", "Low-poly railway block occupancy scene");
viewport.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight(0x8cc9e4, 0x142033, 2.1);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2df, 3.4);
sun.position.set(-8, 14, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0003;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x55d8ff, 1.1);
rim.position.set(10, 7, -9);
scene.add(rim);
const base = new THREE.Mesh(
new THREE.BoxGeometry(19, 0.65, 16),
new THREE.MeshStandardMaterial({ color: 0x0b1b2c, roughness: 0.95, metalness: 0.05 })
);
base.position.y = -0.4;
base.receiveShadow = true;
scene.add(base);
const baseEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(base.geometry),
new THREE.LineBasicMaterial({ color: 0x27445b, transparent: true, opacity: 0.65 })
);
baseEdges.position.copy(base.position);
scene.add(baseEdges);
const grid = new THREE.GridHelper(18, 18, 0x19374d, 0x10283b);
grid.position.y = -0.065;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
function boxBetween(a, b, width, height, y, material, offset = 0) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const ux = dx / length;
const uz = dz / length;
const px = -uz;
const pz = ux;
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(length, height, width),
material
);
mesh.position.set(
(a.x + b.x) * 0.5 + px * offset,
y,
(a.z + b.z) * 0.5 + pz * offset
);
mesh.rotation.y = -Math.atan2(dz, dx);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function drawTrack(a, b, sleepers = true, railColor = 0x71899a) {
const railMaterial = new THREE.MeshStandardMaterial({
color: railColor,
roughness: 0.5,
metalness: 0.65,
flatShading: true
});
scene.add(boxBetween(a, b, 0.085, 0.09, 0.18, railMaterial, 0.34));
scene.add(boxBetween(a, b, 0.085, 0.09, 0.18, railMaterial, -0.34));
if (sleepers) {
const sleeperMaterial = new THREE.MeshStandardMaterial({
color: 0x263b4b,
roughness: 0.95,
flatShading: true
});
const length = a.distanceTo(b);
const count = Math.max(2, Math.floor(length / 0.62));
for (let i = 0; i <= count; i++) {
const t = i / count;
const p = a.clone().lerp(b, t);
const sleeper = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.065, 1.04),
sleeperMaterial
);
sleeper.position.set(p.x, 0.09, p.z);
sleeper.rotation.y = -Math.atan2(b.z - a.z, b.x - a.x);
sleeper.castShadow = true;
sleeper.receiveShadow = true;
scene.add(sleeper);
}
}
}
const blockVisuals = {};
for (const [name, block] of Object.entries(blocks)) {
const a = nodes[block.from];
const b = nodes[block.to];
const padMaterial = new THREE.MeshStandardMaterial({
color: block.empty,
emissive: 0x000000,
emissiveIntensity: 0,
roughness: 0.82,
metalness: 0.08,
flatShading: true
});
const pad = boxBetween(a, b, 1.42, 0.11, 0.015, padMaterial);
scene.add(pad);
drawTrack(a, b, true);
const center = a.clone().lerp(b, 0.5);
const beacon = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.18, 0.32, 8),
new THREE.MeshStandardMaterial({
color: 0x244052,
emissive: 0x000000,
emissiveIntensity: 0,
roughness: 0.6,
flatShading: true
})
);
beacon.position.set(center.x, 0.27, center.z);
beacon.castShadow = true;
scene.add(beacon);
blockVisuals[name] = { pad, padMaterial, beacon, center };
}
Object.values(nodes).forEach((node) => {
const junction = new THREE.Mesh(
new THREE.CylinderGeometry(0.48, 0.54, 0.16, 12),
new THREE.MeshStandardMaterial({
color: 0x31495a,
roughness: 0.68,
metalness: 0.42,
flatShading: true
})
);
junction.position.set(node.x, 0.09, node.z);
junction.castShadow = true;
junction.receiveShadow = true;
scene.add(junction);
});
// Approach and exit spurs.
drawTrack(trainDefs.t1.start, nodes.n0, true, 0x506978);
drawTrack(nodes.n2, trainDefs.t1.exit, true, 0x506978);
drawTrack(trainDefs.t2.start, nodes.n1, true, 0x506978);
drawTrack(nodes.n0, trainDefs.t2.exit, true, 0x506978);
drawTrack(trainDefs.t3.start, nodes.n2, true, 0x506978);
drawTrack(nodes.n1, trainDefs.t3.exit, true, 0x506978);
// Low-poly yard details.
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x142b3d,
roughness: 1,
flatShading: true
});
const rockPositions = [
[-8.3, 5.8], [-8.5, 3.7], [-7.9, -5.9], [8.3, 4.8],
[8.2, 2.8], [6.9, -6.0], [-4.5, 6.7], [3.8, 6.8]
];
rockPositions.forEach(([x, z], index) => {
const rock = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.22 + (index % 3) * 0.08, 0),
rockMaterial
);
rock.position.set(x, 0.08, z);
rock.scale.y = 0.65 + (index % 2) * 0.35;
rock.rotation.set(index * 0.31, index * 0.67, index * 0.19);
rock.castShadow = true;
scene.add(rock);
});
function makeTrain(train) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: train.colorInt,
roughness: 0.58,
metalness: 0.16,
flatShading: true
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x263846,
roughness: 0.72,
metalness: 0.25,
flatShading: true
});
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x102634,
roughness: 0.24,
metalness: 0.55,
emissive: 0x18394a,
emissiveIntensity: 0.22
});
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x101820,
roughness: 0.9,
flatShading: true
});
const body = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.39, 0.48), bodyMaterial);
body.position.y = 0.29;
body.castShadow = true;
group.add(body);
const cab = new THREE.Mesh(new THREE.BoxGeometry(0.43, 0.34, 0.44), bodyMaterial);
cab.position.set(0.38, 0.39, 0);
cab.castShadow = true;
group.add(cab);
const roof = new THREE.Mesh(new THREE.BoxGeometry(0.92, 0.1, 0.52), roofMaterial);
roof.position.set(-0.05, 0.54, 0);
roof.castShadow = true;
group.add(roof);
const frontWindow = new THREE.Mesh(new THREE.BoxGeometry(0.035, 0.16, 0.31), windowMaterial);
frontWindow.position.set(0.607, 0.42, 0);
group.add(frontWindow);
const sideWindow = new THREE.Mesh(new THREE.BoxGeometry(0.28, 0.14, 0.025), windowMaterial);
sideWindow.position.set(0.35, 0.43, 0.226);
group.add(sideWindow);
const headlight = new THREE.Mesh(
new THREE.BoxGeometry(0.045, 0.09, 0.1),
new THREE.MeshStandardMaterial({
color: 0xfff4c9,
emissive: 0xffd66b,
emissiveIntensity: 2
})
);
headlight.position.set(0.72, 0.29, 0.14);
group.add(headlight);
[-0.43, 0.43].forEach((x) => {
[-0.285, 0.285].forEach((z) => {
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.12, 8),
wheelMaterial
);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.12, z);
wheel.castShadow = true;
group.add(wheel);
});
});
const buffer = new THREE.Mesh(
new THREE.BoxGeometry(0.1, 0.08, 0.58),
roofMaterial
);
buffer.position.set(0.74, 0.16, 0);
group.add(buffer);
group.position.copy(train.start);
scene.add(group);
return group;
}
Object.values(trainDefs).forEach((train) => {
train.group = makeTrain(train);
train.heldBlocks = new Set();
train.nextIndex = 0;
train.complete = false;
train.status = "Waiting";
});
// DOM labels projected from world positions.
const blockLabels = {};
for (const [name, visual] of Object.entries(blockVisuals)) {
const el = document.createElement("div");
el.className = "world-label block-label";
el.innerHTML = `<strong>${name}</strong><span>Clear</span>`;
labelsLayer.appendChild(el);
blockLabels[name] = { el, position: visual.center.clone().add(new THREE.Vector3(0, 0.78, 0)) };
}
const trainLabels = {};
Object.values(trainDefs).forEach((train) => {
const el = document.createElement("div");
el.className = "world-label train-label";
el.style.setProperty("--train-color", train.color);
el.textContent = `${train.code} · ${train.name}`;
labelsLayer.appendChild(el);
trainLabels[train.id] = { el, position: new THREE.Vector3() };
});
// ---------------------------------------------------------------------
// Camera: custom orbit, pan, and zoom without addons.
// ---------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0, 1.2),
yaw: 0.63,
polar: 0.82,
distance: 21,
zoom: 0.92
};
function updateCamera() {
const sinPolar = Math.sin(cameraState.polar);
camera.position.set(
cameraState.target.x + cameraState.distance * sinPolar * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.distance * Math.cos(cameraState.polar),
cameraState.target.z + cameraState.distance * sinPolar * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.target.set(0, 0, 1.2);
cameraState.yaw = 0.63;
cameraState.polar = 0.82;
cameraState.distance = 21;
cameraState.zoom = 0.92;
}
let pointerState = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerState = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
pan: event.shiftKey || event.button === 2
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState || pointerState.id !== event.pointerId) return;
const dx = event.clientX - pointerState.x;
const dy = event.clientY - pointerState.y;
pointerState.x = event.clientX;
pointerState.y = event.clientY;
if (pointerState.pan) {
cameraState.target.x -= dx * 0.018;
cameraState.target.z += dy * 0.018;
} else {
cameraState.yaw -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(cameraState.polar + dy * 0.005, 0.35, 1.35);
}
});
function endPointer(event) {
if (pointerState && pointerState.id === event.pointerId) pointerState = null;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.62,
1.75
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
const aspect = width / height;
const halfHeight = 7.6;
renderer.setSize(width, height, false);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewport);
resize();
const projected = new THREE.Vector3();
function positionLabel(label) {
projected.copy(label.position).project(camera);
const x = (projected.x * 0.5 + 0.5) * viewport.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * viewport.clientHeight;
label.el.style.transform = `translate(-50%, -50%) translate(${x}px, ${y}px)`;
label.el.style.display = projected.z > 1 ? "none" : "block";
}
renderer.setAnimationLoop(() => {
updateCamera();
renderer.render(scene, camera);
Object.values(blockLabels).forEach(positionLabel);
Object.entries(trainLabels).forEach(([id, label]) => {
label.position.copy(trainDefs[id].group.position).add(new THREE.Vector3(0, 1.02, 0));
positionLabel(label);
});
});
// ---------------------------------------------------------------------
// Railway simulation
// ---------------------------------------------------------------------
function blockCenter(name) {
const block = blocks[name];
return nodes[block.from].clone().lerp(nodes[block.to], 0.5);
}
function sharedNode(first, second) {
const a = blocks[first];
const b = blocks[second];
if (a.from === b.from || a.from === b.to) return nodes[a.from];
if (a.to === b.from || a.to === b.to) return nodes[a.to];
return nodes[a.to];
}
function orientAlong(train, dx, dz) {
train.group.rotation.y = -Math.atan2(dz, dx);
}
function animateTrain(train, points, duration = 680) {
const cleanPoints = points.map((point) => point.clone());
const lengths = [];
let total = 0;
for (let i = 0; i < cleanPoints.length - 1; i++) {
const length = cleanPoints[i].distanceTo(cleanPoints[i + 1]);
lengths.push(length);
total += length;
}
if (total < 0.001) return Promise.resolve();
return new Promise((resolve) => {
const started = performance.now();
function frame(now) {
const raw = Math.min(1, (now - started) / duration);
const eased = raw < 0.5
? 2 * raw * raw
: 1 - Math.pow(-2 * raw + 2, 2) / 2;
let distance = eased * total;
let segmentIndex = lengths.length - 1;
for (let i = 0; i < lengths.length; i++) {
if (distance <= lengths[i]) {
segmentIndex = i;
break;
}
distance -= lengths[i];
}
const start = cleanPoints[segmentIndex];
const end = cleanPoints[segmentIndex + 1];
const t = lengths[segmentIndex] > 0 ? distance / lengths[segmentIndex] : 0;
train.group.position.lerpVectors(start, end, t);
orientAlong(train, end.x - start.x, end.z - start.z);
if (raw < 1) {
requestAnimationFrame(frame);
} else {
train.group.position.copy(cleanPoints[cleanPoints.length - 1]);
resolve();
}
}
requestAnimationFrame(frame);
});
}
function refreshBlockStates() {
for (const [name, visual] of Object.entries(blockVisuals)) {
const ownerId = occupancy[name];
if (ownerId) {
const owner = trainDefs[ownerId];
visual.padMaterial.color.setHex(owner.colorInt);
visual.padMaterial.emissive.setHex(owner.colorInt);
visual.padMaterial.emissiveIntensity = 0.22;
visual.beacon.material.color.setHex(owner.colorInt);
visual.beacon.material.emissive.setHex(owner.colorInt);
visual.beacon.material.emissiveIntensity = 1.4;
visual.beacon.visible = true;
const label = blockLabels[name];
label.el.classList.add("occupied");
label.el.style.setProperty("--owner-color", owner.color);
label.el.querySelector("span").textContent = `${owner.code} · ${owner.name}`;
} else {
visual.padMaterial.color.setHex(blocks[name].empty);
visual.padMaterial.emissive.setHex(0x000000);
visual.padMaterial.emissiveIntensity = 0;
visual.beacon.material.color.setHex(0x244052);
visual.beacon.material.emissive.setHex(0x000000);
visual.beacon.material.emissiveIntensity = 0;
visual.beacon.visible = false;
const label = blockLabels[name];
label.el.classList.remove("occupied");
label.el.querySelector("span").textContent = "Clear";
}
}
}
function renderRoster() {
trainList.innerHTML = Object.values(trainDefs).map((train) => `
<div class="train-row" style="--train-color:${train.color}">
<div class="train-dot"></div>
<div>
<div class="train-name">${train.code} · ${train.name}</div>
<div class="train-route">${train.route.join(" → ")}</div>
</div>
<div class="train-state">${train.status}</div>
</div>
`).join("");
}
function renderQueue() {
queueList.innerHTML = queueOrder.map((id, index) => {
const item = requests[id];
const train = trainDefs[item.train];
const state = item.state || "pending";
const stateText = {
pending: "Pending",
processing: "Checking",
granted: "Granted",
blocked: "Blocked"
}[state];
return `
<article class="request-card ${state}" style="--train-color:${train.color}" data-id="${id}" draggable="${!running}">
<div class="request-top">
<span class="request-number">REQ ${String(index + 1).padStart(2, "0")}</span>
<span class="request-state">${stateText}</span>
</div>
<div class="request-main">
<div class="train-chip">${train.code}</div>
<div>
<strong>${train.name}</strong>
<span>Reserve block ${item.block}</span>
</div>
</div>
<div class="request-detail">${item.detail || (item.routeIndex === 0 ? "Entry reservation" : "Continuation reservation")}</div>
<div class="request-actions">
<button class="move-button" data-action="left" data-id="${id}" ${running || index === 0 ? "disabled" : ""} aria-label="Move request left">←</button>
<span class="drag-mark">⠿ DRAG</span>
<button class="move-button" data-action="right" data-id="${id}" ${running || index === queueOrder.length - 1 ? "disabled" : ""} aria-label="Move request right">→</button>
</div>
</article>
`;
}).join("");
$("#runBtn").disabled = running;
$("#stepBtn").disabled = running;
$("#deadlockBtn").disabled = running;
$("#safeBtn").disabled = running;
$("#resetBtn").disabled = running;
}
function setOutcome(kind, title, text) {
outcome = kind;
statusBadge.className = `status-badge ${kind}`;
statusBadge.textContent = {
idle: "Ready",
running: "Dispatching",
deadlock: "Deadlock",
success: "Route Clear",
conflict: "Conflict",
order: "Invalid Order"
}[kind] || "Ready";
diagnosis.className = `diagnosis ${kind}`;
diagnosisTitle.textContent = title;
diagnosisText.textContent = text;
}
function resetSimulation() {
occupancy = {};
queueIndex = 0;
Object.values(trainDefs).forEach((train) => {
train.group.position.copy(train.start);
const firstBlock = blocks[train.route[0]];
orientAlong(
train,
nodes[firstBlock.to].x - nodes[firstBlock.from].x,
nodes[firstBlock.to].z - nodes[firstBlock.from].z
);
train.heldBlocks.clear();
train.nextIndex = 0;
train.complete = false;
train.status = "Waiting";
});
Object.values(requests).forEach((request) => {
request.state = "pending";
request.detail = request.routeIndex === 0
? "Entry reservation"
: "Continuation reservation";
});
refreshBlockStates();
renderRoster();
renderQueue();
setOutcome(
"idle",
"Order ready",
"Change the request order, then run the queue. Every grant is checked against the declared exclusion rules."
);
}
async function processRequest(request) {
request.state = "processing";
request.detail = "Checking occupancy and route order…";
renderQueue();
await new Promise((resolve) => setTimeout(resolve, 190));
const train = trainDefs[request.train];
if (request.routeIndex !== train.nextIndex) {
request.state = "blocked";
request.detail = "Route predecessor has not been granted.";
train.status = train.heldBlocks.size ? `Waiting for ${request.block}` : "Blocked";
renderQueue();
renderRoster();
return;
}
const ownerId = occupancy[request.block];
if (ownerId && ownerId !== train.id) {
const owner = trainDefs[ownerId];
request.state = "blocked";
request.detail = `Occupied by ${owner.code} · ${owner.name}.`;
train.status = `Waiting for ${request.block}`;
renderQueue();
renderRoster();
return;
}
// The request is safe: reserve the exclusive block.
occupancy[request.block] = train.id;
train.heldBlocks.add(request.block);
train.nextIndex += 1;
request.state = "granted";
request.detail = `Block ${request.block} reserved.`;
train.status = `Moving to ${request.block}`;
refreshBlockStates();
renderQueue();
renderRoster();
const block = blocks[request.block];
if (request.routeIndex === 0) {
const destination = blockCenter(request.block);
const points = [
train.group.position.clone(),
nodes[block.from].clone(),
destination
];
await animateTrain(train, points);
train.status = `Holding ${request.block}`;
} else {
const previousBlock = train.route[request.routeIndex - 1];
const junction = sharedNode(previousBlock, request.block);
const destination = blockCenter(request.block);
const points = [
train.group.position.clone(),
junction,
destination
];
await animateTrain(train, points);
delete occupancy[previousBlock];
train.heldBlocks.delete(previousBlock);
train.status = `Holding ${request.block}`;
refreshBlockStates();
const finalBlock = blocks[train.route[train.route.length - 1]];
const exitPoints = [
train.group.position.clone(),
nodes[finalBlock.to].clone(),
train.exit.clone()
];
train.status = "Exiting";
renderRoster();
await animateTrain(train, exitPoints);
delete occupancy[request.block];
train.heldBlocks.delete(request.block);
train.complete = true;
train.status = "Clear";
}
refreshBlockStates();
renderQueue();
renderRoster();
}
function assessOutcome() {
const blocked = queueOrder
.map((id) => requests[id])
.filter((request) => request.state === "blocked");
const allClear = Object.values(trainDefs).every((train) => train.complete);
if (allClear && blocked.length === 0) {
setOutcome(
"success",
"All trains cleared safely",
"Every block exclusion was preserved. Each train completed its ordered route and released its blocks before the next train entered."
);
return;
}
const allOccupancyConflicts = blocked.length > 0 && blocked.every(
(request) => request.detail.startsWith("Occupied by")
);
if (allOccupancyConflicts && Object.keys(occupancy).length === 3) {
setOutcome(
"deadlock",
"Circular wait detected",
"Cinder holds A and needs B; Mica holds B and needs C; Vela holds C and needs A. No train can advance without violating EX-01."
);
return;
}
if (blocked.some((request) => request.detail.startsWith("Route predecessor"))) {
setOutcome(
"order",
"Route order was violated",
"A continuation was reached before its train's entry request. Reorder each train's entry before its continuation."
);
return;
}
setOutcome(
"conflict",
"Reservation conflict",
"At least one request could not be granted because its block was already occupied. Reorder the queue to clear the conflict."
);
}
async function runQueue() {
if (running) return;
running = true;
setOutcome(
"running",
"Dispatching requests",
"The dispatcher is evaluating each request in queue order. Occupied blocks are never granted twice."
);
renderQueue();
for (let i = queueIndex; i < queueOrder.length; i++) {
queueIndex = i;
await processRequest(requests[queueOrder[i]]);
}
queueIndex = queueOrder.length;
running = false;
assessOutcome();
renderQueue();
}
function moveRequest(id, targetIndex) {
if (running) return;
const from = queueOrder.indexOf(id);
if (from < 0 || targetIndex < 0 || targetIndex >= queueOrder.length) return;
queueOrder.splice(from, 1);
queueOrder.splice(targetIndex, 0, id);
resetSimulation();
}
queueList.addEventListener("click", (event) => {
const button = event.target.closest("[data-action]");
if (!button || running) return;
const id = button.dataset.id;
const index = queueOrder.indexOf(id);
if (button.dataset.action === "left") moveRequest(id, index - 1);
if (button.dataset.action === "right") moveRequest(id, index + 1);
});
queueList.addEventListener("dragstart", (event) => {
if (running) {
event.preventDefault();
return;
}
const card = event.target.closest(".request-card");
if (!card) return;
draggedId = card.dataset.id;
card.classList.add("dragging");
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", draggedId);
});
queueList.addEventListener("dragover", (event) => {
if (running || !draggedId) return;
event.preventDefault();
const card = event.target.closest(".request-card");
queueList.querySelectorAll(".drag-over").forEach((el) => el.classList.remove("drag-over"));
if (card) card.classList.add("drag-over");
});
queueList.addEventListener("dragleave", (event) => {
const card = event.target.closest(".request-card");
if (card && !card.contains(event.relatedTarget)) card.classList.remove("drag-over");
});
queueList.addEventListener("drop", (event) => {
if (running || !draggedId) return;
event.preventDefault();
const card = event.target.closest(".request-card");
if (!card) return;
const targetId = card.dataset.id;
const targetIndex = queueOrder.indexOf(targetId);
const sourceId = draggedId;
draggedId = null;
moveRequest(sourceId, targetIndex);
});
queueList.addEventListener("dragend", () => {
draggedId = null;
queueList.querySelectorAll(".dragging, .drag-over").forEach((el) => {
el.classList.remove("dragging", "drag-over");
});
});
$("#runBtn").addEventListener("click", () => {
resetSimulation();
runQueue();
});
$("#stepBtn").addEventListener("click", async () => {
if (running) return;
if (queueIndex >= queueOrder.length) resetSimulation();
if (queueIndex >= queueOrder.length) return;
running = true;
setOutcome(
"running",
"Checking next request",
"Only the next request in the current order is being evaluated."
);
renderQueue();
await processRequest(requests[queueOrder[queueIndex]]);
queueIndex += 1;
running = false;
if (queueIndex >= queueOrder.length) assessOutcome();
else {
setOutcome(
"running",
"Step complete",
"The next request remains pending. Step again or apply the entire order."
);
}
renderQueue();
});
$("#resetBtn").addEventListener("click", resetSimulation);
$("#deadlockBtn").addEventListener("click", () => {
queueOrder = [...deadlockOrder];
resetSimulation();
runQueue();
});
$("#safeBtn").addEventListener("click", () => {
queueOrder = [...safeOrder];
resetSimulation();
runQueue();
});
resetSimulation();
// Start with the requested deadlock so the circular conflict is visible.
setTimeout(() => runQueue(), 850);
</script>
</body>
</html>
```