EventManager.cpp 10.6 KB
Newer Older
1
#include "EventManager.h"
2 3 4

using namespace std;

5 6 7 8
/*******************
 Konstruktoren
 ******************/

Ulrich Kemloh's avatar
Ulrich Kemloh committed
9 10 11
#define UPDATE_FREQUENCY 1 // in seconds


12
EventManager::EventManager(Building *_b){
13
    _event_times=vector<double>();
14 15 16
    _event_types=vector<string>();
    _event_states=vector<string>();
    _event_ids=vector<int>();
17
    _projectFilename = "";
18
    _building = _b;
19 20
    _eventCounter=0;
    _dynamic=false;
21
    _file = fopen("../events/events.txt","r");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
22
    _lastUpdateTime=0;
23
    if(!_file){
24
        Log->Write("INFO:\tDatei events.txt nicht gefunden. Dynamisches Eventhandling nicht moeglich.");
25 26
    }
    else{
27
        Log->Write("INFO:\tDatei events.txt gefunden. Dynamisches Eventhandling moeglich.");
28 29
        _dynamic=true;
    }
30
}
31

32 33 34 35 36 37
/*******************
 Dateien einlesen
 ******************/
void EventManager::SetProjectFilename(const std::string &filename){
    _projectFilename=filename;
}
38

39 40 41 42 43
void EventManager::SetProjectRootDir(const std::string &filename){
    _projectRootDir= filename;
}

void EventManager::readEventsXml(){
44
    Log->Write("INFO: \tReading events\n ");
45 46 47
    //get the geometry filename from the project file
    TiXmlDocument doc(_projectFilename);
    if (!doc.LoadFile()){
48
        Log->Write("ERROR: \t%s", doc.ErrorDesc());
49
        Log->Write("ERROR: \t could not parse the project file. ");
50
        exit(EXIT_FAILURE);
51 52
    }

53
    Log->Write("INFO: \tParsing the event file");
54 55 56 57
    TiXmlElement* xMainNode = doc.RootElement();
    string eventfile="";
    if(xMainNode->FirstChild("events")){
        eventfile=_projectRootDir+xMainNode->FirstChild("events")->FirstChild()->Value();
58
        Log->Write("INFO: \tevents <"+eventfile+">");
59
    }
60 61 62

    TiXmlDocument docEvent(eventfile);
    if(!docEvent.LoadFile()){
63
        Log->Write("EROOR: \t%s",docEvent.ErrorDesc());
64 65 66
        Log->Write("ERROR: \t could not parse the event file. So no Events are found.");
        //exit(EXIT_FAILURE);
        return;
67 68 69 70
    }

    TiXmlElement* xRootNode = docEvent.RootElement();
    if(!xRootNode){
71
        Log->Write("ERROR:\tRoot element does not exist.");
72 73 74 75
        exit(EXIT_FAILURE);
    }

    if( xRootNode->ValueStr () != "JPScore" ) {
76
        Log->Write("ERROR:\tRoot element value is not 'JPScore'.");
77 78 79 80
        exit(EXIT_FAILURE);
    }

    TiXmlNode* xEvents = xRootNode->FirstChild("events");
81
    if(!xEvents){
82
        Log->Write("ERROR:\tNo events found.");
83
        exit(EXIT_FAILURE);
84 85 86
    }
    
    for(TiXmlElement* e = xEvents->FirstChildElement("event"); e; e= e->NextSiblingElement("event")){
87
        _event_times.push_back(atoi(e->Attribute("time")));
88 89 90
        _event_types.push_back(e->Attribute("type"));
        _event_states.push_back(e->Attribute("state"));
        _event_ids.push_back(atoi(e->Attribute("id")));
91
    }
92
    Log->Write("INFO: \tEvents were read\n");
93 94 95
}

void EventManager::listEvents(){
96
    if(_event_times.size()==0){
97
        Log->Write("INFO: \tNo events in the events.xml");
98 99
    }
    else{
100
        char buf[10],buf2[10];
101
        for(unsigned int i=0;i<_event_times.size();i++){
102 103 104
            sprintf(buf,"%f",_event_times[i]);
            sprintf(buf2,"%d",_event_ids[i]);
            Log->Write("INFO: \tAfter "+string(buf)+" sec: "+_event_types[i]+" "+string(buf2)+" "+_event_states[i]);
105 106 107 108 109
        }
    }

}

