EventManager.cpp 13.1 KB
Newer Older
Ulrich Kemloh's avatar
Ulrich Kemloh committed
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
/**
 * \file        EventManager.cpp
 * \date        Jul 4, 2014
 * \version     v0.6
 * \copyright   <2009-2014> Forschungszentrum Jülich GmbH. All rights reserved.
 *
 * \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>
#include <fstream>
#include <vector>
#include <math.h>
#include <stdio.h>
#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"
#include "../pedestrian/Pedestrian.h"
46
#include "EventManager.h"
47 48 49

using namespace std;

50
/*******************
Ulrich Kemloh's avatar
Ulrich Kemloh committed
51
 constructors
52 53
 ******************/

Ulrich Kemloh's avatar
Ulrich Kemloh committed
54 55
#define UPDATE_FREQUENCY 1 // in seconds

Ulrich Kemloh's avatar
Ulrich Kemloh committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
EventManager::EventManager(Building *_b)
{
     _event_times = vector<double>();
     _event_types = vector<string>();
     _event_states = vector<string>();
     _event_ids = vector<int>();
     _projectFilename = "";
     _building = _b;
     _eventCounter = 0;
     _dynamic = false;
     _file = fopen("../events/events.txt", "r");
     _lastUpdateTime = 0;
     _deltaT = 0;
     this->SetProjectFilename(_building->GetProjectFilename());
     this->SetProjectRootDir(_building->GetProjectRootDir());
     if (!_file) {
          Log->Write(
                    "INFO:\tFiles 'events.txt' missing. Realtime interaction with the simulation not possible.");
     } else {
          Log->Write(
                    "INFO:\tFile 'events.txt' will be monitored for new events.");
          _dynamic = true;
     }
79
}
80

Ulrich Kemloh's avatar
Ulrich Kemloh committed
81

Ulrich Kemloh's avatar
Ulrich Kemloh committed
82 83 84
void EventManager::SetProjectFilename(const std::string &filename)
{
     _projectFilename = filename;
85
}
86

Ulrich Kemloh's avatar
Ulrich Kemloh committed
87 88 89
void EventManager::SetProjectRootDir(const std::string &filename)
{
     _projectRootDir = filename;
90 91
}

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

     TiXmlElement* xMainNode = doc.RootElement();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
104 105 106 107 108 109
     string eventfile = "";
     if (xMainNode->FirstChild("events")) {
          eventfile = _projectRootDir
                    + xMainNode->FirstChild("events")->FirstChild()->Value();
          Log->Write("INFO: \tevents <" + eventfile + ">");
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
110
          Log->Write("INFO: \tNo events found");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
111
          return true;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
112 113 114 115
     }

     Log->Write("INFO: \tParsing the event file");
     TiXmlDocument docEvent(eventfile);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
116 117
     if (!docEvent.LoadFile()) {
          Log->Write("ERROR: \t%s", docEvent.ErrorDesc());
Ulrich Kemloh's avatar
Ulrich Kemloh committed
118
          Log->Write("ERROR: \t could not parse the event file.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
119
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
120 121 122
     }

     TiXmlElement* xRootNode = docEvent.RootElement();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
123
     if (!xRootNode) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
124
          Log->Write("ERROR:\tRoot element does not exist.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
125
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
126 127
     }

Ulrich Kemloh's avatar
Ulrich Kemloh committed
128
     if (xRootNode->ValueStr() != "JPScore") {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
129
          Log->Write("ERROR:\tRoot element value is not 'JPScore'.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
130
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
131 132 133
     }

     TiXmlNode* xEvents = xRootNode->FirstChild("events");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
134
     if (!xEvents) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
135
          Log->Write("ERROR:\tNo events found.");
Ulrich Kemloh's avatar
Ulrich Kemloh committed
136
          return false;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
137 138
     }

Ulrich Kemloh's avatar
Ulrich Kemloh committed
139 140
     for (TiXmlElement* e = xEvents->FirstChildElement("event"); e;
               e = e->NextSiblingElement("event")) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
141 142 143 144 145
          _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")));
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
146 147
     Log->Write("INFO: \tEvents were initialized\n");
     return true;
148 149
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
150
void EventManager::ListEvents()
151
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165
     if (_event_times.size() == 0) {
          //this notification was already printed ealier
          //Log->Write("INFO: \tNo events in the events.xml");
     } else {
          char buf[10], buf2[10];
          for (unsigned int i = 0; i < _event_times.size(); i++) {
               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]);
          }
     }
