Prompt specification
Build or customize the Three.js 3D scene "Crossing signal phase sequence" 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: Crossing signal phase sequence
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/crossing-signal-phase-sequence-x0422
Scene Description Prompt:
Animate a low-poly crossing signal: vehicles stop, pedestrians cross, then traffic resumes. Include a phase timeline. Three.js from cdnjs, one HTML file.
Working Three.js Starter (crossing-signal-phase-sequence-x0422):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Low-Poly Crossing Signal</title>
<style>
:root {
--ink: #173331;
--muted: #657b78;
--panel: rgba(250, 253, 250, 0.9);
--border: rgba(23, 51, 49, 0.12);
--phase: #48c878;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d3d1;
color: var(--ink);
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;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.ui {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.topbar {
position: absolute;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding: 11px 14px;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 12px 30px rgba(30, 65, 62, 0.09);
backdrop-filter: blur(12px);
}
.brand-mark {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border-radius: 10px;
background: var(--ink);
color: white;
font-weight: 900;
letter-spacing: -0.04em;
}
.brand-copy {
display: grid;
gap: 2px;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.brand-title {
font-size: 14px;
font-weight: 850;
letter-spacing: 0.01em;
}
.right-stack {
display: flex;
align-items: flex-start;
gap: 10px;
}
.status-card {
min-width: 196px;
padding: 11px 14px;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 12px 30px rgba(30, 65, 62, 0.09);
backdrop-filter: blur(12px);
}
.status-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 15px;
}
.phase-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 900;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.phase-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--phase);
box-shadow: 0 0 0 4px color-mix(in srgb, var(--phase) 18%, transparent);
}
.phase-countdown {
font-variant-numeric: tabular-nums;
color: var(--muted);
font-size: 12px;
font-weight: 750;
}
.status-detail {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
}
.controls {
display: flex;
gap: 7px;
pointer-events: auto;
}
.control-button {
height: 42px;
padding: 0 13px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
color: var(--ink);
box-shadow: 0 12px 30px rgba(30, 65, 62, 0.09);
cursor: pointer;
font-size: 12px;
font-weight: 800;
backdrop-filter: blur(12px);
transition:
transform 150ms ease,
background 150ms ease;
}
.control-button:hover {
transform: translateY(-1px);
background: #fff;
}
.control-button.primary {
min-width: 72px;
background: var(--ink);
color: white;
}
.control-button.primary:hover {
background: #244642;
}
.timeline-panel {
position: absolute;
left: 50%;
bottom: 18px;
width: min(1080px, calc(100% - 40px));
transform: translateX(-50%);
padding: 15px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(30, 65, 62, 0.14);
backdrop-filter: blur(16px);
}
.timeline-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 11px;
}
.timeline-title {
display: flex;
align-items: baseline;
gap: 10px;
}
.timeline-title strong {
font-size: 12px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.timeline-title span,
.clock {
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.timeline-track {
display: flex;
gap: 4px;
height: 45px;
overflow: hidden;
border-radius: 11px;
background: rgba(23, 51, 49, 0.06);
}
.timeline-segment {
position: relative;
min-width: 0;
overflow: hidden;
border: 1px solid transparent;
border-radius: 8px;
background: rgba(255, 255, 255, 0.5);
transition:
border-color 180ms ease,
transform 180ms ease;
}
.timeline-segment.current {
z-index: 1;
border-color: rgba(23, 51, 49, 0.2);
transform: scaleY(1.05);
}
.segment-fill {
position: absolute;
inset: 0 auto 0 0;
width: 0;
opacity: 0.82;
transition: width 80ms linear;
}
.segment-label {
position: absolute;
inset: 0;
z-index: 2;
display: grid;
place-items: center;
padding: 0 4px;
color: var(--ink);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
text-align: center;
text-transform: uppercase;
white-space: nowrap;
}
.timeline-meta {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-top: 11px;
}
.state-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.state-chip {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 9px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(255, 255, 255, 0.58);
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.state-chip::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
}
.state-chip.traffic {
color: #279f59;
}
.state-chip.pedestrian {
color: #1b9eaa;
}
.gesture-hint {
position: absolute;
left: 22px;
bottom: 139px;
padding: 7px 10px;
border-radius: 9px;
background: rgba(250, 253, 250, 0.7);
color: rgba(23, 51, 49, 0.58);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
backdrop-filter: blur(8px);
}
@media (max-width: 760px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
}
.brand-copy,
.status-detail,
.gesture-hint {
display: none;
}
.brand {
padding: 7px;
}
.status-card {
min-width: 144px;
padding: 10px;
}
.right-stack {
gap: 6px;
}
.control-button {
height: 38px;
padding: 0 10px;
}
#view-reset {
display: none;
}
.timeline-panel {
bottom: 10px;
width: calc(100% - 20px);
padding: 11px;
}
.timeline-track {
height: 40px;
}
.segment-label {
font-size: 8px;
letter-spacing: 0.02em;
}
.timeline-meta {
gap: 8px;
}
.state-chip {
padding: 5px 7px;
font-size: 8px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="ui">
<div class="topbar">
<div class="brand">
<div class="brand-mark">08</div>
<div class="brand-copy">
<div class="eyebrow">Junction 08</div>
<div class="brand-title">Low-Poly Crossing Cycle</div>
</div>
</div>
<div class="right-stack">
<div class="status-card">
<div class="status-heading">
<div class="phase-name">
<span class="phase-dot"></span>
<span id="phase-name">Green</span>
</div>
<span id="phase-countdown" class="phase-countdown">4.0s</span>
</div>
<div id="phase-detail" class="status-detail">Traffic is moving</div>
</div>
<div class="controls">
<button id="pause-button" class="control-button primary">Pause</button>
<button id="replay-button" class="control-button">Replay</button>
<button id="view-reset" class="control-button">Reset view</button>
</div>
</div>
</div>
<div class="gesture-hint">Drag to orbit · Scroll to zoom</div>
<section class="timeline-panel" aria-label="Signal phase timeline">
<div class="timeline-header">
<div class="timeline-title">
<strong>Phase timeline</strong>
<span id="next-phase">Next: Amber</span>
</div>
<div id="clock" class="clock">00:00.0 / 00:20.0</div>
</div>
<div id="timeline-track" class="timeline-track"></div>
<div class="timeline-meta">
<div class="state-row">
<span id="traffic-state" class="state-chip traffic">Traffic running</span>
<span id="ped-state" class="state-chip pedestrian">Pedestrians waiting</span>
</div>
<span class="clock">20-second repeating cycle</span>
</div>
</section>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, camera
// -------------------------------------------------------------------------
const viewport = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d3d1);
scene.fog = new THREE.Fog(0xb9d3d1, 48, 95);
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.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-15, 15, 10, -10, 0.1, 150);
let cameraYaw = 0.56;
let cameraPitch = 0.61;
let cameraZoom = 1;
function updateCamera() {
const radius = 36;
camera.position.set(
Math.sin(cameraYaw) * Math.cos(cameraPitch) * radius,
Math.sin(cameraPitch) * radius,
Math.cos(cameraYaw) * Math.cos(cameraPitch) * radius
);
camera.lookAt(0, 0.8, 0);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const halfHeight = Math.max(8.6, 13.5 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
resize();
updateCamera();
// Custom orbit controls implemented without addons.
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;
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + deltaY * 0.004,
0.3,
1.05
);
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();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * Math.exp(-event.deltaY * 0.001),
0.65,
1.8
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Lighting and low-poly material helpers
// -------------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(0xeaf8f4, 0x6e8068, 2.2);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2cf, 3.1);
sun.position.set(-16, 24, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -35;
sun.shadow.camera.right = 35;
sun.shadow.camera.top = 28;
sun.shadow.camera.bottom = -28;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 75;
sun.shadow.normalBias = 0.035;
scene.add(sun);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0,
flatShading: true,
...options
});
}
const materials = {
grass: material(0x91aa78),
grassLight: material(0xa4b989),
road: material(0x465353),
roadEdge: material(0x3b4848),
sidewalk: material(0xbfc4b9),
curb: material(0xe1dfcf),
paint: material(0xf2f0df),
yellow: material(0xe6b84f),
pole: material(0x263a3a),
housing: material(0x243333),
panel: material(0x172222),
trunk: material(0x806044),
leafA: material(0x4f8062),
leafB: material(0x638e68),
leafC: material(0x78966c),
buildingA: material(0xc4a888),
buildingB: material(0xaeb9ae),
buildingC: material(0xd0b9a2),
roof: material(0x536565),
window: material(0x8fc3c5, {
emissive: 0x416d72,
emissiveIntensity: 0.28,
roughness: 0.35
}),
tire: material(0x202a2a),
glass: material(0x53747a, { roughness: 0.28, metalness: 0.08 }),
chrome: material(0xbac5c2, { roughness: 0.3, metalness: 0.45 })
};
function addMesh(parent, geometry, mat) {
const mesh = new THREE.Mesh(geometry, mat);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function box(parent, width, height, depth, mat, x = 0, y = 0, z = 0) {
const mesh = addMesh(parent, new THREE.BoxGeometry(width, height, depth), mat);
mesh.position.set(x, y, z);
return mesh;
}
function cylinder(
parent,
radiusTop,
radiusBottom,
height,
mat,
x = 0,
y = 0,
z = 0,
segments = 8
) {
const mesh = addMesh(
parent,
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments),
mat
);
mesh.position.set(x, y, z);
return mesh;
}
// -------------------------------------------------------------------------
// Road, sidewalks, landscaping, and neighborhood
// -------------------------------------------------------------------------
box(scene, 100, 0.3, 70, materials.grass, 0, -0.38, 0);
box(scene, 70, 0.18, 10, materials.road, 0, -0.02, 0);
box(scene, 70, 0.42, 4.2, materials.sidewalk, 0, 0.1, 7.1);
box(scene, 70, 0.42, 4.2, materials.sidewalk, 0, 0.1, -7.1);
box(scene, 70, 0.25, 0.22, materials.curb, 0, 0.18, 5.02);
box(scene, 70, 0.25, 0.22, materials.curb, 0, 0.18, -5.02);
// Edge lines and center markings.
for (let x = -32; x <= 32; x += 4.5) {
box(scene, 2.35, 0.025, 0.1, materials.yellow, x, 0.095, -0.12);
box(scene, 2.35, 0.025, 0.1, materials.yellow, x, 0.095, 0.12);
}
box(scene, 70, 0.025, 0.1, materials.paint, 0, 0.095, 4.72);
box(scene, 70, 0.025, 0.1, materials.paint, 0, 0.095, -4.72);
// Zebra crossing, with bars aligned in the walking direction.
for (const x of [-1.35, -0.45, 0.45, 1.35]) {
box(scene, 0.46, 0.03, 10.15, materials.paint, x, 0.105, 0);
}
// Stop lines for the two traffic directions.
box(scene, 0.28, 0.03, 2.55, materials.paint, -5.2, 0.108, 2.55);
box(scene, 0.28, 0.03, 2.55, materials.paint, 5.2, 0.108, -2.55);
function createTree(x, z, scale = 1, leafMaterial = materials.leafA) {
const tree = new THREE.Group();
tree.position.set(x, 0.32, z);
tree.scale.setScalar(scale);
scene.add(tree);
cylinder(tree, 0.18, 0.25, 1.8, materials.trunk, 0, 0.9, 0, 7);
const crown = addMesh(
tree,
new THREE.IcosahedronGeometry(1.05, 0),
leafMaterial
);
crown.position.y = 2.35;
crown.scale.set(1, 1.15, 0.95);
crown.rotation.y = 0.35;
const crownTop = addMesh(
tree,
new THREE.IcosahedronGeometry(0.72, 0),
leafMaterial
);
crownTop.position.set(0.3, 3.05, -0.08);
crownTop.rotation.set(0.2, 0.4, 0.1);
}
[
[-23, 7.1, 1.1, materials.leafA],
[-13, 7.1, 0.9, materials.leafC],
[10, 7.2, 1.05, materials.leafB],
[22, 7.1, 0.92, materials.leafA],
[-19, -7.1, 0.95, materials.leafB],
[-9, -7.2, 1.1, materials.leafC],
[11, -7.1, 0.9, materials.leafA],
[23, -7.2, 1.08, materials.leafB]
].forEach((args) => createTree(...args));
function createBuilding(x, z, width, height, depth, mat, floors = 2) {
const building = new THREE.Group();
building.position.set(x, 0.31, z);
scene.add(building);
box(building, width, height, depth, mat, 0, height / 2, 0);
box(building, width + 0.25, 0.24, depth + 0.25, materials.roof, 0, height + 0.1, 0);
const columns = Math.max(2, Math.floor(width / 2.2));
const rows = Math.max(1, floors);
for (let row = 0; row < rows; row++) {
for (let column = 0; column < columns; column++) {
const windowWidth = Math.min(1.05, (width / columns) * 0.5);
const windowX =
-width / 2 +
((column + 0.5) * width) / columns;
const windowY = 1.25 + row * 1.75;
if (windowY + 0.5 < height) {
box(
building,
windowWidth,
0.82,
0.05,
materials.window,
windowX,
windowY,
depth / 2 + 0.03
);
}
}
}
box(
building,
1.05,
1.65,
0.08,
materials.roof,
width * 0.22,
0.84,
depth / 2 + 0.045
);
}
createBuilding(-20, -14.2, 8, 5.2, 5, materials.buildingA, 2);
createBuilding(-9.5, -14.5, 7, 6.6, 5.5, materials.buildingB, 3);
createBuilding(1, -14.2, 8.5, 4.5, 5, materials.buildingC, 2);
createBuilding(12, -14.7, 8, 7.2, 5.5, materials.buildingA, 3);
createBuilding(23, -14.3, 8, 5.4, 5, materials.buildingB, 2);
function createStreetLamp(x, z, rotation = 0) {
const lamp = new THREE.Group();
lamp.position.set(x, 0.31, z);
lamp.rotation.y = rotation;
scene.add(lamp);
cylinder(lamp, 0.07, 0.1, 4.4, materials.pole, 0, 2.2, 0, 8);
box(lamp, 1.25, 0.09, 0.09, materials.pole, 0.55, 4.35, 0);
const light = box(
lamp,
0.48,
0.14,
0.3,
material(0xffe5a0, { emissive: 0xffd778, emissiveIntensity: 1.3 }),
1.05,
4.25,
0
);
light.rotation.z = 0.04;
}
createStreetLamp(-16, 5.8, Math.PI);
createStreetLamp(-8, 5.8, Math.PI);
createStreetLamp(8, -5.8, 0);
createStreetLamp(17, -5.8, 0);
// -------------------------------------------------------------------------
// Traffic signals
// -------------------------------------------------------------------------
const trafficSignals = [];
function createTrafficSignal(x, poleZ, headZ, rotationY) {
cylinder(scene, 0.09, 0.12, 4.55, materials.pole, x, 2.3, poleZ, 8);
const armLength = Math.abs(poleZ - headZ);
box(
scene,
0.12,
0.12,
armLength,
materials.pole,
x,
4.35,
(poleZ + headZ) / 2
);
const signal = new THREE.Group();
signal.position.set(x, 3.53, headZ);
signal.rotation.y = rotationY;
scene.add(signal);
box(signal, 0.68, 1.82, 0.42, materials.housing);
box(signal, 0.78, 0.12, 0.48, materials.housing, 0, 0.88, 0);
const redMaterial = material(0x451d1d, {
emissive: 0xff3f45,
emissiveIntensity: 0
});
const amberMaterial = material(0x4a3820, {
emissive: 0xffb52e,
emissiveIntensity: 0
});
const greenMaterial = material(0x173f25, {
emissive: 0x49e275,
emissiveIntensity: 0
});
const redLight = addMesh(
signal,
new THREE.CircleGeometry(0.185, 16),
redMaterial
);
redLight.position.set(0, 0.56, 0.216);
const amberLight = addMesh(
signal,
new THREE.CircleGeometry(0.185, 16),
amberMaterial
);
amberLight.position.set(0, 0, 0.216);
const greenLight = addMesh(
signal,
new THREE.CircleGeometry(0.185, 16),
greenMaterial
);
greenLight.position.set(0, -0.56, 0.216);
trafficSignals.push({
redMaterial,
amberMaterial,
greenMaterial
});
}
// Westbound signal is visible from the default camera.
createTrafficSignal(5.2, -5.55, -2.5, Math.PI / 2);
createTrafficSignal(-5.2, 5.55, 2.5, -Math.PI / 2);
function setLamp(mat, color, active, intensity = 2.2) {
mat.color.setHex(active ? color : 0x1a2524);
mat.emissive.setHex(active ? color : 0x000000);
mat.emissiveIntensity = active ? intensity : 0;
}
// -------------------------------------------------------------------------
// Pedestrian signals
// -------------------------------------------------------------------------
const pedestrianSignals = [];
function createPedestrianSignal(x, z, rotationY = 0) {
cylinder(scene, 0.075, 0.1, 2.35, materials.pole, x, 1.48, z, 8);
const signal = new THREE.Group();
signal.position.set(x, 2.32, z);
signal.rotation.y = rotationY;
scene.add(signal);
box(signal, 0.82, 1.35, 0.42, materials.housing);
box(signal, 0.88, 0.11, 0.48, materials.housing, 0, 0.65, 0);
box(signal, 0.66, 1.12, 0.04, materials.panel, 0, 0, 0.225);
const redMaterial = material(0x481b1b, {
emissive: 0xff3f45,
emissiveIntensity: 1.7
});
const greenMaterial = material(0x153d29, {
emissive: 0x46e17a,
emissiveIntensity: 0
});
const redHand = new THREE.Group();
redHand.position.z = 0.255;
signal.add(redHand);
box(redHand, 0.17, 0.16, 0.035, redMaterial, 0, -0.02, 0);
for (const fingerX of [-0.06, -0.02, 0.02, 0.06]) {
box(redHand, 0.034, 0.19, 0.035, redMaterial, fingerX, 0.145, 0);
}
const thumb = box(
redHand,
0.04,
0.13,
0.035,
redMaterial,
-0.105,
0.02,
0
);
thumb.rotation.z = -0.72;
const greenWalker = new THREE.Group();
greenWalker.position.z = 0.26;
signal.add(greenWalker);
const head = addMesh(
greenWalker,
new THREE.CircleGeometry(0.055, 10),
greenMaterial
);
head.position.set(0.015, 0.29, 0);
box(greenWalker, 0.075, 0.19, 0.03, greenMaterial, 0, 0.12, 0);
const greenArm = box(
greenWalker,
0.04,
0.18,
0.03,
greenMaterial,
-0.075,
0.12,
0
);
greenArm.rotation.z = -0.45;
const greenLeg = box(
greenWalker,
0.04,
0.18,
0.03,
greenMaterial,
0.035,
-0.08,
0
);
greenLeg.rotation.z = -0.28;
pedestrianSignals.push({
redMaterial,
greenMaterial,
redHand,
greenWalker
});
}
createPedestrianSignal(2.55, 5.65, 0);
createPedestrianSignal(-2.55, -5.65, Math.PI);
// -------------------------------------------------------------------------
// Vehicles
// -------------------------------------------------------------------------
const vehicles = [];
function createVehicle(direction, laneZ, initialX, color, variant = 0) {
const group = new THREE.Group();
group.position.set(initialX, 0.1, laneZ);
group.rotation.y = direction > 0 ? 0 : Math.PI;
scene.add(group);
const bodyMaterial = material(color, { roughness: 0.58 });
const bodyHeight = variant === 1 ? 0.72 : 0.52;
box(group, 2.35, bodyHeight, 1.28, bodyMaterial, 0, 0.67, 0);
box(group, 1.22, 0.42, 1.12, materials.glass, -0.12, 1.08, 0);
box(group, 1.48, 0.12, 1.15, bodyMaterial, -0.12, 1.31, 0);
const tailMaterial = material(0x7a2525, {
emissive: 0xff302d,
emissiveIntensity: 0.25
});
for (const x of [-0.77, 0.77]) {
for (const z of [-0.67, 0.67]) {
const wheel = cylinder(
group,
0.31,
0.31,
0.18,
materials.tire,
x,
0.34,
z,
10
);
wheel.rotation.x = Math.PI / 2;
}
}
for (const z of [-0.4, 0.4]) {
box(
group,
0.06,
0.16,
0.26,
material(0xffe8a8, {
emissive: 0xffdf7e,
emissiveIntensity: 1.1
}),
1.19,
0.72,
z
);
box(group, 0.06, 0.14, 0.25, tailMaterial, -1.19, 0.72, z);
}
vehicles.push({
group,
direction,
laneZ,
initialX,
speed: 0,
tailMaterial,
bodyMaterial
});
}
createVehicle(1, 2.5, -16, 0xe66d50);
createVehicle(1, 2.5, -25.5, 0xf0b84e, 1);
createVehicle(-1, -2.5, 16, 0x5d92c5);
createVehicle(-1, -2.5, 25.5, 0x69a879, 1);
function updateVehicles(delta, phaseType) {
const desiredSpeed = phaseType === "green" ? 2.6 : 0;
for (const vehicle of vehicles) {
let targetSpeed = desiredSpeed;
// Maintain a safe gap behind the leading vehicle in the same lane.
for (const other of vehicles) {
if (other === vehicle || other.direction !== vehicle.direction) continue;
const gap =
vehicle.direction > 0
? other.group.position.x - vehicle.group.position.x
: vehicle.group.position.x - other.group.position.x;
if (gap > 0 && gap < 6.2) {
targetSpeed = Math.min(targetSpeed, Math.max(0, (gap - 3.2) * 1.25));
}
}
const acceleration = targetSpeed > vehicle.speed ? 4.5 : 3.4;
const speedStep = acceleration * delta;
vehicle.speed += THREE.MathUtils.clamp(targetSpeed - vehicle.speed, -speedStep, speedStep);
vehicle.group.position.x += vehicle.direction * vehicle.speed * delta;
if (vehicle.direction > 0 && vehicle.group.position.x > 32) {
vehicle.group.position.x = -31;
} else if (vehicle.direction < 0 && vehicle.group.position.x < -32) {
vehicle.group.position.x = 31;
}
const braking = phaseType !== "green" || vehicle.speed < 0.25;
vehicle.tailMaterial.emissiveIntensity = braking ? 2.2 : 0.25;
}
}
// -------------------------------------------------------------------------
// Pedestrians
// -------------------------------------------------------------------------
const pedestrians = [];
function createPerson(x, color, delay) {
const group = new THREE.Group();
scene.add(group);
const shirt = material(color);
const trousers = material(0x344649);
const skin = material(0xc98968);
box(group, 0.34, 0.55, 0.24, shirt, 0, 1.03, 0);
box(group, 0.38, 0.13, 0.27, trousers, 0, 0.73, 0);
const head = addMesh(
group,
new THREE.IcosahedronGeometry(0.17, 0),
skin
);
head.position.set(0, 1.52, 0);
const hair = addMesh(
group,
new THREE.IcosahedronGeometry(0.175, 0),
material(0x493b34)
);
hair.position.set(0, 1.59, -0.015);
hair.scale.set(1, 0.62, 1);
const legs = [];
const arms = [];
for (const side of [-1, 1]) {
const legPivot = new THREE.Group();
legPivot.position.set(side * 0.09, 0.72, 0);
group.add(legPivot);
box(legPivot, 0.12, 0.59, 0.13, trousers, 0, -0.28, 0);
box(legPivot, 0.13, 0.09, 0.22, materials.tire, 0, -0.57, 0.04);
legs.push(legPivot);
const armPivot = new THREE.Group();
armPivot.position.set(side * 0.235, 1.25, 0);
group.add(armPivot);
box(armPivot, 0.09, 0.48, 0.11, shirt, 0, -0.22, 0);
box(armPivot, 0.1, 0.1, 0.11, skin, 0, -0.47, 0);
arms.push(armPivot);
}
pedestrians.push({
group,
x,
delay,
legs,
arms
});
}
createPerson(-0.85, 0xd45d63, 0);
createPerson(-0.08, 0x3f8f9c, 0.35);
createPerson(0.72, 0xe0a04b, 0.7);
function updatePedestrians(phaseIndex, phaseLocal, cycle) {
const southToNorth = cycle % 2 === 0;
const originZ = southToNorth ? 5.78 : -5.78;
const destinationZ = southToNorth ? -5.78 : 5.78;
let crossingProgress = 0;
if (phaseIndex === 3) {
crossingProgress = 1;
} else if (phaseIndex > 3) {
crossingProgress = 1;
}
for (const pedestrian of pedestrians) {
let progress = crossingProgress;
let walking = false;
if (phaseIndex === 3) {
progress = THREE.MathUtils.clamp(
(phaseLocal - pedestrian.delay) / 3.05,
0,
1
);
walking = phaseLocal >= pedestrian.delay && progress < 1;
}
pedestrian.group.position.x = pedestrian.x;
pedestrian.group.position.y = 0.32;
pedestrian.group.position.z = THREE.MathUtils.lerp(
originZ,
destinationZ,
progress
);
const swing = walking ? Math.sin(phaseLocal * 10.5) * 0.62 : 0;
pedestrian.legs[0].rotation.x = swing;
pedestrian.legs[1].rotation.x = -swing;
pedestrian.arms[0].rotation.x = -swing * 0.8;
pedestrian.arms[1].rotation.x = swing * 0.8;
pedestrian.group.position.y += walking
? Math.abs(Math.sin(phaseLocal * 10.5)) * 0.035
: 0;
}
}
// -------------------------------------------------------------------------
// Phase timeline and UI
// -------------------------------------------------------------------------
const phases = [
{
name: "Green",
label: "Green",
duration: 4,
type: "green",
color: "#48c878",
detail: "Traffic is moving"
},
{
name: "Amber",
label: "Amber",
duration: 2,
type: "amber",
color: "#e7a93e",
detail: "Traffic is slowing to a stop"
},
{
name: "All red",
label: "All red",
duration: 2,
type: "red",
color: "#e65e62",
detail: "Traffic is stopped"
},
{
name: "Walk",
label: "Walk",
duration: 4,
type: "walk",
color: "#2db7b1",
detail: "Pedestrians are crossing"
},
{
name: "Flash",
label: "Flash",
duration: 2,
type: "flash",
color: "#e87959",
detail: "Don't walk — crossing is ending"
},
{
name: "All red",
label: "All red",
duration: 2,
type: "red",
color: "#e65e62",
detail: "Traffic remains stopped"
},
{
name: "Green",
label: "Green",
duration: 4,
type: "green",
color: "#48c878",
detail: "Traffic resumes"
}
];
const totalDuration = phases.reduce((sum, phase) => sum + phase.duration, 0);
const timelineTrack = document.getElementById("timeline-track");
const phaseNameElement = document.getElementById("phase-name");
const phaseCountdownElement = document.getElementById("phase-countdown");
const phaseDetailElement = document.getElementById("phase-detail");
const nextPhaseElement = document.getElementById("next-phase");
const clockElement = document.getElementById("clock");
const trafficStateElement = document.getElementById("traffic-state");
const pedestrianStateElement = document.getElementById("ped-state");
const pauseButton = document.getElementById("pause-button");
const segmentElements = phases.map((phase, index) => {
const segment = document.createElement("div");
segment.className = "timeline-segment";
segment.style.flexGrow = String(phase.duration);
segment.setAttribute("aria-label", `${phase.label}, ${phase.duration} seconds`);
const fill = document.createElement("div");
fill.className = "segment-fill";
fill.style.background = phase.color;
const label = document.createElement("div");
label.className = "segment-label";
label.textContent = phase.label;
segment.append(fill, label);
timelineTrack.appendChild(segment);
return { segment, fill };
});
let elapsed = 0;
let paused = false;
function getCurrentPhase(time) {
let index = 0;
let localTime = time;
for (let i = 0; i < phases.length; i++) {
const phase = phases[i];
if (localTime < phase.duration) {
index = i;
break;
}
localTime -= phase.duration;
if (i === phases.length - 1) {
index = i;
localTime = Math.min(localTime, phase.duration);
break;
}
}
return {
index,
localTime,
phase: phases[index],
next: phases[(index + 1) % phases.length]
};
}
function formatClock(time) {
const minutes = Math.floor(time / 60)
.toString()
.padStart(2, "0");
const seconds = (time % 60).toFixed(1).padStart(4, "0");
return `${minutes}:${seconds}`;
}
function updateUI(current) {
const { index, localTime, phase, next } = current;
const remaining = Math.max(0, phase.duration - localTime);
document.documentElement.style.setProperty("--phase", phase.color);
phaseNameElement.textContent = phase.name;
phaseCountdownElement.textContent = `${remaining.toFixed(1)}s`;
phaseDetailElement.textContent = phase.detail;
nextPhaseElement.textContent = `Next: ${next.name}`;
clockElement.textContent = `${formatClock(elapsed)} / ${formatClock(totalDuration)}`;
segmentElements.forEach((entry, segmentIndex) => {
const isCurrent = segmentIndex === index;
entry.segment.classList.toggle("current", isCurrent);
let progress = 0;
if (isCurrent) {
progress = localTime / phase.duration;
} else if (segmentIndex < index) {
progress = 1;
}
entry.fill.style.width = `${THREE.MathUtils.clamp(progress, 0, 1) * 100}%`;
});
if (phase.type === "green") {
trafficStateElement.textContent = "Traffic running";
trafficStateElement.style.color = "#279f59";
} else if (phase.type === "amber") {
trafficStateElement.textContent = "Traffic stopping";
trafficStateElement.style.color = "#b77b18";
} else {
trafficStateElement.textContent = "Traffic stopped";
trafficStateElement.style.color = "#c9494e";
}
if (phase.type === "walk") {
pedestrianStateElement.textContent = "Pedestrians crossing";
pedestrianStateElement.style.color = "#168d91";
} else if (phase.type === "flash") {
pedestrianStateElement.textContent = "Don't walk";
pedestrianStateElement.style.color = "#c55c46";
} else {
pedestrianStateElement.textContent = "Pedestrians waiting";
pedestrianStateElement.style.color = "#168d91";
}
}
function updateSignals(current) {
const type = current.phase.type;
for (const signal of trafficSignals) {
setLamp(signal.redMaterial, 0xff3f45, type !== "green" && type !== "amber");
setLamp(signal.amberMaterial, 0xffb52e, type === "amber");
setLamp(signal.greenMaterial, 0x49e275, type === "green");
}
for (const signal of pedestrianSignals) {
const walking = type === "walk";
const showRed = !walking;
signal.greenWalker.visible = walking;
signal.redHand.visible = showRed;
setLamp(signal.greenMaterial, 0x46e17a, walking, 2.5);
setLamp(
signal.redMaterial,
0xff3f45,
showRed,
type === "flash"
? 1.2 + Math.sin(current.localTime * 9) * 0.8
: 1.8
);
}
}
function resetSimulation() {
elapsed = 0;
paused = false;
pauseButton.textContent = "Pause";
for (const vehicle of vehicles) {
vehicle.group.position.x = vehicle.initialX;
vehicle.speed = 0;
}
}
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
document.getElementById("replay-button").addEventListener("click", resetSimulation);
document.getElementById("view-reset").addEventListener("click", () => {
cameraYaw = 0.56;
cameraPitch = 0.61;
cameraZoom = 1;
updateCamera();
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
} else if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!paused) {
elapsed = (elapsed + delta) % totalDuration;
}
const current = getCurrentPhase(elapsed);
const cycle = Math.floor(elapsed / totalDuration);
if (!paused) {
updateVehicles(delta, current.phase.type);
}
updatePedestrians(current.index, current.localTime, cycle);
updateSignals(current);
updateUI(current);
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```