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/route/waypoint.hxx>
60 #include <simgear/structure/subsystem_mgr.hxx>
61 #include <simgear/xml/easyxml.hxx>
63 #include <AIModel/AIAircraft.hxx>
64 #include <AIModel/AIFlightPlan.hxx>
65 #include <AIModel/AIBase.hxx>
66 #include <Airports/simple.hxx>
67 #include <Main/fg_init.hxx>
71 #include "TrafficMgr.hxx"
76 /******************************************************************************
78 *****************************************************************************/
79 FGTrafficManager::FGTrafficManager() :
82 enabled("/sim/traffic-manager/enabled"),
83 aiEnabled("/sim/ai/enabled"),
84 realWxEnabled("/environment/realwx/enabled"),
85 metarValid("/environment/metar/valid")
92 FGTrafficManager::~FGTrafficManager()
94 // Save the heuristics data
95 bool saveData = false;
97 if (fgGetBool("/sim/traffic-manager/heuristics")) {
98 SGPath cacheData(fgGetString("/sim/fg-home"));
99 cacheData.append("ai");
100 string airport = fgGetString("/sim/presets/airport-id");
102 if ((airport) != "") {
104 ::snprintf(buffer, 128, "%c/%c/%c/",
105 airport[0], airport[1], airport[2]);
106 cacheData.append(buffer);
107 if (!cacheData.exists()) {
108 cacheData.create_dir(0777);
110 cacheData.append(airport + "-cache.txt");
111 //cerr << "Saving AI traffic heuristics" << endl;
113 cachefile.open(cacheData.str().c_str());
114 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
117 for (ScheduleVectorIterator sched = scheduledAircraft.begin();
118 sched != scheduledAircraft.end(); sched++) {
120 cachefile << (*sched)->getRegistration() << " "
121 << (*sched)->getRunCount() << " "
122 << (*sched)->getHits() << " "
123 << (*sched)->getLastUsed() << endl;
130 scheduledAircraft.clear();
135 void FGTrafficManager::init()
137 if (!enabled || !aiEnabled) {
143 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
144 simgear::Dir trafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
145 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
147 BOOST_FOREACH(SGPath p, d) {
149 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
150 schedulesToRead.insert(schedulesToRead.end(), trafficFiles.begin(), trafficFiles.end());
153 fgSetBool("/sim/traffic-manager/heuristics", false);
154 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
155 string ext = path.extension();
156 if (path.extension() == "xml") {
158 readXML(path.str(), *this);
160 } else if (path.extension() == "conf") {
162 readTimeTableFromFile(path);
165 SG_LOG(SG_AI, SG_ALERT,
166 "Unknown data format " << path.str()
173 void FGTrafficManager::initStep()
176 if (schedulesToRead.empty()) {
181 SGPath path = schedulesToRead.front();
182 schedulesToRead.erase(schedulesToRead.begin());
183 SG_LOG(SG_AI, SG_DEBUG, path << " for traffic");
184 readXML(path.str(), *this);
187 void FGTrafficManager::finishInit()
190 SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
193 // Do sorting and scoring separately, to take advantage of the "homeport| variable
194 for (currAircraft = scheduledAircraft.begin();
195 currAircraft != scheduledAircraft.end(); currAircraft++) {
196 (*currAircraft)->setScore();
199 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
201 currAircraft = scheduledAircraft.begin();
202 currAircraftClosest = scheduledAircraft.begin();
208 void FGTrafficManager::loadHeuristics()
210 if (!fgGetBool("/sim/traffic-manager/heuristics")) {
214 HeuristicMap heurMap;
215 //cerr << "Processing Heuristics" << endl;
216 // Load the heuristics data
217 SGPath cacheData(fgGetString("/sim/fg-home"));
218 cacheData.append("ai");
219 string airport = fgGetString("/sim/presets/airport-id");
220 if ((airport) != "") {
222 ::snprintf(buffer, 128, "%c/%c/%c/",
223 airport[0], airport[1], airport[2]);
224 cacheData.append(buffer);
225 cacheData.append(airport + "-cache.txt");
227 if (cacheData.exists()) {
228 ifstream data(cacheData.c_str());
230 if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
231 SG_LOG(SG_GENERAL, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
232 cacheData.c_str() << " for Airport " << airport);
235 Heuristic h; // = new Heuristic;
236 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
239 HeuristicMapIterator itr = heurMap.find(h.registration);
240 if (itr != heurMap.end()) {
241 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
242 h.registration << " for AI aircraft");
244 heurMap[h.registration] = h;
251 for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
252 string registration = (*currAircraft)->getRegistration();
253 HeuristicMapIterator itr = heurMap.find(registration);
254 if (itr != heurMap.end()) {
255 (*currAircraft)->setrunCount(itr->second.runCount);
256 (*currAircraft)->setHits(itr->second.hits);
257 (*currAircraft)->setLastUsed(itr->second.lastRun);
262 void FGTrafficManager::update(double /*dt */ )
264 if (!enabled || !aiEnabled || (realWxEnabled && !metarValid)) {
275 return; // still more to do on next update() call
279 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
280 if (scheduledAircraft.size() == 0) {
284 SGVec3d userCart = globals->get_aircraft_positon_cart();
286 if (currAircraft == scheduledAircraft.end()) {
287 currAircraft = scheduledAircraft.begin();
289 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
290 if (!((*currAircraft)->update(now, userCart))) {
291 (*currAircraft)->taint();
296 void FGTrafficManager::release(int id)
298 releaseList.push_back(id);
301 bool FGTrafficManager::isReleased(int id)
303 IdListIterator i = releaseList.begin();
304 while (i != releaseList.end()) {
306 releaseList.erase(i);
315 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
332 vector <string> tokens, depTime,arrTime;
333 vector <string>::iterator it;
334 ifstream infile(infileName.str().c_str());
336 infile.getline(buffer, 256);
340 //cerr << "Read line : " << buffer << endl;
341 buffString = string(buffer);
343 Tokenize(buffString, tokens, " \t");
344 //for (it = tokens.begin(); it != tokens.end(); it++) {
345 // cerr << "Tokens: " << *(it) << endl;
348 if (!tokens.empty()) {
349 if (tokens[0] == string("AC")) {
350 if (tokens.size() != 13) {
351 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
356 homePort = tokens[1];
357 registration = tokens[2];
358 if (tokens[11] == string("false")) {
365 flightReq = tokens[3] + tokens[5];
366 m_class = tokens[10];
367 FlightType = tokens[9];
368 radius = atof(tokens[8].c_str());
369 offset = atof(tokens[7].c_str());;
370 SG_LOG(SG_GENERAL, SG_ALERT, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
371 << registration << " " << flightReq << " " << isHeavy
372 << " " << acType << " " << airline << " " << m_class
373 << " " << FlightType << " " << radius << " " << offset);
374 scheduledAircraft.push_back(new FGAISchedule(model,
387 if (tokens[0] == string("FLIGHT")) {
388 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
389 if (tokens.size() != 10) {
390 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
393 string callsign = tokens[1];
394 string fltrules = tokens[2];
395 string weekdays = tokens[3];
396 string departurePort = tokens[5];
397 string arrivalPort = tokens[7];
398 int cruiseAlt = atoi(tokens[8].c_str());
399 string depTimeGen = tokens[4];
400 string arrTimeGen = tokens[6];
401 string repeat = "WEEK";
402 string requiredAircraft = tokens[9];
404 if (weekdays.size() != 7) {
405 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
410 Tokenize(depTimeGen, depTime, ":");
411 Tokenize(arrTimeGen, arrTime, ":");
412 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
413 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
414 //cerr << "Using " << dep << " " << arr << endl;
415 bool arrivalWeekdayNeedsIncrement = false;
417 arrivalWeekdayNeedsIncrement = true;
419 for (int i = 0; i < 7; i++) {
421 if (weekdays[i] != '.') {
423 snprintf(buffer, 4, "%d/", j);
424 string departureTime = string(buffer) + depTimeGen + string(":00");
426 if (!arrivalWeekdayNeedsIncrement) {
427 arrivalTime = string(buffer) + arrTimeGen + string(":00");
429 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
430 snprintf(buffer, 4, "%d/", j+1);
431 arrivalTime = string(buffer) + arrTimeGen + string(":00");
433 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
434 snprintf(buffer, 4, "%d/", 0);
435 arrivalTime = string(buffer) + arrTimeGen + string(":00");
437 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
439 << departurePort << " "
440 << arrivalPort << " "
442 << departureTime << " "
443 << arrivalTime << " "
445 << requiredAircraft);
447 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
466 void FGTrafficManager::Tokenize(const string& str,
467 vector<string>& tokens,
468 const string& delimiters)
470 // Skip delimiters at beginning.
471 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
472 // Find first "non-delimiter".
473 string::size_type pos = str.find_first_of(delimiters, lastPos);
475 while (string::npos != pos || string::npos != lastPos)
477 // Found a token, add it to the vector.
478 tokens.push_back(str.substr(lastPos, pos - lastPos));
479 // Skip delimiters. Note the "not_of"
480 lastPos = str.find_first_not_of(delimiters, pos);
481 // Find next "non-delimiter"
482 pos = str.find_first_of(delimiters, lastPos);
487 void FGTrafficManager::startXML()
489 //cout << "Start XML" << endl;
490 requiredAircraft = "";
494 void FGTrafficManager::endXML()
496 //cout << "End XML" << endl;
499 void FGTrafficManager::startElement(const char *name,
500 const XMLAttributes & atts)
503 //cout << "Start element " << name << endl;
504 //FGTrafficManager temp;
505 //for (int i = 0; i < atts.size(); i++)
506 // if (string(atts.getName(i)) == string("include"))
507 attval = atts.getValue("include");
509 //cout << "including " << attval << endl;
510 SGPath path = globals->get_fg_root();
511 path.append("/Traffic/");
513 readXML(path.str(), *this);
515 elementValueStack.push_back("");
516 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
519 void FGTrafficManager::endElement(const char *name)
521 //cout << "End element " << name << endl;
522 const string & value = elementValueStack.back();
524 if (!strcmp(name, "model"))
526 else if (!strcmp(name, "livery"))
528 else if (!strcmp(name, "home-port"))
530 else if (!strcmp(name, "registration"))
531 registration = value;
532 else if (!strcmp(name, "airline"))
534 else if (!strcmp(name, "actype"))
536 else if (!strcmp(name, "required-aircraft"))
537 requiredAircraft = value;
538 else if (!strcmp(name, "flighttype"))
540 else if (!strcmp(name, "radius"))
541 radius = atoi(value.c_str());
542 else if (!strcmp(name, "offset"))
543 offset = atoi(value.c_str());
544 else if (!strcmp(name, "performance-class"))
546 else if (!strcmp(name, "heavy")) {
547 if (value == string("true"))
551 } else if (!strcmp(name, "callsign"))
553 else if (!strcmp(name, "fltrules"))
555 else if (!strcmp(name, "port"))
557 else if (!strcmp(name, "time"))
559 else if (!strcmp(name, "departure")) {
560 departurePort = port;
561 departureTime = timeString;
562 } else if (!strcmp(name, "cruise-alt"))
563 cruiseAlt = atoi(value.c_str());
564 else if (!strcmp(name, "arrival")) {
566 arrivalTime = timeString;
567 } else if (!strcmp(name, "repeat"))
569 else if (!strcmp(name, "flight")) {
570 // We have loaded and parsed all the information belonging to this flight
571 // so we temporarily store it.
572 //cerr << "Pusing back flight " << callsign << endl;
573 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
574 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
576 //Prioritize aircraft
577 string apt = fgGetString("/sim/presets/airport-id");
578 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
579 //if (departurePort == apt) score++;
580 //flights.push_back(new FGScheduledFlight(callsign,
588 if (requiredAircraft == "") {
590 snprintf(buffer, 16, "%d", acCounter);
591 requiredAircraft = buffer;
593 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
595 << departurePort << " "
596 << arrivalPort << " "
598 << departureTime << " "
599 << arrivalTime << " " << repeat << " " << requiredAircraft);
600 // For database maintainance purposes, it may be convenient to
602 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
603 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
605 << departurePort << ","
606 << arrivalPort << ","
608 << departureTime << ","
609 << arrivalTime << "," << repeat << "," << requiredAircraft);
611 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
620 requiredAircraft = "";
621 } else if (!strcmp(name, "aircraft")) {
629 cerr << "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
630 << "," << acType << "," << livery << ","
631 << airline << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl << endl;*/
633 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
634 int randval = rand() & 100;
635 if (randval <= proportion) {
636 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
637 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
638 << "," << acType << "," << livery << ","
639 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
641 //scheduledAircraft.push_back(new FGAISchedule(mdl,
653 if (requiredAircraft == "") {
655 snprintf(buffer, 16, "%d", acCounter);
656 requiredAircraft = buffer;
658 if (homePort == "") {
659 homePort = departurePort;
661 scheduledAircraft.push_back(new FGAISchedule(mdl,
673 // while(flights.begin() != flights.end()) {
674 // flights.pop_back();
677 cerr << "Skipping : " << randval;
680 requiredAircraft = "";
682 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
687 SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
688 << registration << " with prioritization score " << score);
691 elementValueStack.pop_back();
694 void FGTrafficManager::data(const char *s, int len)
696 string token = string(s, len);
697 //cout << "Character data " << string(s,len) << endl;
698 elementValueStack.back() += token;
701 void FGTrafficManager::pi(const char *target, const char *data)
703 //cout << "Processing instruction " << target << ' ' << data << endl;
706 void FGTrafficManager::warning(const char *message, int line, int column)
708 SG_LOG(SG_IO, SG_WARN,
709 "Warning: " << message << " (" << line << ',' << column << ')');
712 void FGTrafficManager::error(const char *message, int line, int column)
714 SG_LOG(SG_IO, SG_ALERT,
715 "Error: " << message << " (" << line << ',' << column << ')');