Prompt specification
Build or customize the Three.js 3D scene "Toy Train Follows the Selected Branch" 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: Toy Train Follows the Selected Branch
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/toy-train-follows-the-selected-branch-x2130
Scene Description Prompt:
Animate a train through a slow simplified switch after its route is set. Prevent the switch from changing while the train occupies the branching region. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Working Three.js Starter (toy-train-follows-the-selected-branch-x2130):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Railway Interlocking</title>
<style>
:root {
color-scheme: dark;
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #98cfe7;
}
#scene,
#scene canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
#panel {
position: fixed;
top: 18px;
left: 18px;
width: min(330px, calc(100vw - 36px));
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 16px;
color: #eef7ff;
background: rgba(17, 28, 39, 0.88);
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(12px);
user-select: none;
}
h1 {
margin: 0 0 6px;
font-size: 20px;
letter-spacing: 0.02em;
}
.subtitle {
margin: 0 0 16px;
color: #a9bac9;
font-size: 13px;
line-height: 1.45;
}
.row {
display: flex;
gap: 8px;
margin: 8px 0;
}
button {
flex: 1;
min-height: 42px;
padding: 10px 12px;
border: 1px solid #435565;
border-radius: 9px;
color: #eef7ff;
background: #263846;
font: inherit;
font-size: 14px;
font-weight: 650;
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 100ms ease;
}
button:hover:not(:disabled) {
background: #344c5e;
border-color: #7291a6;
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button.active {
color: #10212d;
background: #65d6a0;
border-color: #65d6a0;
}
button.primary {
color: #10212d;
background: #ffd166;
border-color: #ffd166;
}
button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
#lockBadge {
display: inline-block;
margin: 6px 0 10px;
padding: 6px 10px;
border-radius: 999px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
}
#lockBadge.free {
color: #baf7d8;
background: rgba(54, 181, 119, 0.22);
border: 1px solid rgba(90, 228, 159, 0.55);
}
#lockBadge.locked {
color: #ffd4d4;
background: rgba(220, 55, 55, 0.25);
border: 1px solid rgba(255, 91, 91, 0.7);
}
#status {
min-height: 42px;
color: #cad7e1;
font-size: 13px;
line-height: 1.45;
}
.legend {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
color: #9fb0bd;
font-size: 11px;
}
.legend-swatch {
width: 23px;
height: 9px;
border-radius: 2px;
background: #f3a52b;
box-shadow: 0 0 8px rgba(243, 165, 43, 0.45);
}
#hint {
position: fixed;
right: 16px;
bottom: 14px;
padding: 9px 12px;
border-radius: 9px;
color: rgba(255, 255, 255, 0.9);
background: rgba(17, 28, 39, 0.65);
font-size: 12px;
pointer-events: none;
}
@media (max-width: 600px) {
#panel {
top: 10px;
left: 10px;
padding: 14px;
}
#hint {
right: 10px;
bottom: 10px;
font-size: 10px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<section id="panel">
<h1>Voxel Turnout</h1>
<p class="subtitle">
Set the route before dispatch. The switch is locked whenever the
train occupies the branching region.
</p>
<div class="row">
<button id="mainBtn" class="active">Set Main</button>
<button id="branchBtn">Set Branch</button>
</div>
<div id="lockBadge" class="free">SWITCH FREE</div>
<div class="row">
<button id="dispatchBtn" class="primary">Dispatch Train</button>
<button id="resetBtn">Reset</button>
</div>
<div id="status" aria-live="polite">
Switch set to MAIN. Ready to dispatch.
</div>
<div class="legend">
<span class="legend-swatch"></span>
<span>Orange blocks mark the protected turnout limits.</span>
</div>
</section>
<div id="hint">Drag to orbit · Wheel to zoom · Double-click to reset view</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and basic scene
// -------------------------------------------------------------------------
const host = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9bd3e9);
scene.fog = new THREE.Fog(0x9bd3e9, 80, 145);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
host.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
46,
window.innerWidth / window.innerHeight,
0.1,
250
);
scene.add(new THREE.HemisphereLight(0xd9f3ff, 0x536443, 2.25));
const sun = new THREE.DirectionalLight(0xfff2d6, 3.1);
sun.position.set(-24, 38, 26);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -50;
sun.shadow.camera.right = 50;
sun.shadow.camera.top = 45;
sun.shadow.camera.bottom = -45;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 110;
sun.shadow.bias = -0.0004;
scene.add(sun);
// -------------------------------------------------------------------------
// Small helpers
// -------------------------------------------------------------------------
const V3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
function addBox(parent, size, position, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function sampleCurve(curve, count) {
const points = [];
for (let i = 0; i <= count; i++) {
points.push(curve.getPoint(i / count));
}
return points;
}
class Polyline {
constructor(points) {
this.points = points;
this.cumulative = [0];
for (let i = 1; i < points.length; i++) {
this.cumulative.push(
this.cumulative[i - 1] + points[i].distanceTo(points[i - 1])
);
}
this.length = this.cumulative[this.cumulative.length - 1];
}
sample(distance, outputPosition, outputTangent) {
const d = THREE.MathUtils.clamp(distance, 0, this.length);
let low = 0;
let high = this.cumulative.length - 1;
while (low + 1 < high) {
const middle = Math.floor((low + high) / 2);
if (this.cumulative[middle] <= d) {
low = middle;
} else {
high = middle;
}
}
const i = Math.max(0, low - 1);
const segmentLength =
this.cumulative[i + 1] - this.cumulative[i];
const t = (d - this.cumulative[i]) / segmentLength;
outputPosition.lerpVectors(this.points[i], this.points[i + 1], t);
outputTangent
.subVectors(this.points[i + 1], this.points[i])
.normalize();
}
}
// -------------------------------------------------------------------------
// Voxel ground
// -------------------------------------------------------------------------
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
});
const groundColumns = 21;
const groundRows = 12;
const groundTiles = groundColumns * groundRows;
const ground = new THREE.InstancedMesh(
new THREE.BoxGeometry(3.88, 0.68, 3.88),
groundMaterial,
groundTiles
);
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
const grassPalette = [
0x739c58,
0x7fa85f,
0x6f9754,
0x83aa63,
0x789f59
];
let tileIndex = 0;
for (let row = 0; row < groundRows; row++) {
for (let column = 0; column < groundColumns; column++) {
dummy.position.set(
-42 + column * 4,
-0.34,
-18 + row * 4
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
ground.setMatrixAt(tileIndex, dummy.matrix);
const paletteIndex =
(column * 3 + row * 5 + (column ^ row)) % grassPalette.length;
tileColor.setHex(grassPalette[paletteIndex]);
ground.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
ground.receiveShadow = true;
scene.add(ground);
// -------------------------------------------------------------------------
// Track paths: common approach, straight main, and simplified branch
// -------------------------------------------------------------------------
const commonCurve = new THREE.LineCurve3(
V3(-50, 0, 0),
V3(-10, 0, 0)
);
const mainCurve = new THREE.LineCurve3(
V3(-10, 0, 0),
V3(40, 0, 0)
);
const branchCurve = new THREE.CubicBezierCurve3(
V3(-10, 0, 0),
V3(-4, 0, 0),
V3(-2, 0, 0),
V3(4, 0, 4)
);
const branchExitCurve = new THREE.LineCurve3(
V3(4, 0, 4),
V3(34, 0, 24)
);
const commonPoints = sampleCurve(commonCurve, 100);
const mainPoints = sampleCurve(mainCurve, 90);
const branchPoints = [
...sampleCurve(branchCurve, 75).slice(0, -1),
...sampleCurve(branchExitCurve, 90)
];
const commonPath = new Polyline(commonPoints);
const mainPath = new Polyline(mainPoints);
const branchPath = new Polyline(branchPoints);
function buildTrack(points) {
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x667681,
metalness: 0.72,
roughness: 0.34
});
const tieMaterial = new THREE.MeshStandardMaterial({
color: 0x76523b,
roughness: 0.95
});
const railMatrices = [];
const tieMatrices = [];
const gauge = 1.45;
let distance = 0;
let nextTie = 0;
for (let i = 1; i < points.length; i++) {
const a = points[i - 1];
const b = points[i];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
if (length < 0.0001) continue;
const nx = -dz / length;
const nz = dx / length;
for (const side of [-1, 1]) {
const railA = V3(
a.x + nx * gauge * 0.5 * side,
0,
a.z + nz * gauge * 0.5 * side
);
const railB = V3(
b.x + nx * gauge * 0.5 * side,
0,
b.z + nz * gauge * 0.5 * side
);
const railDelta = railB.clone().sub(railA);
const railLength = railDelta.length();
const railAngle = -Math.atan2(railDelta.z, railDelta.x);
dummy.position.copy(railA).add(railB).multiplyScalar(0.5);
dummy.position.y = 0.43;
dummy.rotation.set(0, railAngle, 0);
dummy.scale.set(railLength, 0.16, 0.14);
dummy.updateMatrix();
railMatrices.push(dummy.matrix.clone());
}
if (distance >= nextTie) {
const tieAngle = -Math.atan2(dz, dx);
dummy.position.set(a.x, 0.20, a.z);
dummy.rotation.set(0, tieAngle, 0);
dummy.scale.set(0.38, 0.18, 2.5);
dummy.updateMatrix();
tieMatrices.push(dummy.matrix.clone());
nextTie += 1.35;
}
distance += length;
}
const railMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
railMaterial,
railMatrices.length
);
railMatrices.forEach((matrix, index) => {
railMesh.setMatrixAt(index, matrix);
});
railMesh.instanceMatrix.needsUpdate = true;
railMesh.castShadow = true;
railMesh.receiveShadow = true;
scene.add(railMesh);
const tieMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
tieMaterial,
tieMatrices.length
);
tieMatrices.forEach((matrix, index) => {
tieMesh.setMatrixAt(index, matrix);
});
tieMesh.instanceMatrix.needsUpdate = true;
tieMesh.receiveShadow = true;
scene.add(tieMesh);
}
buildTrack(commonPoints);
buildTrack(mainPoints);
buildTrack(branchPoints);
// -------------------------------------------------------------------------
// Protected turnout region and switch hardware
// -------------------------------------------------------------------------
const REGION_START = -10;
const REGION_END = 24;
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xf3a52b,
emissive: 0x7a3500,
emissiveIntensity: 0.18,
roughness: 0.72
});
for (let x = REGION_START; x <= REGION_END; x += 2) {
addBox(
scene,
[1.25, 0.42, 0.58],
[x, 0.22, -4.45],
markerMaterial
);
}
const postMaterial = new THREE.MeshStandardMaterial({
color: 0xffc04d,
roughness: 0.7
});
for (const x of [REGION_START, REGION_END]) {
addBox(scene, [0.48, 1.8, 0.48], [x, 0.9, -4.45], postMaterial);
addBox(scene, [0.8, 0.25, 0.8], [x, 1.9, -4.45], postMaterial);
}
const switchMetal = new THREE.MeshStandardMaterial({
color: 0xc7d0d6,
metalness: 0.78,
roughness: 0.3
});
const bladePivot = new THREE.Group();
bladePivot.position.set(-10.35, 0.56, 0.58);
scene.add(bladePivot);
addBox(
bladePivot,
[4.8, 0.18, 0.18],
[2.4, 0, 0],
switchMetal
);
const actuatorMaterial = new THREE.MeshStandardMaterial({
color: 0x526774,
metalness: 0.35,
roughness: 0.55
});
addBox(
scene,
[1.8, 0.65, 1.5],
[-11.2, 0.33, -2.5],
actuatorMaterial
);
const leverPivot = new THREE.Group();
leverPivot.position.set(-11.2, 0.68, -2.5);
scene.add(leverPivot);
const leverMaterial = new THREE.MeshStandardMaterial({
color: 0xffca58,
roughness: 0.48
});
addBox(
leverPivot,
[0.22, 1.9, 0.22],
[0, 0.95, 0],
leverMaterial
);
addBox(
leverPivot,
[0.85, 0.42, 0.42],
[0.35, 1.75, 0],
leverMaterial
);
const lockLampMaterial = new THREE.MeshStandardMaterial({
color: 0x42e47c,
emissive: 0x42e47c,
emissiveIntensity: 0.8
});
addBox(
scene,
[0.45, 0.45, 0.45],
[-12.35, 1.1, -2.5],
lockLampMaterial
);
// -------------------------------------------------------------------------
// Simple voxel scenery
// -------------------------------------------------------------------------
const houseMaterials = [
new THREE.MeshStandardMaterial({ color: 0xd87b5d, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0xd6b96b, roughness: 0.9 }),
new THREE.MeshStandardMaterial({ color: 0x7398b8, roughness: 0.9 })
];
const roofMaterials = [
new THREE.MeshStandardMaterial({ color: 0x70443d, roughness: 0.95 }),
new THREE.MeshStandardMaterial({ color: 0x465b67, roughness: 0.95 })
];
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0xbcecff,
emissive: 0x315c69,
emissiveIntensity: 0.25,
roughness: 0.25
});
function addHouse(x, z, bodyIndex = 0, roofIndex = 0, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
scene.add(group);
addBox(
group,
[4, 2.7, 3.4],
[0, 1.35, 0],
houseMaterials[bodyIndex % houseMaterials.length]
);
addBox(
group,
[4.7, 0.5, 4],
[0, 2.95, 0],
roofMaterials[roofIndex % roofMaterials.length]
);
addBox(
group,
[3.7, 0.5, 3.1],
[0, 3.45, 0],
roofMaterials[roofIndex % roofMaterials.length]
);
addBox(
group,
[2.6, 0.5, 2.2],
[0, 3.95, 0],
roofMaterials[roofIndex % roofMaterials.length]
);
for (const wx of [-1.1, 1.1]) {
addBox(
group,
[0.75, 0.85, 0.12],
[wx, 1.65, 1.73],
windowMaterial
);
}
addBox(
group,
[0.85, 1.55, 0.13],
[0, 0.78, 1.74],
roofMaterials[roofIndex % roofMaterials.length]
);
}
addHouse(-19, -10, 0, 0, 1.05);
addHouse(-27, 14, 2, 1, 0.85);
addHouse(20, -11, 1, 1, 1.15);
addHouse(28, -11, 0, 0, 0.85);
addHouse(4, -11, 2, 0, 1.0);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x75503a,
roughness: 1
});
const leafMaterials = [
new THREE.MeshStandardMaterial({ color: 0x426e42, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0x527f46, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0x628e4c, roughness: 1 })
];
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
scene.add(group);
addBox(group, [0.65, 2.2, 0.65], [0, 1.1, 0], trunkMaterial);
addBox(group, [2.4, 1.5, 2.4], [0, 2.5, 0], leafMaterials[0]);
addBox(group, [1.7, 1.3, 1.7], [0.25, 3.45, 0], leafMaterials[1]);
addBox(group, [1.1, 0.9, 1.1], [-0.25, 4.25, 0.15], leafMaterials[2]);
}
[
[-29, -10, 1.1],
[-23, 9, 0.9],
[-14, 14, 1.05],
[0, 15, 1.15],
[26, -13, 1],
[-31, 18, 0.85],
[13, -15, 0.9]
].forEach((position) => addTree(...position));
const cloudMaterial = new THREE.MeshStandardMaterial({
color: 0xf4fbff,
roughness: 1
});
function addCloud(x, y, z) {
const group = new THREE.Group();
group.position.set(x, y, z);
scene.add(group);
addBox(group, [3.2, 1.2, 1.8], [0, 0, 0], cloudMaterial);
addBox(group, [2.1, 1.5, 1.8], [-1.8, 0.2, 0], cloudMaterial);
addBox(group, [2.2, 1.1, 1.8], [1.9, 0.1, 0], cloudMaterial);
}
addCloud(-24, 13, -20);
addCloud(13, 15, -22);
addCloud(29, 12, -18);
// -------------------------------------------------------------------------
// Block-built train
// -------------------------------------------------------------------------
const trainMaterials = {
chassis: new THREE.MeshStandardMaterial({
color: 0x25343d,
roughness: 0.58
}),
wheel: new THREE.MeshStandardMaterial({
color: 0x20272c,
roughness: 0.72
}),
hub: new THREE.MeshStandardMaterial({
color: 0xc5d1d7,
metalness: 0.62,
roughness: 0.35
}),
red: new THREE.MeshStandardMaterial({
color: 0xc94f3d,
roughness: 0.58
}),
redDark: new THREE.MeshStandardMaterial({
color: 0x8e352e,
roughness: 0.7
}),
blue: new THREE.MeshStandardMaterial({
color: 0x356d8e,
roughness: 0.62
}),
yellow: new THREE.MeshStandardMaterial({
color: 0xf0b744,
roughness: 0.62
}),
black: new THREE.MeshStandardMaterial({
color: 0x30383c,
roughness: 0.72
}),
wood: new THREE.MeshStandardMaterial({
color: 0x9b7046,
roughness: 0.95
})
};
function addWheel(parent, x, z, wheelList) {
const pivot = new THREE.Group();
pivot.position.set(x, 0.82, z);
parent.add(pivot);
addBox(pivot, [0.64, 0.64, 0.24], [0, 0, 0], trainMaterials.wheel);
addBox(pivot, [0.26, 0.26, 0.28], [0, 0, 0], trainMaterials.hub);
wheelList.push(pivot);
}
function createCar(type) {
const group = new THREE.Group();
const wheels = [];
addBox(
group,
[4.25, 0.35, 1.72],
[0, 1.13, 0],
trainMaterials.chassis
);
if (type === "loco") {
addBox(
group,
[2.85, 1.05, 1.45],
[0.55, 1.87, 0],
trainMaterials.red
);
addBox(
group,
[1.5, 1.65, 1.78],
[-1.25, 2.02, 0],
trainMaterials.red
);
addBox(
group,
[1.75, 0.2, 2],
[-1.25, 2.94, 0],
trainMaterials.black
);
addBox(
group,
[0.55, 0.72, 0.55],
[1.42, 2.68, 0],
trainMaterials.black
);
addBox(
group,
[0.42, 0.42, 0.85],
[1.95, 1.97, 0],
trainMaterials.yellow
);
for (const z of [-0.58, 0, 0.58]) {
addBox(
group,
[0.6, 0.13, 0.13],
[2.15, 0.91, z],
trainMaterials.chassis
);
}
} else if (type === "tender") {
addBox(
group,
[3.15, 1.12, 1.62],
[-0.1, 1.84, 0],
trainMaterials.blue
);
addBox(
group,
[2.2, 0.38, 1.25],
[-0.1, 2.52, 0],
trainMaterials.black
);
} else {
addBox(
group,
[3.85, 0.35, 1.8],
[0, 1.42, 0],
trainMaterials.wood
);
addBox(
group,
[1.35, 1.25, 1.35],
[-0.75, 2.2, 0],
trainMaterials.yellow
);
addBox(
group,
[1.1, 1.05, 1.1],
[0.45, 2.16, 0.1],
trainMaterials.blue
);
addBox(
group,
[0.8, 0.75, 0.85],
[1.25, 1.98, -0.2],
trainMaterials.red
);
}
for (const x of [-1.25, 1.25]) {
addWheel(group, x, -0.94, wheels);
addWheel(group, x, 0.94, wheels);
}
scene.add(group);
return { group, wheels };
}
const trainCars = [
{ ...createCar("loco"), offset: 0 },
{ ...createCar("tender"), offset: 4.8 },
{ ...createCar("wagon"), offset: 9.2 }
];
const CAR_HALF_LENGTH = 2.25;
const TRAIN_SPEED = 2.6;
const START_DISTANCE = 18;
// -------------------------------------------------------------------------
// Interlocking and UI state
// -------------------------------------------------------------------------
const mainButton = document.getElementById("mainBtn");
const branchButton = document.getElementById("branchBtn");
const dispatchButton = document.getElementById("dispatchBtn");
const resetButton = document.getElementById("resetBtn");
const statusElement = document.getElementById("status");
const lockBadge = document.getElementById("lockBadge");
let switchState = "MAIN";
let switchTargetAngle = 0;
let leverTargetAngle = 0.55;
let trainDistance = START_DISTANCE;
let activeSuffix = mainPath;
let totalDistance = commonPath.length + mainPath.length;
let running = false;
let completed = false;
let locked = false;
let committed = false;
let committedRoute = null;
function setStatus(message) {
statusElement.textContent = message;
}
function updateRouteButtons() {
mainButton.classList.toggle("active", switchState === "MAIN");
branchButton.classList.toggle("active", switchState === "BRANCH");
}
function refreshControls() {
mainButton.disabled = locked;
branchButton.disabled = locked;
dispatchButton.disabled = running || completed;
// Reset must not be used to change a switch while it is interlocked.
resetButton.disabled = locked;
dispatchButton.textContent = running
? "Train Running"
: completed
? "Train Arrived"
: "Dispatch Train";
lockBadge.textContent = locked ? "SWITCH INTERLOCKED" : "SWITCH FREE";
lockBadge.className = locked ? "locked" : "free";
}
function setSwitch(route, announce = true) {
// This guard prevents programmatic changes as well as disabled clicks.
if (locked) return;
switchState = route;
switchTargetAngle = route === "BRANCH" ? -0.24 : 0;
leverTargetAngle = route === "BRANCH" ? -0.55 : 0.55;
updateRouteButtons();
if (running && !committed) {
activeSuffix = route === "BRANCH" ? branchPath : mainPath;
totalDistance = commonPath.length + activeSuffix.length;
setStatus(
`Switch set to ${route}. The approaching train will take the ${route.toLowerCase()} route.`
);
} else if (running && committed) {
setStatus(
`Switch set to ${route}. The running train remains on its committed ${committedRoute} route.`
);
} else if (!completed) {
setStatus(`Switch set to ${route}. Ready to dispatch.`);
}
refreshControls();
}
mainButton.addEventListener("click", () => setSwitch("MAIN"));
branchButton.addEventListener("click", () => setSwitch("BRANCH"));
dispatchButton.addEventListener("click", () => {
if (running || completed || locked) return;
running = true;
completed = false;
committed = false;
committedRoute = null;
activeSuffix = switchState === "BRANCH" ? branchPath : mainPath;
totalDistance = commonPath.length + activeSuffix.length;
setStatus(
`Train dispatched at ${TRAIN_SPEED.toFixed(1)} units/s. Set the switch before the turnout.`
);
refreshControls();
});
resetButton.addEventListener("click", () => {
if (locked) return;
running = false;
completed = false;
committed = false;
committedRoute = null;
trainDistance = START_DISTANCE;
activeSuffix = mainPath;
totalDistance = commonPath.length + mainPath.length;
switchState = "MAIN";
switchTargetAngle = 0;
leverTargetAngle = 0.55;
updateRouteButtons();
setStatus("Switch set to MAIN. Ready to dispatch.");
refreshControls();
});
// -------------------------------------------------------------------------
// Train movement and route commitment
// -------------------------------------------------------------------------
const sampledPosition = V3();
const sampledTangent = V3();
function sampleActiveRoute(distance, outputPosition, outputTangent) {
if (distance <= commonPath.length) {
commonPath.sample(distance, outputPosition, outputTangent);
} else {
activeSuffix.sample(
distance - commonPath.length,
outputPosition,
outputTangent
);
}
}
function updateTrain(deltaTime) {
if (running) {
trainDistance = Math.min(
totalDistance,
trainDistance + TRAIN_SPEED * deltaTime
);
}
let maxFront = -Infinity;
let minRear = Infinity;
for (const car of trainCars) {
sampleActiveRoute(
trainDistance - car.offset,
sampledPosition,
sampledTangent
);
car.group.position.set(sampledPosition.x, 0, sampledPosition.z);
car.group.rotation.y = -Math.atan2(
sampledTangent.z,
sampledTangent.x
);
for (const wheel of car.wheels) {
wheel.rotation.z = -trainDistance / 0.64;
}
maxFront = Math.max(maxFront, car.group.position.x + CAR_HALF_LENGTH);
minRear = Math.min(minRear, car.group.position.x - CAR_HALF_LENGTH);
}
const occupiesRegion =
maxFront >= REGION_START && minRear <= REGION_END;
if (!locked && occupiesRegion) {
locked = true;
committed = true;
committedRoute = switchState;
activeSuffix = switchState === "BRANCH" ? branchPath : mainPath;
totalDistance = commonPath.length + activeSuffix.length;
setStatus(
`INTERLOCKED: the train is in the turnout limits. Route committed to ${committedRoute}.`
);
refreshControls();
} else if (locked && !occupiesRegion) {
locked = false;
setStatus(
running
? "Turnout limits clear. The switch can be changed again."
: "Train arrived. The switch is free."
);
refreshControls();
}
if (running && trainDistance >= totalDistance) {
running = false;
completed = true;
setStatus("Train arrived at the end of the route.");
refreshControls();
}
}
// -------------------------------------------------------------------------
// Custom camera controls, implemented without addons
// -------------------------------------------------------------------------
const cameraTarget = V3(-3, 0, 3);
let cameraTheta = 0.72;
let cameraPhi = 0.98;
let cameraRadius = 78;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0.72;
cameraPhi = 0.98;
cameraRadius = 78;
}
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraTheta -= deltaX * 0.005;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.005,
0.28,
1.42
);
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
38,
115
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const deltaTime = Math.min(clock.getDelta(), 0.05);
updateTrain(deltaTime);
const switchLerp = 1 - Math.exp(-deltaTime * 7);
bladePivot.rotation.y = THREE.MathUtils.lerp(
bladePivot.rotation.y,
switchTargetAngle,
switchLerp
);
leverPivot.rotation.z = THREE.MathUtils.lerp(
leverPivot.rotation.z,
leverTargetAngle,
switchLerp
);
if (locked) {
lockLampMaterial.color.setHex(0xff3333);
lockLampMaterial.emissive.setHex(0xff2222);
lockLampMaterial.emissiveIntensity = 1.6;
} else {
lockLampMaterial.color.setHex(0x42e47c);
lockLampMaterial.emissive.setHex(0x42e47c);
lockLampMaterial.emissiveIntensity = 0.75;
}
updateCamera();
renderer.render(scene, camera);
}
updateRouteButtons();
refreshControls();
updateTrain(0);
animate();
</script>
</body>
</html>
```