Prompt specification
Build or customize the Three.js 3D scene "Alternating Right-of-Way at a Crossing" 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: Alternating Right-of-Way at a Crossing
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/alternating-right-of-way-at-a-crossing-x2106
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring conflicting vehicle routes at an intersection. Animate two toy vehicle streams using an explicit alternating access rule. Prevent simultaneous occupancy of the conflict area and show waiting queues forming upstream. Low-poly.
Working Three.js Starter (alternating-right-of-way-at-a-crossing-x2106):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alternating Intersection Access</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(18, 28, 38, 0.88);
--line: rgba(255, 255, 255, 0.12);
--text: #eef7f6;
--muted: #a9b8c2;
--a: #38d6c8;
--b: #ff9257;
--red: #ff6574;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cfe6ef;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
touch-action: none;
}
#hud {
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;
color: var(--text);
background: var(--panel);
box-shadow: 0 18px 50px rgba(14, 25, 34, 0.24);
backdrop-filter: blur(14px);
user-select: none;
}
.eyebrow {
margin: 0 0 5px;
color: var(--a);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.12;
}
.rule {
margin: 11px 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.rule strong {
color: var(--text);
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
#status {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border-radius: 999px;
color: #061717;
background: var(--a);
font-size: 12px;
font-weight: 900;
letter-spacing: 0.04em;
}
#status::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
content: "";
box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.12);
}
.cycle {
display: grid;
grid-template-columns: 1fr 0.55fr 1fr 0.55fr;
gap: 4px;
margin: 10px 0 14px;
}
.cycle span {
padding: 6px 3px;
border: 1px solid var(--line);
border-radius: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
text-align: center;
transition: 160ms ease;
}
.cycle span.active {
color: #071313;
background: var(--a);
border-color: var(--a);
}
.cycle span.clear.active {
color: white;
background: var(--red);
border-color: var(--red);
}
.track {
height: 4px;
overflow: hidden;
margin-bottom: 15px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.09);
}
#progress {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--a);
transition: width 100ms linear;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 12px;
}
.stat {
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.stat span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat strong {
display: block;
overflow: hidden;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.a-color {
color: var(--a);
}
.b-color {
color: var(--b);
}
.legend {
display: flex;
gap: 14px;
margin: 12px 0 15px;
color: var(--muted);
font-size: 12px;
}
.legend div {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--a);
}
.swatch.b {
background: var(--b);
}
.buttons {
display: flex;
gap: 8px;
}
button {
flex: 1;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 9px;
color: var(--text);
background: rgba(255, 255, 255, 0.07);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: 150ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.13);
transform: translateY(-1px);
}
#hint {
position: fixed;
z-index: 5;
right: 18px;
bottom: 16px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.55);
border-radius: 999px;
color: #17303a;
background: rgba(244, 251, 252, 0.76);
box-shadow: 0 8px 24px rgba(18, 40, 50, 0.12);
font-size: 11px;
font-weight: 700;
pointer-events: none;
backdrop-filter: blur(8px);
}
@media (max-width: 600px) {
#hud {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 14px;
}
h1 {
font-size: 20px;
}
.rule {
margin-bottom: 12px;
}
#hint {
right: 10px;
bottom: 10px;
}
}
</style>
</head>
<body>
<div id="hud">
<p class="eyebrow">Low-poly traffic study</p>
<h1>Alternating Intersection Access</h1>
<p class="rule">
<strong>A → drain → B → drain → A.</strong>
The shared conflict zone is reserved for one route at a time.
The next route receives access only after the zone is completely empty.
</p>
<div class="status-row">
<div id="status" aria-live="polite">A GREEN</div>
<span style="color:var(--muted);font-size:11px">Exclusive zone control</span>
</div>
<div class="cycle" aria-hidden="true">
<span data-phase="A_GREEN">A GREEN</span>
<span data-phase="A_CLEAR" class="clear">DRAIN</span>
<span data-phase="B_GREEN">B GREEN</span>
<span data-phase="B_CLEAR" class="clear">DRAIN</span>
</div>
<div class="track"><div id="progress"></div></div>
<div class="stats">
<div class="stat">
<span>Reservation</span>
<strong id="reservation">Stream A</strong>
</div>
<div class="stat">
<span>Conflict zone</span>
<strong id="zone">Empty</strong>
</div>
<div class="stat">
<span>A queue</span>
<strong id="queueA" class="a-color">0 vehicles</strong>
</div>
<div class="stat">
<span>B queue</span>
<strong id="queueB" class="b-color">0 vehicles</strong>
</div>
</div>
<div class="legend">
<div><i class="swatch"></i> A · southbound</div>
<div><i class="swatch b"></i> B · eastbound</div>
</div>
<div class="buttons">
<button id="pause" type="button">Pause</button>
<button id="restart" type="button">Restart</button>
</div>
</div>
<div id="hint">Drag to orbit · Scroll to zoom · Space to pause</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xcfe7f1);
scene.fog = new THREE.Fog(0xcfe7f1, 58, 105);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
180
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xe9f7ff, 0x74836b, 1.8);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1d6, 2.5);
sun.position.set(-18, 30, 24);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -42;
sun.shadow.camera.right = 42;
sun.shadow.camera.top = 42;
sun.shadow.camera.bottom = -42;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 85;
sun.shadow.bias = -0.0003;
scene.add(sun);
// -------------------------------------------------------------------------
// Materials and geometry helpers
// -------------------------------------------------------------------------
const mat = (color, extra = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.02,
flatShading: true,
...extra
});
const materials = {
ground: mat(0x9dbb8c),
road: mat(0x46545d),
sidewalk: mat(0xd8cfb8),
curb: mat(0xeee6cf),
lane: mat(0xf4edcf),
stop: mat(0xffffff),
trunk: mat(0x79543b),
leafA: mat(0x4e8f62),
leafB: mat(0x6da36d),
leafC: mat(0x8eb46f),
glass: mat(0x263f51, { roughness: 0.25, metalness: 0.15 }),
tire: mat(0x22272b),
headlight: mat(0xffe6a3, {
emissive: 0xffd66a,
emissiveIntensity: 0.35
}),
signalBody: mat(0x26343b),
pole: mat(0x4d5c62)
};
function addMesh(geometry, material, x, y, z, cast = true, receive = true) {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = receive;
scene.add(mesh);
return mesh;
}
function addBox(w, h, d, material, x, y, z, cast = true, receive = true) {
return addMesh(
new THREE.BoxGeometry(w, h, d),
material,
x,
y,
z,
cast,
receive
);
}
// -------------------------------------------------------------------------
// Intersection, sidewalks, lane markings, and scenery
// -------------------------------------------------------------------------
const ground = addMesh(
new THREE.PlaneGeometry(120, 120),
materials.ground,
0,
0,
0,
false,
true
);
ground.rotation.x = -Math.PI / 2;
addBox(6.4, 0.08, 70, materials.road, 0, 0.04, 0, false, true);
addBox(70, 0.08, 6.4, materials.road, 0, 0.045, 0, false, true);
// Four raised corner sidewalks.
for (const x of [-10, 10]) {
for (const z of [-10, 10]) {
addBox(
13.6,
0.18,
13.6,
materials.sidewalk,
x,
0.09,
z,
false,
true
);
}
}
// Dashed center lines, omitted around the intersection.
for (let z = -31; z <= -5; z += 4) {
addBox(0.13, 0.025, 1.55, materials.lane, 0, 0.092, z, false, false);
}
for (let z = 5; z <= 31; z += 4) {
addBox(0.13, 0.025, 1.55, materials.lane, 0, 0.092, z, false, false);
}
for (let x = -31; x <= -5; x += 4) {
addBox(1.55, 0.025, 0.13, materials.lane, x, 0.098, 0, false, false);
}
for (let x = 5; x <= 31; x += 4) {
addBox(1.55, 0.025, 0.13, materials.lane, x, 0.098, 0, false, false);
}
// Stop bars are upstream of the reserved zone.
addBox(2.55, 0.03, 0.18, materials.stop, -1.25, 0.105, 4.75, false, false);
addBox(0.18, 0.03, 2.55, materials.stop, -4.75, 0.11, -1.25, false, false);
// Flat painted route arrows.
const arrowShape = new THREE.Shape();
arrowShape.moveTo(-0.16, -0.8);
arrowShape.lineTo(0.16, -0.8);
arrowShape.lineTo(0.16, 0.08);
arrowShape.lineTo(0.43, 0.08);
arrowShape.lineTo(0, 0.72);
arrowShape.lineTo(-0.43, 0.08);
arrowShape.lineTo(-0.16, 0.08);
arrowShape.closePath();
const arrowGeometry = new THREE.ShapeGeometry(arrowShape);
const arrowMaterialA = new THREE.MeshBasicMaterial({
color: 0x38d6c8,
side: THREE.DoubleSide
});
const arrowMaterialB = new THREE.MeshBasicMaterial({
color: 0xff9257,
side: THREE.DoubleSide
});
function addArrow(x, z, angle, material) {
const group = new THREE.Group();
const arrow = new THREE.Mesh(arrowGeometry, material);
arrow.rotation.x = -Math.PI / 2;
group.rotation.y = angle;
group.position.set(x, 0.12, z);
group.add(arrow);
scene.add(group);
}
addArrow(-1.25, 14, 0, arrowMaterialA);
addArrow(-14, -1.25, -Math.PI / 2, arrowMaterialB);
// Conflict-zone fill and outline.
const CONFLICT_HALF = 2.7;
const conflictMaterial = new THREE.MeshBasicMaterial({
color: 0x38d6c8,
transparent: true,
opacity: 0.16,
depthWrite: false,
side: THREE.DoubleSide
});
const conflictFill = new THREE.Mesh(
new THREE.PlaneGeometry(CONFLICT_HALF * 2, CONFLICT_HALF * 2),
conflictMaterial
);
conflictFill.rotation.x = -Math.PI / 2;
conflictFill.position.y = 0.115;
scene.add(conflictFill);
const conflictPoints = [
new THREE.Vector3(-CONFLICT_HALF, 0.14, -CONFLICT_HALF),
new THREE.Vector3(CONFLICT_HALF, 0.14, -CONFLICT_HALF),
new THREE.Vector3(CONFLICT_HALF, 0.14, CONFLICT_HALF),
new THREE.Vector3(-CONFLICT_HALF, 0.14, CONFLICT_HALF)
];
const conflictOutline = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(conflictPoints),
new THREE.LineBasicMaterial({ color: 0x38d6c8 })
);
scene.add(conflictOutline);
// Low-poly corner buildings.
function addBuilding(x, z, w, d, h, color) {
const bodyMaterial = mat(color);
addBox(w, h, d, bodyMaterial, x, 0.18 + h / 2, z);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(1, 1.7, 4),
mat(0x9e5f4d)
);
roof.scale.set(w * 0.39, 1, d * 0.39);
roof.rotation.y = Math.PI / 4;
roof.position.set(x, 0.18 + h + 0.85, z);
roof.castShadow = true;
scene.add(roof);
const windowMaterial = mat(0xffd98b, {
emissive: 0xffc75e,
emissiveIntensity: 0.18
});
for (const dx of [-w * 0.24, 0, w * 0.24]) {
addBox(
0.45,
0.55,
0.05,
windowMaterial,
x + dx,
0.18 + h * 0.6,
z + d / 2 + 0.03,
false,
false
);
}
}
addBuilding(-10, -10, 5.1, 4.8, 4.3, 0xd98264);
addBuilding(10, -10, 5.5, 4.5, 5.1, 0x7f9db2);
addBuilding(-10, 10, 4.7, 5.4, 4.8, 0xb49a68);
addBuilding(10, 10, 5.8, 5.1, 3.8, 0x8b8eaa);
function addTree(x, z, scale = 1, leafMaterial = materials.leafA) {
addMesh(
new THREE.CylinderGeometry(0.14 * scale, 0.19 * scale, 1.4 * scale, 7),
materials.trunk,
x,
0.18 + 0.7 * scale,
z
);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(1.05 * scale, 2.6 * scale, 7),
leafMaterial
);
crown.position.set(x, 0.18 + 2.1 * scale, z);
crown.castShadow = true;
scene.add(crown);
}
[
[-15, -5, 1.05, materials.leafA],
[-6.5, -14, 0.85, materials.leafB],
[-14.5, 6.5, 0.95, materials.leafC],
[6.2, -14.2, 1.0, materials.leafA],
[14.5, 6.2, 1.1, materials.leafC],
[6.4, 14.4, 0.8, materials.leafB],
[14.7, -6.1, 0.9, materials.leafB],
[-6.2, 14.6, 1.0, materials.leafA]
].forEach((v) => addTree(...v));
// -------------------------------------------------------------------------
// Traffic signals
// -------------------------------------------------------------------------
function createSignal(x, z, rotationY) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotationY;
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.09, 2.5, 8),
materials.pole
);
pole.position.y = 1.25;
pole.castShadow = true;
group.add(pole);
const housing = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 1.28, 0.3),
materials.signalBody
);
housing.position.y = 2.55;
housing.castShadow = true;
group.add(housing);
const red = mat(0x4a252a, {
emissive: 0x000000,
roughness: 0.4
});
const amber = mat(0x4a3d23, {
emissive: 0x000000,
roughness: 0.4
});
const green = mat(0x183d34, {
emissive: 0x000000,
roughness: 0.4
});
function bulb(y, material) {
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(0.125, 10, 7),
material
);
mesh.position.set(0, y, 0.18);
group.add(mesh);
return mesh;
}
bulb(2.94, red);
bulb(2.55, amber);
bulb(2.16, green);
scene.add(group);
return { red, amber, green };
}
// A approaches from +Z and looks toward -Z.
const signalA = createSignal(3.9, 5.4, 0);
// B approaches from -X and looks toward +X.
const signalB = createSignal(-5.4, 3.9, Math.PI / 2);
function setLamp(material, on, activeColor, dimColor) {
material.color.set(on ? activeColor : dimColor);
material.emissive.set(on ? activeColor : 0x000000);
material.emissiveIntensity = on ? 1.4 : 0;
}
function updateSignals() {
const aGreen = phase === "A_GREEN";
const bGreen = phase === "B_GREEN";
setLamp(signalA.red, !aGreen, 0xff354f, 0x4a252a);
setLamp(signalA.amber, false, 0xffb332, 0x4a3d23);
setLamp(signalA.green, aGreen, 0x35efae, 0x183d34);
setLamp(signalB.red, !bGreen, 0xff354f, 0x4a252a);
setLamp(signalB.amber, false, 0xffb332, 0x4a3d23);
setLamp(signalB.green, bGreen, 0x35efae, 0x183d34);
}
// -------------------------------------------------------------------------
// Toy cars
// -------------------------------------------------------------------------
const CAR_LENGTH = 1.9;
const CAR_HALF_LENGTH = CAR_LENGTH / 2;
const MAX_SPEED = 4.7;
const ACCELERATION = 3.5;
const BRAKING = 6.2;
const MIN_CENTER_GAP = 2.25;
// Both approaches stop with their noses just before the conflict zone.
const STOP_S = 26.23;
const carGeometry = {
body: new THREE.BoxGeometry(1.28, 0.43, 1.9),
cabin: new THREE.BoxGeometry(1.04, 0.38, 0.98),
roof: new THREE.BoxGeometry(1.06, 0.12, 0.82),
wheel: new THREE.CylinderGeometry(0.24, 0.24, 0.18, 10),
headlight: new THREE.BoxGeometry(0.22, 0.13, 0.07),
bumper: new THREE.BoxGeometry(1.18, 0.13, 0.12)
};
const carPalette = {
A: [0x35c9bf, 0x58d8c9, 0x30aeb9].map((c) => mat(c, { roughness: 0.48 })),
B: [0xff8751, 0xffa45e, 0xf16d58].map((c) => mat(c, { roughness: 0.48 }))
};
let cars = [];
let carSerial = 0;
function createCar(stream) {
const group = new THREE.Group();
const bodyMaterial = carPalette[stream][carSerial % carPalette[stream].length];
carSerial++;
const body = new THREE.Mesh(carGeometry.body, bodyMaterial);
body.position.y = 0.43;
group.add(body);
const cabin = new THREE.Mesh(carGeometry.cabin, materials.glass);
cabin.position.set(0, 0.81, 0.1);
group.add(cabin);
const roof = new THREE.Mesh(carGeometry.roof, bodyMaterial);
roof.position.set(0, 1.03, 0.14);
group.add(roof);
const frontBumper = new THREE.Mesh(carGeometry.bumper, materials.tire);
frontBumper.position.set(0, 0.34, -0.97);
group.add(frontBumper);
const rearBumper = new THREE.Mesh(carGeometry.bumper, materials.tire);
rearBumper.position.set(0, 0.34, 0.97);
group.add(rearBumper);
for (const x of [-0.68, 0.68]) {
for (const z of [-0.59, 0.59]) {
const wheel = new THREE.Mesh(carGeometry.wheel, materials.tire);
wheel.rotation.z = Math.PI / 2;
wheel.position.set(x, 0.25, z);
group.add(wheel);
}
}
for (const x of [-0.38, 0.38]) {
const light = new THREE.Mesh(carGeometry.headlight, materials.headlight);
light.position.set(x, 0.49, -0.98);
group.add(light);
}
group.traverse((object) => {
if (object.isMesh) object.castShadow = true;
});
// Models point toward local -Z. Stream B is rotated toward +X.
if (stream === "B") group.rotation.y = -Math.PI / 2;
scene.add(group);
return {
stream,
s: 0,
speed: MAX_SPEED,
group
};
}
function syncCar(car) {
if (car.stream === "A") {
car.group.position.set(-1.25, 0, 30 - car.s);
} else {
car.group.position.set(-30 + car.s, 0, -1.25);
}
}
function spawnCar(stream, s = 0) {
const car = createCar(stream);
car.s = s;
car.speed = MAX_SPEED;
cars.push(car);
syncCar(car);
}
// -------------------------------------------------------------------------
// Explicit access controller
//
// A_GREEN: only A can enter the zone.
// A_CLEAR: all-red; A vehicles already inside may leave, but nobody enters.
// B_GREEN: only B can enter the zone.
// B_CLEAR: all-red; B vehicles already inside may leave, but nobody enters.
//
// A transition to the next green occurs only when no vehicle occupies the
// shared zone. The canEnterConflict() gate also rejects any mixed-stream
// occupancy as a second layer of protection.
// -------------------------------------------------------------------------
const GREEN_DURATION = 9;
const MIN_CLEAR_TIME = 1.5;
let phase = "A_GREEN";
let phaseTime = 0;
let reservedBy = "A";
let paused = false;
let spawnClock = 0;
function enterPhase(nextPhase) {
phase = nextPhase;
phaseTime = 0;
reservedBy =
nextPhase === "A_GREEN" ? "A" :
nextPhase === "B_GREEN" ? "B" :
null;
}
function conflictOccupants() {
return cars.filter((car) => intersectsConflict(car));
}
function intersectsConflict(car) {
if (car.stream === "A") {
const z = 30 - car.s;
return z + CAR_HALF_LENGTH >= -CONFLICT_HALF &&
z - CAR_HALF_LENGTH <= CONFLICT_HALF;
}
const x = -30 + car.s;
return x + CAR_HALF_LENGTH >= -CONFLICT_HALF &&
x - CAR_HALF_LENGTH <= CONFLICT_HALF;
}
function canEnterConflict(stream) {
if (reservedBy !== stream) return false;
// Never allow a vehicle from another stream into an occupied zone.
return conflictOccupants().every((car) => car.stream === stream);
}
function updatePhase(dt) {
phaseTime += dt;
if (
(phase === "A_GREEN" || phase === "B_GREEN") &&
phaseTime >= GREEN_DURATION
) {
enterPhase(phase === "A_GREEN" ? "A_CLEAR" : "B_CLEAR");
}
// Vehicles are updated after a green-to-clear transition so vehicles
// already inside the zone can drain during the all-red interval.
}
function finishClearanceIfSafe() {
if (
(phase === "A_CLEAR" || phase === "B_CLEAR") &&
phaseTime >= MIN_CLEAR_TIME &&
conflictOccupants().length === 0
) {
enterPhase(phase === "A_CLEAR" ? "B_GREEN" : "A_GREEN");
}
}
// -------------------------------------------------------------------------
// Car following, queuing, and movement
// -------------------------------------------------------------------------
function updateVehicles(dt) {
// Remove vehicles that have left the scene.
for (const car of cars) {
if (car.s > 61) {
scene.remove(car.group);
car.removed = true;
}
}
cars = cars.filter((car) => !car.removed);
for (const stream of ["A", "B"]) {
const streamCars = cars
.filter((car) => car.stream === stream)
.sort((a, b) => a.s - b.s);
for (let i = 0; i < streamCars.length; i++) {
const car = streamCars[i];
const leader = streamCars[i + 1];
let desiredSpeed = MAX_SPEED;
// Car-following model: slow down and form a compact upstream queue.
if (leader) {
const gap = leader.s - car.s;
const followRange = 3.8;
const followFactor = THREE.MathUtils.clamp(
(gap - MIN_CENTER_GAP) / (followRange - MIN_CENTER_GAP),
0,
1
);
desiredSpeed = Math.min(desiredSpeed, MAX_SPEED * followFactor);
}
const currentlyInZone = intersectsConflict(car);
const entryPermitted = canEnterConflict(stream);
// A vehicle outside the zone is held at the stop bar unless its
// stream currently owns the reservation.
const blockedAtStop =
!currentlyInZone &&
!entryPermitted &&
car.s <= STOP_S + 0.02;
if (blockedAtStop) {
const remaining = Math.max(0, STOP_S - car.s);
desiredSpeed = Math.min(
desiredSpeed,
Math.sqrt(2 * BRAKING * remaining)
);
}
const rate = desiredSpeed > car.speed ? ACCELERATION : BRAKING;
let nextSpeed = THREE.MathUtils.clamp(
car.speed + Math.sign(desiredSpeed - car.speed) * rate * dt,
0,
MAX_SPEED
);
let nextS = car.s + nextSpeed * dt;
// Hard safety constraints.
if (leader && nextS > leader.s - MIN_CENTER_GAP) {
nextS = leader.s - MIN_CENTER_GAP;
nextSpeed = 0;
}
if (blockedAtStop && nextS > STOP_S) {
nextS = STOP_S;
nextSpeed = 0;
}
car.s = Math.max(0, nextS);
car.speed = nextSpeed;
syncCar(car);
}
}
}
function trySpawn() {
for (const stream of ["A", "B"]) {
const occupied = cars.some(
(car) => car.stream === stream && car.s < 4.2
);
if (!occupied) spawnCar(stream, 0);
}
}
// -------------------------------------------------------------------------
// Simulation reset
// -------------------------------------------------------------------------
function resetSimulation() {
for (const car of cars) scene.remove(car.group);
cars = [];
carSerial = 0;
paused = false;
phaseTime = 0;
spawnClock = 0;
enterPhase("A_GREEN");
// Existing vehicles make the queues immediately visible.
[2, 10, 18, 25].forEach((s) => spawnCar("A", s));
[5, 14, 22, 25.5].forEach((s) => spawnCar("B", s));
document.getElementById("pause").textContent = "Pause";
}
// -------------------------------------------------------------------------
// Custom camera controls — no external controls addon
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.5, 0);
let cameraTheta = -0.78;
let cameraPhi = 0.91;
let cameraRadius = 48;
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
function updateCamera() {
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);
}
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 dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.006, 0.28, 1.43);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
24,
82
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// HUD
// -------------------------------------------------------------------------
const statusElement = document.getElementById("status");
const reservationElement = document.getElementById("reservation");
const zoneElement = document.getElementById("zone");
const queueAElement = document.getElementById("queueA");
const queueBElement = document.getElementById("queueB");
const progressElement = document.getElementById("progress");
const phaseSegments = [...document.querySelectorAll("[data-phase]")];
function queuedCount(stream) {
return cars.filter(
(car) =>
car.stream === stream &&
car.s <= STOP_S + 0.7 &&
car.speed < 1.25
).length;
}
function updateHUD() {
const labels = {
A_GREEN: "A GREEN",
A_CLEAR: "ALL RED · A CLEARING",
B_GREEN: "B GREEN",
B_CLEAR: "ALL RED · B CLEARING"
};
const colors = {
A_GREEN: "#38d6c8",
A_CLEAR: "#ff6574",
B_GREEN: "#ff9257",
B_CLEAR: "#ff6574"
};
statusElement.textContent = labels[phase];
statusElement.style.background = colors[phase];
reservationElement.textContent =
reservedBy === "A" ? "Stream A" :
reservedBy === "B" ? "Stream B" :
"None · draining";
const occupants = conflictOccupants();
if (occupants.length === 0) {
zoneElement.textContent = "Empty";
zoneElement.style.color = "#eef7f6";
} else {
const streams = [...new Set(occupants.map((car) => car.stream))];
zoneElement.textContent =
`${occupants.length} ${streams.join("/")} vehicle${occupants.length === 1 ? "" : "s"}`;
zoneElement.style.color = streams[0] === "A" ? "#38d6c8" : "#ff9257";
}
queueAElement.textContent = `${queuedCount("A")} vehicle${queuedCount("A") === 1 ? "" : "s"}`;
queueBElement.textContent = `${queuedCount("B")} vehicle${queuedCount("B") === 1 ? "" : "s"}`;
const progress =
phase.endsWith("GREEN")
? Math.min(phaseTime / GREEN_DURATION, 1)
: Math.min(phaseTime / MIN_CLEAR_TIME, 1);
progressElement.style.width = `${progress * 100}%`;
progressElement.style.background = colors[phase];
phaseSegments.forEach((segment) => {
segment.classList.toggle("active", segment.dataset.phase === phase);
});
}
document.getElementById("pause").addEventListener("click", () => {
paused = !paused;
document.getElementById("pause").textContent = paused ? "Resume" : "Pause";
});
document.getElementById("restart").addEventListener("click", resetSimulation);
addEventListener("keydown", (event) => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
paused = !paused;
document.getElementById("pause").textContent = paused ? "Resume" : "Pause";
}
});
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
function updateConflictVisuals(time) {
const occupants = conflictOccupants();
let color = 0x849ba5;
if (reservedBy === "A") color = 0x38d6c8;
if (reservedBy === "B") color = 0xff9257;
if (!reservedBy && occupants.length) color = 0xf4c35b;
conflictMaterial.color.setHex(color);
conflictOutline.material.color.setHex(color);
conflictMaterial.opacity = 0.13 + Math.sin(time * 0.004) * 0.035;
}
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
resetSimulation();
updateCamera();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
if (!paused) {
updatePhase(dt);
spawnClock += dt;
if (spawnClock >= 3.4) {
spawnClock -= 3.4;
trySpawn();
}
updateVehicles(dt);
finishClearanceIfSafe();
}
updateSignals();
updateConflictVisuals(elapsed);
updateHUD();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```