166 167 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
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;
          }
          if (cstring[0] != '#') {        // keine Kommentarzeile
               lines++;
               if (lines > _eventCounter) {
                    Log->Write("INFO:\tEvent: after %f sec: ", time);
                    GetEvent(cstring);
                    _eventCounter++;
               }
          }
     } while (feof(_file) == 0);
188 189
}

190 191 192 193
/***********
 Update
 **********/

Ulrich Kemloh's avatar
Ulrich Kemloh committed
194 195
void EventManager::Update_Events(double time, double d)
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
196 197 198 199 200 201
     //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

Ulrich Kemloh's avatar
Ulrich Kemloh committed
202 203
     _deltaT = d;
     const vector<Pedestrian*>& _allPeds = _building->GetAllPedestrians();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
204 205 206

     //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)
207
     int currentTime = _allPeds[0]->GetGlobalTime();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
208 209
     if (currentTime != _lastUpdateTime)
          if ((currentTime % UPDATE_FREQUENCY) == 0) {
210

Ulrich Kemloh's avatar
Ulrich Kemloh committed
211
               for (unsigned int p1 = 0; p1 < _allPeds.size(); p1++) {
212
                    Pedestrian* ped1 = _allPeds[p1];
Ulrich Kemloh's avatar
Ulrich Kemloh committed
213
                    if (ped1->GetNewEventFlag()) {
214 215 216
                         int rID = ped1->GetRoomID();
                         int srID = ped1->GetSubRoomID();

Ulrich Kemloh's avatar
Ulrich Kemloh committed
217
                         for (unsigned int p2 = 0; p2 < _allPeds.size(); p2++) {
218 219
                              Pedestrian* ped2 = _allPeds[p2];
                              //same room and subroom
Ulrich Kemloh's avatar
Ulrich Kemloh committed
220 221 222 223 224
                              if (rID == ped2->GetRoomID()
                                        && srID == ped2->GetSubRoomID()) {
                                   if (!ped2->GetNewEventFlag()
                                             && ped2->GetReroutingTime()
                                                       > 2.0) {
225 226 227
                                        //wenn der Pedestrian die neuen Infos noch nicht hat und eine Reroutingtime von > 2 Sekunden hat, pruefen ob er nah genug ist
                                        Point pos1 = ped1->GetPos();
                                        Point pos2 = ped2->GetPos();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
228 229 230 231 232 233 234 235
                                        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)
236 237 238
                                             //ped->RerouteIn(2.0);
                                             ped2->RerouteIn(0.0);
                                        }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
239 240 241
                                   }
                              }
                         }
242
                    }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
243
               }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
244
               _lastUpdateTime = currentTime;
Ulrich Kemloh's avatar
Ulrich Kemloh committed
245 246 247 248
               //cout<<"updating..."<<currentTime<<endl<<endl;
          }

     //dann muss die Reroutingzeit der Peds, die die neuen Infos noch nicht haben, aktualisiert werden:
Ulrich Kemloh's avatar
Ulrich Kemloh committed
249
     for (unsigned int p1 = 0; p1 < _allPeds.size(); p1++) {
250 251
          Pedestrian* ped1 = _allPeds[p1];
          ped1->UpdateReroutingTime();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
252
          if (ped1->IsReadyForRerouting()) {
253 254 255
               ped1->ClearMentalMap();
               ped1->ResetRerouting();
               ped1->SetNewEventFlag(true);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
256 257 258 259
          }
     }

     //Events finden
