]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
Break upwards dependency on Traffic in the AI code
[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 #include <boost/foreach.hpp>
54
55 #include <simgear/compiler.h>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/misc/sg_dir.hxx>
58 #include <simgear/props/props.hxx>
59 #include <simgear/structure/subsystem_mgr.hxx>
60 #include <simgear/xml/easyxml.hxx>
61 #include <simgear/threads/SGThread.hxx>
62 #include <simgear/threads/SGGuard.hxx>
63
64 #include <AIModel/AIAircraft.hxx>
65 #include <AIModel/AIFlightPlan.hxx>
66 #include <AIModel/AIBase.hxx>
67 #include <Airports/simple.hxx>
68 #include <Main/fg_init.hxx>
69
70
71
72 #include "TrafficMgr.hxx"
73
74 using std::sort;
75 using std::strcmp;
76
77 /**
78  * Thread encapsulating parsing the traffic schedules. 
79  */
80 class ScheduleParseThread : public SGThread
81 {
82 public:
83   ScheduleParseThread(FGTrafficManager* traffic) :
84     _trafficManager(traffic),
85     _isFinished(false),
86     _cancelThread(false)
87   {
88     
89   }
90   
91   // if we're destroyed while running, ensure the thread exits cleanly
92   ~ScheduleParseThread()
93   {
94     _lock.lock();
95     if (!_isFinished) {
96       _cancelThread = true; // request cancellation so we don't wait ages
97       _lock.unlock();
98       join();
99     } else {
100       _lock.unlock();
101     }
102   }
103   
104   void setTrafficDir(const SGPath& trafficDirPath)
105   {
106     _trafficDirPath = trafficDirPath;
107   }
108   
109   bool isFinished() const
110   {
111     SGGuard<SGMutex> g(_lock);
112     return _isFinished;
113   }
114   
115   virtual void run()
116   {
117     SGTimeStamp st;
118     st.stamp();
119     
120     simgear::Dir trafficDir(_trafficDirPath);
121     simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
122     
123     BOOST_FOREACH(SGPath p, d) {
124       simgear::Dir d2(p);
125       simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
126       BOOST_FOREACH(SGPath xml, trafficFiles) {
127         _trafficManager->parseSchedule(xml);
128         if (_cancelThread) {
129           return;
130         }
131       }
132     } // of sub-directories in AI/Traffic iteration
133     
134   //  _trafficManager->parseSchedules(schedulesToRead);
135     SG_LOG(SG_AI, SG_INFO, "parsing traffic schedules took:" << st.elapsedMSec() << "msec");
136     
137     SGGuard<SGMutex> g(_lock);
138     _isFinished = true;
139   }
140 private:
141   FGTrafficManager* _trafficManager;
142   mutable SGMutex _lock;
143   bool _isFinished;
144   bool _cancelThread;
145   SGPath _trafficDirPath;
146 };
147
148 /******************************************************************************
149  * TrafficManager
150  *****************************************************************************/
151 FGTrafficManager::FGTrafficManager() :
152   inited(false),
153   doingInit(false),
154   waitingMetarTime(0.0),
155   enabled("/sim/traffic-manager/enabled"),
156   aiEnabled("/sim/ai/enabled"),
157   realWxEnabled("/environment/realwx/enabled"),
158   metarValid("/environment/metar/valid")
159 {
160     //score = 0;
161     //runCount = 0;
162     acCounter = 0;
163 }
164
165 FGTrafficManager::~FGTrafficManager()
166 {
167     shutdown();
168 }
169
170 void FGTrafficManager::shutdown()
171 {
172     if (!inited) {
173       if (doingInit) {
174         scheduleParser.reset();
175         doingInit = false;
176       }
177       
178       return;
179     }
180   
181     // Save the heuristics data
182     bool saveData = false;
183     ofstream cachefile;
184     if (fgGetBool("/sim/traffic-manager/heuristics")) {
185         SGPath cacheData(globals->get_fg_home());
186         cacheData.append("ai");
187         string airport = fgGetString("/sim/presets/airport-id");
188
189         if ((airport) != "") {
190             char buffer[128];
191             ::snprintf(buffer, 128, "%c/%c/%c/",
192                        airport[0], airport[1], airport[2]);
193             cacheData.append(buffer);
194             if (!cacheData.exists()) {
195                 cacheData.create_dir(0777);
196             }
197             cacheData.append(airport + "-cache.txt");
198             //cerr << "Saving AI traffic heuristics" << endl;
199             saveData = true;
200             cachefile.open(cacheData.str().c_str());
201             cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
202         }
203     }
204   
205     BOOST_FOREACH(FGAISchedule* acft, scheduledAircraft) {
206         if (saveData) {
207             cachefile << acft->getRegistration() << " "
208                 << acft->getRunCount() << " "
209                 << acft->getHits() << " "
210                 << acft->getLastUsed() << endl;
211         }
212         delete acft;
213     }
214     if (saveData) {
215         cachefile.close();
216     }
217     scheduledAircraft.clear();
218     flights.clear();
219
220     currAircraft = scheduledAircraft.begin();
221     doingInit = false;
222     inited = false;
223 }
224
225 /// caution - this is run on the helper thread to improve startup
226 /// responsiveness - do not access properties or global state from
227 /// here, since there's no locking protection at all
228 void FGTrafficManager::parseSchedule(const SGPath& path)
229 {
230   readXML(path.str(), *this);
231 }
232
233 void FGTrafficManager::init()
234 {
235     if (!enabled) {
236       return;
237     }
238
239     assert(!doingInit);
240     doingInit = true;
241     if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
242         scheduleParser.reset(new ScheduleParseThread(this));
243         scheduleParser->setTrafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));      
244         scheduleParser->start();
245     } else {
246         fgSetBool("/sim/traffic-manager/heuristics", false);
247         SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
248         string ext = path.extension();
249         if (path.extension() == "xml") {
250             if (path.exists()) {
251                 readXML(path.str(), *this);
252             }
253         } else if (path.extension() == "conf") {
254             if (path.exists()) {
255                 readTimeTableFromFile(path);
256             }
257         } else {
258              SG_LOG(SG_AI, SG_ALERT,
259                                "Unknown data format " << path.str()
260                                 << " for traffic");
261         }
262         //exit(1);
263     }
264 }
265
266
267
268 void FGTrafficManager::finishInit()
269 {
270     assert(doingInit);
271     SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
272     loadHeuristics();
273     
274     // Do sorting and scoring separately, to take advantage of the "homeport" variable
275     BOOST_FOREACH(FGAISchedule* schedule, scheduledAircraft) {
276         schedule->setScore();
277     }
278     
279     sort(scheduledAircraft.begin(), scheduledAircraft.end(),
280          compareSchedules);
281     currAircraft = scheduledAircraft.begin();
282     currAircraftClosest = scheduledAircraft.begin();
283     
284     doingInit = false;
285     inited = true;
286 }
287
288 void FGTrafficManager::loadHeuristics()
289 {
290     if (!fgGetBool("/sim/traffic-manager/heuristics")) {
291         return;
292     }
293   
294     HeuristicMap heurMap;
295     //cerr << "Processing Heuristics" << endl;
296     // Load the heuristics data
297     SGPath cacheData(globals->get_fg_home());
298     cacheData.append("ai");
299     string airport = fgGetString("/sim/presets/airport-id");
300     if ((airport) != "") {
301       char buffer[128];
302       ::snprintf(buffer, 128, "%c/%c/%c/",
303                  airport[0], airport[1], airport[2]);
304       cacheData.append(buffer);
305       cacheData.append(airport + "-cache.txt");
306       string revisionStr;
307       if (cacheData.exists()) {
308         ifstream data(cacheData.c_str());
309         data >> revisionStr;
310         if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
311           SG_LOG(SG_GENERAL, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " << 
312                  cacheData.c_str() << " for Airport " << airport);
313         } else {
314           while (1) {
315             Heuristic h; // = new Heuristic;
316             data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
317             if (data.eof())
318               break;
319             HeuristicMapIterator itr = heurMap.find(h.registration);
320             if (itr != heurMap.end()) {
321               SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " << 
322                      h.registration << " for AI aircraft");
323             } else {
324               heurMap[h.registration] = h;
325             }
326           }
327         }
328       }
329     } 
330     
331   for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
332         string registration = (*currAircraft)->getRegistration();
333         HeuristicMapIterator itr = heurMap.find(registration);
334         if (itr != heurMap.end()) {
335             (*currAircraft)->setrunCount(itr->second.runCount);
336             (*currAircraft)->setHits(itr->second.hits);
337             (*currAircraft)->setLastUsed(itr->second.lastRun);
338         }
339     }
340 }
341
342 bool FGTrafficManager::metarReady(double dt)
343 {
344     // wait for valid METAR (when realWX is enabled only), since we need
345     // to know the active runway
346     if (metarValid || !realWxEnabled)
347     {
348         waitingMetarTime = 0.0;
349         return true;
350     }
351
352     // METAR timeout: when running offline, remote server is down etc
353     if (waitingMetarStation != fgGetString("/environment/metar/station-id"))
354     {
355         // station has changed: wait for reply, restart timeout
356         waitingMetarTime = 0.0;
357         waitingMetarStation = fgGetString("/environment/metar/station-id");
358         return false;
359     }
360
361     // timeout elapsed (10 seconds)?
362     if (waitingMetarTime > 20.0)
363     {
364         return true;
365     }
366
367     waitingMetarTime += dt;
368     return false;
369 }
370
371 void FGTrafficManager::update(double dt)
372 {
373     if (!enabled)
374     {
375         if (inited || doingInit)
376             shutdown();
377         return;
378     }
379
380     if (!metarReady(dt))
381         return;
382
383     if (!aiEnabled)
384     {
385         // traffic depends on AI module
386         aiEnabled = true;
387     }
388
389     if (!inited) {
390         if (!doingInit) {
391             init();
392         }
393         
394         if (!scheduleParser->isFinished()) {
395           return;
396         }
397       
398         finishInit();
399     }
400         
401     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
402     if (scheduledAircraft.empty()) {
403         return;
404     }
405
406     SGVec3d userCart = globals->get_aircraft_position_cart();
407
408     if (currAircraft == scheduledAircraft.end()) {
409         currAircraft = scheduledAircraft.begin();
410     }
411     //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
412     if (!((*currAircraft)->update(now, userCart))) {
413         (*currAircraft)->taint();
414     }
415     currAircraft++;
416 }
417
418 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
419 {
420     string model;
421     string livery;
422     string homePort;
423     string registration;
424     string flightReq;
425     bool   isHeavy;
426     string acType;
427     string airline;
428     string m_class;
429     string FlightType;
430     double radius;
431     double offset;
432
433     char buffer[256];
434     string buffString;
435     vector <string> tokens, depTime,arrTime;
436     vector <string>::iterator it;
437     ifstream infile(infileName.str().c_str());
438     while (1) {
439          infile.getline(buffer, 256);
440          if (infile.eof()) {
441              break;
442          }
443          //cerr << "Read line : " << buffer << endl;
444          buffString = string(buffer);
445          tokens.clear();
446          Tokenize(buffString, tokens, " \t");
447          //for (it = tokens.begin(); it != tokens.end(); it++) {
448          //    cerr << "Tokens: " << *(it) << endl;
449          //}
450          //cerr << endl;
451          if (!tokens.empty()) {
452              if (tokens[0] == string("AC")) {
453                  if (tokens.size() != 13) {
454                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
455                      exit(1);
456                  }
457                  model          = tokens[12];
458                  livery         = tokens[6];
459                  homePort       = tokens[1];
460                  registration   = tokens[2];
461                  if (tokens[11] == string("false")) {
462                      isHeavy = false;
463                  } else {
464                      isHeavy = true;
465                  }
466                  acType         = tokens[4];
467                  airline        = tokens[5];
468                  flightReq      = tokens[3] + tokens[5];
469                  m_class        = tokens[10];
470                  FlightType     = tokens[9];
471                  radius         = atof(tokens[8].c_str());
472                  offset         = atof(tokens[7].c_str());;
473                  
474                  if (!FGAISchedule::validModelPath(model)) {
475                      SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << 
476                             model << " from " << infileName.str());
477                  } else {
478                  
479                  SG_LOG(SG_GENERAL, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " " 
480                                                                 << registration << " " << flightReq << " " << isHeavy 
481                                                                 << " " << acType << " " << airline << " " << m_class 
482                                                                 << " " << FlightType << " " << radius << " " << offset);
483                  scheduledAircraft.push_back(new FGAISchedule(model, 
484                                                               livery, 
485                                                               homePort,
486                                                               registration, 
487                                                               flightReq,
488                                                               isHeavy,
489                                                               acType, 
490                                                               airline, 
491                                                               m_class, 
492                                                               FlightType,
493                                                               radius,
494                                                               offset));
495                  } // of valid model path
496              }
497              if (tokens[0] == string("FLIGHT")) {
498                  //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
499                  if (tokens.size() != 10) {
500                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
501                      exit(1);
502                  }
503                  string callsign = tokens[1];
504                  string fltrules = tokens[2];
505                  string weekdays = tokens[3];
506                  string departurePort = tokens[5];
507                  string arrivalPort   = tokens[7];
508                  int    cruiseAlt     = atoi(tokens[8].c_str());
509                  string depTimeGen    = tokens[4];
510                  string arrTimeGen    = tokens[6];
511                  string repeat        = "WEEK";
512                  string requiredAircraft = tokens[9];
513
514                  if (weekdays.size() != 7) {
515                      SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
516                      exit(1);
517                  }
518                  depTime.clear();
519                  arrTime.clear();
520                  Tokenize(depTimeGen, depTime, ":");
521                  Tokenize(arrTimeGen, arrTime, ":");
522                  double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
523                  double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
524                  //cerr << "Using " << dep << " " << arr << endl;
525                  bool arrivalWeekdayNeedsIncrement = false;
526                  if (arr < dep) {
527                        arrivalWeekdayNeedsIncrement = true;
528                  }
529                  for (int i = 0; i < 7; i++) {
530                      int j = i+1;
531                      if (weekdays[i] != '.') {
532                          char buffer[4];
533                          snprintf(buffer, 4, "%d/", j);
534                          string departureTime = string(buffer) + depTimeGen + string(":00");
535                          string arrivalTime;
536                          if (!arrivalWeekdayNeedsIncrement) {
537                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
538                          }
539                          if (arrivalWeekdayNeedsIncrement && i != 6 ) {
540                              snprintf(buffer, 4, "%d/", j+1);
541                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
542                          }
543                          if (arrivalWeekdayNeedsIncrement && i == 6 ) {
544                              snprintf(buffer, 4, "%d/", 0);
545                              arrivalTime   = string(buffer) + arrTimeGen  + string(":00");
546                          }
547                          SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign       << " "
548                                                       << fltrules       << " "
549                                                       <<  departurePort << " "
550                                                       <<  arrivalPort   << " "
551                                                       <<  cruiseAlt     << " "
552                                                       <<  departureTime << " "
553                                                       <<  arrivalTime   << " "
554                                                       << repeat        << " " 
555                                                       <<  requiredAircraft);
556
557                          flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
558                                                                  fltrules,
559                                                                  departurePort,
560                                                                  arrivalPort,
561                                                                  cruiseAlt,
562                                                                  departureTime,
563                                                                  arrivalTime,
564                                                                  repeat,
565                                                                  requiredAircraft));
566                     }
567                 }
568              }
569          }
570
571     }
572     //exit(1);
573 }
574
575
576 void FGTrafficManager::Tokenize(const string& str,
577                       vector<string>& tokens,
578                       const string& delimiters)
579 {
580     // Skip delimiters at beginning.
581     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
582     // Find first "non-delimiter".
583     string::size_type pos     = str.find_first_of(delimiters, lastPos);
584
585     while (string::npos != pos || string::npos != lastPos)
586     {
587         // Found a token, add it to the vector.
588         tokens.push_back(str.substr(lastPos, pos - lastPos));
589         // Skip delimiters.  Note the "not_of"
590         lastPos = str.find_first_not_of(delimiters, pos);
591         // Find next "non-delimiter"
592         pos = str.find_first_of(delimiters, lastPos);
593     }
594 }
595
596
597 void FGTrafficManager::startXML()
598 {
599     //cout << "Start XML" << endl;
600     requiredAircraft = "";
601     homePort = "";
602 }
603
604 void FGTrafficManager::endXML()
605 {
606     //cout << "End XML" << endl;
607 }
608
609 void FGTrafficManager::startElement(const char *name,
610                                     const XMLAttributes & atts)
611 {
612     const char *attval;
613     //cout << "Start element " << name << endl;
614     //FGTrafficManager temp;
615     //for (int i = 0; i < atts.size(); i++)
616     //  if (string(atts.getName(i)) == string("include"))
617     attval = atts.getValue("include");
618     if (attval != 0) {
619         //cout << "including " << attval << endl;
620         SGPath path = globals->get_fg_root();
621         path.append("/Traffic/");
622         path.append(attval);
623         readXML(path.str(), *this);
624     }
625     elementValueStack.push_back("");
626     //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
627 }
628
629 void FGTrafficManager::endElement(const char *name)
630 {
631     //cout << "End element " << name << endl;
632     const string & value = elementValueStack.back();
633
634     if (!strcmp(name, "model"))
635         mdl = value;
636     else if (!strcmp(name, "livery"))
637         livery = value;
638     else if (!strcmp(name, "home-port"))
639         homePort = value;
640     else if (!strcmp(name, "registration"))
641         registration = value;
642     else if (!strcmp(name, "airline"))
643         airline = value;
644     else if (!strcmp(name, "actype"))
645         acType = value;
646     else if (!strcmp(name, "required-aircraft"))
647         requiredAircraft = value;
648     else if (!strcmp(name, "flighttype"))
649         flighttype = value;
650     else if (!strcmp(name, "radius"))
651         radius = atoi(value.c_str());
652     else if (!strcmp(name, "offset"))
653         offset = atoi(value.c_str());
654     else if (!strcmp(name, "performance-class"))
655         m_class = value;
656     else if (!strcmp(name, "heavy")) {
657         if (value == string("true"))
658             heavy = true;
659         else
660             heavy = false;
661     } else if (!strcmp(name, "callsign"))
662         callsign = value;
663     else if (!strcmp(name, "fltrules"))
664         fltrules = value;
665     else if (!strcmp(name, "port"))
666         port = value;
667     else if (!strcmp(name, "time"))
668         timeString = value;
669     else if (!strcmp(name, "departure")) {
670         departurePort = port;
671         departureTime = timeString;
672     } else if (!strcmp(name, "cruise-alt"))
673         cruiseAlt = atoi(value.c_str());
674     else if (!strcmp(name, "arrival")) {
675         arrivalPort = port;
676         arrivalTime = timeString;
677     } else if (!strcmp(name, "repeat"))
678         repeat = value;
679     else if (!strcmp(name, "flight")) {
680         // We have loaded and parsed all the information belonging to this flight
681         // so we temporarily store it. 
682         //cerr << "Pusing back flight " << callsign << endl;
683         //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
684         //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
685
686         //Prioritize aircraft 
687         string apt = fgGetString("/sim/presets/airport-id");
688         //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
689         //if (departurePort == apt) score++;
690         //flights.push_back(new FGScheduledFlight(callsign,
691         //                                fltrules,
692         //                                departurePort,
693         //                                arrivalPort,
694         //                                cruiseAlt,
695         //                                departureTime,
696         //                                arrivalTime,
697         //                                repeat));
698         if (requiredAircraft == "") {
699             char buffer[16];
700             snprintf(buffer, 16, "%d", acCounter);
701             requiredAircraft = buffer;
702         }
703         SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
704                << fltrules << " "
705                << departurePort << " "
706                << arrivalPort << " "
707                << cruiseAlt << " "
708                << departureTime << " "
709                << arrivalTime << " " << repeat << " " << requiredAircraft);
710         // For database maintainance purposes, it may be convenient to
711         // 
712         if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
713              SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
714                           << fltrules << ","
715                           << departurePort << ","
716                           << arrivalPort << ","
717                           << cruiseAlt << ","
718                           << departureTime << ","
719                           << arrivalTime << "," << repeat << "," << requiredAircraft);
720         }
721         flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
722                                                                   fltrules,
723                                                                   departurePort,
724                                                                   arrivalPort,
725                                                                   cruiseAlt,
726                                                                   departureTime,
727                                                                   arrivalTime,
728                                                                   repeat,
729                                                                   requiredAircraft));
730         requiredAircraft = "";
731     } else if (!strcmp(name, "aircraft")) {
732         endAircraft();
733     }
734     
735     elementValueStack.pop_back();
736 }
737
738 void FGTrafficManager::endAircraft()
739 {
740     string isHeavy = heavy ? "true" : "false";
741
742     if (missingModels.find(mdl) != missingModels.end()) {
743     // don't stat() or warn again
744         requiredAircraft = homePort = "";
745         return;
746     }
747     
748     if (!FGAISchedule::validModelPath(mdl)) {
749         missingModels.insert(mdl);
750         SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
751         requiredAircraft = homePort = "";
752         return;
753     }
754         
755     int proportion =
756         (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
757     int randval = rand() & 100;
758     if (randval > proportion) {
759         requiredAircraft = homePort = "";
760         return;
761     }
762     
763     if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
764         SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft 
765                << "," << acType << "," << livery << "," 
766                << airline << ","  << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
767     }
768
769     if (requiredAircraft == "") {
770         char buffer[16];
771         snprintf(buffer, 16, "%d", acCounter);
772         requiredAircraft = buffer;
773     }
774     if (homePort == "") {
775         homePort = departurePort;
776     }
777     
778     scheduledAircraft.push_back(new FGAISchedule(mdl,
779                                                  livery,
780                                                  homePort,
781                                                  registration,
782                                                  requiredAircraft,
783                                                  heavy,
784                                                  acType,
785                                                  airline,
786                                                  m_class,
787                                                  flighttype,
788                                                  radius, offset));
789             
790     acCounter++;
791     requiredAircraft = "";
792     homePort = "";
793     score = 0;
794 }
795     
796 void FGTrafficManager::data(const char *s, int len)
797 {
798     string token = string(s, len);
799     //cout << "Character data " << string(s,len) << endl;
800     elementValueStack.back() += token;
801 }
802
803 void FGTrafficManager::pi(const char *target, const char *data)
804 {
805     //cout << "Processing instruction " << target << ' ' << data << endl;
806 }
807
808 void FGTrafficManager::warning(const char *message, int line, int column)
809 {
810     SG_LOG(SG_IO, SG_WARN,
811            "Warning: " << message << " (" << line << ',' << column << ')');
812 }
813
814 void FGTrafficManager::error(const char *message, int line, int column)
815 {
816     SG_LOG(SG_IO, SG_ALERT,
817            "Error: " << message << " (" << line << ',' << column << ')');
818 }