]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
Use a helper thread to init the traffic-manager.
[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   enabled("/sim/traffic-manager/enabled"),
155   aiEnabled("/sim/ai/enabled"),
156   realWxEnabled("/environment/realwx/enabled"),
157   metarValid("/environment/metar/valid")
158 {
159     //score = 0;
160     //runCount = 0;
161     acCounter = 0;
162 }
163
164 FGTrafficManager::~FGTrafficManager()
165 {
166     shutdown();
167 }
168
169 void FGTrafficManager::shutdown()
170 {
171     if (!inited) {
172       if (doingInit) {
173         scheduleParser.reset();
174         doingInit = false;
175       }
176       
177       return;
178     }
179   
180     // Save the heuristics data
181     bool saveData = false;
182     ofstream cachefile;
183     if (fgGetBool("/sim/traffic-manager/heuristics")) {
184         SGPath cacheData(globals->get_fg_home());
185         cacheData.append("ai");
186         string airport = fgGetString("/sim/presets/airport-id");
187
188         if ((airport) != "") {
189             char buffer[128];
190             ::snprintf(buffer, 128, "%c/%c/%c/",
191                        airport[0], airport[1], airport[2]);
192             cacheData.append(buffer);
193             if (!cacheData.exists()) {
194                 cacheData.create_dir(0777);
195             }
196             cacheData.append(airport + "-cache.txt");
197             //cerr << "Saving AI traffic heuristics" << endl;
198             saveData = true;
199             cachefile.open(cacheData.str().c_str());
200             cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
201         }
202     }
203     for (ScheduleVectorIterator sched = scheduledAircraft.begin();
204          sched != scheduledAircraft.end(); sched++) {
205         if (saveData) {
206             cachefile << (*sched)->getRegistration() << " "
207                 << (*sched)->getRunCount() << " "
208                 << (*sched)->getHits() << " "
209                 << (*sched)->getLastUsed() << endl;
210         }
211         delete(*sched);
212     }
213     if (saveData) {
214         cachefile.close();
215     }
216     scheduledAircraft.clear();
217     flights.clear();
218     releaseList.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     for (currAircraft = scheduledAircraft.begin();
276          currAircraft != scheduledAircraft.end(); currAircraft++) {
277         (*currAircraft)->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 void FGTrafficManager::update(double /*dt */ )
344 {
345     if (!enabled)
346     {
347         if (inited || doingInit)
348             shutdown();
349         return;
350     }
351
352     if ((realWxEnabled && !metarValid)) {
353         return;
354     }
355
356     if (!aiEnabled)
357     {
358         // traffic depends on AI module
359         aiEnabled = true;
360     }
361
362     if (!inited) {
363         if (!doingInit) {
364             init();
365         }
366         
367         if (!scheduleParser->isFinished()) {
368           return;
369         }
370       
371         finishInit();
372     }
373         
374     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
375     if (scheduledAircraft.size() == 0) {
376         return;
377     }
378
379     SGVec3d userCart = globals->get_aircraft_position_cart();
380
381     if (currAircraft == scheduledAircraft.end()) {
382         currAircraft = scheduledAircraft.begin();
383     }
384     //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
385     if (!((*currAircraft)->update(now, userCart))) {
386         (*currAircraft)->taint();
387     }
388     currAircraft++;
389 }
390
391 void FGTrafficManager::release(int id)
392 {
393     releaseList.push_back(id);
394 }
395
396 bool FGTrafficManager::isReleased(int id)
397 {
398     IdListIterator i = releaseList.begin();
399     while (i != releaseList.end()) {
400         if ((*i) == id) {
401             releaseList.erase(i);
402             return true;
403         }
404         i++;
405     }
406     return false;
407 }
408
409
410 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
411 {
412     string model;
413     string livery;
414     string homePort;
415     string registration;
416     string flightReq;
417     bool   isHeavy;
418     string acType;
419     string airline;
420     string m_class;
421     string FlightType;
422     double radius;
423     double offset;
424
425     char buffer[256];
426     string buffString;
427     vector <string> tokens, depTime,arrTime;
428     vector <string>::iterator it;
429     ifstream infile(infileName.str().c_str());
430     while (1) {
431          infile.getline(buffer, 256);
432          if (infile.eof()) {
433              break;
434          }
435          //cerr << "Read line : " << buffer << endl;
436          buffString = string(buffer);
437          tokens.clear();
438          Tokenize(buffString, tokens, " \t");
439          //for (it = tokens.begin(); it != tokens.end(); it++) {
440          //    cerr << "Tokens: " << *(it) << endl;
441          //}
442          //cerr << endl;
443          if (!tokens.empty()) {
444              if (tokens[0] == string("AC")) {
445                  if (tokens.size() != 13) {
446                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
447                      exit(1);
448                  }
449                  model          = tokens[12];
450                  livery         = tokens[6];
451                  homePort       = tokens[1];
452                  registration   = tokens[2];
453                  if (tokens[11] == string("false")) {
454                      isHeavy = false;
455                  } else {
456                      isHeavy = true;
457                  }
458                  acType         = tokens[4];
459                  airline        = tokens[5];
460                  flightReq      = tokens[3] + tokens[5];
461                  m_class        = tokens[10];
462                  FlightType     = tokens[9];
463                  radius         = atof(tokens[8].c_str());
464                  offset         = atof(tokens[7].c_str());;
465                  
466                  if (!FGAISchedule::validModelPath(model)) {
467                      SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << 
468                             model << " from " << infileName.str());
469                  } else {
470                  
471                  SG_LOG(SG_GENERAL, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " " 
472                                                                 << registration << " " << flightReq << " " << isHeavy 
473                                                                 << " " << acType << " " << airline << " " << m_class 
474                                                                 << " " << FlightType << " " << radius << " " << offset);
475                  scheduledAircraft.push_back(new FGAISchedule(model, 
476                                                               livery, 
477                                                               homePort,
478                                                               registration, 
479                                                               flightReq,
480                                                               isHeavy,
481                                                               acType, 
482                                                               airline, 
483                                                               m_class, 
484                                                               FlightType,
485                                                               radius,
486                                                               offset));
487                  } // of valid model path
488              }
489              if (tokens[0] == string("FLIGHT")) {
490                  //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
491                  if (tokens.size() != 10) {
492                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
493                      exit(1);
494                  }
495                  string callsign = tokens[1];
496                  string fltrules = tokens[2];
497                  string weekdays = tokens[3];
498                  string departurePort = tokens[5];
499                  string arrivalPort   = tokens[7];
500                  int    cruiseAlt     = atoi(tokens[8].c_str());
501                  string depTimeGen    = tokens[4];
502                  string arrTimeGen    = tokens[6];
503                  string repeat        = "WEEK";
504                  string requiredAircraft = tokens[9];
505
506                  if (weekdays.size() != 7) {
507                      SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
508                      exit(1);
509                  }
510                  depTime.clear();
511                  arrTime.clear();
512                  Tokenize(depTimeGen, depTime, ":");
513                  Tokenize(arrTimeGen, arrTime, ":");
514                  double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
515                  double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
516                  //cerr << "Using " << dep << " " << arr << endl;
517                  bool arrivalWeekdayNeedsIncrement = false;
518                  if (arr < dep) {
519                        arrivalWeekdayNeedsIncrement = true;
520                  }
521                  for (int i = 0; i < 7; i++) {
522                      int j = i+1;
523                      if (weekdays[i] != '.') {
524                          char buffer[4];
525                          snprintf(buffer, 4, "%d/", j);
526                          string departureTime = string(buffer) + depTimeGen + string(":00");
527                          string arrivalTime;
528                          if (!arrivalWeekdayNeedsIncrement) {
529                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
530                          }
531                          if (arrivalWeekdayNeedsIncrement && i != 6 ) {
532                              snprintf(buffer, 4, "%d/", j+1);
533                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
534                          }
535                          if (arrivalWeekdayNeedsIncrement && i == 6 ) {
536                              snprintf(buffer, 4, "%d/", 0);
537                              arrivalTime   = string(buffer) + arrTimeGen  + string(":00");
538                          }
539                          SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign       << " "
540                                                       << fltrules       << " "
541                                                       <<  departurePort << " "
542                                                       <<  arrivalPort   << " "
543                                                       <<  cruiseAlt     << " "
544                                                       <<  departureTime << " "
545                                                       <<  arrivalTime   << " "
546                                                       << repeat        << " " 
547                                                       <<  requiredAircraft);
548
549                          flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
550                                                                  fltrules,
551                                                                  departurePort,
552                                                                  arrivalPort,
553                                                                  cruiseAlt,
554                                                                  departureTime,
555                                                                  arrivalTime,
556                                                                  repeat,
557                                                                  requiredAircraft));
558                     }
559                 }
560              }
561          }
562
563     }
564     //exit(1);
565 }
566
567
568 void FGTrafficManager::Tokenize(const string& str,
569                       vector<string>& tokens,
570                       const string& delimiters)
571 {
572     // Skip delimiters at beginning.
573     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
574     // Find first "non-delimiter".
575     string::size_type pos     = str.find_first_of(delimiters, lastPos);
576
577     while (string::npos != pos || string::npos != lastPos)
578     {
579         // Found a token, add it to the vector.
580         tokens.push_back(str.substr(lastPos, pos - lastPos));
581         // Skip delimiters.  Note the "not_of"
582         lastPos = str.find_first_not_of(delimiters, pos);
583         // Find next "non-delimiter"
584         pos = str.find_first_of(delimiters, lastPos);
585     }
586 }
587
588
589 void FGTrafficManager::startXML()
590 {
591     //cout << "Start XML" << endl;
592     requiredAircraft = "";
593     homePort = "";
594 }
595
596 void FGTrafficManager::endXML()
597 {
598     //cout << "End XML" << endl;
599 }
600
601 void FGTrafficManager::startElement(const char *name,
602                                     const XMLAttributes & atts)
603 {
604     const char *attval;
605     //cout << "Start element " << name << endl;
606     //FGTrafficManager temp;
607     //for (int i = 0; i < atts.size(); i++)
608     //  if (string(atts.getName(i)) == string("include"))
609     attval = atts.getValue("include");
610     if (attval != 0) {
611         //cout << "including " << attval << endl;
612         SGPath path = globals->get_fg_root();
613         path.append("/Traffic/");
614         path.append(attval);
615         readXML(path.str(), *this);
616     }
617     elementValueStack.push_back("");
618     //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
619 }
620
621 void FGTrafficManager::endElement(const char *name)
622 {
623     //cout << "End element " << name << endl;
624     const string & value = elementValueStack.back();
625
626     if (!strcmp(name, "model"))
627         mdl = value;
628     else if (!strcmp(name, "livery"))
629         livery = value;
630     else if (!strcmp(name, "home-port"))
631         homePort = value;
632     else if (!strcmp(name, "registration"))
633         registration = value;
634     else if (!strcmp(name, "airline"))
635         airline = value;
636     else if (!strcmp(name, "actype"))
637         acType = value;
638     else if (!strcmp(name, "required-aircraft"))
639         requiredAircraft = value;
640     else if (!strcmp(name, "flighttype"))
641         flighttype = value;
642     else if (!strcmp(name, "radius"))
643         radius = atoi(value.c_str());
644     else if (!strcmp(name, "offset"))
645         offset = atoi(value.c_str());
646     else if (!strcmp(name, "performance-class"))
647         m_class = value;
648     else if (!strcmp(name, "heavy")) {
649         if (value == string("true"))
650             heavy = true;
651         else
652             heavy = false;
653     } else if (!strcmp(name, "callsign"))
654         callsign = value;
655     else if (!strcmp(name, "fltrules"))
656         fltrules = value;
657     else if (!strcmp(name, "port"))
658         port = value;
659     else if (!strcmp(name, "time"))
660         timeString = value;
661     else if (!strcmp(name, "departure")) {
662         departurePort = port;
663         departureTime = timeString;
664     } else if (!strcmp(name, "cruise-alt"))
665         cruiseAlt = atoi(value.c_str());
666     else if (!strcmp(name, "arrival")) {
667         arrivalPort = port;
668         arrivalTime = timeString;
669     } else if (!strcmp(name, "repeat"))
670         repeat = value;
671     else if (!strcmp(name, "flight")) {
672         // We have loaded and parsed all the information belonging to this flight
673         // so we temporarily store it. 
674         //cerr << "Pusing back flight " << callsign << endl;
675         //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
676         //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
677
678         //Prioritize aircraft 
679         string apt = fgGetString("/sim/presets/airport-id");
680         //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
681         //if (departurePort == apt) score++;
682         //flights.push_back(new FGScheduledFlight(callsign,
683         //                                fltrules,
684         //                                departurePort,
685         //                                arrivalPort,
686         //                                cruiseAlt,
687         //                                departureTime,
688         //                                arrivalTime,
689         //                                repeat));
690         if (requiredAircraft == "") {
691             char buffer[16];
692             snprintf(buffer, 16, "%d", acCounter);
693             requiredAircraft = buffer;
694         }
695         SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
696                << fltrules << " "
697                << departurePort << " "
698                << arrivalPort << " "
699                << cruiseAlt << " "
700                << departureTime << " "
701                << arrivalTime << " " << repeat << " " << requiredAircraft);
702         // For database maintainance purposes, it may be convenient to
703         // 
704         if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
705              SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
706                           << fltrules << ","
707                           << departurePort << ","
708                           << arrivalPort << ","
709                           << cruiseAlt << ","
710                           << departureTime << ","
711                           << arrivalTime << "," << repeat << "," << requiredAircraft);
712         }
713         flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
714                                                                   fltrules,
715                                                                   departurePort,
716                                                                   arrivalPort,
717                                                                   cruiseAlt,
718                                                                   departureTime,
719                                                                   arrivalTime,
720                                                                   repeat,
721                                                                   requiredAircraft));
722         requiredAircraft = "";
723     } else if (!strcmp(name, "aircraft")) {
724         endAircraft();
725     }
726     
727     elementValueStack.pop_back();
728 }
729
730 void FGTrafficManager::endAircraft()
731 {
732     string isHeavy = heavy ? "true" : "false";
733
734     if (missingModels.find(mdl) != missingModels.end()) {
735     // don't stat() or warn again
736         requiredAircraft = homePort = "";
737         return;
738     }
739     
740     if (!FGAISchedule::validModelPath(mdl)) {
741         missingModels.insert(mdl);
742         SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
743         requiredAircraft = homePort = "";
744         return;
745     }
746         
747     int proportion =
748         (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
749     int randval = rand() & 100;
750     if (randval > proportion) {
751         requiredAircraft = homePort = "";
752         return;
753     }
754     
755     if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
756         SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft 
757                << "," << acType << "," << livery << "," 
758                << airline << ","  << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
759     }
760
761     if (requiredAircraft == "") {
762         char buffer[16];
763         snprintf(buffer, 16, "%d", acCounter);
764         requiredAircraft = buffer;
765     }
766     if (homePort == "") {
767         homePort = departurePort;
768     }
769     
770     scheduledAircraft.push_back(new FGAISchedule(mdl,
771                                                  livery,
772                                                  homePort,
773                                                  registration,
774                                                  requiredAircraft,
775                                                  heavy,
776                                                  acType,
777                                                  airline,
778                                                  m_class,
779                                                  flighttype,
780                                                  radius, offset));
781             
782     acCounter++;
783     requiredAircraft = "";
784     homePort = "";
785     SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
786            << registration << " with prioritization score " << score);
787     score = 0;
788 }
789     
790 void FGTrafficManager::data(const char *s, int len)
791 {
792     string token = string(s, len);
793     //cout << "Character data " << string(s,len) << endl;
794     elementValueStack.back() += token;
795 }
796
797 void FGTrafficManager::pi(const char *target, const char *data)
798 {
799     //cout << "Processing instruction " << target << ' ' << data << endl;
800 }
801
802 void FGTrafficManager::warning(const char *message, int line, int column)
803 {
804     SG_LOG(SG_IO, SG_WARN,
805            "Warning: " << message << " (" << line << ',' << column << ')');
806 }
807
808 void FGTrafficManager::error(const char *message, int line, int column)
809 {
810     SG_LOG(SG_IO, SG_ALERT,
811            "Error: " << message << " (" << line << ',' << column << ')');
812 }