Prompt specification
Build or customize the Three.js 3D scene "Wagon Ordering Yard Puzzle" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Wagon Ordering Yard Puzzle
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/wagon-ordering-yard-puzzle-x2132
Scene Description Prompt:
Make a low-poly wagon-ordering game with short sidings, limited capacity, and legal shunting moves. Use Three.js from cdnjs in one HTML file.
Working Three.js Starter (wagon-ordering-yard-puzzle-x2132):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Coupling & Co. — Shunting Puzzle</title>
<style>
:root {
--ink: #182421;
--muted: #63706b;
--paper: #f4f1e8;
--panel: rgba(250, 248, 240, 0.93);
--line: rgba(24, 36, 33, 0.14);
--green: #247a62;
--green-light: #d9ebe3;
--amber: #e8a735;
--red: #bc5147;
--shadow: 0 12px 35px rgba(25, 39, 34, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dbe3dc;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.ui {
position: fixed;
inset: 0;
z-index: 10;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.75);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
header {
position: absolute;
top: 20px;
left: 22px;
right: 22px;
height: 62px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 14px;
font-weight: 900;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.6);
}
.brand small {
display: block;
margin-top: 3px;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.2em;
color: var(--muted);
}
.brand-mark {
position: relative;
width: 43px;
height: 43px;
border-radius: 12px;
background: var(--ink);
box-shadow: 0 6px 18px rgba(24, 36, 33, 0.23);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
left: 8px;
right: 8px;
height: 4px;
border-radius: 3px;
background: #f3d88b;
}
.brand-mark::before {
top: 12px;
}
.brand-mark::after {
bottom: 12px;
}
.brand-mark span {
position: absolute;
left: 17px;
top: 16px;
width: 9px;
height: 12px;
border-left: 3px solid #f3d88b;
border-right: 3px solid #f3d88b;
}
.level-pill {
pointer-events: auto;
display: flex;
align-items: center;
gap: 12px;
padding: 10px 13px 10px 15px;
border-radius: 999px;
background: rgba(250, 248, 240, 0.9);
border: 1px solid rgba(255, 255, 255, 0.8);
box-shadow: 0 6px 20px rgba(25, 39, 34, 0.1);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
#levelDots {
display: flex;
gap: 5px;
}
#levelDots i {
width: 7px;
height: 7px;
border-radius: 50%;
background: #c6ccc8;
transition: 0.2s ease;
}
#levelDots i.active {
width: 18px;
border-radius: 8px;
background: var(--green);
}
#levelDots i.done {
background: var(--amber);
}
.order-panel {
position: absolute;
top: 102px;
left: 22px;
width: 310px;
border-radius: 20px;
padding: 20px;
}
.eyebrow {
color: var(--green);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 6px 0 4px;
font-size: 25px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.client {
color: var(--muted);
font-size: 12px;
font-weight: 650;
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 20px;
margin-bottom: 9px;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.13em;
text-transform: uppercase;
color: var(--muted);
}
.section-label span:last-child {
letter-spacing: 0.03em;
font-size: 8px;
}
.sequence {
display: flex;
align-items: center;
gap: 7px;
min-height: 63px;
}
.order-piece {
position: relative;
flex: 1 1 0;
min-width: 0;
height: 55px;
display: grid;
place-items: center;
border: 1px solid rgba(24, 36, 33, 0.13);
background: var(--tone);
box-shadow: inset 0 -7px 0 rgba(24, 36, 33, 0.07);
color: #17221f;
overflow: hidden;
}
.order-piece::before {
content: "";
position: absolute;
inset: 6px;
border: 1px solid rgba(255, 255, 255, 0.3);
}
.order-piece span {
position: relative;
z-index: 1;
font-size: 22px;
font-weight: 950;
}
.order-piece small {
position: absolute;
z-index: 2;
bottom: 3px;
right: 5px;
max-width: 70%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 6px;
font-weight: 900;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.order-piece.hopper {
clip-path: polygon(8% 0, 92% 0, 100% 100%, 0 100%);
}
.order-piece.tank {
border-radius: 30px;
}
.order-piece.reefer {
border-radius: 5px 5px 2px 2px;
}
.order-arrow {
color: #9ca6a1;
font-size: 12px;
font-weight: 900;
flex: 0 0 auto;
}
.delivery-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 14px;
padding: 10px 12px;
border-radius: 11px;
background: var(--green-light);
color: #245b4b;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.delivery-line strong {
font-size: 13px;
}
.rules {
margin-top: 17px;
padding-top: 15px;
border-top: 1px solid var(--line);
}
.rules b {
display: block;
margin-bottom: 6px;
font-size: 9px;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.rules p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.status-panel {
position: absolute;
top: 102px;
right: 22px;
width: 264px;
border-radius: 20px;
padding: 16px;
}
.status-heading {
display: flex;
align-items: center;
justify-content: space-between;
padding: 2px 2px 12px;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.status-heading span:last-child {
color: var(--muted);
font-size: 8px;
}
.track-card {
width: 100%;
display: block;
margin-top: 8px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.64);
color: var(--ink);
text-align: left;
cursor: pointer;
transition:
transform 0.16s ease,
border-color 0.16s ease,
box-shadow 0.16s ease,
background 0.16s ease;
}
.track-card:hover {
transform: translateY(-1px);
border-color: rgba(36, 122, 98, 0.4);
box-shadow: 0 6px 16px rgba(28, 45, 39, 0.08);
}
.track-card.source {
border-color: var(--amber);
background: #fff8df;
box-shadow: 0 0 0 2px rgba(232, 167, 53, 0.13);
}
.track-card.target {
border-color: var(--green);
background: #edf7f2;
}
.track-card.hint-source {
animation: hintPulse 0.85s ease-in-out infinite alternate;
}
.track-card.hint-target {
animation: hintPulse 0.85s 0.2s ease-in-out infinite alternate;
}
.track-top {
display: grid;
grid-template-columns: 33px 1fr auto;
align-items: center;
gap: 9px;
}
.track-letter {
width: 31px;
height: 31px;
display: grid;
place-items: center;
border-radius: 9px;
background: var(--ink);
color: white;
font-size: 13px;
font-weight: 900;
}
.track-card strong {
display: block;
font-size: 10px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.track-action {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.track-count {
font-size: 11px;
font-weight: 900;
}
.capacity {
display: flex;
gap: 4px;
margin-top: 9px;
}
.capacity i {
height: 4px;
flex: 1;
border-radius: 5px;
background: #d8ddda;
}
.capacity i.full {
background: var(--green);
}
.yard-note {
margin: 13px 3px 0;
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.toolbar {
position: absolute;
left: 50%;
bottom: 22px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 7px;
padding: 7px;
border-radius: 16px;
pointer-events: auto;
background: rgba(250, 248, 240, 0.94);
border: 1px solid rgba(255, 255, 255, 0.8);
box-shadow: var(--shadow);
}
.tool-button {
min-width: 79px;
height: 43px;
padding: 0 13px;
border: 0;
border-radius: 11px;
background: #e8e9e3;
color: var(--ink);
cursor: pointer;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.04em;
text-transform: uppercase;
transition:
transform 0.15s ease,
opacity 0.15s ease,
background 0.15s ease;
}
.tool-button:hover:not(:disabled) {
transform: translateY(-2px);
background: #dde3de;
}
.tool-button:disabled {
cursor: default;
opacity: 0.38;
}
.tool-button.dispatch {
min-width: 122px;
background: var(--ink);
color: white;
}
.tool-button.dispatch.ready {
background: var(--green);
box-shadow: 0 5px 15px rgba(36, 122, 98, 0.26);
}
.move-counter {
min-width: 87px;
padding: 0 9px;
text-align: center;
}
.move-counter strong {
display: block;
font-size: 17px;
line-height: 1;
}
.move-counter small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 7px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.camera-help {
position: absolute;
left: 23px;
bottom: 24px;
padding: 8px 11px;
border-radius: 10px;
background: rgba(250, 248, 240, 0.76);
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.03em;
box-shadow: 0 5px 18px rgba(25, 39, 34, 0.07);
}
#toast {
position: absolute;
left: 50%;
bottom: 93px;
transform: translate(-50%, 12px);
max-width: min(520px, calc(100vw - 30px));
padding: 11px 17px;
border-radius: 999px;
background: rgba(24, 36, 33, 0.94);
color: white;
box-shadow: 0 10px 25px rgba(24, 36, 33, 0.23);
opacity: 0;
pointer-events: none;
font-size: 11px;
font-weight: 750;
text-align: center;
transition: 0.2s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#labels {
position: fixed;
inset: 0;
z-index: 4;
pointer-events: none;
overflow: hidden;
}
.wagon-label {
position: absolute;
width: 22px;
height: 22px;
display: grid;
place-items: center;
border: 2px solid rgba(255, 255, 255, 0.92);
border-radius: 7px;
background: var(--tone);
color: #17221f;
box-shadow: 0 4px 10px rgba(24, 36, 33, 0.23);
font-size: 10px;
font-weight: 950;
transform: translate(-50%, -50%);
will-change: transform;
}
.track-label {
position: absolute;
padding: 4px 7px;
border-radius: 6px;
background: rgba(24, 36, 33, 0.84);
color: white;
font-size: 8px;
font-weight: 900;
letter-spacing: 0.08em;
transform: translate(-50%, -50%);
white-space: nowrap;
}
.modal {
position: fixed;
inset: 0;
z-index: 30;
display: grid;
place-items: center;
padding: 20px;
background: rgba(17, 28, 25, 0.42);
backdrop-filter: blur(7px);
-webkit-backdrop-filter: blur(7px);
opacity: 0;
visibility: hidden;
pointer-events: none;
transition: 0.25s ease;
}
.modal.open {
opacity: 1;
visibility: visible;
pointer-events: auto;
}
.modal-card {
width: min(420px, 100%);
padding: 31px;
border-radius: 24px;
background: var(--paper);
box-shadow: 0 30px 80px rgba(11, 23, 19, 0.3);
text-align: center;
transform: translateY(15px) scale(0.97);
transition: 0.25s ease;
}
.modal.open .modal-card {
transform: translateY(0) scale(1);
}
.modal-stars {
color: var(--amber);
font-size: 29px;
letter-spacing: 0.16em;
}
.modal h2 {
margin: 8px 0;
font-size: 29px;
letter-spacing: -0.04em;
}
.modal p {
margin: 0 auto 20px;
max-width: 320px;
color: var(--muted);
font-size: 13px;
line-height: 1.6;
}
.modal button {
height: 48px;
min-width: 170px;
border: 0;
border-radius: 13px;
background: var(--green);
color: white;
cursor: pointer;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@keyframes hintPulse {
from {
box-shadow: 0 0 0 0 rgba(36, 122, 98, 0);
}
to {
box-shadow: 0 0 0 4px rgba(36, 122, 98, 0.18);
}
}
@media (max-width: 760px) {
header {
top: 12px;
left: 12px;
right: 12px;
}
.brand {
font-size: 11px;
}
.brand small {
display: none;
}
.brand-mark {
width: 36px;
height: 36px;
}
.order-panel {
top: 66px;
left: 12px;
right: 12px;
width: auto;
padding: 13px;
border-radius: 16px;
}
.order-panel h1 {
display: inline-block;
margin-right: 7px;
font-size: 18px;
}
.client {
display: inline;
font-size: 10px;
}
.order-panel .section-label {
margin-top: 10px;
}
.sequence {
min-height: 47px;
}
.order-piece {
height: 43px;
}
.order-piece small,
.rules {
display: none;
}
.delivery-line {
margin-top: 9px;
padding: 7px 9px;
}
.status-panel {
top: auto;
right: 12px;
bottom: 80px;
width: 180px;
padding: 10px;
border-radius: 15px;
}
.status-heading,
.yard-note {
display: none;
}
.track-card {
padding: 7px;
margin-top: 5px;
}
.track-top {
grid-template-columns: 27px 1fr auto;
gap: 6px;
}
.track-letter {
width: 26px;
height: 26px;
font-size: 10px;
}
.track-card strong {
font-size: 8px;
}
.track-action,
.capacity {
display: none;
}
.toolbar {
bottom: 12px;
gap: 4px;
padding: 5px;
}
.tool-button {
min-width: 48px;
height: 39px;
padding: 0 8px;
font-size: 0;
}
.tool-button::first-letter {
font-size: 13px;
}
.tool-button.dispatch {
min-width: 93px;
font-size: 9px;
}
.move-counter {
min-width: 58px;
}
.camera-help {
display: none;
}
#toast {
bottom: 220px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="labels"></div>
<div class="ui">
<header>
<div class="brand">
<div class="brand-mark"><span></span></div>
<div>
Coupling & Co.
<small>Short siding puzzle</small>
</div>
</div>
<div class="level-pill">
<span id="levelText">Order 01</span>
<div id="levelDots"></div>
</div>
</header>
<section class="panel order-panel">
<div class="eyebrow">Current order</div>
<h1 id="orderTitle">Morning Run</h1>
<div class="client" id="orderClient">Northgate Creamery</div>
<div class="section-label">
<span>Requested sequence</span>
<span>Buffer → coupling</span>
</div>
<div class="sequence" id="orderSequence"></div>
<div class="delivery-line">
<span>Dispatch into track</span>
<strong id="deliveryTrack">B</strong>
</div>
<div class="rules">
<b>Legal shunting rules</b>
<p>
Pull only the amber-ringed wagon at a siding’s coupling end. Send it through
the common lead to another siding. Never exceed a siding’s capacity.
Build the requested sequence, then dispatch.
</p>
</div>
</section>
<aside class="panel status-panel">
<div class="status-heading">
<span>Yard status</span>
<span>Short sidings</span>
</div>
<div id="trackCards"></div>
<div class="yard-note">
Select a source track, then select a destination track. The shared approach
makes every siding-to-siding transfer possible.
</div>
</aside>
<div class="toolbar">
<button class="tool-button" id="undoButton" title="Undo (U)">↶ Undo</button>
<button class="tool-button" id="hintButton" title="Hint (H)">✦ Hint</button>
<button class="tool-button" id="resetButton" title="Reset (R)">Reset</button>
<div class="move-counter">
<strong id="moveCount">0</strong>
<small>Shunts · par <span id="parCount">0</span></small>
</div>
<button class="tool-button dispatch" id="dispatchButton" title="Dispatch (D)">
Dispatch
</button>
</div>
<div class="camera-help">Drag to orbit · Scroll to zoom · Arrow keys rotate</div>
<div id="toast" role="status" aria-live="polite"></div>
</div>
<div class="modal" id="modal">
<div class="modal-card">
<div class="modal-stars" id="modalStars">★★★</div>
<div class="eyebrow">Order complete</div>
<h2 id="modalTitle">Order dispatched</h2>
<p id="modalText"></p>
<button id="nextButton">Next order</button>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const TRACK_NAMES = ["NORTH BAY", "ENGINE YARD", "FREIGHT ROAD"];
const TRACK_Z = [-3.6, 0, 3.6];
const CAPACITIES = [4, 3, 4];
const TRACK_LETTERS = ["A", "B", "C"];
const TYPES = {
C: {
id: "C",
letter: "C",
name: "Citrus",
color: 0xe8b13e,
css: "#edb642",
shape: "crate"
},
B: {
id: "B",
letter: "B",
name: "Berry",
color: 0xd85f83,
css: "#df6b89",
shape: "crate"
},
M: {
id: "M",
letter: "M",
name: "Mint",
color: 0x39a78d,
css: "#43ad94",
shape: "hopper"
},
P: {
id: "P",
letter: "P",
name: "Copper",
color: 0xd8783f,
css: "#dc7b43",
shape: "tank"
},
L: {
id: "L",
letter: "L",
name: "Plum",
color: 0x8668b4,
css: "#8c70b9",
shape: "tank"
},
I: {
id: "I",
letter: "I",
name: "Ice",
color: 0x5a9fc4,
css: "#65a9cb",
shape: "reefer"
}
};
const LEVELS = [
{
title: "Morning Run",
client: "Northgate Creamery",
delivery: 1,
target: ["C", "B", "M"]
},
{
title: "Chilled Produce",
client: "Bluebird Market",
delivery: 0,
target: ["M", "P", "I", "B"]
},
{
title: "Evening Consignment",
client: "Harbor Supply Co.",
delivery: 1,
target: ["L", "C", "P"]
},
{
title: "Cold Chain Express",
client: "Northern Grocers",
delivery: 2,
target: ["I", "M", "L", "P"]
},
{
title: "Final Depot Run",
client: "Grand Junction Works",
delivery: 0,
target: ["C", "L", "B", "I"]
}
];
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe3dc);
scene.fog = new THREE.Fog(0xdbe3dc, 30, 58);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
document.querySelector("#scene").appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-10, 10, 8, -8, 0.1, 100);
const cameraTarget = new THREE.Vector3(0.2, 0, 0);
let cameraAzimuth = 0.63;
let cameraPolar = 0.94;
let cameraZoom = 1;
const hemi = new THREE.HemisphereLight(0xf5f2df, 0x53685e, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2d2, 3.2);
sun.position.set(-9, 16, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0008;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8d8e4, 0.65);
fill.position.set(10, 8, -12);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(36, 27),
new THREE.MeshStandardMaterial({
color: 0xa9b7a6,
roughness: 1,
flatShading: true
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.15;
ground.receiveShadow = true;
scene.add(ground);
const yardPatch = new THREE.Mesh(
new THREE.PlaneGeometry(25, 18),
new THREE.MeshStandardMaterial({
color: 0xb9b6a8,
roughness: 1
})
);
yardPatch.rotation.x = -Math.PI / 2;
yardPatch.position.set(0.3, -0.12, 0);
yardPatch.receiveShadow = true;
scene.add(yardPatch);
function addBox(parent, size, position, color, castShadow = true) {
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.83,
metalness: 0.02,
flatShading: true
});
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);
mesh.position.set(...position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addRailSegment(parent, x1, z1, x2, z2) {
const dx = x2 - x1;
const dz = z2 - z1;
const length = Math.hypot(dx, dz);
const angle = -Math.atan2(dz, dx);
const perpX = (-dz / length) * 0.53;
const perpZ = (dx / length) * 0.53;
for (const side of [-1, 1]) {
const rail = addBox(
parent,
[length, 0.12, 0.10],
[
(x1 + x2) / 2 + perpX * side,
0.22,
(z1 + z2) / 2 + perpZ * side
],
0x5d6969,
false
);
rail.rotation.y = angle;
}
}
const trackHitBoxes = [];
const trackLabelAnchors = [];
for (let trackIndex = 0; trackIndex < 3; trackIndex++) {
const group = new THREE.Group();
group.position.z = TRACK_Z[trackIndex];
scene.add(group);
addBox(group, [8.9, 0.18, 1.65], [-0.8, 0.02, 0], 0x777a70, false);
addBox(group, [8.9, 0.13, 0.10], [-0.8, 0.20, -0.53], 0x596363, false);
addBox(group, [8.9, 0.13, 0.10], [-0.8, 0.20, 0.53], 0x596363, false);
for (let x = -5.05; x <= 3.45; x += 0.72) {
addBox(group, [0.19, 0.13, 1.38], [x, 0.13, 0], 0x554f45, false);
}
// Buffer stop at the closed end.
addBox(group, [0.24, 0.85, 0.20], [-5.08, 0.47, -0.57], 0x9b443b);
addBox(group, [0.24, 0.85, 0.20], [-5.08, 0.47, 0.57], 0x9b443b);
addBox(group, [0.26, 0.20, 1.42], [-5.08, 0.77, 0], 0xb95348);
// Coupling-end marker.
addBox(group, [0.18, 0.46, 0.18], [3.64, 0.35, 0], 0xe5a53b, false);
addBox(group, [0.50, 0.12, 0.12], [3.92, 0.32, 0], 0xe5a53b, false);
// Track number sign.
const sign = addBox(group, [0.78, 0.52, 0.12], [-4.55, 0.75, -1.04], 0x24342f);
const signFace = addBox(
group,
[0.58, 0.32, 0.03],
[-4.55, 0.75, -1.115],
0xf0ead7,
false
);
signFace.rotation.y = Math.PI;
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
const hitBox = new THREE.Mesh(
new THREE.BoxGeometry(8.9, 1.2, 1.65),
hitMaterial
);
hitBox.position.set(-0.8, 0.55, 0);
hitBox.userData.trackIndex = trackIndex;
group.add(hitBox);
trackHitBoxes.push(hitBox);
trackLabelAnchors.push(
new THREE.Vector3(-4.4, 1.15, TRACK_Z[trackIndex] - 1.0)
);
}
// Common approach into the shared lead.
for (const z of TRACK_Z) {
addRailSegment(scene, 3.65, z, 7.25, 0);
}
addRailSegment(scene, 7.25, 0, 10.4, 0);
addBox(scene, [0.22, 1.4, 0.22], [7.55, 0.7, -1.28], 0x3f504a);
addBox(scene, [0.64, 0.40, 0.42], [7.55, 1.52, -1.28], 0x263630);
const signalLight = new THREE.Mesh(
new THREE.SphereGeometry(0.13, 8, 6),
new THREE.MeshBasicMaterial({ color: 0xefb23f })
);
signalLight.position.set(7.55, 1.54, -1.04);
scene.add(signalLight);
// Low-poly scenery.
function addTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.10, 0.15, 1.05, 5),
new THREE.MeshStandardMaterial({ color: 0x67503b, flatShading: true })
);
trunk.position.y = 0.38;
trunk.castShadow = true;
tree.add(trunk);
const lower = new THREE.Mesh(
new THREE.ConeGeometry(0.72, 1.5, 6),
new THREE.MeshStandardMaterial({
color: 0x52735a,
roughness: 1,
flatShading: true
})
);
lower.position.y = 1.28;
lower.castShadow = true;
tree.add(lower);
const upper = new THREE.Mesh(
new THREE.ConeGeometry(0.52, 1.25, 6),
new THREE.MeshStandardMaterial({
color: 0x6e8c68,
roughness: 1,
flatShading: true
})
);
upper.position.y = 2.05;
upper.castShadow = true;
tree.add(upper);
scene.add(tree);
}
[
[-11, -8, 1.25],
[-9.5, -9, 0.95],
[11, -8, 1.2],
[12, -5.5, 0.9],
[-11.5, 7.8, 1.05],
[11.8, 8, 1.35],
[9.8, 9.4, 0.85]
].forEach((args) => addTree(...args));
const warehouse = new THREE.Group();
warehouse.position.set(-9.3, 0, -5.3);
scene.add(warehouse);
addBox(warehouse, [6.2, 2.4, 3.5], [0, 1.05, 0], 0x927b61);
const roof = new THREE.Mesh(
new THREE.CylinderGeometry(1.9, 1.9, 6.2, 4, 1, false, 0, Math.PI),
new THREE.MeshStandardMaterial({
color: 0x495854,
roughness: 0.85,
flatShading: true
})
);
roof.rotation.z = Math.PI / 2;
roof.rotation.y = Math.PI / 4;
roof.position.y = 2.3;
roof.castShadow = true;
warehouse.add(roof);
addBox(warehouse, [1.1, 1.75, 0.05], [0, 0.72, 1.77], 0x34433f);
function slotPosition(trackIndex, slotIndex) {
return new THREE.Vector3(
-3.9 + slotIndex * 1.45,
0,
TRACK_Z[trackIndex]
);
}
const wagonMeshes = new Map();
const wagonLabels = new Map();
const labelLayer = document.querySelector("#labels");
function createWagon(type) {
const group = new THREE.Group();
group.userData.wagonId = type.id;
const chassis = addBox(
group,
[1.24, 0.18, 0.91],
[0, 0.36, 0],
0x35413e
);
const wheelGeometry = new THREE.CylinderGeometry(0.19, 0.19, 0.13, 10);
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x202826,
roughness: 0.75,
flatShading: true
});
for (const x of [-0.39, 0.39]) {
for (const z of [-0.49, 0.49]) {
const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.22, z);
wheel.castShadow = true;
group.add(wheel);
}
}
const cargoMaterial = new THREE.MeshStandardMaterial({
color: type.color,
roughness: 0.68,
metalness: 0.03,
flatShading: true,
emissive: 0x000000
});
group.userData.cargoMaterial = cargoMaterial;
if (type.shape === "crate") {
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.02, 0.57, 0.78),
cargoMaterial
);
body.position.y = 0.73;
body.castShadow = true;
group.add(body);
const roof = addBox(
group,
[1.10, 0.11, 0.84],
[0, 1.05, 0],
type.color
);
roof.material.roughness = 0.6;
} else if (type.shape === "hopper") {
const hopper = new THREE.Mesh(
new THREE.CylinderGeometry(0.48, 0.34, 0.66, 6),
cargoMaterial
);
hopper.position.y = 0.75;
hopper.castShadow = true;
group.add(hopper);
const rim = new THREE.Mesh(
new THREE.CylinderGeometry(0.49, 0.49, 0.08, 6),
new THREE.MeshStandardMaterial({
color: 0x37433f,
flatShading: true
})
);
rim.position.y = 1.09;
group.add(rim);
} else if (type.shape === "tank") {
const tank = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.34, 0.98, 10),
cargoMaterial
);
tank.rotation.z = Math.PI / 2;
tank.position.y = 0.75;
tank.castShadow = true;
group.add(tank);
for (const x of [-0.49, 0.49]) {
const cap = new THREE.Mesh(
new THREE.SphereGeometry(0.34, 10, 6),
cargoMaterial
);
cap.position.set(x, 0.75, 0);
cap.scale.x = 0.35;
cap.castShadow = true;
group.add(cap);
}
addBox(group, [0.18, 0.18, 0.26], [0, 1.11, 0], 0x33413c);
} else {
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.0, 0.52, 0.76),
cargoMaterial
);
body.position.y = 0.72;
body.castShadow = true;
group.add(body);
addBox(group, [0.58, 0.19, 0.61], [-0.1, 1.07, 0], 0xd5e5e6);
addBox(group, [0.04, 0.27, 0.54], [0.34, 0.72, 0], 0x3a595d);
}
addBox(group, [0.34, 0.10, 0.13], [0.72, 0.34, 0], 0x717b77);
const indicatorMaterial = new THREE.MeshBasicMaterial({
color: 0xe8a735,
transparent: true,
opacity: 0.9
});
const indicator = new THREE.Mesh(
new THREE.TorusGeometry(0.31, 0.035, 5, 18),
indicatorMaterial
);
indicator.rotation.x = Math.PI / 2;
indicator.position.y = 1.38;
indicator.visible = false;
group.add(indicator);
group.userData.indicator = indicator;
const label = document.createElement("div");
label.className = "wagon-label";
label.style.setProperty("--tone", type.css);
label.textContent = type.letter;
labelLayer.appendChild(label);
wagonLabels.set(type.id, label);
wagonMeshes.set(type.id, group);
return group;
}
Object.values(TYPES).forEach(createWagon);
let levelIndex = 0;
let tracks = [[], [], []];
let selectedSource = null;
let moveCount = 0;
let par = 0;
let undoStack = [];
let moving = false;
let animations = [];
let hintMove = null;
let toastTimer = null;
const trackCards = [];
const trackCardsContainer = document.querySelector("#trackCards");
for (let i = 0; i < 3; i++) {
const card = document.createElement("button");
card.className = "track-card";
card.type = "button";
card.innerHTML = `
<div class="track-top">
<span class="track-letter">${TRACK_LETTERS[i]}</span>
<div>
<strong>${TRACK_NAMES[i]}</strong>
<small class="track-action">Select end wagon</small>
</div>
<span class="track-count">0/${CAPACITIES[i]}</span>
</div>
<div class="capacity">
${Array.from({ length: CAPACITIES[i] }, () => "<i></i>").join("")}
</div>
`;
card.addEventListener("click", () => handleTrackClick(i));
trackCardsContainer.appendChild(card);
trackCards.push(card);
}
const orderSequence = document.querySelector("#orderSequence");
const orderTitle = document.querySelector("#orderTitle");
const orderClient = document.querySelector("#orderClient");
const deliveryTrack = document.querySelector("#deliveryTrack");
const moveCountElement = document.querySelector("#moveCount");
const parCountElement = document.querySelector("#parCount");
const levelText = document.querySelector("#levelText");
const levelDots = document.querySelector("#levelDots");
const undoButton = document.querySelector("#undoButton");
const hintButton = document.querySelector("#hintButton");
const resetButton = document.querySelector("#resetButton");
const dispatchButton = document.querySelector("#dispatchButton");
const toastElement = document.querySelector("#toast");
const modal = document.querySelector("#modal");
const modalTitle = document.querySelector("#modalTitle");
const modalText = document.querySelector("#modalText");
const modalStars = document.querySelector("#modalStars");
const nextButton = document.querySelector("#nextButton");
function showToast(message, duration = 2600) {
clearTimeout(toastTimer);
toastElement.textContent = message;
toastElement.classList.add("show");
toastTimer = setTimeout(() => {
toastElement.classList.remove("show");
}, duration);
}
function stateKey(state) {
return JSON.stringify(state);
}
function findSolution(startState, level) {
const startKey = stateKey(startState);
const queue = [startKey];
const parents = new Map([[startKey, null]]);
let goalKey = null;
while (queue.length) {
const key = queue.shift();
const state = JSON.parse(key);
if (
state[level.delivery].length === level.target.length &&
state[level.delivery].every((id, index) => id === level.target[index])
) {
goalKey = key;
break;
}
for (let source = 0; source < 3; source++) {
if (!state[source].length) continue;
for (let destination = 0; destination < 3; destination++) {
if (destination === source) continue;
if (state[destination].length >= CAPACITIES[destination]) continue;
const next = state.map((track) => track.slice());
const wagon = next[source].pop();
next[destination].push(wagon);
const nextKey = stateKey(next);
if (!parents.has(nextKey)) {
parents.set(nextKey, {
previous: key,
move: { source, destination, wagon }
});
queue.push(nextKey);
}
}
}
}
if (!goalKey) return null;
const path = [];
let cursor = goalKey;
while (parents.get(cursor)) {
const record = parents.get(cursor);
path.unshift(record.move);
cursor = record.previous;
}
return path;
}
function mulberry32(seed) {
return function random() {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function generateScramble(level) {
const temporaryTracks = [0, 1, 2].filter((index) => index !== level.delivery);
let fallback = null;
let fallbackScore = -1;
for (let seed = 1; seed <= 160; seed++) {
const random = mulberry32(seed * 9173 + level.delivery * 71);
const state = [[], [], []];
state[level.delivery] = level.target.slice();
// Reverse legal moves from the solved state.
for (let i = level.target.length - 1; i >= 0; i--) {
let destination = temporaryTracks[i % temporaryTracks.length];
if (state[destination].length >= CAPACITIES[destination]) {
destination = temporaryTracks.find(
(track) => state[track].length < CAPACITIES[track]
);
}
state[destination].push(state[level.delivery].pop());
}
let previousPair = null;
const shuffleCount = 12 + Math.floor(random() * 12);
for (let i = 0; i < shuffleCount; i++) {
const destination =
temporaryTracks[Math.floor(random() * temporaryTracks.length)];
const source = temporaryTracks.find((track) => track !== destination);
if (!source || !state[destination].length) continue;
if (state[source].length >= CAPACITIES[source]) continue;
if (
previousPair &&
previousPair.source === source &&
previousPair.destination === destination
) {
continue;
}
const wagon = state[destination].pop();
state[source].push(wagon);
previousPair = { source, destination };
}
const solution = findSolution(state, level);
if (!solution) continue;
const score = solution.length;
if (!fallback || score > fallbackScore) {
fallback = state.map((track) => track.slice());
fallbackScore = score;
}
if (
score >= level.target.length + 2 &&
score <= level.target.length + 9
) {
return state;
}
}
return fallback;
}
function updateIndicators() {
for (let trackIndex = 0; trackIndex < 3; trackIndex++) {
const track = tracks[trackIndex];
if (!track.length) continue;
for (let index = 0; index < track.length; index++) {
const wagon = wagonMeshes.get(track[index]);
const isEnd = index === track.length - 1;
wagon.userData.indicator.visible = isEnd && !moving;
wagon.userData.indicator.material.color.set(
selectedSource === trackIndex ? 0x36a879 : 0xe8a735
);
wagon.userData.cargoMaterial.emissive.setHex(
selectedSource === trackIndex && isEnd ? 0x174a39 : 0x000000
);
}
}
}
function updateUI() {
const level = LEVELS[levelIndex];
orderTitle.textContent = level.title;
orderClient.textContent = level.client;
deliveryTrack.textContent = TRACK_LETTERS[level.delivery];
orderSequence.innerHTML = level.target
.map((id) => {
const type = TYPES[id];
return `
<div class="order-piece ${type.shape}" style="--tone:${type.css}">
<span>${type.letter}</span>
<small>${type.name}</small>
</div>
`;
})
.join('<b class="order-arrow">→</b>');
levelText.textContent = `Order ${String(levelIndex + 1).padStart(2, "0")}`;
levelDots.innerHTML = LEVELS.map(
(_, index) =>
`<i class="${index === levelIndex ? "active" : index < levelIndex ? "done" : ""}"></i>`
).join("");
moveCountElement.textContent = moveCount;
parCountElement.textContent = par;
for (let i = 0; i < 3; i++) {
const card = trackCards[i];
const count = tracks[i].length;
const full = count >= CAPACITIES[i];
const isSource = selectedSource === i;
const canReceive =
selectedSource !== null && i !== selectedSource && !full;
card.classList.toggle("source", isSource);
card.classList.toggle("target", canReceive);
card.classList.toggle(
"hint-source",
Boolean(hintMove && hintMove.source === i)
);
card.classList.toggle(
"hint-target",
Boolean(hintMove && hintMove.destination === i)
);
card.querySelector(".track-count").textContent =
`${count}/${CAPACITIES[i]}`;
card.querySelector(".track-action").textContent = isSource
? "Source selected"
: canReceive
? "Shunt here"
: full
? "Siding full"
: count
? "Select end wagon"
: "Empty siding";
card.querySelectorAll(".capacity i").forEach((pip, index) => {
pip.classList.toggle("full", index < count);
});
}
const goalReached = isGoalReached();
undoButton.disabled = undoStack.length === 0 || moving;
hintButton.disabled = moving;
resetButton.disabled = moving;
dispatchButton.disabled = !goalReached || moving;
dispatchButton.classList.toggle("ready", goalReached && !moving);
updateIndicators();
}
function isGoalReached() {
const level = LEVELS[levelIndex];
return (
tracks[level.delivery].length === level.target.length &&
tracks[level.delivery].every(
(id, index) => id === level.target[index]
)
);
}
function loadLevel(index) {
levelIndex = index;
const level = LEVELS[levelIndex];
tracks = generateScramble(level);
selectedSource = null;
moveCount = 0;
undoStack = [];
hintMove = null;
moving = false;
animations = [];
for (const wagon of wagonMeshes.values()) {
if (wagon.parent) wagon.parent.remove(wagon);
wagon.visible = false;
wagon.position.set(0, 0, 0);
wagon.rotation.set(0, 0, 0);
wagon.userData.trackIndex = -1;
wagon.userData.indicator.visible = false;
wagon.userData.cargoMaterial.emissive.setHex(0x000000);
}
for (let trackIndex = 0; trackIndex < 3; trackIndex++) {
tracks[trackIndex].forEach((id, slotIndex) => {
const wagon = wagonMeshes.get(id);
wagon.visible = true;
wagon.userData.trackIndex = trackIndex;
wagon.position.copy(slotPosition(trackIndex, slotIndex));
scene.add(wagon);
});
}
const solution = findSolution(tracks, level);
par = solution ? solution.length : 0;
updateUI();
showToast(
"Order loaded. Select an amber-ringed coupling-end wagon.",
3400
);
}
function selectSource(trackIndex) {
if (moving) return;
if (!tracks[trackIndex].length) {
showToast(`Track ${TRACK_LETTERS[trackIndex]} is empty.`);
return;
}
selectedSource = trackIndex;
updateUI();
const wagonId = tracks[trackIndex][tracks[trackIndex].length - 1];
showToast(
`${TYPES[wagonId].name} selected. Choose another siding to shunt it.`
);
}
function handleTrackClick(trackIndex) {
if (moving) return;
if (selectedSource !== null && trackIndex !== selectedSource) {
attemptMove(selectedSource, trackIndex);
} else if (selectedSource === trackIndex) {
selectedSource = null;
updateUI();
} else {
selectSource(trackIndex);
}
}
function attemptMove(source, destination) {
if (moving) return;
if (source === destination) return;
if (!tracks[source].length) {
showToast("There is no wagon to pull from that siding.");
return;
}
if (tracks[destination].length >= CAPACITIES[destination]) {
showToast(
`Track ${TRACK_LETTERS[destination]} is at capacity. Choose another siding.`
);
return;
}
const wagonId = tracks[source].pop();
tracks[destination].push(wagonId);
const wagon = wagonMeshes.get(wagonId);
wagon.userData.trackIndex = destination;
moveCount++;
undoStack.push({ source, destination, wagonId });
hintMove = null;
const remainingSolution = findSolution(tracks, LEVELS[levelIndex]);
updateUI();
startMoveAnimation(wagon, source, destination);
showToast(
remainingSolution
? `${TYPES[wagonId].name} shunted to Track ${TRACK_LETTERS[destination]}.`
: "Legal shunt, but this creates a dead end. Undo is available.",
remainingSolution ? 1900 : 3200
);
}
function startMoveAnimation(wagon, source, destination) {
const start = wagon.position.clone();
const end = slotPosition(
destination,
tracks[destination].length - 1
);
const curve = new THREE.CatmullRomCurve3(
[
start,
new THREE.Vector3(4.0, 0.05, TRACK_Z[source]),
new THREE.Vector3(7.25, 0.05, 0),
new THREE.Vector3(4.0, 0.05, TRACK_Z[destination]),
end
],
false,
"catmullrom",
0.18
);
moving = true;
animations = [
{
kind: "move",
object: wagon,
curve,
startTime: performance.now(),
duration: 1120
}
];
updateIndicators();
}
function undoMove() {
if (moving || !undoStack.length) return;
const last = undoStack.pop();
const wagon = wagonMeshes.get(last.wagonId);
if (
tracks[last.destination].length &&
tracks[last.destination][tracks[last.destination].length - 1] ===
last.wagonId
) {
tracks[last.destination].pop();
tracks[last.source].push(last.wagonId);
} else {
tracks[last.source].push(last.wagonId);
}
wagon.userData.trackIndex = last.source;
moveCount = Math.max(0, moveCount - 1);
selectedSource = null;
hintMove = null;
updateUI();
startMoveAnimation(wagon, last.destination, last.source);
showToast("Last shunt undone.");
}
function showHint() {
if (moving) return;
const solution = findSolution(tracks, LEVELS[levelIndex]);
if (!solution || !solution.length) {
showToast(
"No route remains from this arrangement. Try undoing the last shunt.",
3500
);
return;
}
hintMove = solution[0];
updateUI();
const type = TYPES[hintMove.wagon];
showToast(
`Hint: pull the ${type.name} wagon from Track ${
TRACK_LETTERS[hintMove.source]
} to Track ${TRACK_LETTERS[hintMove.destination]}.`,
4000
);
}
function startDispatch() {
if (moving || !isGoalReached()) return;
moving = true;
hintMove = null;
updateUI();
const level = LEVELS[levelIndex];
const now = performance.now();
animations = tracks[level.delivery].map((id, index) => {
const wagon = wagonMeshes.get(id);
return {
kind: "dispatch",
object: wagon,
start: wagon.position.clone(),
startTime: now + index * 120,
duration: 1250
};
});
showToast("Coupling up. Dispatching the completed order…", 2500);
}
function showCompletion() {
const stars = moveCount <= par ? 3 : moveCount <= par + 2 ? 2 : 1;
const isFinal = levelIndex === LEVELS.length - 1;
modalStars.textContent = "★".repeat(stars) + "☆".repeat(3 - stars);
modalTitle.textContent = isFinal ? "Yard cleared" : "Order dispatched";
modalText.textContent = isFinal
? `Every order has been delivered. You completed the final run in ${moveCount} shunts, with a yard par of ${par}.`
: `${LEVELS[levelIndex].client} received the correct ${LEVELS[levelIndex].target.length}-wagon sequence in ${moveCount} shunts. Yard par: ${par}.`;
nextButton.textContent = isFinal ? "New shift" : "Next order";
modal.classList.add("open");
}
function easeOutCubic(value) {
return 1 - Math.pow(1 - value, 3);
}
function updateAnimations(now) {
if (!animations.length) return;
let allDone = true;
for (let i = animations.length - 1; i >= 0; i--) {
const animation = animations[i];
if (now < animation.startTime) {
allDone = false;
continue;
}
const raw = Math.min(
1,
(now - animation.startTime) / animation.duration
);
const eased = easeOutCubic(raw);
if (animation.kind === "move") {
const point = animation.curve.getPoint(eased);
animation.object.position.copy(point);
animation.object.position.y += Math.sin(Math.PI * eased) * 0.28;
animation.object.rotation.y =
Math.sin(Math.PI * eased) * 0.09;
} else {
animation.object.position.x = THREE.MathUtils.lerp(
animation.start.x,
12.5,
eased
);
animation.object.position.y = Math.sin(Math.PI * eased) * 0.08;
animation.object.rotation.y = Math.sin(Math.PI * eased) * 0.05;
}
if (raw >= 1) {
animations.splice(i, 1);
} else {
allDone = false;
}
}
if (allDone && animations.length === 0) {
moving = false;
updateUI();
if (animations.length === 0 && document.querySelector("#modal").classList.contains("open") === false) {
// Dispatch completion is handled by the dispatch-specific marker below.
}
}
}
// A separate flag avoids showing the completion modal for ordinary moves.
let dispatching = false;
const originalStartDispatch = startDispatch;
function updateDispatchState(now) {
if (!dispatching || !animations.length) return;
const allDone = animations.every(
(animation) => now >= animation.startTime + animation.duration
);
if (allDone) {
dispatching = false;
moving = false;
showCompletion();
}
}
undoButton.addEventListener("click", undoMove);
hintButton.addEventListener("click", showHint);
resetButton.addEventListener("click", () => {
if (!moving) {
loadLevel(levelIndex);
showToast("Siding arrangement reset.");
}
});
dispatchButton.addEventListener("click", () => {
originalStartDispatch();
dispatching = true;
});
nextButton.addEventListener("click", () => {
modal.classList.remove("open");
if (levelIndex === LEVELS.length - 1) {
loadLevel(0);
} else {
loadLevel(levelIndex + 1);
}
});
// Raycasting and custom camera interaction.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let dragged = false;
let lastPointerX = 0;
let lastPointerY = 0;
let totalDrag = 0;
function setPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function wagonFromObject(object) {
let current = object;
while (current) {
if (current.userData && current.userData.wagonId) return current;
current = current.parent;
}
return null;
}
function handleWorldClick(event) {
if (moving) return;
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const visibleWagons = [...wagonMeshes.values()].filter(
(wagon) => wagon.visible
);
const wagonHits = raycaster.intersectObjects(visibleWagons, true);
const wagonHit = wagonHits[0];
const wagon = wagonHit ? wagonFromObject(wagonHit.object) : null;
if (wagon) {
const trackIndex = wagon.userData.trackIndex;
if (
selectedSource !== null &&
trackIndex !== selectedSource
) {
attemptMove(selectedSource, trackIndex);
return;
}
const track = tracks[trackIndex];
const isCouplingEnd =
track.length && track[track.length - 1] === wagon.userData.wagonId;
if (isCouplingEnd) {
if (selectedSource === trackIndex) {
selectedSource = null;
updateUI();
} else {
selectSource(trackIndex);
}
} else {
showToast(
"That wagon is blocked. Only the coupling-end wagon can be pulled."
);
}
return;
}
const trackHits = raycaster.intersectObjects(trackHitBoxes, false);
if (!trackHits.length) return;
const trackIndex = trackHits[0].object.userData.trackIndex;
handleTrackClick(trackIndex);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.pointerType === "mouse") return;
pointerDown = true;
dragged = false;
totalDrag = 0;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerDown) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
totalDrag += Math.abs(dx) + Math.abs(dy);
if (totalDrag > 5) dragged = true;
cameraAzimuth -= dx * 0.006;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar + dy * 0.004,
0.62,
1.25
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (pointerDown && !dragged) handleWorldClick(event);
pointerDown = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
dragged = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * Math.exp(-event.deltaY * 0.001),
0.72,
1.65
);
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "u") undoMove();
if (event.key.toLowerCase() === "h") showHint();
if (event.key.toLowerCase() === "r" && !moving) {
loadLevel(levelIndex);
}
if (event.key.toLowerCase() === "d") startDispatch();
if (event.key === "ArrowLeft") cameraAzimuth -= 0.12;
if (event.key === "ArrowRight") cameraAzimuth += 0.12;
if (event.key === "ArrowUp") cameraPolar -= 0.08;
if (event.key === "ArrowDown") cameraPolar += 0.08;
cameraPolar = THREE.MathUtils.clamp(cameraPolar, 0.62, 1.25);
});
function updateCamera() {
const radius = 28;
const sinPolar = Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + radius * sinPolar * Math.sin(cameraAzimuth),
cameraTarget.y + radius * Math.cos(cameraPolar),
cameraTarget.z + radius * sinPolar * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
let viewHeight = 16.4 / cameraZoom;
viewHeight = Math.max(viewHeight, 21 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
function positionLabel(element, worldPosition, yOffset = 0) {
const point = worldPosition.clone();
point.y += yOffset;
point.project(camera);
const x = (point.x * 0.5 + 0.5) * window.innerWidth;
const y = (-point.y * 0.5 + 0.5) * window.innerHeight;
const visible = point.z > -1 && point.z < 1;
element.style.display = visible ? "grid" : "none";
element.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
const trackLabelElements = [];
for (let i = 0; i < 3; i++) {
const label = document.createElement("div");
label.className = "track-label";
label.textContent = `${TRACK_LETTERS[i]} · ${TRACK_NAMES[i]}`;
labelLayer.appendChild(label);
trackLabelElements.push(label);
}
function updateLabels() {
for (const [id, wagon] of wagonMeshes.entries()) {
const label = wagonLabels.get(id);
if (!wagon.visible) {
label.style.display = "none";
} else {
positionLabel(label, wagon.position, 1.63);
}
}
for (let i = 0; i < 3; i++) {
positionLabel(
trackLabelElements[i],
trackLabelAnchors[i],
0
);
}
}
function animate(now) {
requestAnimationFrame(animate);
updateCamera();
updateAnimations(now);
updateDispatchState(now);
updateLabels();
renderer.render(scene, camera);
}
resize();
loadLevel(0);
requestAnimationFrame(animate);
</script>
</body>
</html>
```