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