Ulrich Kemloh's avatar
Ulrich Kemloh committed
260 261
     for (unsigned int i = 0; i < _event_times.size(); i++) {
          if (fabs(_event_times[i] - time) < J_EPS_EVENT) {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
262
               //Event findet statt
Ulrich Kemloh's avatar
Ulrich Kemloh committed
263 264 265 266 267
               Log->Write("INFO:\tEvent: after %f sec: ", time);
               if (_event_states[i].compare("close") == 0) {
                    CloseDoor(_event_ids[i]);
               } else {
                    OpenDoor(_event_ids[i]);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
268 269 270
               }
          }
     }
Ulrich Kemloh's avatar
Ulrich Kemloh committed
271 272
     if (_dynamic)
          ReadEventsTxt(time);
273 274 275 276 277
}

/***************
 Eventhandling
 **************/
Ulrich Kemloh's avatar
Ulrich Kemloh committed
278 279

//close the door if it was open and relaunch the routing procedure
Ulrich Kemloh's avatar
Ulrich Kemloh committed
280 281
void EventManager::CloseDoor(int id)
{
Ulrich Kemloh's avatar
Ulrich Kemloh committed
282

Ulrich Kemloh's avatar
Ulrich Kemloh committed
283 284 285
     Transition *t = _building->GetTransition(id);
     if (t->IsOpen()) {
          t->Close();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
286
          Log->Write("INFO:\tClosing door %d ", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
287 288
          ChangeRouting(id, "close");
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
289
          Log->Write("WARNING: \tdoor %d is already close", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
290
     }
291 292 293

}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
294
//open the door if it was open and relaunch the routing procedure
Ulrich Kemloh's avatar
Ulrich Kemloh committed
295 296 297 298 299
void EventManager::OpenDoor(int id)
{
     Transition *t = _building->GetTransition(id);
     if (!t->IsOpen()) {
          t->Open();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
300
          Log->Write("INFO:\tOpening door %d ", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
301 302
          ChangeRouting(id, "open");
     } else {
Ulrich Kemloh's avatar
Ulrich Kemloh committed
303
          Log->Write("WARNING: \tdoor %d is already open", id);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
304
     }
305 306
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
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
void EventManager::ChangeRouting(int id, const std::string& state)
{
     RoutingEngine* routingEngine = _building->GetRoutingEngine();
     routingEngine->Init(_building);
     //_building->InitPhiAllPeds(_deltaT);
     const vector<Pedestrian*>& _allPedestrians =
               _building->GetAllPedestrians();
     unsigned int nSize = _allPedestrians.size();

     //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
     Transition *t = _building->GetTransition(id);
     //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.
     Line* l = new Line(t->GetPoint1(), t->GetPoint2());
     for (unsigned int p = 0; p < nSize; ++p) {
          //if(_allPedestrians[p]->GetExitIndex()==t->GetUniqueID()){
          _allPedestrians[p]->SetNewEventFlag(false);
          double dist = l->DistTo(_allPedestrians[p]->GetPos());
          Point v = _allPedestrians[p]->GetV();
          double norm = sqrt((v.GetX() * v.GetX()) + (v.GetY() * v.GetY()));
          if (norm == 0.0) {
               norm = 0.01;
          }
          double time = dist / norm;
          if (time < 1.0) {
               _allPedestrians[p]->ClearMentalMap();
               _allPedestrians[p]->ResetRerouting();
               _allPedestrians[p]->SetNewEventFlag(true);
          } else {
               _allPedestrians[p]->RerouteIn(time);
          }
          //if(dist>0.0&&dist<0.5){
340
          // _allPedestrians[p]->ClearMentalMap();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
341 342
          //}
          //else if(dist>=0.5&&dist<3.0){
343
          // _allPedestrians[p]->RerouteIn(1.0);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
344 345
          //}
          //else{
346
          // _allPedestrians[p]->RerouteIn(2.0);
Ulrich Kemloh's avatar
Ulrich Kemloh committed
347 348 349
          //}
          //}
          //else{
350
          //  _allPedestrians[p]->ClearMentalMap();
Ulrich Kemloh's avatar
Ulrich Kemloh committed
351 352
          //}
     }
353 354
}

Ulrich Kemloh's avatar
Ulrich Kemloh committed
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
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()));
     }
383
}