-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrafficManager.cpp
More file actions
458 lines (421 loc) · 17.2 KB
/
Copy pathTrafficManager.cpp
File metadata and controls
458 lines (421 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#include "TrafficManager.hpp"
#include "json.hpp" // nlohmann::json header
#include "QTableLoader.hpp"
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>
#include <climits>
#include <cmath>
#include <unordered_map>
// Utility: Convert a state (pair) to a string that matches the JSON Q‑table keys.
std::string stateToString(const std::pair<int, int>& state) {
std::ostringstream oss;
oss << "(" << state.first << ", " << state.second << ")";
return oss.str();
}
TrafficManager::TrafficManager()
: topLeftLight(sf::Vector2f(310.f, 160.f)),
topRightLight(sf::Vector2f(600.f, 160.f)),
bottomLeftLight(sf::Vector2f(310.f, 440.f)),
bottomRightLight(sf::Vector2f(600.f, 440.f)),
phase(Phase::NS_Green),
phaseTimer(0.f),
greenTime(5.f),
yellowTime(2.f),
currentGreenTime(5.f),
minGreen(3.f),
maxGreen(10.f),
queueNS(0),
queueEW(0),
spawnTimer(0.f),
spawnInterval(1.f),
vehicleSpeed(120.f)
{
std::srand(static_cast<unsigned>(std::time(nullptr)));
// Load the Q‑table using our QTableLoader (returns a map with string keys)
qTable = QTableLoader::loadQTable("q_table.json");
// Logical grouping: NS group starts green, EW group red.
topLeftLight.setState(LightState::Green);
bottomLeftLight.setState(LightState::Green);
topRightLight.setState(LightState::Red);
bottomRightLight.setState(LightState::Red);
}
TrafficManager::~TrafficManager() {
for (auto v : vehicles) {
delete v;
}
}
void TrafficManager::applyRLDecision(const std::pair<int, int>& stateKey, const char* phaseLabel, int prevQueueNS, int prevQueueEW) {
std::string keyStr = stateToString(stateKey);
int action = 0; // Default action: 0 = no change
// Try to look up the state in the Q-table.
auto it = qTable.find(keyStr);
if (it != qTable.end()) {
const std::vector<double>& qValues = it->second;
action = std::distance(qValues.begin(), std::max_element(qValues.begin(), qValues.end()));
std::cout << "RL Decision (" << phaseLabel << ") for state " << keyStr
<< ": Action = " << action << std::endl;
} else {
std::cout << "No RL Q-values found for state " << keyStr << std::endl;
action = (std::rand() % 2) + 1; // Explore between action 1 and 2
std::cout << "[DEBUG] Choosing random action: " << action << std::endl;
}
// --- Exponential Moving Average (EMA) for queue trends (Faster Adaptation)
static float emaQueueNS = static_cast<float>(prevQueueNS);
static float emaQueueEW = static_cast<float>(prevQueueEW);
float emaAlpha = 0.8f; // Increased to make smoothing more responsive
emaQueueNS = emaAlpha * queueNS + (1 - emaAlpha) * emaQueueNS;
emaQueueEW = emaAlpha * queueEW + (1 - emaAlpha) * emaQueueEW;
std::pair<int, int> smoothedState = {
static_cast<int>(std::round(emaQueueNS)),
static_cast<int>(std::round(emaQueueEW))
};
std::cout << "[DEBUG] Smoothed state: " << stateToString(smoothedState) << std::endl;
// --- Adjust Reward Scaling.
int queueReduction = (prevQueueNS + prevQueueEW) - (queueNS + queueEW);
double reward = (queueReduction > 0) ? 5.0 * std::pow(queueReduction, 1.5) : -1.5;
std::cout << "[DEBUG] Reward computed (Adaptive Scaling): " << reward << std::endl;
// --- Set max green time based on congestion level
float maxGreenTime = 5.f; // Default base max
if (queueNS >= 9 || queueEW >= 9) {
std::cout << "[DEBUG] Extreme congestion detected; reinforcing max green time to 8 sec." << std::endl;
maxGreenTime = 8.f;
} else if (queueNS >= 6 || queueEW >= 6) {
std::cout << "[DEBUG] High congestion detected; capping max green time at 6 sec." << std::endl;
maxGreenTime = 6.f;
}
// --- Now update currentGreenTime so it fully respects the new maxGreenTime.
if (currentGreenTime < maxGreenTime) {
std::cout << "[DEBUG] Increasing green time to match new max limit." << std::endl;
currentGreenTime = maxGreenTime;
} else {
currentGreenTime = std::clamp(currentGreenTime, minGreen, maxGreenTime);
}
// --- Override Action 0 Only If Congestion is Increasing (AFTER setting maxGreenTime)
if ((queueNS >= 6 || queueEW >= 6) && action == 0) {
if (queueNS > prevQueueNS || queueEW > prevQueueEW) { // Override only if congestion is rising
std::cout << "[DEBUG] High congestion worsening; forcing non-zero action." << std::endl;
action = (std::rand() % 2) + 1;
std::cout << "[DEBUG] Overriding RL action to: " << action << std::endl;
}
}
// --- Immediate adjustment if the spawn interval was changed by the user.
if (spawnIntervalChanged) {
std::cout << "[DEBUG] User changed congestion settings, forcing immediate green time update." << std::endl;
if (queueNS >= 9 || queueEW >= 9) {
maxGreenTime = 8.f;
} else if (queueNS >= 6 || queueEW >= 6) {
maxGreenTime = 6.f;
}
currentGreenTime = maxGreenTime; // Immediately apply new max limit
spawnIntervalChanged = false; // Reset the flag
}
// --- Mid-phase congestion adaptation for real-time response.
if (currentGreenTime < maxGreenTime) {
std::cout << "[DEBUG] Adjusting green time dynamically mid-phase!" << std::endl;
currentGreenTime = std::min(currentGreenTime + 1, maxGreenTime);
}
// --- Dynamic Green Time Adjustments based on congestion.
if (queueNS >= 6 || queueEW >= 6) {
std::cout << "[DEBUG] High congestion detected; increasing green time." << std::endl;
currentGreenTime = std::min(currentGreenTime + 1, maxGreenTime);
} else if (queueNS < 3 && queueEW < 3) {
std::cout << "[DEBUG] Low traffic detected; decreasing green time." << std::endl;
currentGreenTime = std::max(currentGreenTime - 1, minGreen + 1); // Avoid reducing too fast
}
// --- Apply the RL-based green time adjustment.
if (action == 1) {
currentGreenTime += 1;
} else if (action == 2) {
currentGreenTime -= 1;
}
// --- Final clamp of currentGreenTime.
currentGreenTime = std::clamp(currentGreenTime, minGreen, maxGreenTime);
std::cout << "[DEBUG] " << phaseLabel << " phase - New green time set to: "
<< currentGreenTime << std::endl;
}
void TrafficManager::setSpawnInterval(float newInterval) {
if (newInterval != spawnInterval) { // Only trigger if the value is actually different
spawnInterval = newInterval;
spawnIntervalChanged = true; // Mark that it has changed
}
}
void TrafficManager::updateLights(float dt) {
phaseTimer += dt;
switch (phase) {
case Phase::NS_Green:
topLeftLight.setState(LightState::Green);
bottomLeftLight.setState(LightState::Green);
topRightLight.setState(LightState::Red);
bottomRightLight.setState(LightState::Red);
if (phaseTimer >= currentGreenTime) {
phase = Phase::NS_Yellow;
phaseTimer = 0.f;
}
break;
case Phase::NS_Yellow:
{
topLeftLight.setState(LightState::Yellow);
bottomLeftLight.setState(LightState::Yellow);
topRightLight.setState(LightState::Red);
bottomRightLight.setState(LightState::Red);
if (phaseTimer >= yellowTime) {
int prevQueueNS = queueNS;
int prevQueueEW = queueEW;
measureQueues();
std::pair<int,int> stateKey = {queueNS, queueEW};
std::cout << "[DEBUG] NS_Yellow phase - QueueNS: " << queueNS
<< ", QueueEW: " << queueEW << std::endl;
applyRLDecision(stateKey, "NS_Yellow", prevQueueNS, prevQueueEW);
phase = Phase::EW_Green;
phaseTimer = 0.f;
}
break;
}
case Phase::EW_Green:
topLeftLight.setState(LightState::Red);
bottomLeftLight.setState(LightState::Red);
topRightLight.setState(LightState::Green);
bottomRightLight.setState(LightState::Green);
if (phaseTimer >= currentGreenTime) {
phase = Phase::EW_Yellow;
phaseTimer = 0.f;
}
break;
case Phase::EW_Yellow:
{
topLeftLight.setState(LightState::Red);
bottomLeftLight.setState(LightState::Red);
topRightLight.setState(LightState::Yellow);
bottomRightLight.setState(LightState::Yellow);
if (phaseTimer >= yellowTime) {
int prevQueueNS = queueNS;
int prevQueueEW = queueEW;
measureQueues();
std::pair<int,int> stateKey = {queueNS, queueEW};
std::cout << "[DEBUG] EW_Yellow phase - QueueNS: " << queueNS
<< ", QueueEW: " << queueEW << std::endl;
applyRLDecision(stateKey, "EW_Yellow", prevQueueNS, prevQueueEW);
phase = Phase::NS_Green;
phaseTimer = 0.f;
}
break;
}
}
topLeftLight.update(dt);
topRightLight.update(dt);
bottomLeftLight.update(dt);
bottomRightLight.update(dt);
}
// Returns true if the vehicle's speed is below the threshold (i.e., it is effectively stopped)
bool isVehicleQueuedBySpeed(Vehicle* v) {
const float SPEED_THRESHOLD = 5.f; // Adjust this value based on your simulation units
return (v->speed < SPEED_THRESHOLD);
}
void TrafficManager::measureQueues() {
queueNS = 0;
queueEW = 0;
// Separate vehicles by direction
std::vector<Vehicle*> topVec, bottomVec, leftVec, rightVec;
for (auto* v : vehicles) {
switch (v->getDirection()) {
case Direction::TopToBottom: topVec.push_back(v); break;
case Direction::BottomToTop: bottomVec.push_back(v); break;
case Direction::LeftToRight: leftVec.push_back(v); break;
case Direction::RightToLeft: rightVec.push_back(v); break;
}
}
// Sort them by position so we can iterate from front to back
std::sort(topVec.begin(), topVec.end(), [](auto* a, auto* b){return a->getY() < b->getY();});
std::sort(bottomVec.begin(), bottomVec.end(),[](auto* a, auto* b){return a->getY() > b->getY();});
std::sort(leftVec.begin(), leftVec.end(), [](auto* a, auto* b){return a->getX() < b->getX();});
std::sort(rightVec.begin(), rightVec.end(),[](auto* a, auto* b){return a->getX() > b->getX();});
// Helper to process each lane
auto processLane = [&](std::vector<Vehicle*>& lane, bool isNS) {
bool frontIsStopped = false;
for (size_t i = 0; i < lane.size(); ++i) {
Vehicle* v = lane[i];
if (shouldStopVehicle(v) || isVehicleQueuedBySpeed(v) || frontIsStopped) {
if (isNS) queueNS++;
else queueEW++;
frontIsStopped = true;
} else {
frontIsStopped = false;
}
}
};
processLane(topVec, true);
processLane(bottomVec, true);
processLane(leftVec, false);
processLane(rightVec, false);
}
void TrafficManager::spawnVehicle() {
int approach = std::rand() % 4;
VehicleType t = VehicleType::Normal;
int r = std::rand() % 8;
switch (r) {
case 0: t = VehicleType::Normal; break;
case 1: t = VehicleType::Taxi; break;
case 2: t = VehicleType::Ambulance; break;
case 3: t = VehicleType::Audi; break;
case 4: t = VehicleType::Truck; break;
case 5: t = VehicleType::Bus; break;
case 6: t = VehicleType::BlackViper; break;
case 7: t = VehicleType::BigTruck; break;
}
Vehicle* v = nullptr;
if (approach == 0) {
v = new Vehicle(sf::Vector2f(390.f, -50.f), t, Direction::TopToBottom);
} else if (approach == 1) {
v = new Vehicle(sf::Vector2f(500.f, 650.f), t, Direction::BottomToTop);
} else if (approach == 2) {
v = new Vehicle(sf::Vector2f(-50.f, 250.f), t, Direction::LeftToRight);
} else {
v = new Vehicle(sf::Vector2f(950.f, 350.f), t, Direction::RightToLeft);
}
vehicles.push_back(v);
}
bool TrafficManager::shouldStopVehicle(Vehicle* v)
{
// If the vehicle has been stopped for at least 2 seconds, count it as queued
// (this helps catch vehicles that remain stopped even after crossing the line).
if (v->stoppedTime >= 2.0f) {
return true;
}
float x = v->getX();
float y = v->getY();
Direction d = v->getDirection();
// If the vehicle was already marked as having passed the stop line
// AND it's not forced to stop, we won't count it as queued anymore.
// (Because typically it has cleared or is clearing the intersection.)
if (v->hasPassedStopLine()) {
return false;
}
// Otherwise, check each approach with your existing thresholds:
if (d == Direction::TopToBottom) {
// Once y > 150.f, the vehicle is at/near the intersection
if (y > 150.f) {
LightState s = topLeftLight.getState();
// If red or yellow, the vehicle must stop => still queued
if (s == LightState::Red || s == LightState::Yellow) {
return true;
} else {
// Green => let it pass, mark as passedStopLine
v->setPassedStopLine(true);
return false;
}
}
}
else if (d == Direction::BottomToTop) {
if (y < 450.f) {
LightState s = bottomLeftLight.getState();
if (s == LightState::Red || s == LightState::Yellow) {
return true;
} else {
v->setPassedStopLine(true);
return false;
}
}
}
else if (d == Direction::LeftToRight) {
if (x > 300.f) {
LightState s = topRightLight.getState();
if (s == LightState::Red || s == LightState::Yellow) {
return true;
} else {
v->setPassedStopLine(true);
return false;
}
}
}
else { // RightToLeft
if (x < 605.f) {
LightState s = bottomRightLight.getState();
if (s == LightState::Red || s == LightState::Yellow) {
return true;
} else {
v->setPassedStopLine(true);
return false;
}
}
}
// If none of the above conditions apply (vehicle not near intersection), it's not queued
return false;
}
void TrafficManager::update(float dt) {
updateLights(dt);
spawnTimer += dt;
if (spawnTimer >= spawnInterval) {
spawnVehicle();
spawnTimer = 0.f;
}
float minDistance = 80.f;
std::vector<Vehicle*> topVec, bottomVec, leftVec, rightVec;
for (auto* veh : vehicles) {
switch (veh->getDirection()) {
case Direction::TopToBottom: topVec.push_back(veh); break;
case Direction::BottomToTop: bottomVec.push_back(veh); break;
case Direction::LeftToRight: leftVec.push_back(veh); break;
case Direction::RightToLeft: rightVec.push_back(veh); break;
}
}
std::sort(topVec.begin(), topVec.end(), [](Vehicle* a, Vehicle* b) {
return a->getY() < b->getY();
});
std::sort(bottomVec.begin(), bottomVec.end(), [](Vehicle* a, Vehicle* b) {
return a->getY() > b->getY();
});
std::sort(leftVec.begin(), leftVec.end(), [](Vehicle* a, Vehicle* b) {
return a->getX() < b->getX();
});
std::sort(rightVec.begin(), rightVec.end(), [](Vehicle* a, Vehicle* b) {
return a->getX() > b->getX();
});
auto updateGroup = [&](std::vector<Vehicle*>& group, bool vertical) {
for (size_t i = 0; i < group.size(); ++i) {
Vehicle* current = group[i];
bool canMove = true;
if (shouldStopVehicle(current))
canMove = false;
if (i + 1 < group.size()) {
Vehicle* front = group[i + 1];
float dist = vertical ? (front->getY() - current->getY())
: (front->getX() - current->getX());
if (dist < 0) dist = -dist;
if (dist < minDistance)
canMove = false;
}
if (canMove)
current->update(dt, vehicleSpeed);
}
};
updateGroup(topVec, true);
updateGroup(bottomVec, true);
updateGroup(leftVec, false);
updateGroup(rightVec, false);
vehicles.erase(
std::remove_if(vehicles.begin(), vehicles.end(), [&](Vehicle* v) {
float xx = v->getX();
float yy = v->getY();
if (xx < -50.f || xx > 950.f || yy < -50.f || yy > 650.f) {
delete v;
return true;
}
return false;
}),
vehicles.end()
);
}
void TrafficManager::render(sf::RenderWindow& window) {
topLeftLight.render(window);
topRightLight.render(window);
bottomLeftLight.render(window);
bottomRightLight.render(window);
for (auto* v : vehicles)
v->render(window);
}
size_t TrafficManager::getVehicleCount() const {
return vehicles.size();
}