110
void EventManager::readEventsTxt(double time){
111
    rewind(_file);
112 113
    char cstring[256];
    int lines=0;
114 115 116 117 118 119 120 121 122
    do{
        fgets(cstring,30,_file);
        if(cstring[0]!='#'){// keine Kommentarzeile
            lines++;
            if(lines>_eventCounter){
                Log->Write("INFO:\tEvent: after %f sec: ",time);
                getTheEvent(cstring);
                _eventCounter++;
            }
123
        }
124
     }while (feof(_file)==0);
125 126
}

127 128 129 130
/***********
 Update
 **********/

131
void EventManager::Update_Events(double time, double d){
Ulrich Kemloh's avatar
Ulrich Kemloh committed
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
     //1. pruefen ob in _event_times der zeitstempel time zu finden ist. Wenn ja zu 2. sonst zu 3.
     //2. Event aus _event_times und _event_values verarbeiten (Tuere schliessen/oeffnen, neues Routing)
     //   Dann pruefen, ob eine neue Zeile in der .txt Datei steht
     //3. .txt Datei auf neue Zeilen pruefen. Wenn es neue gibt diese Events verarbeiten ( Tuere schliessen/oeffnen,
     //   neues Routing) ansonsten fertig

     _deltaT=d;
     vector<Pedestrian*> _allPedestrians=_building->GetAllPedestrians();
     int nSize = _allPedestrians.size();

     //zuerst muss geprueft werden, ob die Peds, die die neuen Infos schon haben sie an andere Peds weiter-
     //leiten muessen (wenn diese sich in der naechsten Umgebung befinden)
     int currentTime = _allPedestrians[0]->GetGlobalTime();
     if(currentTime!=_lastUpdateTime)
          if((currentTime%UPDATE_FREQUENCY)==0) {
               for(int p=0;p<nSize;p++){
                    if(_allPedestrians[p]->GetNewEventFlag()){
                         int rID = _allPedestrians[p]->GetRoomID();
                         int srID = _allPedestrians[p]->GetSubRoomID();
                         Room* room = _building->GetRoom(rID);
                         SubRoom* sub = room->GetSubRoom(srID);//Nur Infos an Leute im gleichen Raum weitergeben
                         for (int k = 0; k < sub->GetNumberOfPedestrians(); k++) {
                              Pedestrian* ped = sub->GetPedestrian(k);
                              if(!ped->GetNewEventFlag()&&ped->GetReroutingTime()>2.0){
                                   //wenn der Pedestrian die neuen Infos noch nicht hat und eine Reroutingtime von > 2 Sekunden hat, pruefen ob er nah genug ist
                                   Point pos1 = _allPedestrians[p]->GetPos();
                                   Point pos2 = ped->GetPos();
                                   double distX = pos1.GetX()-pos2.GetX();
                                   double distY = pos1.GetY()-pos2.GetY();
                                   double dist = sqrt(distX*distX+distY*distY);
                                   if(dist<=J_EPS_INFO_DIST){// wenn er nah genug (weniger als 2m) ist, Info weitergeben (Reroutetime auf 2 Sek)
                                        //ped->RerouteIn(2.0);
                                        ped->RerouteIn(0.0);
                                   }
                              }
                         }
168
                    }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
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
               }
               _lastUpdateTime=currentTime;
               //cout<<"updating..."<<currentTime<<endl<<endl;
          }

     //dann muss die Reroutingzeit der Peds, die die neuen Infos noch nicht haben, aktualisiert werden:
     for(int p=0;p<nSize;p++){
          //if(!_allPedestrians[p]->GetNewEventFlag()){
          _allPedestrians[p]->UpdateReroutingTime();
          if(_allPedestrians[p]->IsReadyForRerouting()){
               _allPedestrians[p]->ClearMentalMap();
               _allPedestrians[p]->ResetRerouting();
               _allPedestrians[p]->SetNewEventFlag(true);
          }
          //}
     }

     //Events finden
     for(unsigned int i=0;i<_event_times.size();i++){
          if(fabs(_event_times[i]-time)<J_EPS_EVENT){
               //Event findet statt
               Log->Write("INFO:\tEvent: after %f sec: ",time);
               if(_event_states[i].compare("close")==0){
                    closeDoor(_event_ids[i]);
               }
               else{
                    openDoor(_event_ids[i]);
               }
          }
     }
     if(_dynamic)
          readEventsTxt(time);
201 202 203 204 205 206 207 208 209 210
}

