1 /******************************************************************************
3 * Written by Durk Talsma, started May 5, 2004.
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.
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.
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.
20 **************************************************************************/
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.
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
33 * 4) Each aircraft leaves at exactly the departure time.
34 * 5) Each aircraft arrives at exactly the specified arrival time.
37 *****************************************************************************/
53 #include <boost/foreach.hpp>
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>
62 #include <AIModel/AIAircraft.hxx>
63 #include <AIModel/AIFlightPlan.hxx>
64 #include <AIModel/AIBase.hxx>
65 #include <Airports/simple.hxx>
66 #include <Main/fg_init.hxx>
70 #include "TrafficMgr.hxx"
75 /******************************************************************************
77 *****************************************************************************/
78 FGTrafficManager::FGTrafficManager() :
81 enabled("/sim/traffic-manager/enabled"),
82 aiEnabled("/sim/ai/enabled"),
83 realWxEnabled("/environment/realwx/enabled"),
84 metarValid("/environment/metar/valid")
91 FGTrafficManager::~FGTrafficManager()
96 void FGTrafficManager::shutdown()
98 // Save the heuristics data
99 bool saveData = false;
101 if (fgGetBool("/sim/traffic-manager/heuristics")) {
102 SGPath cacheData(fgGetString("/sim/fg-home"));
103 cacheData.append("ai");
104 string airport = fgGetString("/sim/presets/airport-id");
106 if ((airport) != "") {
108 ::snprintf(buffer, 128, "%c/%c/%c/",
109 airport[0], airport[1], airport[2]);
110 cacheData.append(buffer);
111 if (!cacheData.exists()) {
112 cacheData.create_dir(0777);
114 cacheData.append(airport + "-cache.txt");
115 //cerr << "Saving AI traffic heuristics" << endl;
117 cachefile.open(cacheData.str().c_str());
118 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
121 for (ScheduleVectorIterator sched = scheduledAircraft.begin();
122 sched != scheduledAircraft.end(); sched++) {
124 cachefile << (*sched)->getRegistration() << " "
125 << (*sched)->getRunCount() << " "
126 << (*sched)->getHits() << " "
127 << (*sched)->getLastUsed() << endl;
134 scheduledAircraft.clear();
138 currAircraft = scheduledAircraft.begin();
144 void FGTrafficManager::init()
152 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
153 simgear::Dir trafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
154 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
156 BOOST_FOREACH(SGPath p, d) {
158 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
159 schedulesToRead.insert(schedulesToRead.end(), trafficFiles.begin(), trafficFiles.end());
162 fgSetBool("/sim/traffic-manager/heuristics", false);
163 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
164 string ext = path.extension();
165 if (path.extension() == "xml") {
167 readXML(path.str(), *this);
169 } else if (path.extension() == "conf") {
171 readTimeTableFromFile(path);
174 SG_LOG(SG_AI, SG_ALERT,
175 "Unknown data format " << path.str()
182 void FGTrafficManager::initStep()
185 if (schedulesToRead.empty()) {
190 SGPath path = schedulesToRead.front();
191 schedulesToRead.erase(schedulesToRead.begin());
192 SG_LOG(SG_AI, SG_DEBUG, path << " for traffic");
193 readXML(path.str(), *this);
196 void FGTrafficManager::finishInit()
199 SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
202 // Do sorting and scoring separately, to take advantage of the "homeport| variable
203 for (currAircraft = scheduledAircraft.begin();
204 currAircraft != scheduledAircraft.end(); currAircraft++) {
205 (*currAircraft)->setScore();
208 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
210 currAircraft = scheduledAircraft.begin();
211 currAircraftClosest = scheduledAircraft.begin();
217 void FGTrafficManager::loadHeuristics()
219 if (!fgGetBool("/sim/traffic-manager/heuristics")) {
223 HeuristicMap heurMap;
224 //cerr << "Processing Heuristics" << endl;
225 // Load the heuristics data
226 SGPath cacheData(fgGetString("/sim/fg-home"));
227 cacheData.append("ai");
228 string airport = fgGetString("/sim/presets/airport-id");
229 if ((airport) != "") {
231 ::snprintf(buffer, 128, "%c/%c/%c/",
232 airport[0], airport[1], airport[2]);
233 cacheData.append(buffer);
234 cacheData.append(airport + "-cache.txt");
236 if (cacheData.exists()) {
237 ifstream data(cacheData.c_str());
239 if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
240 SG_LOG(SG_GENERAL, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
241 cacheData.c_str() << " for Airport " << airport);
244 Heuristic h; // = new Heuristic;
245 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
248 HeuristicMapIterator itr = heurMap.find(h.registration);
249 if (itr != heurMap.end()) {
250 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
251 h.registration << " for AI aircraft");
253 heurMap[h.registration] = h;
260 for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
261 string registration = (*currAircraft)->getRegistration();
262 HeuristicMapIterator itr = heurMap.find(registration);
263 if (itr != heurMap.end()) {
264 (*currAircraft)->setrunCount(itr->second.runCount);
265 (*currAircraft)->setHits(itr->second.hits);
266 (*currAircraft)->setLastUsed(itr->second.lastRun);
271 void FGTrafficManager::update(double /*dt */ )
275 if (inited || doingInit)
280 if ((realWxEnabled && !metarValid)) {
286 // traffic depends on AI module
297 return; // still more to do on next update() call
301 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
302 if (scheduledAircraft.size() == 0) {
306 SGVec3d userCart = globals->get_aircraft_positon_cart();
308 if (currAircraft == scheduledAircraft.end()) {
309 currAircraft = scheduledAircraft.begin();
311 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
312 if (!((*currAircraft)->update(now, userCart))) {
313 (*currAircraft)->taint();
318 void FGTrafficManager::release(int id)
320 releaseList.push_back(id);
323 bool FGTrafficManager::isReleased(int id)
325 IdListIterator i = releaseList.begin();
326 while (i != releaseList.end()) {
328 releaseList.erase(i);
337 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
354 vector <string> tokens, depTime,arrTime;
355 vector <string>::iterator it;
356 ifstream infile(infileName.str().c_str());
358 infile.getline(buffer, 256);
362 //cerr << "Read line : " << buffer << endl;
363 buffString = string(buffer);
365 Tokenize(buffString, tokens, " \t");
366 //for (it = tokens.begin(); it != tokens.end(); it++) {
367 // cerr << "Tokens: " << *(it) << endl;
370 if (!tokens.empty()) {
371 if (tokens[0] == string("AC")) {
372 if (tokens.size() != 13) {
373 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
378 homePort = tokens[1];
379 registration = tokens[2];
380 if (tokens[11] == string("false")) {
387 flightReq = tokens[3] + tokens[5];
388 m_class = tokens[10];
389 FlightType = tokens[9];
390 radius = atof(tokens[8].c_str());
391 offset = atof(tokens[7].c_str());;
393 if (!FGAISchedule::validModelPath(model)) {
394 SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" <<
395 model << " from " << infileName.str());
398 SG_LOG(SG_GENERAL, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
399 << registration << " " << flightReq << " " << isHeavy
400 << " " << acType << " " << airline << " " << m_class
401 << " " << FlightType << " " << radius << " " << offset);
402 scheduledAircraft.push_back(new FGAISchedule(model,
414 } // of valid model path
416 if (tokens[0] == string("FLIGHT")) {
417 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
418 if (tokens.size() != 10) {
419 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
422 string callsign = tokens[1];
423 string fltrules = tokens[2];
424 string weekdays = tokens[3];
425 string departurePort = tokens[5];
426 string arrivalPort = tokens[7];
427 int cruiseAlt = atoi(tokens[8].c_str());
428 string depTimeGen = tokens[4];
429 string arrTimeGen = tokens[6];
430 string repeat = "WEEK";
431 string requiredAircraft = tokens[9];
433 if (weekdays.size() != 7) {
434 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
439 Tokenize(depTimeGen, depTime, ":");
440 Tokenize(arrTimeGen, arrTime, ":");
441 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
442 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
443 //cerr << "Using " << dep << " " << arr << endl;
444 bool arrivalWeekdayNeedsIncrement = false;
446 arrivalWeekdayNeedsIncrement = true;
448 for (int i = 0; i < 7; i++) {
450 if (weekdays[i] != '.') {
452 snprintf(buffer, 4, "%d/", j);
453 string departureTime = string(buffer) + depTimeGen + string(":00");
455 if (!arrivalWeekdayNeedsIncrement) {
456 arrivalTime = string(buffer) + arrTimeGen + string(":00");
458 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
459 snprintf(buffer, 4, "%d/", j+1);
460 arrivalTime = string(buffer) + arrTimeGen + string(":00");
462 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
463 snprintf(buffer, 4, "%d/", 0);
464 arrivalTime = string(buffer) + arrTimeGen + string(":00");
466 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
468 << departurePort << " "
469 << arrivalPort << " "
471 << departureTime << " "
472 << arrivalTime << " "
474 << requiredAircraft);
476 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
495 void FGTrafficManager::Tokenize(const string& str,
496 vector<string>& tokens,
497 const string& delimiters)
499 // Skip delimiters at beginning.
500 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
501 // Find first "non-delimiter".
502 string::size_type pos = str.find_first_of(delimiters, lastPos);
504 while (string::npos != pos || string::npos != lastPos)
506 // Found a token, add it to the vector.
507 tokens.push_back(str.substr(lastPos, pos - lastPos));
508 // Skip delimiters. Note the "not_of"
509 lastPos = str.find_first_not_of(delimiters, pos);
510 // Find next "non-delimiter"
511 pos = str.find_first_of(delimiters, lastPos);
516 void FGTrafficManager::startXML()
518 //cout << "Start XML" << endl;
519 requiredAircraft = "";
523 void FGTrafficManager::endXML()
525 //cout << "End XML" << endl;
528 void FGTrafficManager::startElement(const char *name,
529 const XMLAttributes & atts)
532 //cout << "Start element " << name << endl;
533 //FGTrafficManager temp;
534 //for (int i = 0; i < atts.size(); i++)
535 // if (string(atts.getName(i)) == string("include"))
536 attval = atts.getValue("include");
538 //cout << "including " << attval << endl;
539 SGPath path = globals->get_fg_root();
540 path.append("/Traffic/");
542 readXML(path.str(), *this);
544 elementValueStack.push_back("");
545 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
548 void FGTrafficManager::endElement(const char *name)
550 //cout << "End element " << name << endl;
551 const string & value = elementValueStack.back();
553 if (!strcmp(name, "model"))
555 else if (!strcmp(name, "livery"))
557 else if (!strcmp(name, "home-port"))
559 else if (!strcmp(name, "registration"))
560 registration = value;
561 else if (!strcmp(name, "airline"))
563 else if (!strcmp(name, "actype"))
565 else if (!strcmp(name, "required-aircraft"))
566 requiredAircraft = value;
567 else if (!strcmp(name, "flighttype"))
569 else if (!strcmp(name, "radius"))
570 radius = atoi(value.c_str());
571 else if (!strcmp(name, "offset"))
572 offset = atoi(value.c_str());
573 else if (!strcmp(name, "performance-class"))
575 else if (!strcmp(name, "heavy")) {
576 if (value == string("true"))
580 } else if (!strcmp(name, "callsign"))
582 else if (!strcmp(name, "fltrules"))
584 else if (!strcmp(name, "port"))
586 else if (!strcmp(name, "time"))
588 else if (!strcmp(name, "departure")) {
589 departurePort = port;
590 departureTime = timeString;
591 } else if (!strcmp(name, "cruise-alt"))
592 cruiseAlt = atoi(value.c_str());
593 else if (!strcmp(name, "arrival")) {
595 arrivalTime = timeString;
596 } else if (!strcmp(name, "repeat"))
598 else if (!strcmp(name, "flight")) {
599 // We have loaded and parsed all the information belonging to this flight
600 // so we temporarily store it.
601 //cerr << "Pusing back flight " << callsign << endl;
602 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
603 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
605 //Prioritize aircraft
606 string apt = fgGetString("/sim/presets/airport-id");
607 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
608 //if (departurePort == apt) score++;
609 //flights.push_back(new FGScheduledFlight(callsign,
617 if (requiredAircraft == "") {
619 snprintf(buffer, 16, "%d", acCounter);
620 requiredAircraft = buffer;
622 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
624 << departurePort << " "
625 << arrivalPort << " "
627 << departureTime << " "
628 << arrivalTime << " " << repeat << " " << requiredAircraft);
629 // For database maintainance purposes, it may be convenient to
631 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
632 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
634 << departurePort << ","
635 << arrivalPort << ","
637 << departureTime << ","
638 << arrivalTime << "," << repeat << "," << requiredAircraft);
640 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
649 requiredAircraft = "";
650 } else if (!strcmp(name, "aircraft")) {
654 elementValueStack.pop_back();
657 void FGTrafficManager::endAircraft()
659 string isHeavy = heavy ? "true" : "false";
661 if (missingModels.find(mdl) != missingModels.end()) {
662 // don't stat() or warn again
663 requiredAircraft = homePort = "";
667 if (!FGAISchedule::validModelPath(mdl)) {
668 missingModels.insert(mdl);
669 SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
670 requiredAircraft = homePort = "";
675 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
676 int randval = rand() & 100;
677 if (randval > proportion) {
678 requiredAircraft = homePort = "";
682 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
683 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
684 << "," << acType << "," << livery << ","
685 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
688 if (requiredAircraft == "") {
690 snprintf(buffer, 16, "%d", acCounter);
691 requiredAircraft = buffer;
693 if (homePort == "") {
694 homePort = departurePort;
697 scheduledAircraft.push_back(new FGAISchedule(mdl,
710 requiredAircraft = "";
712 SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
713 << registration << " with prioritization score " << score);
717 void FGTrafficManager::data(const char *s, int len)
719 string token = string(s, len);
720 //cout << "Character data " << string(s,len) << endl;
721 elementValueStack.back() += token;
724 void FGTrafficManager::pi(const char *target, const char *data)
726 //cout << "Processing instruction " << target << ' ' << data << endl;
729 void FGTrafficManager::warning(const char *message, int line, int column)
731 SG_LOG(SG_IO, SG_WARN,
732 "Warning: " << message << " (" << line << ',' << column << ')');
735 void FGTrafficManager::error(const char *message, int line, int column)
737 SG_LOG(SG_IO, SG_ALERT,
738 "Error: " << message << " (" << line << ',' << column << ')');