EventManager.cpp 21.8 KB
Newer Older
Ulrich Kemloh's avatar
Ulrich Kemloh committed
1 2 3
/**
 * \file        EventManager.cpp
 * \date        Jul 4, 2014
4 5
 * \version     v0.7
 * \copyright   <2009-2015> Forschungszentrum Jülich GmbH. All rights reserved.
Ulrich Kemloh's avatar
Ulrich Kemloh committed
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
 *
 * \section License
 * This file is part of JuPedSim.
 *
 * JuPedSim is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * JuPedSim is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with JuPedSim. If not, see <http://www.gnu.org/licenses/>.
 *
 * \section Description
 *
 *
 **/


#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
33
#include <algorithm>
Ulrich Kemloh's avatar
Ulrich Kemloh committed
34 35 36 37
#include <fstream>
#include <vector>
#include <math.h>
#include <stdio.h>
38
#include "../pedestrian/Pedestrian.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
39
#include "../pedestrian/Knowledge.h"
40
#include "../mpi/LCGrid.h"
Ulrich Kemloh's avatar
Ulrich Kemloh committed
41 42 43 44 45 46 47 48
#include "../geometry/Building.h"
#include "../geometry/SubRoom.h"
#include "../geometry/Transition.h"
#include "../geometry/Point.h"
#include "../tinyxml/tinyxml.h"
#include "../IO/OutputHandler.h"
#include "../IO/IODispatcher.h"
#include "../routing/RoutingEngine.h"
49 50 51 52 53 54
#include "../routing/GlobalRouter.h"
#include "../routing/QuickestPathRouter.h"
#include "../routing/MeshRouter.h"
#include "../routing/DummyRouter.h"
#include "../routing/SafestPathRouter.h"
#include "../routing/CognitiveMapRouter.h"
55
#include "EventManager.h"
56 57 58

using namespace std;

59
/*******************
Ulrich Kemloh's avatar
Ulrich Kemloh committed
60
 constructors
61 62
 ******************/

