inital demo w/ basic cycle

This commit is contained in:
SowinskiBraeden committed 2026-11-12 21:03:38 -07:00
1 parent a898ddf6e0
commit 8a23655524
7 files changed
+925 -47

No files matched your search

+6
View File
@@ -25,3 +25,9 @@ wasm-bindgen-test = "0.3.34"
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
[package.metadata.wasm-pack.profile.release]
# The wasm-opt available on this machine (binaryen 108) corrupts the
# externref table that current wasm-bindgen emits, so skip it rather
# than ship a build that fails WebAssembly.Table.grow() at runtime.
wasm-opt = false
+189
View File
@@ -0,0 +1,189 @@
import init, { Controller, Interval } from './pkg/traffic_lights.js';
const phases = [
{ id: 1, label: 'West left', path: 'M200 342H264Q342 342 342 264V200', x: 196, y: 342, labelX: 166, labelY: 348 },
{ id: 2, label: 'East through', path: 'M440 254H200', x: 444, y: 254, labelX: 474, labelY: 260 },
{ id: 3, label: 'North left', path: 'M298 200V264Q298 342 376 342H440', x: 298, y: 196, labelX: 298, labelY: 168 },
{ id: 4, label: 'South through', path: 'M386 440V200', x: 386, y: 444, labelX: 386, labelY: 483 },
{ id: 5, label: 'East left', path: 'M440 298H376Q298 298 298 376V440', x: 444, y: 298, labelX: 474, labelY: 304 },
{ id: 6, label: 'West through', path: 'M200 386H440', x: 196, y: 386, labelX: 166, labelY: 392 },
{ id: 7, label: 'South left', path: 'M342 440V376Q342 298 264 298H200', x: 342, y: 444, labelX: 342, labelY: 483 },
{ id: 8, label: 'North through', path: 'M254 200V440', x: 254, y: 196, labelX: 254, labelY: 168 },
];
const byId = (id) => document.getElementById(id);
let controller;
let timer = null;
function buildControls() {
byId('phase-controls').innerHTML = phases.map((phase) => `
<tr>
<th scope="row">${phase.id}</th>
<td>${phase.label}</td>
<td><span id="signal-${phase.id}" class="signal-word signal-red">RED</span></td>
<td><button class="btn btn-outline-primary btn-sm call-button" data-call="${phase.id}" type="button" aria-label="Detector call for phase ${phase.id}" disabled>Call</button></td>
<td><div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" id="recall-${phase.id}" aria-label="Minimum recall for phase ${phase.id}" checked disabled></div></td>
</tr>
`).join('');
byId('phase-timing').innerHTML = phases.map((phase) => `
<tr>
<th scope="row">${phase.id}</th><td>${phase.label}</td>
<td><input class="form-control form-control-sm" id="min-${phase.id}" aria-label="Phase ${phase.id} minimum green seconds" type="number" min="1" max="255" step="1" value="${phase.id % 2 ? 5 : 8}" required></td>
<td><input class="form-control form-control-sm" id="max-${phase.id}" aria-label="Phase ${phase.id} maximum green seconds" type="number" min="1" max="255" step="1" value="${phase.id % 2 ? 15 : 25}" required></td>
<td><input class="form-control form-control-sm" id="pass-${phase.id}" aria-label="Phase ${phase.id} passage seconds" type="number" min="1" max="255" step="1" value="3" required></td>
</tr>
`).join('');
byId('movements').innerHTML = phases.map((phase) => `<path id="movement-${phase.id}" class="movement" d="${phase.path}" stroke="#899096" opacity=".25" marker-end="url(#arrow-off)"/>`).join('');
byId('lights').innerHTML = phases.map((phase) => `
<g id="light-${phase.id}" role="img" aria-label="Phase ${phase.id}: red">
<rect class="signal-box" x="${phase.x - 17}" y="${phase.y - 17}" width="34" height="34"/>
<circle id="lamp-${phase.id}" cx="${phase.x}" cy="${phase.y}" r="12" fill="#dc3545"/>
<text id="lamp-letter-${phase.id}" class="lamp-letter" x="${phase.x}" y="${phase.y}" fill="white">R</text>
<text class="phase-number" x="${phase.labelX}" y="${phase.labelY}">${phase.id}</text>
</g>
`).join('');
}
function render() {
const green = [];
const yellow = [];
let clearing = false;
const pending = controller.pending_calls();
for (const phase of phases) {
const signal = controller.signal(phase.id);
const isGreen = signal === Interval.Green;
const isYellow = signal === Interval.Yellow;
const name = isGreen ? 'green' : isYellow ? 'yellow' : 'red';
const color = isGreen ? '#35c66a' : isYellow ? '#ffc107' : '#dc3545';
if (isGreen) green.push(phase.id);
if (isYellow) yellow.push(phase.id);
if (signal === Interval.RedClearance) clearing = true;
byId(`lamp-${phase.id}`).setAttribute('fill', color);
byId(`lamp-letter-${phase.id}`).textContent = name[0].toUpperCase();
byId(`lamp-letter-${phase.id}`).setAttribute('fill', isYellow ? '#212529' : 'white');
byId(`light-${phase.id}`).setAttribute('aria-label', `Phase ${phase.id}: ${name}`);
const path = byId(`movement-${phase.id}`);
path.setAttribute('stroke', isGreen || isYellow ? color : '#899096');
path.setAttribute('opacity', isGreen || isYellow ? '1' : '.18');
path.setAttribute('marker-end', `url(#arrow-${isGreen ? 'green' : isYellow ? 'yellow' : 'off'})`);
const word = byId(`signal-${phase.id}`);
word.className = `signal-word signal-${name}`;
word.textContent = name.toUpperCase();
const call = document.querySelector(`[data-call="${phase.id}"]`);
const waiting = (pending & (1 << (phase.id - 1))) !== 0;
call.classList.toggle('waiting', waiting);
call.textContent = waiting ? 'Waiting' : 'Call';
}
const seconds = controller.time();
byId('clock').textContent = `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
byId('controller-screen').textContent = controller.render();
byId('signal-summary').textContent = green.length ? `Green: ${green.join(' / ')}`
: yellow.length ? `Yellow: ${yellow.join(' / ')}`
: clearing ? 'Red clearance · all red' : 'Startup · all red';
}
function pause() {
clearInterval(timer);
timer = null;
byId('run').textContent = 'Run';
byId('run').className = 'btn btn-primary';
byId('run').setAttribute('aria-pressed', 'false');
byId('run-state').textContent = 'Paused';
byId('step').disabled = false;
}
function run() {
const delay = 1000 / Number(byId('speed').value);
timer = setInterval(() => { controller.step(); render(); }, delay);
byId('run').textContent = 'Pause';
byId('run').className = 'btn btn-warning';
byId('run').setAttribute('aria-pressed', 'true');
byId('run-state').textContent = 'Running';
byId('step').disabled = true;
}
function updateRecall() {
let mask = 0;
for (const phase of phases) {
if (byId(`recall-${phase.id}`).checked) mask |= 1 << (phase.id - 1);
}
controller.set_min_recall(mask);
byId('last-action').textContent = `Minimum recall updated. Mask: ${mask}.`;
render();
}
function applyTiming(event) {
event.preventDefault();
if (!byId('timing-form').reportValidity()) return;
const values = phases.map((phase) => ({
id: phase.id,
min: Number(byId(`min-${phase.id}`).value),
max: Number(byId(`max-${phase.id}`).value),
pass: Number(byId(`pass-${phase.id}`).value),
}));
const yellow = Number(byId('yellow').value);
const red = Number(byId('red-clearance').value);
for (const phase of values) {
if (phase.min > phase.max) {
byId('config-error').textContent = `Phase ${phase.id}: maximum green must be at least minimum green.`;
byId(`max-${phase.id}`).focus();
return;
}
}
pause();
for (const phase of values) {
controller.configure_phase(phase.id, phase.min, phase.max, phase.pass, yellow, red);
}
controller.reset();
byId('config-error').textContent = '';
byId('last-action').textContent = 'Timing applied. Controller reset to startup all red.';
render();
}
buildControls();
try {
await init();
controller = Controller.demo();
for (const button of document.querySelectorAll('button, #speed, [id^="recall-"]')) button.disabled = false;
pause();
render();
byId('last-action').textContent = 'Minimum recall is on for all eight phases. Press Run or Step.';
byId('run').addEventListener('click', () => timer === null ? run() : pause());
byId('step').addEventListener('click', () => { controller.step(); render(); });
byId('reset').addEventListener('click', () => {
pause();
controller.reset();
byId('last-action').textContent = 'Controller reset. Applied timing and recall settings retained.';
render();
});
byId('speed').addEventListener('change', () => { if (timer !== null) { pause(); run(); } });
byId('lcd-toggle').addEventListener('change', () => {
byId('controller-screen').classList.toggle('lcd-mode', byId('lcd-toggle').checked);
});
for (const phase of phases) {
document.querySelector(`[data-call="${phase.id}"]`).addEventListener('click', () => {
controller.call(phase.id);
byId('last-action').textContent = `Detector hit sent to phase ${phase.id} (${phase.label.toLowerCase()}).`;
render();
});
byId(`recall-${phase.id}`).addEventListener('change', updateRecall);
}
byId('timing-form').addEventListener('submit', applyTiming);
} catch (error) {
byId('error').classList.remove('d-none');
byId('error').textContent = `The WASM controller could not load. ${error.message}`;
byId('run-state').textContent = 'Controller unavailable';
console.error(error);
}
+145
View File
@@ -0,0 +1,145 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="An eight-phase traffic controller with a simple intersection display and timing controls.">
<title>Traffic controller</title>
<link rel="stylesheet" href="./vendor/bootstrap.min.css">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<header class="border-bottom bg-white">
<div class="container py-3 d-flex align-items-center justify-content-between gap-3">
<h1 class="h4 mb-0">Traffic controller</h1>
<span class="small text-secondary">8 phases · Rust / WASM</span>
</div>
</header>
<main class="container py-3">
<div id="error" class="alert alert-danger d-none" role="alert"></div>
<section class="panel mb-3" aria-label="Simulation controls">
<div class="d-flex align-items-center flex-wrap gap-2">
<button id="run" class="btn btn-primary" type="button" disabled>Run</button>
<button id="step" class="btn btn-outline-secondary" type="button" disabled>Step +1s</button>
<button id="reset" class="btn btn-outline-danger" type="button" disabled>Reset</button>
<label for="speed" class="ms-sm-2 small">Speed</label>
<select id="speed" class="form-select form-select-sm speed-select" disabled>
<option value="1">1×</option>
<option value="2">2×</option>
<option value="4">4×</option>
</select>
<div class="ms-sm-auto d-flex align-items-center gap-3">
<span id="run-state" class="small text-secondary" role="status">Loading WASM…</span>
<output id="clock" class="font-monospace fw-bold">00:00</output>
</div>
</div>
</section>
<div class="row g-3 mb-3">
<div class="col-lg-7">
<section class="panel h-100">
<div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-2">
<h2 class="h6 mb-0">Intersection</h2>
<span id="signal-summary" class="small font-monospace">All red</span>
</div>
<svg id="intersection" viewBox="0 0 640 640" role="img" aria-labelledby="map-title map-description">
<title id="map-title">Eight-phase intersection</title>
<desc id="map-description">West and east are the main road. Each approach has a through movement and a left turn. Numbered lights match the phase controls.</desc>
<defs>
<marker id="arrow-off" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="3" markerHeight="3" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10Z" fill="#899096"/></marker>
<marker id="arrow-green" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="3" markerHeight="3" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10Z" fill="#35c66a"/></marker>
<marker id="arrow-yellow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="3" markerHeight="3" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10Z" fill="#ffc107"/></marker>
</defs>
<rect width="640" height="640" fill="#eef0f2"/>
<rect x="232" width="176" height="640" fill="#45494e"/>
<rect y="232" width="640" height="176" fill="#45494e"/>
<g stroke="#f3cd44" stroke-width="2">
<path d="M318 0V216 M322 0V216 M318 424V640 M322 424V640"/>
<path d="M0 318H216 M0 322H216 M424 318H640 M424 322H640"/>
</g>
<g stroke="#bdc1c4" stroke-width="2" stroke-dasharray="14 12">
<path d="M276 0V210 M364 0V210 M276 430V640 M364 430V640"/>
<path d="M0 276H210 M0 364H210 M430 276H640 M430 364H640"/>
</g>
<g stroke="white" stroke-width="5">
<path d="M234 218H314 M326 422H406 M218 326V406 M422 234V314"/>
</g>
<g fill="#202428" font-size="17" font-family="system-ui, sans-serif" font-weight="600">
<text x="216" y="31" text-anchor="end">NORTH</text>
<text x="425" y="623">SOUTH</text>
<text x="24" y="216">WEST · MAIN</text>
<text x="616" y="438" text-anchor="end">EAST · MAIN</text>
</g>
<g id="movements" fill="none" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"></g>
<g id="lights"></g>
</svg>
<div class="d-flex gap-3 flex-wrap small mt-2">
<span><i class="legend-light red"></i>Red</span>
<span><i class="legend-light yellow"></i>Yellow</span>
<span><i class="legend-light green"></i>Green</span>
<span class="text-secondary">Numbers identify phases.</span>
</div>
</section>
</div>
<div class="col-lg-5">
<section class="panel h-100">
<h2 class="h6 mb-3">Calls &amp; minimum recall</h2>
<div class="table-responsive">
<table class="table table-sm align-middle phase-table mb-2">
<thead><tr><th scope="col">Phase</th><th scope="col">Movement</th><th scope="col">Signal</th><th scope="col">Detector</th><th scope="col">Recall</th></tr></thead>
<tbody id="phase-controls"></tbody>
</table>
</div>
<p class="small text-secondary mb-2">A call waits on red and resets passage time on green. Recall requests service automatically.</p>
<p id="last-action" class="small mb-0 action-message" role="status">Ready to load.</p>
</section>
</div>
</div>
<details class="panel mb-3" open>
<summary class="h6 mb-0">Controller display</summary>
<div class="d-flex justify-content-end mt-2">
<div class="form-check form-switch mb-0">
<input class="form-check-input" type="checkbox" role="switch" id="lcd-toggle">
<label class="form-check-label small" for="lcd-toggle">LCD display</label>
</div>
</div>
<pre id="controller-screen" class="mt-2 mb-0" aria-label="Current controller state">Loading controller…</pre>
</details>
<details class="panel mb-3" id="configuration">
<summary class="h6 mb-0">Timing configuration</summary>
<form id="timing-form" class="mt-3">
<div class="table-responsive">
<table class="table table-sm align-middle timing-table">
<thead><tr><th scope="col">Phase</th><th scope="col">Movement</th><th scope="col">Min green (s)</th><th scope="col">Max green (s)</th><th scope="col">Passage (s)</th></tr></thead>
<tbody id="phase-timing"></tbody>
</table>
</div>
<div class="d-flex flex-wrap align-items-end gap-3">
<div><label class="form-label small" for="yellow">Yellow (s)</label><input id="yellow" class="form-control form-control-sm clearance-input" type="number" min="1" max="255" step="1" value="3" required></div>
<div><label class="form-label small" for="red-clearance">Red clearance (s)</label><input id="red-clearance" class="form-control form-control-sm clearance-input" type="number" min="1" max="255" step="1" value="1" required></div>
<button id="apply" type="submit" class="btn btn-primary btn-sm" disabled>Apply &amp; reset</button>
<span class="small text-secondary">Changes restart with 5 seconds of all red.</span>
</div>
<p id="config-error" class="text-danger small mt-2 mb-0" role="alert"></p>
</form>
</details>
<footer class="d-flex justify-content-between gap-3 small text-secondary pb-2">
<span>Fixed pairs: 1/5 → 2/6 → 3/7 → 4/8</span>
<svg class="icon" aria-hidden="true"><use href="/icons.svg#chip" /></svg>
<span>Rust/WebAssembly demo</span>
<span class="dot">&middot;</span>
<a href="https://git.sowinski.dev/SowinskiBraeden/traffic-lights" target="_blank" rel="noreferrer">
<svg class="icon" aria-hidden="true"><use href="/icons.svg#gitea" /></svg>
Source
</a>
</footer>
</main>
<script type="module" src="./app.js"></script>
</body>
</html>
+515 -47
View File
@@ -1,34 +1,17 @@
use std::fmt;
use wasm_bindgen::prelude::*;
/*
* Descriptive comments/inspuration sourced from here:
* https://www.cedengineering.com/userfiles/Introduction%20to%20Traffic%20Signal%20Phasing-R1.pdf
*
* This first version uses four fixed pairs:
* ring 1: 1 -> 2 | 3 -> 4
* ring 2: 5 -> 6 | 7 -> 8
* The vertical line marks the main/side street barrier.
* Each pair completes green, yellow and red clearance together.
*/
enum Bearing {
North = 0,
East = 90,
South = 180,
West = 270,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ApproachId(u8);
struct Approach {
id: ApproachId,
bearing: Bearing, // center outward, e.g. north approach has north outbound lanes, and south inbound lanes
bearing_offset_deg: i8, // e.g. +/- 15 deg from north
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LaneId(u8);
struct Lane {
id: LaneId,
approach_id: ApproachId,
inbound: bool,
pedestrian: bool,
}
/*
* NEMA (the National Electrical Manufacturers Association) follows a generally
* accepted procedure for numbering the eight standard vehicle phases of an intersection,
@@ -46,7 +29,16 @@ struct Lane {
*/
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PhaseId(u8);
impl PhaseId {
pub fn new(number: u8) -> Option<Self> {
if !(1..=8).contains(&number) {
return None;
}
Some(Self(number))
}
// convert num 1-8 to a bit representation for the timing tables
fn bit(self) -> u8 {
1u8 << (self.0 - 1)
@@ -57,13 +49,14 @@ impl PhaseId {
* A phase is any traffic signal display with its
* own set of timings that controls an individual vehicle or pedestrian movement.
*/
struct Phase {
#[derive(Clone)]
pub struct Phase {
id: PhaseId,
incoming_lane_id: LaneId,
outgoing_lane_id: LaneId,
min_seconds: u8,
max_seconds: u8,
pass_seconds: u8,
yellow_seconds: u8,
red_seconds: u8,
/*
* A vehicle phase is serviced when it becomes active and displays a green (G) indication.
* A vehicle phase remains active thru its subsequent yellow (Y) interval and all-red
@@ -83,14 +76,24 @@ struct Phase {
* |__G__|_Y|AR|_G&W|__G&FDW__|_Y|_AR|
* | 01 active | 02 active |
*/
serviced: bool,
// Service is tracked by RingState::interval in this vehicle-only version.
}
/*
* For a phase to be serviced it must first receive a call for service. A vehicle call is a
* demand for the green interval of a vehicle phase while a pedestrian call is a demand
* for the walk interval of a pedestrian phase
*/
calls: u8,
impl Phase {
pub fn new(id: PhaseId, min_seconds: u8, max_seconds: u8, pass_seconds: u8) -> Self {
assert!(min_seconds > 0);
assert!(max_seconds >= min_seconds);
assert!(pass_seconds > 0);
Self {
id,
min_seconds,
max_seconds,
pass_seconds,
yellow_seconds: 3,
red_seconds: 1,
}
}
}
/*
@@ -105,11 +108,22 @@ struct Phase {
*/
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PhaseSetId(u8);
struct PhaseSet {
#[derive(Clone)]
pub struct PhaseSet {
id: PhaseSetId,
phases: Vec<PhaseId>,
}
impl PhaseSet {
pub fn new(id: u8, first: PhaseId, second: PhaseId) -> Self {
Self {
id: PhaseSetId(id),
phases: vec![first, second],
}
}
}
/*
* u8 bits represents phases 1-8
* each bit indicates whether recall is active
@@ -133,6 +147,7 @@ struct TimingChart {
* initial setting.
*/
min_recall: u8,
// Remaining recall notes are preserved for later implementation.
/*
* Maximum recall places a call on a phase and then keeps the phase green for a time
@@ -145,7 +160,7 @@ struct TimingChart {
* longer than their maximum green setting. The recall phases are said to rest in green
* during the period when the actual green time exceeds the maximum green time
*/
max_recall: u8,
// max_recall: u8,
/*
* Pedestrian recalls, Activating ped recall for a phase
@@ -153,7 +168,7 @@ struct TimingChart {
* in the phase rotation, the pedestrian call will be serviced through display of the walk
* and pedestrian clearance intervals.
*/
ped_recall: u8,
// ped_recall: u8,
/*
* Soft recall is almost the same as minimum recall, with one important difference: soft
@@ -163,22 +178,58 @@ struct TimingChart {
* minimum recall, the recall phases are never skipped, they are always serviced even if
* there is no actual demand
*/
soft_recall: u8,
// soft_recall: u8,
// ... more?
}
impl TimingChart {
fn new() -> Self {
Self { min_recall: 0 }
}
}
#[wasm_bindgen]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Interval {
Red,
Green,
Yellow,
RedClearance,
}
struct RingState {
phase: PhaseId,
interval: Interval,
elapsed_seconds: u32,
gap_remaining: u32,
maximum_elapsed: Option<u32>,
ready: bool,
}
impl RingState {
fn new(phase: PhaseId) -> Self {
Self {
phase,
interval: Interval::Red,
elapsed_seconds: 0,
gap_remaining: 0,
maximum_elapsed: None,
ready: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IntersectionId(usize);
struct Controller {
#[wasm_bindgen]
pub struct Controller {
id: IntersectionId,
phases: Vec<Phase>,
// A traffic signal cycle is one complete set of signal phase sets.
// also can represent, phase rotation (phasing sequence): order of phase sets on conflicting calls
rotation: Vec<PhaseSet>,
timimg_chart: TimingChart,
timing_chart: TimingChart,
// external monitor checks controller for bad output (conflicts)
// if detected, an external monitor can put the whole system into flash
@@ -188,11 +239,428 @@ struct Controller {
//
// can be programmed in controller to flash during low-volume periods
// (program flash)
flash: bool,
// flash: bool,
// A flash plan needs per-approach indications; all-yellow is not a universal conflict response.
// start up time in seconds to display red light on all phases
startup_seconds: u8,
startup_remaining: u32,
// manual control of the phase set timing by input
manual: bool,
// manual: bool,
rings: [RingState; 2],
current_set: usize,
/*
* For a phase to be serviced it must first receive a call for service. A vehicle call is a
* demand for the green interval of a vehicle phase while a pedestrian call is a demand
* for the walk interval of a pedestrian phase
*/
pending_calls: u8,
elapsed_seconds: u32,
}
impl Controller {
pub fn new(id: usize, phases: Vec<Phase>, rotation: Vec<PhaseSet>) -> Self {
assert_eq!(phases.len(), 8, "Configure phases 1 through 8");
for number in 1..=8 {
let count = phases.iter().filter(|phase| phase.id.0 == number).count();
assert_eq!(count, 1, "Each phase must be configured exactly once");
}
let pairs = [[1, 5], [2, 6], [3, 7], [4, 8]];
assert_eq!(rotation.len(), pairs.len());
for (set, pair) in rotation.iter().zip(pairs) {
assert_eq!(set.phases.len(), 2);
assert_eq!(set.phases[0].0, pair[0]);
assert_eq!(set.phases[1].0, pair[1]);
}
let rings = [
RingState::new(rotation[0].phases[0]),
RingState::new(rotation[0].phases[1]),
];
let startup_seconds = 5;
Self {
id: IntersectionId(id),
phases,
rotation,
timing_chart: TimingChart::new(),
startup_seconds,
startup_remaining: u32::from(startup_seconds),
rings,
current_set: 0,
pending_calls: 0,
elapsed_seconds: 0,
}
}
fn phase(&self, id: PhaseId) -> &Phase {
self.phases.iter().find(|phase| phase.id == id).unwrap()
}
fn set_mask(&self, index: usize) -> u8 {
self.rotation[index]
.phases
.iter()
.fold(0, |mask, phase| mask | phase.bit())
}
fn demand(&self) -> u8 {
self.pending_calls | self.timing_chart.min_recall
}
fn has_conflicting_call(&self) -> bool {
self.demand() & !self.set_mask(self.current_set) != 0
}
fn start_phase_set(&mut self, index: usize) {
self.current_set = index;
self.pending_calls &= !self.set_mask(index);
let conflicting_call = self.has_conflicting_call();
for (ring, &phase) in self.rings.iter_mut().zip(&self.rotation[index].phases) {
*ring = RingState::new(phase);
ring.interval = Interval::Green;
if conflicting_call {
ring.maximum_elapsed = Some(0);
}
}
}
fn start_interval(&mut self, interval: Interval) {
for ring in &mut self.rings {
ring.interval = interval;
ring.elapsed_seconds = 0;
}
}
fn next_phase_set(&self) -> usize {
for offset in 1..=self.rotation.len() {
let index = (self.current_set + offset) % self.rotation.len();
if self.demand() & self.set_mask(index) != 0 {
return index;
}
}
self.current_set
}
fn step_green(&mut self) {
let conflicting_call = self.has_conflicting_call();
for index in 0..self.rings.len() {
let phase = self.phase(self.rings[index].phase).clone();
let ring = &mut self.rings[index];
ring.gap_remaining = ring.gap_remaining.saturating_sub(1);
if !conflicting_call || ring.ready {
continue;
}
let maximum = ring.maximum_elapsed.get_or_insert(0);
*maximum += 1;
if ring.elapsed_seconds >= u32::from(phase.min_seconds) {
ring.ready = ring.gap_remaining == 0 || *maximum >= u32::from(phase.max_seconds);
}
}
if self.rings.iter().all(|ring| ring.ready) {
self.start_interval(Interval::Yellow);
}
}
fn clearance_seconds(&self, interval: Interval) -> u32 {
self.rings
.iter()
.map(|ring| {
let phase = self.phase(ring.phase);
match interval {
Interval::Yellow => u32::from(phase.yellow_seconds),
_ => u32::from(phase.red_seconds),
}
})
.max()
.unwrap()
}
}
#[wasm_bindgen]
impl Controller {
pub fn demo() -> Self {
let phases = (1..=8)
.map(|number| {
let id = PhaseId::new(number).unwrap();
if number % 2 == 0 {
Phase::new(id, 8, 25, 3)
} else {
Phase::new(id, 5, 15, 3)
}
})
.collect();
let rotation = vec![
PhaseSet::new(1, PhaseId(1), PhaseId(5)),
PhaseSet::new(2, PhaseId(2), PhaseId(6)),
PhaseSet::new(3, PhaseId(3), PhaseId(7)),
PhaseSet::new(4, PhaseId(4), PhaseId(8)),
];
let mut controller = Controller::new(0, phases, rotation);
controller.timing_chart.min_recall = u8::MAX;
controller
}
// One call advances one simulated second.
pub fn step(&mut self) {
self.elapsed_seconds += 1;
if self.startup_remaining > 0 {
self.startup_remaining -= 1;
if self.startup_remaining == 0 {
self.start_phase_set(0);
}
return;
}
for ring in &mut self.rings {
ring.elapsed_seconds += 1;
}
match self.rings[0].interval {
Interval::Green => self.step_green(),
Interval::Yellow => {
if self.rings[0].elapsed_seconds >= self.clearance_seconds(Interval::Yellow) {
self.start_interval(Interval::RedClearance);
}
}
Interval::RedClearance => {
if self.rings[0].elapsed_seconds >= self.clearance_seconds(Interval::RedClearance) {
self.start_phase_set(self.next_phase_set());
}
}
Interval::Red => {}
}
}
// A red/yellow call latches. A green hit restarts passage time.
pub fn call(&mut self, number: u8) -> bool {
let Some(id) = PhaseId::new(number) else {
return false;
};
let passage = u32::from(self.phase(id).pass_seconds);
for ring in &mut self.rings {
if ring.phase == id && ring.interval == Interval::Green {
if !ring.ready {
ring.gap_remaining = passage;
}
return true;
}
}
self.pending_calls |= id.bit();
if self.startup_remaining == 0 && self.rings[0].interval == Interval::Green {
for ring in &mut self.rings {
ring.maximum_elapsed.get_or_insert(0);
}
}
true
}
pub fn set_min_recall(&mut self, mask: u8) {
self.timing_chart.min_recall = mask;
if self.startup_remaining == 0 && self.rings[0].interval == Interval::Green {
let conflicting_call = self.has_conflicting_call();
for ring in &mut self.rings {
if conflicting_call {
ring.maximum_elapsed.get_or_insert(0);
} else {
ring.maximum_elapsed = None;
ring.ready = false;
}
}
}
}
pub fn signal(&self, number: u8) -> Interval {
for ring in &self.rings {
if ring.phase.0 == number {
return ring.interval;
}
}
Interval::Red
}
pub fn pending_calls(&self) -> u8 {
self.pending_calls
}
pub fn time(&self) -> u32 {
self.elapsed_seconds
}
pub fn configure_phase(&mut self, number: u8, min: u8, max: u8, pass: u8, yellow: u8, red: u8) {
let Some(id) = PhaseId::new(number) else {
return;
};
if let Some(phase) = self.phases.iter_mut().find(|phase| phase.id == id) {
phase.min_seconds = min;
phase.max_seconds = max;
phase.pass_seconds = pass;
phase.yellow_seconds = yellow;
phase.red_seconds = red;
}
}
pub fn reset(&mut self) {
let mut controller = Controller::new(self.id.0, self.phases.clone(), self.rotation.clone());
controller.timing_chart.min_recall = self.timing_chart.min_recall;
*self = controller;
}
pub fn render(&self) -> String {
self.to_string()
}
pub fn render_timing(&self) -> String {
let mut output = String::from("VEHICLE TIMING / SECONDS\nPHASE ");
for number in 1..=8 {
output.push_str(&format!("{number:>3} "));
}
output.push('\n');
let rows = ["MIN GRN", "MAX GRN", "PASS", "YELLOW", "RED CLR"];
for (row, label) in rows.iter().enumerate() {
output.push_str(&format!("{label:<8}"));
for number in 1..=8 {
let phase = self.phase(PhaseId(number));
let values = [
phase.min_seconds,
phase.max_seconds,
phase.pass_seconds,
phase.yellow_seconds,
phase.red_seconds,
];
output.push_str(&format!("{:>3} ", values[row]));
}
output.push('\n');
}
output.push_str(&format!("STARTUP {}s\n", self.startup_seconds));
output
}
}
impl fmt::Display for Controller {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(
f,
"CONTROLLER {} TIME {}s",
self.id.0, self.elapsed_seconds
)?;
if self.startup_remaining > 0 {
writeln!(f, "STARTUP ALL RED {}s", self.startup_remaining)?;
} else {
writeln!(f, "PHASE SET {}", self.rotation[self.current_set].id.0)?;
}
write!(f, "PHASE ")?;
for number in 1..=8 {
write!(f, "{number:>4}")?;
}
write!(f, "\nLAMP ")?;
for number in 1..=8 {
let lamp = match self.signal(number) {
Interval::Green => 'G',
Interval::Yellow => 'Y',
_ => 'R',
};
write!(f, "{lamp:>4}")?;
}
write!(f, "\nCALL ")?;
for number in 1..=8 {
let call = if self.pending_calls & PhaseId(number).bit() != 0 {
'X'
} else {
'.'
};
write!(f, "{call:>4}")?;
}
write!(f, "\nRECALL")?;
for number in 1..=8 {
let recall = if self.timing_chart.min_recall & PhaseId(number).bit() != 0 {
'X'
} else {
'.'
};
write!(f, "{recall:>4}")?;
}
writeln!(f)?;
writeln!(
f,
"\n{:>4} {:>6} {:<14} {:>7} {:>3} {:>3} {:>3} READY",
"RING", "PHASE", "INTERVAL", "ELAPSED", "MIN", "GAP", "MAX",
)?;
for (index, ring) in self.rings.iter().enumerate() {
let phase = self.phase(ring.phase);
let interval = match ring.interval {
Interval::Red => "Red",
Interval::Green => "Green",
Interval::Yellow => "Yellow",
Interval::RedClearance => "RedClearance",
};
let green = ring.interval == Interval::Green;
let min = if green {
u32::from(phase.min_seconds)
.saturating_sub(ring.elapsed_seconds)
.to_string()
} else {
String::from("-")
};
let gap = if green {
ring.gap_remaining.to_string()
} else {
String::from("-")
};
let max = if green {
match ring.maximum_elapsed {
Some(elapsed) => u32::from(phase.max_seconds)
.saturating_sub(elapsed)
.to_string(),
None => String::from("-"),
}
} else {
String::from("-")
};
writeln!(
f,
"{:>4} {:>6} {:<14} {:>7} {:>3} {:>3} {:>3} {}",
index + 1,
ring.phase.0,
interval,
ring.elapsed_seconds,
min,
gap,
max,
if ring.ready { "YES" } else { "NO" },
)?;
}
Ok(())
}
}
+64
View File
@@ -0,0 +1,64 @@
:root {
--bs-border-radius: .2rem;
--bs-border-radius-sm: .15rem;
}
@font-face {
font-family: 'Silkscreen';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url('./vendor/silkscreen.woff2') format('woff2');
}
body { background: #f5f5f5; color: #212529; }
.container { max-width: 1180px; }
.panel { background: white; border: 1px solid #b8bfc6; padding: 1rem; }
.speed-select { width: 76px; }
.btn { font-weight: 500; }
#run, #step, #reset { min-width: 90px; }
#clock { min-width: 5ch; font-size: 1.15rem; }
#intersection { display: block; width: 100%; max-width: 520px; margin: 0 auto; }
.legend-light { display: inline-block; width: 11px; height: 11px; margin-right: 5px; border: 1px solid #343a40; border-radius: 50%; }
.red { background: #dc3545; }
.yellow { background: #ffc107; }
.green { background: #198754; }
.phase-table { font-size: .875rem; }
.phase-table td, .phase-table th { padding: .55rem .3rem; white-space: nowrap; }
.phase-table th:last-child, .phase-table td:last-child { text-align: center; }
.phase-table .form-check { display: inline-flex; min-height: 0; margin: 0; }
.phase-table .form-check-input { cursor: pointer; margin-top: 0; }
.signal-word { font-size: .7rem; font-weight: 700; display: inline-block; min-width: 54px; text-align: center; padding: 3px 4px; border: 1px solid currentColor; }
.signal-red { color: #b02a37; background: #fff; }
.signal-yellow { color: #212529; background: #ffc107; }
.signal-green { color: white; background: #198754; border-color: #146c43; }
.call-button { min-width: 54px; }
.waiting { background: #0d6efd; color: white; }
.action-message { min-height: 2.5em; border-top: 1px solid #dee2e6; padding-top: .6rem; }
.timing-table { max-width: 780px; }
.timing-table input { width: 84px; }
.clearance-input { width: 110px; }
summary { cursor: pointer; }
#controller-screen { background: #f3f4f5; border: 1px solid #ced4da; padding: 1rem; font-size: .8rem; line-height: 1.6; white-space: pre; overflow-x: auto; }
#controller-screen.lcd-mode {
background: #1a3fd6;
color: #ffffff;
font-family: 'Silkscreen', monospace;
font-size: 1rem;
line-height: 1.6;
}
.movement { transition: stroke .1s; }
.signal-box { fill: #202428; stroke: #f8f9fa; stroke-width: 1; }
.phase-number { font: bold 16px system-ui, sans-serif; fill: white; text-anchor: middle; }
.lamp-letter { font: bold 12px system-ui, sans-serif; text-anchor: middle; dominant-baseline: central; }
@media (max-width: 575px) {
.panel { padding: .75rem; }
header .small { font-size: .7rem; }
.phase-table { font-size: .8rem; }
.phase-table td, .phase-table th { padding: .5rem .2rem; }
.call-button { min-width: 48px; font-size: .75rem; }
.signal-word { min-width: 44px; font-size: .6rem; }
footer { flex-wrap: wrap; }
}
+6
View File
@@ -0,0 +1,6 @@
@charset "UTF-8";/*!
* Bootstrap v5.3.3 (https://getbootstrap.com/)
* Copyright 2011-2024 The Bootstrap Authors
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/:root,[data-bs-theme=light]{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-black:#000;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-gray-100:#f8f9fa;--bs-gray-200:#e9ecef;--bs-gray-300:#dee2e6;--bs-gray-400:#ced4da;--bs-gray-500:#adb5bd;--bs-gray-600:#6c757d;--bs-gray-700:#495057;--bs-gray-800:#343a40;--bs-gray-900:#212529;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-primary-rgb:13,110,253;--bs-secondary-rgb:108,117,125;--bs-success-rgb:25,135,84;--bs-info-rgb:13,202,240;--bs-warning-rgb:255,193,7;--bs-danger-rgb:220,53,69;--bs-light-rgb:248,249,250;--bs-dark-rgb:33,37,41;--bs-primary-text-emphasis:#052c65;--bs-secondary-text-emphasis:#2b2f32;--bs-success-text-emphasis:#0a3622;--bs-info-text-emphasis:#055160;--bs-warning-text-emphasis:#664d03;--bs-danger-text-emphasis:#58151c;--bs-light-text-emphasis:#495057;--bs-dark-text-emphasis:#495057;--bs-primary-bg-subtle:#cfe2ff;--bs-secondary-bg-subtle:#e2e3e5;--bs-success-bg-subtle:#d1e7dd;--bs-info-bg-subtle:#cff4fc;--bs-warning-bg-subtle:#fff3cd;--bs-danger-bg-subtle:#f8d7da;--bs-light-bg-subtle:#fcfcfd;--bs-dark-bg-subtle:#ced4da;--bs-primary-border-subtle:#9ec5fe;--bs-secondary-border-subtle:#c4c8cb;--bs-success-border-subtle:#a3cfbb;--bs-info-border-subtle:#9eeaf9;--bs-warning-border-subtle:#ffe69c;--bs-danger-border-subtle:#f1aeb5;--bs-light-border-subtle:#e9ecef;--bs-dark-border-subtle:#adb5bd;--bs-white-rgb:255,255,255;--bs-black-rgb:0,0,0;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, 0.75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, 0.5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, 0.175);--bs-border-radius:0.375rem;--bs-border-radius-sm:0.25rem;--bs-border-radius-lg:0.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 0.5rem 1rem rgba(0, 0, 0, 0.15);--bs-box-shadow-sm:0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, 0.175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, 0.075);--bs-focus-ring-width:0.25rem;--bs-focus-ring-opacity:0.25;--bs-focus-ring-color:rgba(13, 110, 253, 0.25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, 0.75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222, 226, 230, 0.5);--bs-tertiary-color-rgb:222,226,230;--bs-tertiary-bg:#2b3035;--bs-tertiary-bg-rgb:43,48,53;--bs-primary-text-emphasis:#6ea8fe;--bs-secondary-text-emphasis:#a7acb1;--bs-success-text-emphasis:#75b798;--bs-info-text-emphasis:#6edff6;--bs-warning-text-emphasis:#ffda6a;--bs-danger-text-emphasis:#ea868f;--bs-light-text-emphasis:#f8f9fa;--bs-dark-text-emphasis:#dee2e6;--bs-primary-bg-subtle:#031633;--bs-secondary-bg-subtle:#161719;--bs-success-bg-subtle:#051b11;--bs-info-bg-subtle:#032830;--bs-warning-bg-subtle:#332701;--bs-danger-bg-subtle:#2c0b0e;--bs-light-bg-subtle:#343a40;--bs-dark-bg-subtle:#1a1d20;--bs-primary-border-subtle:#084298;--bs-secondary-border-subtle:#41464b;--bs-success-border-subtle:#0f5132;--bs-info-border-subtle:#087990;--bs-warning-border-subtle:#997404;--bs-danger-border-subtle:#842029;--bs-light-border-subtle:#495057;--bs-dark-border-subtle:#343a40;--bs-heading-color:inherLine truncated
/*# sourceMappingURL=bootstrap.min.css.map */
BIN
View File
Binary file not shown.
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.