/***************
 Eventhandling
 **************/
void EventManager::closeDoor(int id){
    //pruefen ob entsprechende Tuer schon zu ist, wenn nicht dann schliessen und neues Routing berechnen
    Transition *t=_building->GetTransition(id);
    if(t->IsOpen()){
        t->Close();
211
        Log->Write("\tDoor %d closed.",id);
212
        changeRouting(id,"close");
213
    }
214
    else{
215
        Log->Write("Door %d is already close yet.", id);
216
    }
217 218 219 220 221 222 223 224

}

void EventManager::openDoor(int id){
    //pruefen ob entsprechende Tuer schon offen ist, wenn nicht dann oeffnen und neues Routing berechnen
    Transition *t=_building->GetTransition(id);
    if(!t->IsOpen()){
        t->Open();
225
        Log->Write("\tDoor %d opened.",id);
226 227 228
        changeRouting(id,"open");
    }
    else{
229
        Log->Write("Door %d is already open yet.", id);
230 231 232
    }
}

233 234 235 236 237 238
void EventManager::changeRouting(int id, string state){
    RoutingEngine* routingEngine= _building->GetRoutingEngine();
    routingEngine->Init(_building);
    _building->InitPhiAllPeds(_deltaT);
    vector<Pedestrian*> _allPedestrians=_building->GetAllPedestrians();
    unsigned int nSize = _allPedestrians.size();
239

240 241
    //Pedestrians sollen, damit es realitaetsnaeher wird, je nachdem wo sie stehen erst spaeter(abh. von der
    //Entfernung zur Tuer) merken, dass sich Tueren aendern. Oder sie bekommen die Info von anderen Pedestrians
242
    Transition *t = _building->GetTransition(id);
243
    //Abstand der aktuellen Position des Pedestrians zur entsprechenden Tuer: Tuer als Linie sehen und mit
244
    //DistTo(ped.GetPos()) den Abstand messen. Reroutezeit dann aus Entfernung und Geschwindigkeit berechnen.
245
    Line* l = new Line(t->GetPoint1(),t->GetPoint2());
246
    for (unsigned int p = 0; p < nSize; ++p) {
247
        //if(_allPedestrians[p]->GetExitIndex()==t->GetUniqueID()){
248
        _allPedestrians[p]->SetNewEventFlag(false);
249
        double dist = l->DistTo(_allPedestrians[p]->GetPos());
250 251
        Point v = _allPedestrians[p]->GetV();
        double norm =sqrt((v.GetX()*v.GetX())+(v.GetY()*v.GetY()));
252
        if(norm==0.0){
253
            norm=0.01;
254
        }
255 256 257 258
        double time = dist/norm;
        if(time<1.0){
            _allPedestrians[p]->ClearMentalMap();
            _allPedestrians[p]->ResetRerouting();
259
            _allPedestrians[p]->SetNewEventFlag(true);
260 261
        }
        else{
262
            _allPedestrians[p]->RerouteIn(time);
263
        }
264 265 266 267 268 269 270 271 272
        //if(dist>0.0&&dist<0.5){
          // _allPedestrians[p]->ClearMentalMap();
        //}
        //else if(dist>=0.5&&dist<3.0){
          // _allPedestrians[p]->RerouteIn(1.0);
        //}
        //else{
          // _allPedestrians[p]->RerouteIn(2.0);
        //}
273 274 275 276
        //}
        //else{
          //  _allPedestrians[p]->ClearMentalMap();
        //}
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
    }
}

void EventManager::getTheEvent(char* c){
    int split = 0;
    string type = "";
    string id = "";
    string state = "";
    for(int i=0;i<20;i++){
        if(c[i]==NULL){
            break;
        }
        else if(c[i]==' '){
            split++;
        }
        else if(c[i]=='\n'){

        }
        else{
            if(split==0){
                type+=c[i];
            }
            else if(split==1){
                id+=c[i];
            }
            else if(split==2){
                state+=c[i];
            }
        }

    }
    if(state.compare("close")==0){
        closeDoor(atoi(id.c_str()));
    }
    else{
        openDoor(atoi(id.c_str()));
313
    }
314
}