]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
#895: AI traffic not working when system is offline but real-wx is enabled
[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     releaseList.clear();
220
221     currAircraft = scheduledAircraft.begin();
222     doingInit = false;
223     inited = false;
224 }
225
226 /// caution - this is run on the helper thread to improve startup
227 /// responsiveness - do not access properties or global state from
228 /// here, since there's no locking protection at all
229 void FGTrafficManager::parseSchedule(const SGPath& path)
230 {
231   readXML(path.str(), *this);
232 }
233
234 void FGTrafficManager::init()
235 {
236     if (!enabled) {
237       return;
238     }
239
240     assert(!doingInit);
241     doingInit = true;
242     if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
243         scheduleParser.reset(new ScheduleParseThread(this));
244         scheduleParser->setTrafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));      
245         scheduleParser->start();
246     } else {
247         fgSetBool("/sim/traffic-manager/heuristics", false);
248         SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
249         string ext = path.extension();
250         if (path.extension() == "xml") {
251             if (path.exists()) {
252                 readXML(path.str(), *this);
253             }
254         } else if (path.extension() == "conf") {
255             if (path.exists()) {
256                 readTimeTableFromFile(path);
257             }
258         } else {
259              SG_LOG(SG_AI, SG_ALERT,
260                                "Unknown data format " << path.str()
261                                 << " for traffic");
262         }
263         //exit(1);
264     }
265 }
266
267
268
269 void FGTrafficManager::finishInit()
270 {
271     assert(doingInit);
272     SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
273     loadHeuristics();
274     
275     // Do sorting and scoring separately, to take advantage of the "homeport" variable
276     BOOST_FOREACH(FGAISchedule* schedule, scheduledAircraft) {
277         schedule->setScore();
278     }
279     
280     sort(scheduledAircraft.begin(), scheduledAircraft.end(),
281          compareSchedules);
282     currAircraft = scheduledAircraft.begin();
283     currAircraftClosest = scheduledAircraft.begin();
284     
285     doingInit = false;
286     inited = true;
287 }
288
289 void FGTrafficManager::loadHeuristics()
290 {
291     if (!fgGetBool("/sim/traffic-manager/heuristics")) {
292         return;
293     }
294   
295     HeuristicMap heurMap;
296     //cerr << "Processing Heuristics" << endl;
297     // Load the heuristics data
298     SGPath cacheData(globals->get_fg_home());
299     cacheData.append("ai");
300     string airport = fgGetString("/sim/presets/airport-id");
301     if ((airport) != "") {
302       char buffer[128];
303       ::snprintf(buffer, 128, "%c/%c/%c/",
304                  airport[0], airport[1], airport[2]);
305       cacheData.append(buffer);
306       cacheData.append(airport + "-cache.txt");
307       string revisionStr;
308       if (cacheData.exists()) {
309         ifstream data(cacheData.c_str());
310         data >> revisionStr;
311         if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
312           SG_LOG(SG_GENERAL, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " << 
313                  cacheData.c_str() << " for Airport " << airport);
314         } else {
315           while (1) {
316             Heuristic h; // = new Heuristic;
317             data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
318             if (data.eof())
319               break;
320             HeuristicMapIterator itr = heurMap.find(h.registration);
321             if (itr != heurMap.end()) {
322               SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " << 
323                      h.registration << " for AI aircraft");
324             } else {
325               heurMap[h.registration] = h;
326             }
327           }
328         }
329       }
330     } 
331     
332   for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
333         string registration = (*currAircraft)->getRegistration();
334         HeuristicMapIterator itr = heurMap.find(registration);
335         if (itr != heurMap.end()) {
336             (*currAircraft)->setrunCount(itr->second.runCount);
337             (*currAircraft)->setHits(itr->second.hits);
338             (*currAircraft)->setLastUsed(itr->second.lastRun);
339         }
340     }
341 }
342
343 bool FGTrafficManager::metarReady(double dt)
344 {
345     // wait for valid METAR (when realWX is enabled only), since we need
346     // to know the active runway
347     if (metarValid || !realWxEnabled)
348     {
349         waitingMetarTime = 0.0;
350         return true;
351     }
352
353     // METAR timeout: when running offline, remote server is down etc
354     if (waitingMetarStation != fgGetString("/environment/metar/station-id"))
355     {
356         // station has changed: wait for reply, restart timeout
357         waitingMetarTime = 0.0;
358         waitingMetarStation = fgGetString("/environment/metar/station-id");
359         return false;
360     }
361
362     // timeout elapsed (10 seconds)?
363     if (waitingMetarTime > 20.0)
364     {
365         return true;
366     }
367
368     waitingMetarTime += dt;
369     return false;
370 }
371
372 void FGTrafficManager::update(double dt)
373 {
374     if (!enabled)
375     {
376         if (inited || doingInit)
377             shutdown();
378         return;
379     }
380
381     if (!metarReady(dt))
382         return;
383
384     if (!aiEnabled)
385     {
386         // traffic depends on AI module
387         aiEnabled = true;
388     }
389
390     if (!inited) {
391         if (!doingInit) {
392             init();
393         }
394         
395         if (!scheduleParser->isFinished()) {
396           return;
397         }
398       
399         finishInit();
400     }
401         
402     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
403     if (scheduledAircraft.empty()) {
404         return;
405     }
406
407     SGVec3d userCart = globals->get_aircraft_position_cart();
408
409     if (currAircraft == scheduledAircraft.end()) {
410         currAircraft = scheduledAircraft.begin();
411     }
412     //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
413     if (!((*currAircraft)->update(now, userCart))) {
414         (*currAircraft)->taint();
415     }
416     currAircraft++;
417 }
418
419 void FGTrafficManager::release(int id)
420 {
421     releaseList.push_back(id);
422 }
423
424 bool FGTrafficManager::isReleased(int id)
425 {
426     IdListIterator i = releaseList.begin();
427     while (i != releaseList.end()) {
428         if ((*i) == id) {
429             releaseList.erase(i);
430             return true;
431         }
432         i++;
433     }
434     return false;
435 }
436
437
438 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
439 {
440     string model;
441     string livery;
442     string homePort;
443     string registration;
444     string flightReq;
445     bool   isHeavy;
446     string acType;
447     string airline;
448     string m_class;
449     string FlightType;
450     double radius;
451     double offset;
452
453     char buffer[256];
454     string buffString;
455     vector <string> tokens, depTime,arrTime;
456     vector <string>::iterator it;
457     ifstream infile(infileName.str().c_str());
458     while (1) {
459          infile.getline(buffer, 256);
460          if (infile.eof()) {
461              break;
462          }
463          //cerr << "Read line : " << buffer << endl;
464          buffString = string(buffer);
465          tokens.clear();
466          Tokenize(buffString, tokens, " \t");
467          //for (it = tokens.begin(); it != tokens.end(); it++) {
468          //    cerr << "Tokens: " << *(it) << endl;
469          //}
470          //cerr << endl;
471          if (!tokens.empty()) {
472              if (tokens[0] == string("AC")) {
473                  if (tokens.size() != 13) {
474                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
475                      exit(1);
476                  }
477                  model          = tokens[12];
478                  livery         = tokens[6];
479                  homePort       = tokens[1];
480                  registration   = tokens[2];
481                  if (tokens[11] == string("false")) {
482                      isHeavy = false;
483                  } else {
484                      isHeavy = true;
485                  }
486                  acType         = tokens[4];
487                  airline        = tokens[5];
488                  flightReq      = tokens[3] + tokens[5];
489                  m_class        = tokens[10];
490                  FlightType     = tokens[9];
491                  radius         = atof(tokens[8].c_str());
492                  offset         = atof(tokens[7].c_str());;
493                  
494                  if (!FGAISchedule::validModelPath(model)) {
495                      SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << 
496                             model << " from " << infileName.str());
497                  } else {
498                  
499                  SG_LOG(SG_GENERAL, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " " 
500                                                                 << registration << " " << flightReq << " " << isHeavy 
501                                                                 << " " << acType << " " << airline << " " << m_class 
502                                                                 << " " << FlightType << " " << radius << " " << offset);
503                  scheduledAircraft.push_back(new FGAISchedule(model, 
504                                                               livery, 
505                                                               homePort,
506                                                               registration, 
507                                                               flightReq,
508                                                               isHeavy,
509                                                               acType, 
510                                                               airline, 
511                                                               m_class, 
512                                                               FlightType,
513                                                               radius,
514                                                               offset));
515                  } // of valid model path
516              }
517              if (tokens[0] == string("FLIGHT")) {
518                  //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
519                  if (tokens.size() != 10) {
520                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
521                      exit(1);
522                  }
523                  string callsign = tokens[1];
524                  string fltrules = tokens[2];
525                  string weekdays = tokens[3];
526                  string departurePort = tokens[5];
527                  string arrivalPort   = tokens[7];
528                  int    cruiseAlt     = atoi(tokens[8].c_str());
529                  string depTimeGen    = tokens[4];
530                  string arrTimeGen    = tokens[6];
531                  string repeat        = "WEEK";
532                  string requiredAircraft = tokens[9];
533
534                  if (weekdays.size() != 7) {
535                      SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
536                      exit(1);
537                  }
538                  depTime.clear();
539                  arrTime.clear();
540                  Tokenize(depTimeGen, depTime, ":");
541                  Tokenize(arrTimeGen, arrTime, ":");
542                  double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
543                  double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
544                  //cerr << "Using " << dep << " " << arr << endl;
545                  bool arrivalWeekdayNeedsIncrement = false;
546                  if (arr < dep) {
547                        arrivalWeekdayNeedsIncrement = true;
548                  }
549                  for (int i = 0; i < 7; i++) {
550                      int j = i+1;
551                      if (weekdays[i] != '.') {
552                          char buffer[4];
553                          snprintf(buffer, 4, "%d/", j);
554                          string departureTime = string(buffer) + depTimeGen + string(":00");
555                          string arrivalTime;
556                          if (!arrivalWeekdayNeedsIncrement) {
557                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
558                          }
559                          if (arrivalWeekdayNeedsIncrement && i != 6 ) {
560                              snprintf(buffer, 4, "%d/", j+1);
561                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
562                          }
563                          if (arrivalWeekdayNeedsIncrement && i == 6 ) {
564                              snprintf(buffer, 4, "%d/", 0);
565                              arrivalTime   = string(buffer) + arrTimeGen  + string(":00");
566                          }
567                          SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign       << " "
568                                                       << fltrules       << " "
569                                                       <<  departurePort << " "
570                                                       <<  arrivalPort   << " "
571                                                       <<  cruiseAlt     << " "
572                                                       <<  departureTime << " "
573                                                       <<  arrivalTime   << " "
574                                                       << repeat        << " " 
575                                                       <<  requiredAircraft);
576
577                          flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
578                                                                  fltrules,
579                                                                  departurePort,
580                                                                  arrivalPort,
581                                                                  cruiseAlt,
582                                                                  departureTime,
583                                                                  arrivalTime,
584                                                                  repeat,
585                                                                  requiredAircraft));
586                     }
587                 }
588              }
589          }
590
591     }
592     //exit(1);
593 }
594
595
596 void FGTrafficManager::Tokenize(const string& str,
597                       vector<string>& tokens,
598                       const string& delimiters)
599 {
600     // Skip delimiters at beginning.
601     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
602     // Find first "non-delimiter".
603     string::size_type pos     = str.find_first_of(delimiters, lastPos);
604
605     while (string::npos != pos || string::npos != lastPos)
606     {
607         // Found a token, add it to the vector.
608         tokens.push_back(str.substr(lastPos, pos - lastPos));
609         // Skip delimiters.  Note the "not_of"
610         lastPos = str.find_first_not_of(delimiters, pos);
611         // Find next "non-delimiter"
612         pos = str.find_first_of(delimiters, lastPos);
613     }
614 }
615
616
617 void FGTrafficManager::startXML()
618 {
619     //cout << "Start XML" << endl;
620     requiredAircraft = "";
621     homePort = "";
622 }
623
624 void FGTrafficManager::endXML()
625 {
626     //cout << "End XML" << endl;
627 }
628
629 void FGTrafficManager::startElement(const char *name,
630                                     const XMLAttributes & atts)
631 {
632     const char *attval;
633     //cout << "Start element " << name << endl;
634     //FGTrafficManager temp;
635     //for (int i = 0; i < atts.size(); i++)
636     //  if (string(atts.getName(i)) == string("include"))
637     attval = atts.getValue("include");
638     if (attval != 0) {
639         //cout << "including " << attval << endl;
640         SGPath path = globals->get_fg_root();
641         path.append("/Traffic/");
642         path.append(attval);
643         readXML(path.str(), *this);
644     }
645     elementValueStack.push_back("");
646     //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
647 }
648
649 void FGTrafficManager::endElement(const char *name)
650 {
651     //cout << "End element " << name << endl;
652     const string & value = elementValueStack.back();
653
654     if (!strcmp(name, "model"))
655         mdl = value;
656     else if (!strcmp(name, "livery"))
657         livery = value;
658     else if (!strcmp(name, "home-port"))
659         homePort = value;
660     else if (!strcmp(name, "registration"))
661         registration = value;
662     else if (!strcmp(name, "airline"))
663         airline = value;
664     else if (!strcmp(name, "actype"))
665         acType = value;
666     else if (!strcmp(name, "required-aircraft"))
667         requiredAircraft = value;
668     else if (!strcmp(name, "flighttype"))
669         flighttype = value;
670     else if (!strcmp(name, "radius"))
671         radius = atoi(value.c_str());
672     else if (!strcmp(name, "offset"))
673         offset = atoi(value.c_str());
674     else if (!strcmp(name, "performance-class"))
675         m_class = value;
676     else if (!strcmp(name, "heavy")) {
677         if (value == string("true"))
678             heavy = true;
679         else
680             heavy = false;
681     } else if (!strcmp(name, "callsign"))
682         callsign = value;
683     else if (!strcmp(name, "fltrules"))
684         fltrules = value;
685     else if (!strcmp(name, "port"))
686         port = value;
687     else if (!strcmp(name, "time"))
688         timeString = value;
689     else if (!strcmp(name, "departure")) {
690         departurePort = port;
691         departureTime = timeString;
692     } else if (!strcmp(name, "cruise-alt"))
693         cruiseAlt = atoi(value.c_str());
694     else if (!strcmp(name, "arrival")) {
695         arrivalPort = port;
696         arrivalTime = timeString;
697     } else if (!strcmp(name, "repeat"))
698         repeat = value;
699     else if (!strcmp(name, "flight")) {
700         // We have loaded and parsed all the information belonging to this flight
701         // so we temporarily store it. 
702         //cerr << "Pusing back flight " << callsign << endl;
703         //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
704         //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
705
706         //Prioritize aircraft 
707         string apt = fgGetString("/sim/presets/airport-id");
708         //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
709         //if (departurePort == apt) score++;
710         //flights.push_back(new FGScheduledFlight(callsign,
711         //                                fltrules,
712         //                                departurePort,
713         //                                arrivalPort,
714         //                                cruiseAlt,
715         //                                departureTime,
716         //                                arrivalTime,
717         //                                repeat));
718         if (requiredAircraft == "") {
719             char buffer[16];
720             snprintf(buffer, 16, "%d", acCounter);
721             requiredAircraft = buffer;
722         }
723         SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
724                << fltrules << " "
725                << departurePort << " "
726                << arrivalPort << " "
727                << cruiseAlt << " "
728                << departureTime << " "
729                << arrivalTime << " " << repeat << " " << requiredAircraft);
730         // For database maintainance purposes, it may be convenient to
731         // 
732         if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
733              SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
734                           << fltrules << ","
735                           << departurePort << ","
736                           << arrivalPort << ","
737                           << cruiseAlt << ","
738                           << departureTime << ","
739                           << arrivalTime << "," << repeat << "," << requiredAircraft);
740         }
741         flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
742                                                                   fltrules,
743                                                                   departurePort,
744                                                                   arrivalPort,
745                                                                   cruiseAlt,
746                                                                   departureTime,
747                                                                   arrivalTime,
748                                                                   repeat,
749                                                                   requiredAircraft));
750         requiredAircraft = "";
751     } else if (!strcmp(name, "aircraft")) {
752         endAircraft();
753     }
754     
755     elementValueStack.pop_back();
756 }
757
758 void FGTrafficManager::endAircraft()
759 {
760     string isHeavy = heavy ? "true" : "false";
761
762     if (missingModels.find(mdl) != missingModels.end()) {
763     // don't stat() or warn again
764         requiredAircraft = homePort = "";
765         return;
766     }
767     
768     if (!FGAISchedule::validModelPath(mdl)) {
769         missingModels.insert(mdl);
770         SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
771         requiredAircraft = homePort = "";
772         return;
773     }
774         
775     int proportion =
776         (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
777     int randval = rand() & 100;
778     if (randval > proportion) {
779         requiredAircraft = homePort = "";
780         return;
781     }
782     
783     if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
784         SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft 
785                << "," << acType << "," << livery << "," 
786                << airline << ","  << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
787     }
788
789     if (requiredAircraft == "") {
790         char buffer[16];
791         snprintf(buffer, 16, "%d", acCounter);
792         requiredAircraft = buffer;
793     }
794     if (homePort == "") {
795         homePort = departurePort;
796     }
797     
798     scheduledAircraft.push_back(new FGAISchedule(mdl,
799                                                  livery,
800                                                  homePort,
801                                                  registration,
802                                                  requiredAircraft,
803                                                  heavy,
804                                                  acType,
805                                                  airline,
806                                                  m_class,
807                                                  flighttype,
808                                                  radius, offset));
809             
810     acCounter++;
811     requiredAircraft = "";
812     homePort = "";
813     score = 0;
814 }
815     
816 void FGTrafficManager::data(const char *s, int len)
817 {
818     string token = string(s, len);
819     //cout << "Character data " << string(s,len) << endl;
820     elementValueStack.back() += token;
821 }
822
823 void FGTrafficManager::pi(const char *target, const char *data)
824 {
825     //cout << "Processing instruction " << target << ' ' << data << endl;
826 }
827
828 void FGTrafficManager::warning(const char *message, int line, int column)
829 {
830     SG_LOG(SG_IO, SG_WARN,
831            "Warning: " << message << " (" << line << ',' << column << ')');
832 }
833
834 void FGTrafficManager::error(const char *message, int line, int column)
835 {
836     SG_LOG(SG_IO, SG_ALERT,
837            "Error: " << message << " (" << line << ',' << column << ')');
838 }