Ulrich Kemloh's avatar
Ulrich Kemloh committed
63 64 65 66 67 68 69 70 71 72
EventManager::EventManager(Building *_b)
{
     _event_times = vector<double>();
     _event_types = vector<string>();
     _event_states = vector<string>();
     _event_ids = vector<int>();
     _building = _b;
     _eventCounter = 0;
     _dynamic = false;
     _lastUpdateTime = 0;
73 74 75
     //_deltaT = 0;
     _projectFilename=_building->GetProjectFilename();
     _projectRootDir=_building->GetProjectRootDir();
76 77
     _updateFrequency =1 ;//seconds
     _updateRadius =2;//meters
78
     _file = fopen("../events/events.txt", "r");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
79
     if (!_file) {
80 81
          Log->Write("INFO:\tFiles 'events.txt' missing. "
                    "Realtime interaction with the simulation not possible.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
82
     } else {
83
          Log->Write("INFO:\tFile 'events.txt' will be monitored for new events.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
84 85
          _dynamic = true;
     }
86

87 88
     //save the first graph
     CreateRoutingEngine(_b, true);
89 90
}

91 92 93 94
EventManager::~EventManager()
{
     if(_file)
          fclose(_file);
95 96

     _eventEngineStorage.clear();
97 98
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
99
bool EventManager::ReadEventsXml()
Ulrich Kemloh's avatar
Ulrich Kemloh committed
100
{
101
     Log->Write("INFO: \tLooking for pre-defined events in other files");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
102 103
     //get the geometry filename from the project file
     TiXmlDocument doc(_projectFilename);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
104
     if (!doc.LoadFile()) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
105 106
          Log->Write("ERROR: \t%s", doc.ErrorDesc());
          Log->Write("ERROR: \t could not parse the project file.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
107
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
108 109 110
     }

     TiXmlElement* xMainNode = doc.RootElement();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
111
     string eventfile = "";
Ulrich Kemloh's avatar
Ulrich Kemloh committed
112
     if (xMainNode->FirstChild("events_file")) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
113
          eventfile = _projectRootDir
114
                    + xMainNode->FirstChild("events_file")->FirstChild()->Value();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
115 116
          Log->Write("INFO: \tevents <" + eventfile + ">");
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
117
          Log->Write("INFO: \tNo events found");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
118
          return true;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
119 120 121 122
     }

     Log->Write("INFO: \tParsing the event file");
     TiXmlDocument docEvent(eventfile);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
123 124
     if (!docEvent.LoadFile()) {
          Log->Write("ERROR: \t%s", docEvent.ErrorDesc());
Ulrich Kemloh's avatar
Ulrich Kemloh committed
125
          Log->Write("ERROR: \t could not parse the event file.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
126
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
127 128 129
     }

     TiXmlElement* xRootNode = docEvent.RootElement();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
130
     if (!xRootNode) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
131
          Log->Write("ERROR:\tRoot element does not exist.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
132
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
133 134
     }

Ulrich Kemloh's avatar
Ulrich Kemloh committed
135
     if (xRootNode->ValueStr() != "JPScore") {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
136
          Log->Write("ERROR:\tRoot element value is not 'JPScore'.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
137
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
138 139 140
     }

     TiXmlNode* xEvents = xRootNode->FirstChild("events");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
141
     if (!xEvents) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
142
          Log->Write("ERROR:\tNo events found.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
143
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
144
     }
145
     _updateFrequency = xmltoi(xEvents->ToElement()->Attribute("update_time"), 1);
146 147 148
     _updateRadius = xmltoi(xEvents->ToElement()->Attribute("update_radius"), 2);

     //Pedestrian::SetColorMode(BY_SPOTLIGHT);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
149

Ulrich Kemloh's avatar
Ulrich Kemloh committed
150 151
     for (TiXmlElement* e = xEvents->FirstChildElement("event"); e;
               e = e->NextSiblingElement("event")) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
152 153 154 155 156
          _event_times.push_back(atoi(e->Attribute("time")));
          _event_types.push_back(e->Attribute("type"));
          _event_states.push_back(e->Attribute("state"));
          _event_ids.push_back(atoi(e->Attribute("id")));
     }
157
     Log->Write("INFO: \tEvents were initialized");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
158
     return true;
159 160
}

161

Ulrich Kemloh's avatar
Ulrich Kemloh committed
162
void EventManager::ListEvents()
163
{
164 165 166 167
     for (unsigned int i = 0; i < _event_times.size(); i++)
     {
          Log->Write("INFO: \tAfter %.2f sec, %s door %d", _event_times[i],
                    _event_states[i].c_str(), _event_ids[i]);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
168
     }
169 170
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
171 172 173 174 175 176 177 178 179 180
void EventManager::ReadEventsTxt(double time)
{
     rewind(_file);
     char cstring[256];
     int lines = 0;
     do {
          if (fgets(cstring, 30, _file) == NULL) {
               Log->Write("WARNING: \tCould not read the event file");
               return;
          }
181
          if (cstring[0] != '#') {// skip comments
Ulrich Kemloh's avatar
Ulrich Kemloh committed
182 183
               lines++;
               if (lines > _eventCounter) {
184
                    Log->Write("INFO:\tEvent: after %.2f sec: ", time);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
185 186 187 188 189
                    GetEvent(cstring);
                    _eventCounter++;
               }
          }
     } while (feof(_file) == 0);
190 191
}

192 193 194
/***********
 Update
 **********/
195 196
bool EventManager::UpdateAgentKnowledge(Building* _b)
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
197
//#pragma omp parallel
198 199 200 201
     for(auto&& ped:_b->GetAllPedestrians())
     {
          for (auto&& door: _b->GetAllTransitions())
          {
202
               if(door.second->DistTo(ped->GetPos())<1)//distance to door to register its state
203 204 205
               {
                    //actualize the information about the newly closed door
                    if(door.second->IsOpen()==false)
206
                    {
207
                         ped->AddKnownClosedDoor(door.first, Pedestrian::GetGlobalTime());
208 209
                         ped->SetNewEventFlag(true);

210
                    }
211 212 213 214
               }
          }
     }

215 216 217 218
     //collect the peds that are allowed to forward the information.
     vector<Pedestrian*> informant;
     for(auto&& ped:_b->GetAllPedestrians())
     {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
219 220
          if (ped->GetNewEventFlag())
               informant.push_back(ped);
221
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
222

223 224

     for(auto&& ped1:informant)
225 226 227 228 229
     {
          vector<Pedestrian*> neighbourhood;
          _b->GetGrid()->GetNeighbourhood(ped1,neighbourhood);
          for(auto&& ped2:neighbourhood)
          {
230
               if( (ped1->GetPos()-ped2->GetPos()).Norm()<_updateRadius)
231 232
               {
                    //maybe same room and subroom ?
233 234
                    vector<SubRoom*> empty;
                    if(_b->IsVisible(ped1->GetPos(),ped2->GetPos(),empty))
Ulrich Kemloh's avatar
Ulrich Kemloh committed
235 236 237 238
                    {
                         MergeKnowledge(ped1, ped2);  //ped1->SetSpotlight(true);
                         ped2->SetNewEventFlag(true);
                    }
239 240 241 242
               }
          }
     }

Ulrich Kemloh's avatar
Ulrich Kemloh committed
243 244 245
     //TODO: what happen when they all have the new event flag ? reset maybe?
     if(informant.size()==_b->GetAllPedestrians().size())
     {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
246

Ulrich Kemloh's avatar
Ulrich Kemloh committed
247 248 249 250
          for(auto&& ped:_b->GetAllPedestrians())
               ped->SetNewEventFlag(false);
     }

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
     // information speed to fast
//     for(auto&& ped1:_b->GetAllPedestrians())
//     {
//          vector<Pedestrian*> neighbourhood;
//          _b->GetGrid()->GetNeighbourhood(ped1,neighbourhood);
//          for(auto&& ped2:neighbourhood)
//          {
//               if( (ped1->GetPos()-ped2->GetPos()).Norm()<_updateRadius)
//               {
//                    //maybe same room and subroom ?
//                    if(_b->IsVisible(ped1->GetPos(),ped2->GetPos()))
//                    MergeKnowledge(ped1, ped2);  //ped1->SetSpotlight(true);
//               }
//          }
//     }

267 268 269 270 271 272 273 274 275
     //update the routers based on the configurations
     //#pragma omp parallel
     for(auto&& ped:_b->GetAllPedestrians())
     {
          if(UpdateRoute(ped)==false)
          {
               //Clear the memory and attempt to reroute
               //this can happen if all doors are known to be closed
               ped->ClearKnowledge();
276
               //Log->Write("ERROR: \t clearing ped knowledge");
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
               if(UpdateRoute(ped)==false)
               {
                    Log->Write("ERROR: \t cannot reroute the pedestrian. unknown problem");
                    //return false;
                    exit(EXIT_FAILURE);
               }
          }
     }
     return true;
}

bool EventManager::UpdateRoute(Pedestrian* ped)
{
     //create the key as string.
     //map are sorted by default
292
     string key= ped->GetKnowledgeAsString();
293 294 295 296 297 298 299 300 301 302 303
     //get the router engine corresponding to the actual configuration
     bool status=true;
     if (_eventEngineStorage.count(key)>0)
     {
          RoutingEngine* engine=_eventEngineStorage[key];
          //retrieve the old strategy
          RoutingStrategy strategy=ped->GetRouter()->GetStrategy();
          //retrieve the new router
          Router*rout =engine->GetRouter(strategy);
          //check for validity
          ped->SetRouter(rout);
304 305
          //clear all previous routes
          ped->ClearMentalMap();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
306
          //ped->ClearKnowledge();
307 308 309 310 311
          //overwrite/update the pedestrian router
          if(!rout) status= false;
     }
     else
     {
312 313
          //Log->Write("WARNING: \t unknown configuration <%s>", key.c_str());
          //Log->Write("WARNING: \t  [%d] router available", _eventEngineStorage.size());
Ulrich Kemloh's avatar
Ulrich Kemloh committed
314 315
          //Log->Write("       : \t trying to create");
          //CreateRoutingEngine(_building);
316 317 318 319 320 321 322
          status= false;
     }
     return status;
}

void EventManager::MergeKnowledge(Pedestrian* p1, Pedestrian* p2)
{
323 324
     auto const & old_info1 = p1->GetKnownledge();
     auto const & old_info2 = p2->GetKnownledge();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
325
     map<int, Knowledge> merge_info;
326 327 328 329 330 331 332

     //collect the most recent knowledge
     for (auto&& info1 : old_info1)
     {
          merge_info[info1.first] = info1.second;
     }

333
     for (auto&& info2 : old_info2)
334 335
     {
          //update infos according to a newest time
336
          if (merge_info.count(info2.first) > 0)
337
          {
338
               if (info2.second.GetTime() > merge_info[info2.first].GetTime())
339
               {
340
                    merge_info[info2.first] = info2.second;
341 342
               }
          }
343
          else //the info was not present, just add
344
          {
345
               merge_info[info2.first] = info2.second;
346 347 348 349 350 351 352 353
          }
     }

     //synchronize the knowledge
     p1->ClearKnowledge();
     p2->ClearKnowledge();
     for (auto&& info : merge_info)
     {
354 355
          p1->AddKnownClosedDoor(info.first, info.second.GetTime());
          p2->AddKnownClosedDoor(info.first, info.second.GetTime());
356 357 358 359 360 361 362 363 364 365
     }
}

void EventManager::ProcessEvent()
{
     if (_event_times.size() == 0) return;

     int current_time = Pedestrian::GetGlobalTime();

     if ( (current_time != _lastUpdateTime) &&
366
               ((current_time % _updateFrequency) == 0))
367 368 369 370
     {
          //update knowledge about closed doors
          //share the information between the pedestrians
          UpdateAgentKnowledge(_building);
371
          //cout<<"updating buildling..."<<endl;
372 373 374 375 376 377 378 379 380 381 382 383
          //actualize based on the new knowledge
          _lastUpdateTime = current_time;
          //cout<<"updating..."<<currentTime<<endl<<endl;
     }

     //update the building state
     // the time is needed as double
     double current_time_d = Pedestrian::GetGlobalTime();
     for (unsigned int i = 0; i < _event_times.size(); i++)
     {
          if (fabs(_event_times[i] - current_time_d) < J_EPS_EVENT) {
               //Event with current time stamp detected
384
               Log->Write("INFO:\tEvent: after %.2f sec: ", current_time_d);
385 386 387 388 389 390 391 392 393 394 395 396 397 398
               if (_event_states[i].compare("close") == 0) {
                    CloseDoor(_event_ids[i]);
               } else {
                    OpenDoor(_event_ids[i]);
               }
          }
     }

     if (_dynamic)
          ReadEventsTxt(current_time);
}


void EventManager::Update_Events(double time )
Ulrich Kemloh's avatar
Ulrich Kemloh committed
399
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
400 401 402 403 404 405
     //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

406
     //_deltaT = d;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
407
     const vector<Pedestrian*>& _allPeds = _building->GetAllPedestrians();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
408 409 410

     //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)
411 412 413 414
     //int currentTime = _allPeds[0]->GetGlobalTime();
     int currentTime = Pedestrian::GetGlobalTime();

     if ( (currentTime != _lastUpdateTime) &&
415
               ((currentTime % _updateFrequency) == 0))
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
     {
          for (unsigned int p1 = 0; p1 < _allPeds.size(); p1++) {
               Pedestrian* ped1 = _allPeds[p1];
               if (ped1->GetNewEventFlag()) {
                    int rID = ped1->GetRoomID();
                    int srID = ped1->GetSubRoomID();

                    for (unsigned int p2 = 0; p2 < _allPeds.size(); p2++) {
                         Pedestrian* ped2 = _allPeds[p2];
                         //same room and subroom
                         if (rID == ped2->GetRoomID()
                                   && srID == ped2->GetSubRoomID()) {
                              if (!ped2->GetNewEventFlag()
                                        && ped2->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
                                   double dist= (ped1->GetPos()-ped2->GetPos()).Norm();

434
                                   if (dist <= _updateRadius) { // wenn er nah genug (weniger als 2m) ist, Info weitergeben (Reroutetime auf 2 Sek)
435 436
                                        //ped->RerouteIn(2.0);
                                        ped2->RerouteIn(0.0);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
437 438 439
                                   }
                              }
                         }
440
                    }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
441 442
               }
          }
443 444 445
          _lastUpdateTime = currentTime;
          //cout<<"updating..."<<currentTime<<endl<<endl;
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
446 447

     //dann muss die Reroutingzeit der Peds, die die neuen Infos noch nicht haben, aktualisiert werden:
Ulrich Kemloh's avatar
Ulrich Kemloh committed
448
     for (unsigned int p1 = 0; p1 < _allPeds.size(); p1++) {
449 450
          Pedestrian* ped1 = _allPeds[p1];
          ped1->UpdateReroutingTime();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
451
          if (ped1->IsReadyForRerouting()) {
452 453 454
               ped1->ClearMentalMap();
               ped1->ResetRerouting();
               ped1->SetNewEventFlag(true);
455
               ped1->SetSpotlight(true);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
456 457 458 459
          }
     }

     //Events finden
Ulrich Kemloh's avatar
Ulrich Kemloh committed
460 461
     for (unsigned int i = 0; i < _event_times.size(); i++) {
          if (fabs(_event_times[i] - time) < J_EPS_EVENT) {
462
               //Event with current time stamp detected
463
               Log->Write("INFO:\tEvent: after %.2f sec: ", time);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
464 465 466 467
               if (_event_states[i].compare("close") == 0) {
                    CloseDoor(_event_ids[i]);
               } else {
                    OpenDoor(_event_ids[i]);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
468 469 470
               }
          }
     }
471

Ulrich Kemloh's avatar
Ulrich Kemloh committed
472 473
     if (_dynamic)
          ReadEventsTxt(time);
474 475 476
}

/***************
477
 Event handling
478
 **************/
Ulrich Kemloh's avatar
Ulrich Kemloh committed
479
//close the door if it was open and relaunch the routing procedure
Ulrich Kemloh's avatar
Ulrich Kemloh committed
480 481 482 483 484
void EventManager::CloseDoor(int id)
{
     Transition *t = _building->GetTransition(id);
     if (t->IsOpen()) {
          t->Close();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
485
          Log->Write("INFO:\tClosing door %d ", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
486 487
          ChangeRouting(id, "close");
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
488
          Log->Write("WARNING: \tdoor %d is already close", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
489
     }
490 491 492

}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
493
//open the door if it was open and relaunch the routing procedure
Ulrich Kemloh's avatar
Ulrich Kemloh committed
494 495 496 497 498
void EventManager::OpenDoor(int id)
{
     Transition *t = _building->GetTransition(id);
     if (!t->IsOpen()) {
          t->Open();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
499
          Log->Write("INFO:\tOpening door %d ", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
500 501
          ChangeRouting(id, "open");
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
502
          Log->Write("WARNING: \tdoor %d is already open", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
503
     }
504 505
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
506 507 508 509 510 511 512
void EventManager::ChangeRouting(int id, const std::string& state)
{

     //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
     //Abstand der aktuellen Position des Pedestrians zur entsprechenden Tuer: Tuer als Linie sehen und mit
     //DistTo(ped.GetPos()) den Abstand messen. Reroutezeit dann aus Entfernung und Geschwindigkeit berechnen.
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
     //Transition *t = _building->GetTransition(id);
//     for(auto&& ped:_building->GetAllPedestrians())
//     {
//          //if(_allPedestrians[p]->GetExitIndex()==t->GetUniqueID()){
//          ped->SetNewEventFlag(false);
//          double dist = t->DistTo(ped->GetPos());
//          const Point& v = ped->GetV();
//          double norm = v.Norm();
//          if (norm == 0.0) {
//               norm = 0.01;
//          }
//          double time = dist / norm;
//          if (time < 1.0) {
//               ped->ClearMentalMap();
//               ped->ResetRerouting();
//               ped->SetNewEventFlag(true);
//          } else {
//               ped->RerouteIn(time);
//          }
//     }
534 535 536 537 538

     //Create and save a graph corresponding to the actual state of the building.
     if(CreateRoutingEngine(_building)==false)
     {
          Log->Write("ERROR: \tcannot create a routing engine with the new event");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
539
     }
540 541
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
void EventManager::GetEvent(char* c)
{
     int split = 0;
     string type = "";
     string id = "";
     string state = "";
     for (int i = 0; i < 20; i++) {
          if (!c[i]) {
               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()));
     }
570
}
571 572 573 574

bool EventManager::CreateRoutingEngine(Building* _b, int first_engine)
{
     std::vector<int> closed_doors;
575
     closed_doors.clear();
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

     for(auto&& t:_b->GetAllTransitions())
     {
          if(t.second->IsOpen()==false)
               closed_doors.push_back(t.second->GetID());
     }
     std::sort(closed_doors.begin(), closed_doors.end());

     //create the key as string.
     string key="";
     for(int door:closed_doors)
     {
          if(key.empty())
               key.append(std::to_string(door));
          else
               key.append(":"+std::to_string(door));
     }

     //the first (default) engine was created in the simulation
     // collect the defined routers
     if(first_engine)
     {
          RoutingEngine* engine=_b->GetRoutingEngine();
          _eventEngineStorage[key]=engine;

          for(auto&& rout: engine->GetAvailableRouters())
          {
               _availableRouters.push_back(rout->GetStrategy());
          }
          Log->Write("INFO: \tAdding a new routing Engine with the key: "+key+"\n");
          return true;
     }

     // the engine was not created
     // create a new one with the actual configuration
     if (_eventEngineStorage.count(key)==0)
     {
          //std::shared_ptr<RoutingEngine> engine = std::shared_ptr<RoutingEngine>(new RoutingEngine());
          //engine.get()->Init(_b);
          //_eventEngineStorage[key]=engine.get();

          //populate the engine with the routers defined in the ini file
          //and initialize
          RoutingEngine* engine= new RoutingEngine();
          for(auto&& rout:_availableRouters)
          {
               engine->AddRouter(CreateRouter(rout));
          }

          if(engine->Init(_b)==false)
               return false;

          //save the configuration
          _eventEngineStorage[key]=engine;
          Log->Write("INFO: \tAdding a new routing Engine with the key: "+key+"\n");
     }
     else
     {
          Log->Write("INFO: \tA routing already exits with the key: "+key+"\n");
     }

     return true;
}

Router * EventManager::CreateRouter(const RoutingStrategy& strategy)
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
642
     Router * rout=nullptr;
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

     switch(strategy)
     {
     case ROUTING_LOCAL_SHORTEST:
          rout = new GlobalRouter(ROUTING_LOCAL_SHORTEST, ROUTING_LOCAL_SHORTEST);
          break;

     case ROUTING_GLOBAL_SHORTEST:
          rout = new GlobalRouter(ROUTING_GLOBAL_SHORTEST, ROUTING_GLOBAL_SHORTEST);
          break;

     case ROUTING_QUICKEST:
          rout = new QuickestPathRouter(ROUTING_QUICKEST, ROUTING_QUICKEST);
          break;

     case ROUTING_NAV_MESH:
          rout = new MeshRouter(ROUTING_NAV_MESH, ROUTING_NAV_MESH);
          break;

     case ROUTING_DUMMY:
          rout = new DummyRouter(ROUTING_DUMMY, ROUTING_DUMMY);
          break;

     case ROUTING_SAFEST:
          rout = new SafestPathRouter(ROUTING_SAFEST, ROUTING_SAFEST);
          break;

     case ROUTING_COGNITIVEMAP:
          rout = new CognitiveMapRouter(ROUTING_COGNITIVEMAP, ROUTING_COGNITIVEMAP);
          break;

     default:
          Log->Write("ERROR: \twrong value for routing strategy [%d]!!!\n", strategy );
676
          exit(EXIT_FAILURE);
677 678 679 680 681
          break;

     }
     return rout;
}
682 683