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>
61 #include <simgear/threads/SGThread.hxx>
62 #include <simgear/threads/SGGuard.hxx>
64 #include <AIModel/AIAircraft.hxx>
65 #include <AIModel/AIFlightPlan.hxx>
66 #include <AIModel/AIBase.hxx>
67 #include <Airports/airport.hxx>
68 #include <Main/fg_init.hxx>
70 #include "TrafficMgr.hxx"
77 * Thread encapsulating parsing the traffic schedules.
79 class ScheduleParseThread : public SGThread
82 ScheduleParseThread(FGTrafficManager* traffic) :
83 _trafficManager(traffic),
90 // if we're destroyed while running, ensure the thread exits cleanly
91 ~ScheduleParseThread()
95 _cancelThread = true; // request cancellation so we don't wait ages
103 void setTrafficDir(const SGPath& trafficDirPath)
105 _trafficDirPath = trafficDirPath;
108 bool isFinished() const
110 SGGuard<SGMutex> g(_lock);
119 simgear::Dir trafficDir(_trafficDirPath);
120 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
122 BOOST_FOREACH(SGPath p, d) {
124 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
125 BOOST_FOREACH(SGPath xml, trafficFiles) {
126 _trafficManager->parseSchedule(xml);
131 } // of sub-directories in AI/Traffic iteration
133 // _trafficManager->parseSchedules(schedulesToRead);
134 SG_LOG(SG_AI, SG_INFO, "parsing traffic schedules took:" << st.elapsedMSec() << "msec");
136 SGGuard<SGMutex> g(_lock);
140 FGTrafficManager* _trafficManager;
141 mutable SGMutex _lock;
144 SGPath _trafficDirPath;
147 /******************************************************************************
149 *****************************************************************************/
150 FGTrafficManager::FGTrafficManager() :
153 waitingMetarTime(0.0),
161 enabled("/sim/traffic-manager/enabled"),
162 aiEnabled("/sim/ai/enabled"),
163 realWxEnabled("/environment/realwx/enabled"),
164 metarValid("/environment/metar/valid")
168 FGTrafficManager::~FGTrafficManager()
173 void FGTrafficManager::shutdown()
177 scheduleParser.reset();
184 // Save the heuristics data
185 bool saveData = false;
186 std::ofstream cachefile;
187 if (fgGetBool("/sim/traffic-manager/heuristics")) {
188 SGPath cacheData(globals->get_fg_home());
189 cacheData.append("ai");
190 const string airport = fgGetString("/sim/presets/airport-id");
192 if ((airport) != "") {
194 ::snprintf(buffer, 128, "%c/%c/%c/",
195 airport[0], airport[1], airport[2]);
196 cacheData.append(buffer);
197 if (!cacheData.exists()) {
198 cacheData.create_dir(0777);
200 cacheData.append(airport + "-cache.txt");
201 //cerr << "Saving AI traffic heuristics" << endl;
203 cachefile.open(cacheData.str().c_str());
204 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
208 BOOST_FOREACH(FGAISchedule* acft, scheduledAircraft) {
210 cachefile << acft->getRegistration() << " "
211 << acft->getRunCount() << " "
212 << acft->getHits() << " "
213 << acft->getLastUsed() << endl;
220 scheduledAircraft.clear();
223 currAircraft = scheduledAircraft.begin();
228 /// caution - this is run on the helper thread to improve startup
229 /// responsiveness - do not access properties or global state from
230 /// here, since there's no locking protection at all
231 void FGTrafficManager::parseSchedule(const SGPath& path)
233 readXML(path.str(), *this);
236 void FGTrafficManager::init()
244 if (string(fgGetString("/sim/traffic-manager/datafile")).empty()) {
245 scheduleParser.reset(new ScheduleParseThread(this));
246 scheduleParser->setTrafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
247 scheduleParser->start();
249 fgSetBool("/sim/traffic-manager/heuristics", false);
250 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
251 string ext = path.extension();
252 if (path.extension() == "xml") {
254 readXML(path.str(), *this);
256 } else if (path.extension() == "conf") {
258 readTimeTableFromFile(path);
261 SG_LOG(SG_AI, SG_ALERT,
262 "Unknown data format " << path.str()
271 void FGTrafficManager::finishInit()
274 SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
277 // Do sorting and scoring separately, to take advantage of the "homeport" variable
278 BOOST_FOREACH(FGAISchedule* schedule, scheduledAircraft) {
279 schedule->setScore();
282 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
284 currAircraft = scheduledAircraft.begin();
285 currAircraftClosest = scheduledAircraft.begin();
291 void FGTrafficManager::loadHeuristics()
293 if (!fgGetBool("/sim/traffic-manager/heuristics")) {
297 HeuristicMap heurMap;
298 //cerr << "Processing Heuristics" << endl;
299 // Load the heuristics data
300 SGPath cacheData(globals->get_fg_home());
301 cacheData.append("ai");
302 string airport = fgGetString("/sim/presets/airport-id");
303 if ((airport) != "") {
305 ::snprintf(buffer, 128, "%c/%c/%c/",
306 airport[0], airport[1], airport[2]);
307 cacheData.append(buffer);
308 cacheData.append(airport + "-cache.txt");
310 if (cacheData.exists()) {
311 std::ifstream data(cacheData.c_str());
313 if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
314 SG_LOG(SG_AI, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
315 cacheData.c_str() << " for Airport " << airport);
318 Heuristic h; // = new Heuristic;
319 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
322 HeuristicMapIterator itr = heurMap.find(h.registration);
323 if (itr != heurMap.end()) {
324 SG_LOG(SG_AI, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
325 h.registration << " for AI aircraft");
327 heurMap[h.registration] = h;
334 for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
335 const string& registration = (*currAircraft)->getRegistration();
336 HeuristicMapIterator itr = heurMap.find(registration);
337 if (itr != heurMap.end()) {
338 (*currAircraft)->setrunCount(itr->second.runCount);
339 (*currAircraft)->setHits(itr->second.hits);
340 (*currAircraft)->setLastUsed(itr->second.lastRun);
345 bool FGTrafficManager::metarReady(double dt)
347 // wait for valid METAR (when realWX is enabled only), since we need
348 // to know the active runway
349 if (metarValid || !realWxEnabled)
351 waitingMetarTime = 0.0;
355 // METAR timeout: when running offline, remote server is down etc
356 if (waitingMetarStation != fgGetString("/environment/metar/station-id"))
358 // station has changed: wait for reply, restart timeout
359 waitingMetarTime = 0.0;
360 waitingMetarStation = fgGetString("/environment/metar/station-id");
364 // timeout elapsed (10 seconds)?
365 if (waitingMetarTime > 20.0)
370 waitingMetarTime += dt;
374 void FGTrafficManager::update(double dt)
378 if (inited || doingInit)
388 // traffic depends on AI module
397 if (!scheduleParser->isFinished()) {
404 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
405 if (scheduledAircraft.empty()) {
409 SGVec3d userCart = globals->get_aircraft_position_cart();
411 if (currAircraft == scheduledAircraft.end()) {
412 currAircraft = scheduledAircraft.begin();
415 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
416 if ((*currAircraft)->update(now, userCart)) {
417 // schedule is done - process another aircraft in next iteration
422 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
439 vector <string> tokens, depTime,arrTime;
440 vector <string>::iterator it;
441 std::ifstream infile(infileName.str().c_str());
443 infile.getline(buffer, 256);
447 //cerr << "Read line : " << buffer << endl;
448 buffString = string(buffer);
450 Tokenize(buffString, tokens, " \t");
451 //for (it = tokens.begin(); it != tokens.end(); it++) {
452 // cerr << "Tokens: " << *(it) << endl;
455 if (!tokens.empty()) {
456 if (tokens[0] == string("AC")) {
457 if (tokens.size() != 13) {
458 SG_LOG(SG_AI, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
463 homePort = tokens[1];
464 registration = tokens[2];
465 if (tokens[11] == string("false")) {
472 flightReq = tokens[3] + tokens[5];
473 m_class = tokens[10];
474 FlightType = tokens[9];
475 radius = atof(tokens[8].c_str());
476 offset = atof(tokens[7].c_str());;
478 if (!FGAISchedule::validModelPath(model)) {
479 SG_LOG(SG_AI, SG_WARN, "TrafficMgr: Missing model path:" <<
480 model << " from " << infileName.str());
483 SG_LOG(SG_AI, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
484 << registration << " " << flightReq << " " << isHeavy
485 << " " << acType << " " << airline << " " << m_class
486 << " " << FlightType << " " << radius << " " << offset);
487 scheduledAircraft.push_back(new FGAISchedule(model,
499 } // of valid model path
501 if (tokens[0] == string("FLIGHT")) {
502 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
503 if (tokens.size() != 10) {
504 SG_LOG(SG_AI, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
507 string callsign = tokens[1];
508 string fltrules = tokens[2];
509 string weekdays = tokens[3];
510 string departurePort = tokens[5];
511 string arrivalPort = tokens[7];
512 int cruiseAlt = atoi(tokens[8].c_str());
513 string depTimeGen = tokens[4];
514 string arrTimeGen = tokens[6];
515 string repeat = "WEEK";
516 string requiredAircraft = tokens[9];
518 if (weekdays.size() != 7) {
519 SG_LOG(SG_AI, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
524 Tokenize(depTimeGen, depTime, ":");
525 Tokenize(arrTimeGen, arrTime, ":");
526 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
527 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
528 //cerr << "Using " << dep << " " << arr << endl;
529 bool arrivalWeekdayNeedsIncrement = false;
531 arrivalWeekdayNeedsIncrement = true;
533 for (int i = 0; i < 7; i++) {
535 if (weekdays[i] != '.') {
537 snprintf(buffer, 4, "%d/", j);
538 string departureTime = string(buffer) + depTimeGen + string(":00");
540 if (!arrivalWeekdayNeedsIncrement) {
541 arrivalTime = string(buffer) + arrTimeGen + string(":00");
543 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
544 snprintf(buffer, 4, "%d/", j+1);
545 arrivalTime = string(buffer) + arrTimeGen + string(":00");
547 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
548 snprintf(buffer, 4, "%d/", 0);
549 arrivalTime = string(buffer) + arrTimeGen + string(":00");
551 SG_LOG(SG_AI, SG_ALERT, "Adding flight " << callsign << " "
553 << departurePort << " "
554 << arrivalPort << " "
556 << departureTime << " "
557 << arrivalTime << " "
559 << requiredAircraft);
561 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
580 void FGTrafficManager::Tokenize(const string& str,
581 vector<string>& tokens,
582 const string& delimiters)
584 // Skip delimiters at beginning.
585 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
586 // Find first "non-delimiter".
587 string::size_type pos = str.find_first_of(delimiters, lastPos);
589 while (string::npos != pos || string::npos != lastPos)
591 // Found a token, add it to the vector.
592 tokens.push_back(str.substr(lastPos, pos - lastPos));
593 // Skip delimiters. Note the "not_of"
594 lastPos = str.find_first_not_of(delimiters, pos);
595 // Find next "non-delimiter"
596 pos = str.find_first_of(delimiters, lastPos);
601 void FGTrafficManager::startXML()
603 //cout << "Start XML" << endl;
604 requiredAircraft = "";
608 void FGTrafficManager::endXML()
610 //cout << "End XML" << endl;
613 void FGTrafficManager::startElement(const char *name,
614 const XMLAttributes & atts)
617 //cout << "Start element " << name << endl;
618 //FGTrafficManager temp;
619 //for (int i = 0; i < atts.size(); i++)
620 // if (string(atts.getName(i)) == string("include"))
621 attval = atts.getValue("include");
623 //cout << "including " << attval << endl;
624 SGPath path = globals->get_fg_root();
625 path.append("/Traffic/");
627 readXML(path.str(), *this);
629 elementValueStack.push_back("");
630 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
633 void FGTrafficManager::endElement(const char *name)
635 //cout << "End element " << name << endl;
636 const string & value = elementValueStack.back();
638 if (!strcmp(name, "model"))
640 else if (!strcmp(name, "livery"))
642 else if (!strcmp(name, "home-port"))
644 else if (!strcmp(name, "registration"))
645 registration = value;
646 else if (!strcmp(name, "airline"))
648 else if (!strcmp(name, "actype"))
650 else if (!strcmp(name, "required-aircraft"))
651 requiredAircraft = value;
652 else if (!strcmp(name, "flighttype"))
654 else if (!strcmp(name, "radius"))
655 radius = atoi(value.c_str());
656 else if (!strcmp(name, "offset"))
657 offset = atoi(value.c_str());
658 else if (!strcmp(name, "performance-class"))
660 else if (!strcmp(name, "heavy")) {
661 if (value == string("true"))
665 } else if (!strcmp(name, "callsign"))
667 else if (!strcmp(name, "fltrules"))
669 else if (!strcmp(name, "port"))
671 else if (!strcmp(name, "time"))
673 else if (!strcmp(name, "departure")) {
674 departurePort = port;
675 departureTime = timeString;
676 } else if (!strcmp(name, "cruise-alt"))
677 cruiseAlt = atoi(value.c_str());
678 else if (!strcmp(name, "arrival")) {
680 arrivalTime = timeString;
681 } else if (!strcmp(name, "repeat"))
683 else if (!strcmp(name, "flight")) {
684 // We have loaded and parsed all the information belonging to this flight
685 // so we temporarily store it.
686 //cerr << "Pusing back flight " << callsign << endl;
687 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
688 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
690 //Prioritize aircraft
691 string apt = fgGetString("/sim/presets/airport-id");
692 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
693 //if (departurePort == apt) score++;
694 //flights.push_back(new FGScheduledFlight(callsign,
702 if (requiredAircraft == "") {
704 snprintf(buffer, 16, "%d", acCounter);
705 requiredAircraft = buffer;
707 SG_LOG(SG_AI, SG_DEBUG, "Adding flight: " << callsign << " "
709 << departurePort << " "
710 << arrivalPort << " "
712 << departureTime << " "
713 << arrivalTime << " " << repeat << " " << requiredAircraft);
714 // For database maintainance purposes, it may be convenient to
716 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
717 SG_LOG(SG_AI, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
719 << departurePort << ","
720 << arrivalPort << ","
722 << departureTime << ","
723 << arrivalTime << "," << repeat << "," << requiredAircraft);
725 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
734 requiredAircraft = "";
735 } else if (!strcmp(name, "aircraft")) {
739 elementValueStack.pop_back();
742 void FGTrafficManager::endAircraft()
744 string isHeavy = heavy ? "true" : "false";
746 if (missingModels.find(mdl) != missingModels.end()) {
747 // don't stat() or warn again
748 requiredAircraft = homePort = "";
752 if (!FGAISchedule::validModelPath(mdl)) {
753 missingModels.insert(mdl);
754 SG_LOG(SG_AI, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
755 requiredAircraft = homePort = "";
760 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
761 int randval = rand() & 100;
762 if (randval > proportion) {
763 requiredAircraft = homePort = "";
767 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
768 SG_LOG(SG_AI, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
769 << "," << acType << "," << livery << ","
770 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
773 if (requiredAircraft == "") {
775 snprintf(buffer, 16, "%d", acCounter);
776 requiredAircraft = buffer;
778 if (homePort == "") {
779 homePort = departurePort;
782 scheduledAircraft.push_back(new FGAISchedule(mdl,
795 requiredAircraft = "";
800 void FGTrafficManager::data(const char *s, int len)
802 string token = string(s, len);
803 //cout << "Character data " << string(s,len) << endl;
804 elementValueStack.back() += token;
807 void FGTrafficManager::pi(const char *target, const char *data)
809 //cout << "Processing instruction " << target << ' ' << data << endl;
812 void FGTrafficManager::warning(const char *message, int line, int column)
814 SG_LOG(SG_IO, SG_WARN,
815 "Warning: " << message << " (" << line << ',' << column << ')');
818 void FGTrafficManager::error(const char *message, int line, int column)
820 SG_LOG(SG_IO, SG_ALERT,
821 "Error: " << message << " (" << line << ',' << column << ')');