Prompt specification
Build or customize the Three.js 3D scene "Two Trains One Shared Block" 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: Two Trains One Shared Block
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/two-trains-one-shared-block-x2126
Scene Description Prompt:
Two voxel trains reserve one shared block; release it only after the entire first train exits. Three.js from cdnjs, one HTML file.
Working Three.js Starter (two-trains-one-shared-block-x2126):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Railway — Shared Block Interlocking</title>
<style>
:root {
--cyan: #45d7ff;
--amber: #ffb640;
--green: #58e6a4;
--red: #ff526f;
--panel: rgba(10, 19, 31, 0.88);
--line: rgba(171, 213, 230, 0.16);
--muted: #91a7b7;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #09131e;
color: #eef8ff;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
#panel {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(350px, calc(100vw - 36px));
padding: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(18px);
user-select: none;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 2px;
font-size: 27px;
line-height: 1.1;
letter-spacing: -0.03em;
}
.subtitle {
margin: 0 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.status-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-bottom: 10px;
}
.status-card {
min-width: 0;
padding: 11px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.035);
}
.status-card .label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.status-card strong {
display: block;
overflow: hidden;
font-size: 15px;
text-overflow: ellipsis;
white-space: nowrap;
}
#blockPill {
display: inline-flex;
align-items: center;
gap: 7px;
}
#blockPill::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px currentColor;
content: "";
}
#blockPill[data-state="reserved"]::before {
background: var(--amber);
}
#blockPill[data-state="occupied"]::before {
background: var(--red);
}
#statusText {
min-height: 36px;
margin: 2px 0 13px;
color: #c7d8e2;
font-size: 13px;
line-height: 1.45;
}
.release-panel {
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
}
.release-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
#releasePercent {
color: #eef8ff;
}
.bar {
height: 7px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
#releaseBar {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--cyan), var(--amber));
transition: width 120ms linear;
}
#releaseText {
margin-top: 9px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
#events {
min-height: 100px;
margin: 13px 0 14px;
padding: 0;
list-style: none;
}
#events li {
display: grid;
grid-template-columns: 48px 1fr;
gap: 8px;
padding: 5px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.055);
color: #c6d6df;
font-size: 11px;
line-height: 1.35;
}
#events li:last-child {
border-bottom: 0;
}
#events time {
color: #647e8e;
font-variant-numeric: tabular-nums;
}
.buttons {
display: flex;
gap: 8px;
}
button {
flex: 1;
padding: 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.07);
color: #eff9ff;
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: background 150ms ease, transform 150ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.12);
transform: translateY(-1px);
}
#replayButton {
border-color: rgba(69, 215, 255, 0.28);
color: var(--cyan);
}
#hint {
position: fixed;
z-index: 5;
right: 18px;
bottom: 16px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(8, 17, 28, 0.72);
color: #9fb4c1;
font-size: 11px;
backdrop-filter: blur(10px);
pointer-events: none;
}
.world-label {
position: fixed;
z-index: 4;
display: none;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 7px;
background: rgba(7, 16, 26, 0.8);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.22);
color: #eef8ff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
#blockLabel {
border-color: rgba(88, 230, 164, 0.35);
color: var(--green);
}
#trainALabel {
border-color: rgba(69, 215, 255, 0.45);
color: var(--cyan);
}
#trainBLabel {
border-color: rgba(255, 182, 64, 0.45);
color: var(--amber);
}
@media (max-width: 640px) {
#panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 14px;
}
h1 {
font-size: 23px;
}
#events {
min-height: 0;
}
#events li:nth-child(n + 4) {
display: none;
}
#hint {
right: 10px;
bottom: 10px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<section id="panel">
<div class="eyebrow">Railway Interlocking</div>
<h1>One Shared Block</h1>
<p class="subtitle">
Two voxel trains approach on separate routes. The first owns the shared block;
the next train waits until the entire first consist clears the exit.
</p>
<div class="status-grid">
<div class="status-card">
<span class="label">Reservation</span>
<strong id="ownerValue">AUTO SELECT</strong>
</div>
<div class="status-card">
<span class="label">Shared block</span>
<strong id="blockPill" data-state="free">FREE</strong>
</div>
</div>
<div id="statusText">First arrival will receive the reservation.</div>
<div class="release-panel">
<div class="release-heading">
<span>Tail-clear release check</span>
<span id="releasePercent">0%</span>
</div>
<div class="bar">
<div id="releaseBar"></div>
</div>
<div id="releaseText">
Release is inhibited until the last vehicle passes the exit boundary.
</div>
</div>
<ul id="events" aria-live="polite"></ul>
<div class="buttons">
<button id="replayButton" type="button">Replay cycle</button>
<button id="pauseButton" type="button">Pause</button>
</div>
</section>
<div id="hint">Drag to orbit · Scroll to zoom</div>
<div id="blockLabel" class="world-label">SHARED BLOCK</div>
<div id="entryLabel" class="world-label">ENTRY</div>
<div id="exitLabel" class="world-label">EXIT · TAIL CLEAR</div>
<div id="trainALabel" class="world-label">TRAIN A</div>
<div id="trainBLabel" class="world-label">TRAIN B</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
// -------------------------------------------------------------------------
// Renderer, scene, lighting
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a1520);
scene.fog = new THREE.Fog(0x0a1520, 48, 115);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
180
);
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;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
$("stage").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc8efff, 0x26362c, 1.75);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d8, 2.6);
sun.position.set(-18, 31, 19);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -38;
sun.shadow.camera.right = 38;
sun.shadow.camera.top = 28;
sun.shadow.camera.bottom = -28;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 90;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x4ac9ff, 0.65);
rimLight.position.set(20, 12, -24);
scene.add(rimLight);
function standardMaterial(color, roughness = 0.75, metalness = 0) {
return new THREE.MeshStandardMaterial({
color,
roughness,
metalness
});
}
function addBox(parent, size, position, material, castShadow = true) {
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 = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Voxel landscape
// -------------------------------------------------------------------------
const groundMaterial = standardMaterial(0x29483d, 0.95);
addBox(
scene,
[72, 0.8, 42],
[0, -0.45, 0],
groundMaterial,
false
);
const baseMaterial = standardMaterial(0x172b2c, 0.9);
addBox(
scene,
[72.8, 0.38, 42.8],
[0, -0.86, 0],
baseMaterial,
false
);
const grid = new THREE.GridHelper(70, 35, 0x6b9b87, 0x416a60);
grid.position.y = -0.035;
grid.scale.z = 0.58;
grid.material.transparent = true;
grid.material.opacity = 0.15;
scene.add(grid);
const trunkMaterial = standardMaterial(0x654c36);
const leafMaterials = [
standardMaterial(0x3f7950),
standardMaterial(0x4d8a56),
standardMaterial(0x326c49)
];
const treePositions = [
[-26, -13], [-22, 12], [-18, -15], [-14, 14], [-9, 13],
[-3, 15], [4, 14], [11, 14], [17, 13], [23, 14],
[28, -13], [23, -15], [17, -15], [10, -15], [4, -16],
[-27, 7], [-24, -7], [27, 7], [25, -7]
];
treePositions.forEach(([x, z], index) => {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
addBox(tree, [0.45, 1.7, 0.45], [0, 0.8, 0], trunkMaterial);
addBox(
tree,
[2.3, 1.8, 2.3],
[0, 2.25, 0],
leafMaterials[index % leafMaterials.length]
);
addBox(
tree,
[1.55, 1.25, 1.55],
[0.15, 3.35, -0.1],
leafMaterials[(index + 1) % leafMaterials.length]
);
scene.add(tree);
});
const rockMaterial = standardMaterial(0x52605d);
[
[-29, 10, 1.6], [-12, -12, 1.2], [20, 10, 1.4],
[29, -4, 1.8], [7, -17, 1.5]
].forEach(([x, z, s]) => {
addBox(scene, [s, s * 0.65, s], [x, s * 0.28, z], rockMaterial);
});
function addHouse(x, z, width, height, depth, color) {
const group = new THREE.Group();
group.position.set(x, 0, z);
const wall = standardMaterial(color);
const roof = standardMaterial(0x354b58, 0.85);
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x8edcff,
emissive: 0x24566d,
emissiveIntensity: 0.8,
roughness: 0.35
});
addBox(group, [width, height, depth], [0, height / 2, 0], wall);
addBox(
group,
[width + 0.3, 0.32, depth + 0.3],
[0, height + 0.12, 0],
roof
);
addBox(
group,
[0.45, 1.1, 0.45],
[width * 0.25, height + 0.65, 0],
roof
);
addBox(
group,
[width * 0.22, height * 0.26, 0.08],
[-width * 0.2, height * 0.6, depth / 2 + 0.045],
windowMaterial
);
scene.add(group);
}
addHouse(-18, -12.5, 4.2, 2.8, 3.1, 0x927356);
addHouse(15, -13, 4.8, 3.2, 3.5, 0x6e8790);
addHouse(-20, 13.5, 3.8, 2.4, 3.2, 0x8a6b58);
addHouse(20, 13.2, 4.1, 2.7, 3.1, 0x657b85);
// Interlocking control tower.
const tower = new THREE.Group();
tower.position.set(0, 0, -9.6);
const towerWall = standardMaterial(0x566b73);
const towerRoof = standardMaterial(0x263945);
const towerWindow = new THREE.MeshStandardMaterial({
color: 0x76d8ff,
emissive: 0x1f809f,
emissiveIntensity: 0.9,
roughness: 0.25
});
addBox(tower, [3.5, 3.3, 2.8], [0, 1.65, 0], towerWall);
addBox(tower, [3.9, 0.38, 3.2], [0, 3.5, 0], towerRoof);
addBox(tower, [3.55, 0.78, 2.86], [0, 2.6, 0], towerWindow);
addBox(tower, [0.18, 2.2, 0.18], [0.7, 4.6, 0], towerRoof);
addBox(tower, [0.55, 0.18, 0.18], [0.7, 5.55, 0], towerRoof);
scene.add(tower);
const towerBeaconMaterial = new THREE.MeshStandardMaterial({
color: 0xff526f,
emissive: 0xff193c,
emissiveIntensity: 1.4
});
addBox(tower, [0.24, 0.24, 0.24], [0.7, 5.75, 0], towerBeaconMaterial);
// -------------------------------------------------------------------------
// Routes: two approaches, one shared center, two separate exits
// -------------------------------------------------------------------------
const V = (x, z) => new THREE.Vector3(x, 0, z);
class Route {
constructor(z) {
this.curves = [
new THREE.LineCurve3(V(-30, z), V(-10, z)),
new THREE.CubicBezierCurve3(
V(-10, z),
V(-6, z),
V(-8, 0),
V(-4, 0)
),
new THREE.LineCurve3(V(-4, 0), V(4, 0)),
new THREE.CubicBezierCurve3(
V(4, 0),
V(8, 0),
V(6, z),
V(12, z)
),
new THREE.LineCurve3(V(12, z), V(30, z))
];
this.starts = [];
this.totalLength = 0;
this.curves.forEach((curve) => {
this.starts.push(this.totalLength);
this.totalLength += curve.getLength();
});
this.entryDistance = this.starts[2];
this.exitDistance = this.starts[3];
}
locate(distance) {
const d = THREE.MathUtils.clamp(distance, 0, this.totalLength);
let index = this.curves.length - 1;
for (let i = 0; i < this.curves.length; i++) {
if (d <= this.starts[i] + this.curves[i].getLength()) {
index = i;
break;
}
}
const length = this.curves[index].getLength();
const local = THREE.MathUtils.clamp(
(d - this.starts[index]) / length,
0,
1
);
return { curve: this.curves[index], local };
}
pointAt(distance) {
const { curve, local } = this.locate(distance);
return curve.getPointAt(local);
}
tangentAt(distance) {
const { curve, local } = this.locate(distance);
return curve.getTangentAt(local).normalize();
}
}
const routeA = new Route(-4);
const routeB = new Route(4);
const sharedStart = routeA.entryDistance;
const sharedEnd = routeA.exitDistance;
const requestDistance = sharedStart - 3.0;
const tieMaterial = standardMaterial(0x685640, 0.95);
const sharedTieMaterial = standardMaterial(0x9b7a47, 0.9);
const railMaterial = standardMaterial(0x9baeb6, 0.32, 0.72);
function buildTrackSegment(route, startDistance, endDistance, ties) {
const length = endDistance - startDistance;
const count = Math.max(1, Math.ceil(length / 0.62));
const step = length / count;
const sleeperGeometry = new THREE.BoxGeometry(1.72, 0.14, 0.27);
const railGeometry = new THREE.BoxGeometry(0.12, 0.12, step * 1.12);
const sleeperMesh = new THREE.InstancedMesh(
sleeperGeometry,
ties,
count
);
const railMesh = new THREE.InstancedMesh(
railGeometry,
railMaterial,
count * 2
);
sleeperMesh.castShadow = true;
sleeperMesh.receiveShadow = true;
railMesh.castShadow = true;
railMesh.receiveShadow = true;
const dummy = new THREE.Object3D();
for (let i = 0; i < count; i++) {
const distance = startDistance + (i + 0.5) * step;
const point = route.pointAt(distance);
const tangent = route.tangentAt(distance);
const yaw = Math.atan2(tangent.x, tangent.z);
dummy.position.set(point.x, 0.13, point.z);
dummy.rotation.set(0, yaw, 0);
dummy.updateMatrix();
sleeperMesh.setMatrixAt(i, dummy.matrix);
const perpendicular = new THREE.Vector3(
tangent.z,
0,
-tangent.x
).normalize();
for (let side = 0; side < 2; side++) {
const offset = side === 0 ? -0.63 : 0.63;
dummy.position.set(
point.x + perpendicular.x * offset,
0.29,
point.z + perpendicular.z * offset
);
dummy.rotation.set(0, yaw, 0);
dummy.updateMatrix();
railMesh.setMatrixAt(i * 2 + side, dummy.matrix);
}
}
sleeperMesh.instanceMatrix.needsUpdate = true;
railMesh.instanceMatrix.needsUpdate = true;
scene.add(sleeperMesh, railMesh);
}
buildTrackSegment(routeA, 0, sharedStart, tieMaterial);
buildTrackSegment(routeB, 0, sharedStart, tieMaterial);
buildTrackSegment(routeA, sharedStart, sharedEnd, sharedTieMaterial);
buildTrackSegment(routeA, sharedEnd, routeA.totalLength, tieMaterial);
buildTrackSegment(routeB, sharedEnd, routeB.totalLength, tieMaterial);
// Highlighted shared block.
const blockMaterial = new THREE.MeshStandardMaterial({
color: 0x58e6a4,
emissive: 0x123c2b,
emissiveIntensity: 0.75,
transparent: true,
opacity: 0.22,
depthWrite: false,
roughness: 0.7
});
const blockBed = addBox(
scene,
[8, 0.07, 2.5],
[0, 0.025, 0],
blockMaterial,
false
);
blockBed.receiveShadow = false;
const boundaryMaterial = standardMaterial(0xf4c34f, 0.55);
const darkBoundaryMaterial = standardMaterial(0x263038);
for (const x of [-4, 4]) {
for (const z of [-1.42, 1.42]) {
addBox(
scene,
[0.36, 0.22, 0.36],
[x, 0.11, z],
darkBoundaryMaterial
);
addBox(
scene,
[0.18, 1.45, 0.18],
[x, 0.84, z],
boundaryMaterial
);
addBox(
scene,
[0.3, 0.18, 0.3],
[x, 1.58, z],
darkBoundaryMaterial
);
}
}
// Exit strip changes from red to green when the tail clears.
const exitStripMaterial = new THREE.MeshStandardMaterial({
color: 0xff526f,
emissive: 0xff193c,
emissiveIntensity: 0.8,
transparent: true,
opacity: 0.9
});
addBox(
scene,
[0.12, 0.05, 2.65],
[4, 0.1, 0],
exitStripMaterial,
false
);
// -------------------------------------------------------------------------
// Signals
// -------------------------------------------------------------------------
function makeSignal(route, side) {
const point = route.pointAt(requestDistance);
const tangent = route.tangentAt(requestDistance);
const perpendicular = new THREE.Vector3(
tangent.z,
0,
-tangent.x
).normalize();
point.addScaledVector(perpendicular, 1.55 * side);
const group = new THREE.Group();
group.position.copy(point);
group.rotation.y = Math.atan2(tangent.x, tangent.z);
const mastMaterial = standardMaterial(0x26343b);
const housingMaterial = standardMaterial(0x172128);
const redMaterial = new THREE.MeshStandardMaterial({
color: 0xff3158,
emissive: 0xff193c,
emissiveIntensity: 1.4,
roughness: 0.3
});
const greenMaterial = new THREE.MeshStandardMaterial({
color: 0x244638,
emissive: 0x0b2a20,
emissiveIntensity: 0.2,
roughness: 0.3
});
addBox(group, [0.38, 0.18, 0.38], [0, 0.09, 0], mastMaterial);
addBox(group, [0.16, 1.45, 0.16], [0, 0.8, 0], mastMaterial);
addBox(group, [0.7, 0.65, 0.32], [0, 1.5, 0], housingMaterial);
addBox(group, [0.22, 0.22, 0.12], [-0.17, 1.51, -0.2], redMaterial);
addBox(group, [0.22, 0.22, 0.12], [0.17, 1.51, -0.2], greenMaterial);
scene.add(group);
return { redMaterial, greenMaterial };
}
const signalA = makeSignal(routeA, 1);
const signalB = makeSignal(routeB, -1);
function setSignal(signal, green) {
signal.redMaterial.color.setHex(green ? 0x3a1420 : 0xff3158);
signal.redMaterial.emissive.setHex(green ? 0x130309 : 0xff193c);
signal.redMaterial.emissiveIntensity = green ? 0.12 : 1.4;
signal.greenMaterial.color.setHex(green ? 0x58e6a4 : 0x244638);
signal.greenMaterial.emissive.setHex(green ? 0x2cff91 : 0x0b2a20);
signal.greenMaterial.emissiveIntensity = green ? 1.35 : 0.16;
}
// -------------------------------------------------------------------------
// Voxel trains
// -------------------------------------------------------------------------
const wheelMaterial = standardMaterial(0x151b21, 0.85);
const chassisMaterial = standardMaterial(0x273039, 0.75, 0.15);
const darkMetalMaterial = standardMaterial(0x3d4851, 0.55, 0.35);
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x9aeaff,
emissive: 0x21627c,
emissiveIntensity: 0.7,
roughness: 0.25
});
const headlightMaterial = new THREE.MeshStandardMaterial({
color: 0xfff5bd,
emissive: 0xffd86a,
emissiveIntensity: 1.5,
roughness: 0.25
});
function makeVehicle(bodyColor, cargoColor, isEngine) {
const group = new THREE.Group();
const bodyMaterial = standardMaterial(bodyColor, 0.55, 0.08);
const cargoMaterial = standardMaterial(cargoColor, 0.8);
const darkBodyMaterial = standardMaterial(
new THREE.Color(bodyColor).multiplyScalar(0.55),
0.65
);
// Four cubic wheels.
for (const x of [-0.65, 0.65]) {
for (const z of [-0.52, 0.52]) {
addBox(
group,
[0.4, 0.4, 0.4],
[x, 0.43, z],
wheelMaterial
);
}
}
addBox(
group,
[1.38, 0.22, 1.62],
[0, 0.68, 0],
chassisMaterial
);
addBox(
group,
[0.15, 0.12, 0.42],
[0, 0.59, -0.98],
darkMetalMaterial
);
if (isEngine) {
addBox(
group,
[1.12, 0.66, 1.12],
[0, 1.03, 0.24],
bodyMaterial
);
addBox(
group,
[1.26, 0.88, 0.72],
[0, 1.08, -0.49],
darkBodyMaterial
);
addBox(
group,
[1.4, 0.14, 0.82],
[0, 1.57, -0.49],
chassisMaterial
);
addBox(
group,
[0.28, 0.55, 0.28],
[0, 1.58, 0.55],
darkMetalMaterial
);
addBox(
group,
[0.23, 0.23, 0.12],
[0, 1.11, 0.84],
headlightMaterial
);
for (const x of [-0.34, 0.34]) {
addBox(
group,
[0.34, 0.34, 0.05],
[x, 1.23, -0.87],
windowMaterial
);
}
} else {
addBox(
group,
[1.16, 0.72, 1.28],
[0, 1.05, 0],
cargoMaterial
);
addBox(
group,
[1.24, 0.12, 1.36],
[0, 1.46, 0],
bodyMaterial
);
for (const x of [-0.61, 0.61]) {
addBox(
group,
[0.05, 0.36, 0.48],
[x, 1.08, 0.1],
bodyMaterial
);
}
}
return group;
}
function createTrain(id, route, bodyColor, cargoColor) {
const vehicles = [];
for (let i = 0; i < 4; i++) {
const vehicle = makeVehicle(
bodyColor,
cargoColor,
i === 0
);
scene.add(vehicle);
vehicles.push(vehicle);
}
return {
id,
route,
vehicles,
head: 0,
requested: false,
enteredBlock: false,
completed: false
};
}
const trainA = createTrain("A", routeA, 0x29bfe8, 0x157b9a);
const trainB = createTrain("B", routeB, 0xf3a333, 0xb96821);
const trains = [trainA, trainB];
const vehicleSpacing = 1.78;
const vehicleLength = 1.58;
const trainOverallLength =
(4 - 1) * vehicleSpacing + vehicleLength;
// -------------------------------------------------------------------------
// Interlocking simulation
// -------------------------------------------------------------------------
let owner = null;
let blockOccupied = false;
let elapsed = 0;
let paused = false;
let visualTime = 0;
function frontDistance(train) {
return train.head + vehicleLength / 2;
}
function tailRearDistance(train) {
return train.head - trainOverallLength;
}
function logEvent(message) {
const item = document.createElement("li");
const time = document.createElement("time");
time.textContent = `+${elapsed.toFixed(1)}s`;
const text = document.createElement("span");
text.textContent = message;
item.append(time, text);
$("events").prepend(item);
while ($("events").children.length > 5) {
$("events").lastElementChild.remove();
}
}
function grantReservation(train) {
if (owner !== null || train.completed) return;
owner = train.id;
logEvent(`${train.id} received the shared-block reservation.`);
}
function requestReservation(train) {
train.requested = true;
if (owner === null) {
grantReservation(train);
} else {
logEvent(`${train.id} requested the block and is held at the signal.`);
}
}
function releaseReservation(train) {
// Critical rule: release only when the REAR of the entire train has
// passed the shared block's exit boundary.
if (tailRearDistance(train) < sharedEnd) return;
logEvent(
`${train.id} tail cleared the exit; shared block released.`
);
train.completed = true;
owner = null;
blockOccupied = false;
const nextTrain = trains.find(
(candidate) => candidate.requested && !candidate.completed
);
if (nextTrain) {
grantReservation(nextTrain);
}
}
function updateSimulation(dt) {
elapsed += dt;
const speed = 3.15;
const advance = speed * dt;
const endLimit = routeA.totalLength - 0.8;
for (const train of trains) {
if (train.completed) {
train.head = Math.min(endLimit, train.head + advance);
continue;
}
if (!train.requested) {
if (train.head + advance >= requestDistance) {
train.head = requestDistance;
requestReservation(train);
} else {
train.head += advance;
}
} else if (owner === train.id) {
train.head = Math.min(endLimit, train.head + advance);
}
// A requested train whose owner is different remains at requestDistance.
}
for (const train of trains) {
if (
owner === train.id &&
!train.enteredBlock &&
frontDistance(train) >= sharedStart
) {
train.enteredBlock = true;
blockOccupied = true;
logEvent(`${train.id} entered the shared block.`);
}
}
if (owner !== null) {
const ownerTrain = trains.find((train) => train.id === owner);
if (ownerTrain && ownerTrain.enteredBlock) {
releaseReservation(ownerTrain);
}
}
// Position every vehicle along its route.
for (const train of trains) {
train.vehicles.forEach((vehicle, index) => {
const distance = train.head - index * vehicleSpacing;
const point = train.route.pointAt(distance);
const tangent = train.route.tangentAt(distance);
vehicle.position.set(point.x, 0, point.z);
vehicle.rotation.y = Math.atan2(tangent.x, tangent.z);
});
}
}
function resetSimulation() {
owner = null;
blockOccupied = false;
elapsed = 0;
trainA.head = 9.2;
trainB.head = 7.2;
for (const train of trains) {
train.requested = false;
train.enteredBlock = false;
train.completed = false;
}
$("events").replaceChildren();
logEvent("Train A leads; the first arrival receives priority.");
updateTrainPositions();
}
function updateTrainPositions() {
for (const train of trains) {
train.vehicles.forEach((vehicle, index) => {
const distance = train.head - index * vehicleSpacing;
const point = train.route.pointAt(distance);
const tangent = train.route.tangentAt(distance);
vehicle.position.set(point.x, 0, point.z);
vehicle.rotation.y = Math.atan2(tangent.x, tangent.z);
});
}
}
// -------------------------------------------------------------------------
// Status UI and scene indicators
// -------------------------------------------------------------------------
function updateEnvironment() {
const pulse = 0.5 + 0.5 * Math.sin(visualTime * 4.5);
if (blockOccupied) {
blockMaterial.color.setHex(0xff526f);
blockMaterial.emissive.setHex(0x5b0d20);
blockMaterial.opacity = 0.25 + pulse * 0.08;
exitStripMaterial.color.setHex(0xff526f);
exitStripMaterial.emissive.setHex(0xff193c);
} else if (owner !== null) {
blockMaterial.color.setHex(0xffb640);
blockMaterial.emissive.setHex(0x593007);
blockMaterial.opacity = 0.2 + pulse * 0.05;
exitStripMaterial.color.setHex(0xffb640);
exitStripMaterial.emissive.setHex(0xff8c1a);
} else {
blockMaterial.color.setHex(0x58e6a4);
blockMaterial.emissive.setHex(0x123c2b);
blockMaterial.opacity = 0.16 + pulse * 0.05;
exitStripMaterial.color.setHex(0x58e6a4);
exitStripMaterial.emissive.setHex(0x2cff91);
}
setSignal(signalA, owner === "A" || (owner === null && !trainA.completed));
setSignal(signalB, owner === "B" || (owner === null && !trainB.completed));
towerBeaconMaterial.emissiveIntensity =
0.9 + Math.max(0, Math.sin(visualTime * 3.5)) * 0.8;
}
function updateUI() {
const ownerTrain = owner
? trains.find((train) => train.id === owner)
: null;
const waitingTrain = trains.find(
(train) =>
train.requested &&
!train.completed &&
owner !== train.id
);
if (ownerTrain) {
$("ownerValue").textContent = `TRAIN ${ownerTrain.id}`;
$("ownerValue").style.color =
ownerTrain.id === "A" ? "#45d7ff" : "#ffb640";
} else if (trains.every((train) => train.completed)) {
$("ownerValue").textContent = "CYCLE COMPLETE";
$("ownerValue").style.color = "#58e6a4";
} else {
$("ownerValue").textContent = "AUTO SELECT";
$("ownerValue").style.color = "#eef8ff";
}
if (blockOccupied) {
$("blockPill").textContent = "OCCUPIED";
$("blockPill").dataset.state = "occupied";
} else if (owner !== null) {
$("blockPill").textContent = "RESERVED";
$("blockPill").dataset.state = "reserved";
} else {
$("blockPill").textContent = "FREE";
$("blockPill").dataset.state = "free";
}
if (ownerTrain && blockOccupied) {
const other = ownerTrain.id === "A" ? "B" : "A";
$("statusText").textContent =
`Train ${ownerTrain.id} is inside the shared block. ` +
`Train ${other} is held at its signal.`;
} else if (ownerTrain) {
$("statusText").textContent =
`Train ${ownerTrain.id} owns the reservation; the block is still clear.`;
} else if (waitingTrain) {
$("statusText").textContent =
`Train ${waitingTrain.id} is waiting for the previous owner's tail to clear.`;
} else if (trains.every((train) => train.completed)) {
$("statusText").textContent =
"Both trains cleared safely. The shared block is available again.";
} else {
$("statusText").textContent =
"First arrival will receive the reservation.";
}
let progress = 0;
if (ownerTrain) {
const releaseHeadDistance = sharedEnd + trainOverallLength;
progress = THREE.MathUtils.clamp(
(ownerTrain.head - sharedStart) /
(releaseHeadDistance - sharedStart),
0,
1
);
}
$("releaseBar").style.width = `${progress * 100}%`;
$("releasePercent").textContent = `${Math.round(progress * 100)}%`;
if (ownerTrain && blockOccupied) {
$("releaseText").textContent =
"Release inhibited until the final vehicle passes the EXIT marker.";
} else if (ownerTrain) {
$("releaseText").textContent =
"Reservation granted. Entry is permitted, but release still requires a tail-clear check.";
} else {
$("releaseText").textContent =
"The block is clear. Any waiting train may receive the next reservation.";
}
}
// -------------------------------------------------------------------------
// Custom camera controls — no addons or OrbitControls
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.8, 0);
let cameraTheta = 0.57;
let cameraPhi = 0.91;
let cameraRadius = 45;
let targetTheta = cameraTheta;
let targetPhi = cameraPhi;
let targetRadius = cameraRadius;
let dragging = false;
let pointerX = 0;
let pointerY = 0;
const canvas = renderer.domElement;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
targetTheta -= dx * 0.006;
targetPhi = THREE.MathUtils.clamp(targetPhi - dy * 0.005, 0.35, 1.35);
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
targetRadius = THREE.MathUtils.clamp(
targetRadius * Math.exp(event.deltaY * 0.001),
25,
70
);
},
{ passive: false }
);
function updateCamera(dt) {
const smoothing = 1 - Math.exp(-dt * 9);
cameraTheta = THREE.MathUtils.lerp(cameraTheta, targetTheta, smoothing);
cameraPhi = THREE.MathUtils.lerp(cameraPhi, targetPhi, smoothing);
cameraRadius = THREE.MathUtils.lerp(cameraRadius, targetRadius, smoothing);
const horizontal = Math.sin(cameraPhi) * cameraRadius;
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraTheta),
cameraTarget.y + Math.cos(cameraPhi) * cameraRadius,
cameraTarget.z + horizontal * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
// -------------------------------------------------------------------------
// HTML world labels projected directly onto the 3D scene
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function placeLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
element.style.display = visible ? "block" : "none";
if (!visible) return;
element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function updateLabels() {
placeLabel($("blockLabel"), new THREE.Vector3(0, 3.0, 0));
placeLabel($("entryLabel"), new THREE.Vector3(-4, 2.15, -2.1));
placeLabel($("exitLabel"), new THREE.Vector3(4, 2.15, -2.1));
for (const train of trains) {
const point = train.route.pointAt(train.head);
point.y = 3.25;
placeLabel(
$(`train${train.id}Label`),
point
);
}
}
// -------------------------------------------------------------------------
// Controls and render loop
// -------------------------------------------------------------------------
$("replayButton").addEventListener("click", resetSimulation);
$("pauseButton").addEventListener("click", () => {
paused = !paused;
$("pauseButton").textContent = paused ? "Resume" : "Pause";
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetSimulation();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
visualTime += dt;
if (!paused) {
updateSimulation(dt);
}
updateEnvironment();
updateCamera(dt);
updateUI();
updateLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```