forked from n1ay/3D-Traffic-Simulation-Model
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCrossroad.cpp
106 lines (90 loc) · 2.31 KB
/
Crossroad.cpp
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
/*
* Crossroad.cpp
*
* Created on: 04.12.2016
* Author: kamil
*/
#include "Crossroad.hpp"
#include <iostream>
#include "Car.hpp"
#include "Road.hpp"
Crossroad::Crossroad() {
}
Crossroad::~Crossroad() {
}
void Crossroad::addRule(Lane* from, std::vector<std::pair<Lane*, int> > rule) {
int sum = 0;
for(auto& iter: rule)
sum += iter.second;
if(sum != 100) {
std::cerr<<"Cumulative probability of all possibilities have to sum up to 100!"<<std::endl;
exit(-1);
}
rules.insert(std::pair<Lane*, std::vector<std::pair<Lane*, int> > >(from, rule));
}
void Crossroad::setDestination(Lane* from) {
Car* car = from->getCar(from->getLength()-1);
if(!car || car->getDestination()) return;
int cumulativeProbability = 0;
auto vec = rules.find(from);
if(vec == rules.end()) return;
int r = rand()%100;
for(auto& iter: vec->second) {
cumulativeProbability += iter.second;
if(r<cumulativeProbability) {
car->setDestination(iter.first);
return;
}
}
}
void Crossroad::transfer(Lane* from) {
Car* car = from->getCar(from->getLength()-1);
TrafficLight::LightColor color;
color = (from->getTrafficLight()==nullptr)?(TrafficLight::GREEN):(from->getTrafficLight()->getLightColor());
if(!car || !car->getDestination() || color==TrafficLight::RED || car->getDestination()->isUsed(0, 1)) return;
car->getDestination()->putCar(car, 0);
from->putCar(nullptr, from->getLength()-1);
car->setLane(car->getDestination());
car->setPosition(0);
car->setDestination(nullptr);
}
void Crossroad::transferAll() {
for(auto& iter: rules) {
setDestination(iter.first);
transfer(iter.first);
}
}
std::ostream & operator<< (std::ostream & ostr, Crossroad & crossroad) {
for(auto& iter: crossroad.roads) {
ostr<<*iter;
ostr<<"==============================\n";
ostr<<"==============================\n";
}
return ostr;
}
void Crossroad::addRoad(Road* road) {
for(auto r: roads) {
if(r==road)
return;
}
roads.push_back(road);
}
void Crossroad::update() {
for(auto& iter: roads)
iter->update();
}
void Crossroad::allowUpdate() {
for(auto& iter: roads)
iter->allowUpdate();
}
void Crossroad::lockUpdate() {
for(auto& iter: roads)
iter->lockUpdate();
}
void Crossroad::cleanUpdate() {
for(auto& iter: roads)
iter->cleanUpdate();
}
void Crossroad::setIntersection(bool intersects) {
this->intersects=intersects;
}