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