]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
Merge branch 'jsd/atmos' into topic/atmos-merge
[flightgear.git] / src / Traffic / TrafficMgr.cxx
1 /******************************************************************************
2  * TrafficMGr.cxx
3  * Written by Durk Talsma, started May 5, 2004.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  *
19  *
20  **************************************************************************/
21  
22 /* 
23  * Traffic manager parses airlines timetable-like data and uses this to 
24  * determine the approximate position of each AI aircraft in its database.
25  * When an AI aircraft is close to the user's position, a more detailed 
26  * AIModels based simulation is set up. 
27  * 
28  * I'm currently assuming the following simplifications:
29  * 1) The earth is a perfect sphere
30  * 2) Each aircraft flies a perfect great circle route.
31  * 3) Each aircraft flies at a constant speed (with infinite accelerations and
32  *    decelerations) 
33  * 4) Each aircraft leaves at exactly the departure time. 
34  * 5) Each aircraft arrives at exactly the specified arrival time. 
35  *
36  *
37  *****************************************************************************/
38
39 #ifdef HAVE_CONFIG_H
40 #  include "config.h"
41 #endif
42
43 #include <stdlib.h>
44 #include <time.h>
45 #include <iostream>
46 #include <fstream>
47
48
49 #include <string>
50 #include <vector>
51 #include <algorithm>
52
53 #include <plib/ul.h>
54
55 #include <simgear/compiler.h>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/props/props.hxx>
58 #include <simgear/route/waypoint.hxx>
59 #include <simgear/structure/subsystem_mgr.hxx>
60 #include <simgear/xml/easyxml.hxx>
61
62 #include <AIModel/AIAircraft.hxx>
63 #include <AIModel/AIFlightPlan.hxx>
64 #include <AIModel/AIBase.hxx>
65 #include <Airports/simple.hxx>
66 #include <Main/fg_init.hxx>
67
68
69
70 #include "TrafficMgr.hxx"
71
72 using std::sort;
73  
74 /******************************************************************************
75  * TrafficManager
76  *****************************************************************************/
77 FGTrafficManager::FGTrafficManager()
78 {
79   //score = 0;
80   //runCount = 0;
81   acCounter = 0;
82 }
83
84 FGTrafficManager:: ~FGTrafficManager()
85 {
86   for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++)
87     {
88       delete (*sched);
89     }
90   scheduledAircraft.clear();
91   flights.clear();
92 }
93
94
95 void FGTrafficManager::init()
96
97   ulDir* d, *d2;
98   ulDirEnt* dent, *dent2;
99   SGPath aircraftDir = globals->get_fg_root();
100
101   SGPath path = aircraftDir;
102   
103   aircraftDir.append("AI/Traffic");
104   if ((d = ulOpenDir(aircraftDir.c_str())) != NULL)
105     {
106       while((dent = ulReadDir(d)) != NULL) {
107         if (string(dent->d_name) != string(".")  && 
108             string(dent->d_name) != string("..") &&
109             dent->d_isdir)
110           {
111             SGPath currACDir = aircraftDir;
112             currACDir.append(dent->d_name);
113             if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
114               return;
115             while ((dent2 = ulReadDir(d2)) != NULL) {
116               SGPath currFile = currACDir;
117               currFile.append(dent2->d_name);
118               if (currFile.extension() == string("xml"))
119                 {
120                   SGPath currFile = currACDir;
121                   currFile.append(dent2->d_name);
122                   SG_LOG(SG_GENERAL, SG_INFO, "Scanning " << currFile.str() << " for traffic");
123                   readXML(currFile.str(),*this);
124                 }
125             }
126             ulCloseDir(d2);
127           }
128       }
129       ulCloseDir(d);
130     }
131     
132     currAircraft = scheduledAircraft.begin();
133     currAircraftClosest = scheduledAircraft.begin();
134 }
135
136 void FGTrafficManager::update(double /*dt*/)
137 {
138
139   time_t now = time(NULL) + fgGetLong("/sim/time/warp");
140   if (scheduledAircraft.size() == 0) {
141     return;
142   }
143   if(currAircraft == scheduledAircraft.end())
144     {
145       currAircraft = scheduledAircraft.begin();
146     }
147   if (!((*currAircraft)->update(now)))
148     {
149       // NOTE: With traffic manager II, this statement below is no longer true
150       // after proper initialization, we shouldnt get here.
151       // But let's make sure
152       //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
153     }
154   currAircraft++;
155 }
156
157 void FGTrafficManager::release(int id)
158 {
159   releaseList.push_back(id);
160 }
161
162 bool FGTrafficManager::isReleased(int id)
163 {
164   IdListIterator i = releaseList.begin();
165   while (i != releaseList.end())
166     {
167       if ((*i) == id)
168         {
169           releaseList.erase(i);
170           return true;
171         }
172       i++;
173     }
174   return false;
175 }
176 /*
177 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
178 {
179     string model;
180     string livery;
181     string homePort;
182     string registration;
183     string flightReq;
184     bool   isHeavy;
185     string acType;
186     string airline;
187     string m_class;
188     string FlightType;
189     double radius;
190     double offset;
191
192     char buffer[256];
193     string buffString;
194     vector <string> tokens, depTime,arrTime;
195     vector <string>::iterator it;
196     ifstream infile(infileName.str().c_str());
197     while (1) {
198          infile.getline(buffer, 256);
199          if (infile.eof()) {
200              break;
201          }
202          //cerr << "Read line : " << buffer << endl;
203          buffString = string(buffer);
204          tokens.clear();
205          Tokenize(buffString, tokens, " \t");
206          //for (it = tokens.begin(); it != tokens.end(); it++) {
207          //    cerr << "Tokens: " << *(it) << endl;
208          //}
209          //cerr << endl;
210          if (!tokens.empty()) {
211              if (tokens[0] == string("AC")) {
212                  if (tokens.size() != 13) {
213                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
214                      exit(1);
215                  }
216                  model          = tokens[12];
217                  livery         = tokens[6];
218                  homePort       = tokens[1];
219                  registration   = tokens[2];
220                  if (tokens[11] == string("false")) {
221                      isHeavy = false;
222                  } else {
223                      isHeavy = true;
224                  }
225                  acType         = tokens[4];
226                  airline        = tokens[5];
227                  flightReq      = tokens[3] + tokens[5];
228                  m_class        = tokens[10];
229                  FlightType     = tokens[9];
230                  radius         = atof(tokens[8].c_str());
231                  offset         = atof(tokens[7].c_str());;
232                  //cerr << "Found AC string " << model << " " << livery << " " << homePort << " " 
233                  //     << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class 
234                  //     << " " << FlightType << " " << radius << " " << offset << endl;
235                  scheduledAircraft.push_back(new FGAISchedule(model, 
236                                                               livery, 
237                                                               homePort,
238                                                               registration, 
239                                                               flightReq,
240                                                               isHeavy,
241                                                               acType, 
242                                                               airline, 
243                                                               m_class, 
244                                                               FlightType,
245                                                               radius,
246                                                               offset));
247              }
248              if (tokens[0] == string("FLIGHT")) {
249                  //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
250                  if (tokens.size() != 10) {
251                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
252                      exit(1);
253                  }
254                  string callsign = tokens[1];
255                  string fltrules = tokens[2];
256                  string weekdays = tokens[3];
257                  string departurePort = tokens[5];
258                  string arrivalPort   = tokens[7];
259                  int    cruiseAlt     = atoi(tokens[8].c_str());
260                  string depTimeGen    = tokens[4];
261                  string arrTimeGen    = tokens[6];
262                  string repeat        = "WEEK";
263                  string requiredAircraft = tokens[9];
264                  
265                  if (weekdays.size() != 7) {
266                      cerr << "Found misconfigured weekdays string" << weekdays << endl;
267                      exit(1);
268                  }
269                  depTime.clear();
270                  arrTime.clear();
271                  Tokenize(depTimeGen, depTime, ":");
272                  Tokenize(arrTimeGen, arrTime, ":");
273                  double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
274                  double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
275                  //cerr << "Using " << dep << " " << arr << endl;
276                  bool arrivalWeekdayNeedsIncrement = false;
277                  if (arr < dep) {
278                        arrivalWeekdayNeedsIncrement = true;
279                  }
280                  for (int i = 0; i < 7; i++) {
281                      if (weekdays[i] != '.') {
282                          char buffer[4];
283                          snprintf(buffer, 4, "%d/", i);
284                          string departureTime = string(buffer) + depTimeGen + string(":00");
285                          string arrivalTime;
286                          if (!arrivalWeekdayNeedsIncrement) {
287                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
288                          }
289                          if (arrivalWeekdayNeedsIncrement && i != 6 ) {
290                              snprintf(buffer, 4, "%d/", i+1);
291                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
292                          }
293                          if (arrivalWeekdayNeedsIncrement && i == 6 ) {
294                              snprintf(buffer, 4, "%d/", 0);
295                              arrivalTime   = string(buffer) + arrTimeGen  + string(":00");
296                          }
297                          cerr << "Adding flight: " << callsign       << " "
298                                                    << fltrules       << " "
299                                                    <<  departurePort << " "
300                                                    <<  arrivalPort   << " "
301                                                    <<  cruiseAlt     << " "
302                                                    <<  departureTime << " "
303                                                    <<  arrivalTime   << " "
304                                                    <<  repeat        << " " 
305                                                    <<  requiredAircraft << endl;
306
307                          flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
308                                                                  fltrules,
309                                                                  departurePort,
310                                                                  arrivalPort,
311                                                                  cruiseAlt,
312                                                                  departureTime,
313                                                                  arrivalTime,
314                                                                  repeat,
315                                                                  requiredAircraft));
316                     }
317                 }
318              }
319          }
320
321     }
322     //exit(1);
323 }*/
324
325 /*
326 void FGTrafficManager::Tokenize(const string& str,
327                       vector<string>& tokens,
328                       const string& delimiters)
329 {
330     // Skip delimiters at beginning.
331     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
332     // Find first "non-delimiter".
333     string::size_type pos     = str.find_first_of(delimiters, lastPos);
334
335     while (string::npos != pos || string::npos != lastPos)
336     {
337         // Found a token, add it to the vector.
338         tokens.push_back(str.substr(lastPos, pos - lastPos));
339         // Skip delimiters.  Note the "not_of"
340         lastPos = str.find_first_not_of(delimiters, pos);
341         // Find next "non-delimiter"
342         pos = str.find_first_of(delimiters, lastPos);
343     }
344 }
345 */
346
347 void  FGTrafficManager::startXML () {
348   //cout << "Start XML" << endl;
349   requiredAircraft = "";
350   homePort         = "";
351 }
352
353 void  FGTrafficManager::endXML () {
354   //cout << "End XML" << endl;
355 }
356
357 void  FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
358   const char * attval;
359   //cout << "Start element " << name << endl;
360   //FGTrafficManager temp;
361   //for (int i = 0; i < atts.size(); i++)
362   //  if (string(atts.getName(i)) == string("include"))
363   attval = atts.getValue("include");
364   if (attval != 0)
365       {
366         //cout << "including " << attval << endl;
367         SGPath path = 
368           globals->get_fg_root();
369         path.append("/Traffic/");
370         path.append(attval);
371         readXML(path.str(), *this);
372       }
373   elementValueStack.push_back( "" );
374   //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
375 }
376
377 void  FGTrafficManager::endElement (const char * name) {
378   //cout << "End element " << name << endl;
379   string element(name);
380   string value = elementValueStack.back();
381   elementValueStack.pop_back();
382
383   if (element == string("model"))
384     mdl = value;
385   else if (element == string("livery"))
386     livery = value;
387   else if (element == string("home-port"))
388     homePort = value;
389   else if (element == string("registration"))
390     registration = value;
391   else if (element == string("airline"))
392     airline = value;
393   else if (element == string("actype"))
394     acType = value;
395   else if (element == string("required-aircraft"))
396     requiredAircraft = value;
397   else if (element == string("flighttype"))
398     flighttype = value;
399   else if (element == string("radius"))
400     radius = atoi(value.c_str());
401   else if (element == string("offset"))
402     offset = atoi(value.c_str());
403   else if (element == string("performance-class"))
404     m_class = value;
405   else if (element == string("heavy"))
406     {
407       if(value == string("true"))
408         heavy = true;
409       else
410         heavy = false;
411     }
412   else if (element == string("callsign"))
413     callsign = value;
414   else if (element == string("fltrules"))
415     fltrules = value;
416   else if (element == string("port"))
417     port = value;
418   else if (element == string("time"))
419     timeString = value;
420   else if (element == string("departure"))
421     {
422       departurePort = port;
423       departureTime = timeString;
424     }
425   else if (element == string("cruise-alt"))
426     cruiseAlt = atoi(value.c_str());
427   else if (element == string("arrival"))
428     {
429       arrivalPort = port;
430       arrivalTime = timeString;
431     }
432   else if (element == string("repeat"))
433     repeat = value;
434   else if (element == string("flight"))
435     {
436       // We have loaded and parsed all the information belonging to this flight
437       // so we temporarily store it. 
438       //cerr << "Pusing back flight " << callsign << endl;
439       //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
440       //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
441
442       //Prioritize aircraft 
443       string apt = fgGetString("/sim/presets/airport-id");
444       //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
445       //if (departurePort == apt) score++;
446       //flights.push_back(new FGScheduledFlight(callsign,
447         //                                fltrules,
448         //                                departurePort,
449         //                                arrivalPort,
450         //                                cruiseAlt,
451         //                                departureTime,
452         //                                arrivalTime,
453         //                                repeat));
454     if (requiredAircraft == "") {
455         char buffer[16];
456         snprintf(buffer, 16, "%d", acCounter);
457         requiredAircraft = buffer;
458     }
459     SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign       << " "
460                               << fltrules       << " "
461                               <<  departurePort << " "
462                               <<  arrivalPort   << " "
463                               <<  cruiseAlt     << " "
464                               <<  departureTime << " "
465                               <<  arrivalTime   << " "
466                               <<  repeat        << " " 
467                               <<  requiredAircraft);
468
469      flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
470                                                                  fltrules,
471                                                                  departurePort,
472                                                                  arrivalPort,
473                                                                  cruiseAlt,
474                                                                  departureTime,
475                                                                  arrivalTime,
476                                                                  repeat,
477                                                                  requiredAircraft));
478       requiredAircraft = "";
479   }
480   else if (element == string("aircraft"))
481     {
482       int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
483       int randval = rand() & 100;
484       if (randval < proportion) {
485           //scheduledAircraft.push_back(new FGAISchedule(mdl, 
486         //                                     livery, 
487         //                                     registration, 
488         //                                     heavy,
489         //                                     acType, 
490         //                                     airline, 
491         //                                     m_class, 
492         //                                     flighttype,
493         //                                     radius,
494         //                                     offset,
495         //                                     score,
496         //                                     flights));
497     if (requiredAircraft == "") {
498         char buffer[16];
499         snprintf(buffer, 16, "%d", acCounter);
500         requiredAircraft = buffer;
501     }
502     if (homePort == "") {
503         homePort = departurePort;
504     }
505             scheduledAircraft.push_back(new FGAISchedule(mdl, 
506                                                          livery, 
507                                                          homePort,
508                                                          registration, 
509                                                          requiredAircraft,
510                                                          heavy,
511                                                          acType, 
512                                                          airline, 
513                                                          m_class, 
514                                                          flighttype,
515                                                          radius,
516                                                          offset));
517
518      //  while(flights.begin() != flights.end()) {
519 //      flights.pop_back();
520 //       }
521         }
522     acCounter++;
523     requiredAircraft = "";
524     homePort = "";
525   //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
526   //  {
527   //    delete (*flt);
528   //  }
529   //flights.clear();
530       SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : " 
531               << registration 
532               << " with prioritization score " 
533               << score);
534       score = 0;
535     }
536 }
537
538 void  FGTrafficManager::data (const char * s, int len) {
539   string token = string(s,len);
540   //cout << "Character data " << string(s,len) << endl;
541   elementValueStack.back() += token;
542 }
543
544 void  FGTrafficManager::pi (const char * target, const char * data) {
545   //cout << "Processing instruction " << target << ' ' << data << endl;
546 }
547
548 void  FGTrafficManager::warning (const char * message, int line, int column) {
549   SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
550 }
551
552 void  FGTrafficManager::error (const char * message, int line, int column) {
553   SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
554 }
555