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/simple.hxx>
68 #include <Main/fg_init.hxx>
72 #include "TrafficMgr.hxx"
78 * Thread encapsulating parsing the traffic schedules.
80 class ScheduleParseThread : public SGThread
83 ScheduleParseThread(FGTrafficManager* traffic) :
84 _trafficManager(traffic),
91 // if we're destroyed while running, ensure the thread exits cleanly
92 ~ScheduleParseThread()
96 _cancelThread = true; // request cancellation so we don't wait ages
104 void setTrafficDir(const SGPath& trafficDirPath)
106 _trafficDirPath = trafficDirPath;
109 bool isFinished() const
111 SGGuard<SGMutex> g(_lock);
120 simgear::Dir trafficDir(_trafficDirPath);
121 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
123 BOOST_FOREACH(SGPath p, d) {
125 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
126 BOOST_FOREACH(SGPath xml, trafficFiles) {
127 _trafficManager->parseSchedule(xml);
132 } // of sub-directories in AI/Traffic iteration
134 // _trafficManager->parseSchedules(schedulesToRead);
135 SG_LOG(SG_AI, SG_INFO, "parsing traffic schedules took:" << st.elapsedMSec() << "msec");
137 SGGuard<SGMutex> g(_lock);
141 FGTrafficManager* _trafficManager;
142 mutable SGMutex _lock;
145 SGPath _trafficDirPath;
148 /******************************************************************************
150 *****************************************************************************/
151 FGTrafficManager::FGTrafficManager() :
154 waitingMetarTime(0.0),
155 enabled("/sim/traffic-manager/enabled"),
156 aiEnabled("/sim/ai/enabled"),
157 realWxEnabled("/environment/realwx/enabled"),
158 metarValid("/environment/metar/valid")
165 FGTrafficManager::~FGTrafficManager()
170 void FGTrafficManager::shutdown()
174 scheduleParser.reset();
181 // Save the heuristics data
182 bool saveData = false;
184 if (fgGetBool("/sim/traffic-manager/heuristics")) {
185 SGPath cacheData(globals->get_fg_home());
186 cacheData.append("ai");
187 string airport = fgGetString("/sim/presets/airport-id");
189 if ((airport) != "") {
191 ::snprintf(buffer, 128, "%c/%c/%c/",
192 airport[0], airport[1], airport[2]);
193 cacheData.append(buffer);
194 if (!cacheData.exists()) {
195 cacheData.create_dir(0777);
197 cacheData.append(airport + "-cache.txt");
198 //cerr << "Saving AI traffic heuristics" << endl;
200 cachefile.open(cacheData.str().c_str());
201 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
205 BOOST_FOREACH(FGAISchedule* acft, scheduledAircraft) {
207 cachefile << acft->getRegistration() << " "
208 << acft->getRunCount() << " "
209 << acft->getHits() << " "
210 << acft->getLastUsed() << endl;
217 scheduledAircraft.clear();
221 currAircraft = scheduledAircraft.begin();
226 /// caution - this is run on the helper thread to improve startup
227 /// responsiveness - do not access properties or global state from
228 /// here, since there's no locking protection at all
229 void FGTrafficManager::parseSchedule(const SGPath& path)
231 readXML(path.str(), *this);
234 void FGTrafficManager::init()
242 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
243 scheduleParser.reset(new ScheduleParseThread(this));
244 scheduleParser->setTrafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
245 scheduleParser->start();
247 fgSetBool("/sim/traffic-manager/heuristics", false);
248 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
249 string ext = path.extension();
250 if (path.extension() == "xml") {
252 readXML(path.str(), *this);
254 } else if (path.extension() == "conf") {
256 readTimeTableFromFile(path);
259 SG_LOG(SG_AI, SG_ALERT,
260 "Unknown data format " << path.str()
269 void FGTrafficManager::finishInit()
272 SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
275 // Do sorting and scoring separately, to take advantage of the "homeport" variable
276 BOOST_FOREACH(FGAISchedule* schedule, scheduledAircraft) {
277 schedule->setScore();
280 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
282 currAircraft = scheduledAircraft.begin();
283 currAircraftClosest = scheduledAircraft.begin();
289 void FGTrafficManager::loadHeuristics()
291 if (!fgGetBool("/sim/traffic-manager/heuristics")) {
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) != "") {
303 ::snprintf(buffer, 128, "%c/%c/%c/",
304 airport[0], airport[1], airport[2]);
305 cacheData.append(buffer);
306 cacheData.append(airport + "-cache.txt");
308 if (cacheData.exists()) {
309 ifstream data(cacheData.c_str());
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);
316 Heuristic h; // = new Heuristic;
317 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
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");
325 heurMap[h.registration] = h;
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);
343 bool FGTrafficManager::metarReady(double dt)
345 // wait for valid METAR (when realWX is enabled only), since we need
346 // to know the active runway
347 if (metarValid || !realWxEnabled)
349 waitingMetarTime = 0.0;
353 // METAR timeout: when running offline, remote server is down etc
354 if (waitingMetarStation != fgGetString("/environment/metar/station-id"))
356 // station has changed: wait for reply, restart timeout
357 waitingMetarTime = 0.0;
358 waitingMetarStation = fgGetString("/environment/metar/station-id");
362 // timeout elapsed (10 seconds)?
363 if (waitingMetarTime > 20.0)
368 waitingMetarTime += dt;
372 void FGTrafficManager::update(double dt)
376 if (inited || doingInit)
386 // traffic depends on AI module
395 if (!scheduleParser->isFinished()) {
402 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
403 if (scheduledAircraft.empty()) {
407 SGVec3d userCart = globals->get_aircraft_position_cart();
409 if (currAircraft == scheduledAircraft.end()) {
410 currAircraft = scheduledAircraft.begin();
412 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
413 if (!((*currAircraft)->update(now, userCart))) {
414 (*currAircraft)->taint();
419 void FGTrafficManager::release(int id)
421 releaseList.push_back(id);
424 bool FGTrafficManager::isReleased(int id)
426 IdListIterator i = releaseList.begin();
427 while (i != releaseList.end()) {
429 releaseList.erase(i);
438 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
455 vector <string> tokens, depTime,arrTime;
456 vector <string>::iterator it;
457 ifstream infile(infileName.str().c_str());
459 infile.getline(buffer, 256);
463 //cerr << "Read line : " << buffer << endl;
464 buffString = string(buffer);
466 Tokenize(buffString, tokens, " \t");
467 //for (it = tokens.begin(); it != tokens.end(); it++) {
468 // cerr << "Tokens: " << *(it) << endl;
471 if (!tokens.empty()) {
472 if (tokens[0] == string("AC")) {
473 if (tokens.size() != 13) {
474 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
479 homePort = tokens[1];
480 registration = tokens[2];
481 if (tokens[11] == string("false")) {
488 flightReq = tokens[3] + tokens[5];
489 m_class = tokens[10];
490 FlightType = tokens[9];
491 radius = atof(tokens[8].c_str());
492 offset = atof(tokens[7].c_str());;
494 if (!FGAISchedule::validModelPath(model)) {
495 SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" <<
496 model << " from " << infileName.str());
499 SG_LOG(SG_GENERAL, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
500 << registration << " " << flightReq << " " << isHeavy
501 << " " << acType << " " << airline << " " << m_class
502 << " " << FlightType << " " << radius << " " << offset);
503 scheduledAircraft.push_back(new FGAISchedule(model,
515 } // of valid model path
517 if (tokens[0] == string("FLIGHT")) {
518 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
519 if (tokens.size() != 10) {
520 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
523 string callsign = tokens[1];
524 string fltrules = tokens[2];
525 string weekdays = tokens[3];
526 string departurePort = tokens[5];
527 string arrivalPort = tokens[7];
528 int cruiseAlt = atoi(tokens[8].c_str());
529 string depTimeGen = tokens[4];
530 string arrTimeGen = tokens[6];
531 string repeat = "WEEK";
532 string requiredAircraft = tokens[9];
534 if (weekdays.size() != 7) {
535 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
540 Tokenize(depTimeGen, depTime, ":");
541 Tokenize(arrTimeGen, arrTime, ":");
542 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
543 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
544 //cerr << "Using " << dep << " " << arr << endl;
545 bool arrivalWeekdayNeedsIncrement = false;
547 arrivalWeekdayNeedsIncrement = true;
549 for (int i = 0; i < 7; i++) {
551 if (weekdays[i] != '.') {
553 snprintf(buffer, 4, "%d/", j);
554 string departureTime = string(buffer) + depTimeGen + string(":00");
556 if (!arrivalWeekdayNeedsIncrement) {
557 arrivalTime = string(buffer) + arrTimeGen + string(":00");
559 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
560 snprintf(buffer, 4, "%d/", j+1);
561 arrivalTime = string(buffer) + arrTimeGen + string(":00");
563 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
564 snprintf(buffer, 4, "%d/", 0);
565 arrivalTime = string(buffer) + arrTimeGen + string(":00");
567 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
569 << departurePort << " "
570 << arrivalPort << " "
572 << departureTime << " "
573 << arrivalTime << " "
575 << requiredAircraft);
577 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
596 void FGTrafficManager::Tokenize(const string& str,
597 vector<string>& tokens,
598 const string& delimiters)
600 // Skip delimiters at beginning.
601 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
602 // Find first "non-delimiter".
603 string::size_type pos = str.find_first_of(delimiters, lastPos);
605 while (string::npos != pos || string::npos != lastPos)
607 // Found a token, add it to the vector.
608 tokens.push_back(str.substr(lastPos, pos - lastPos));
609 // Skip delimiters. Note the "not_of"
610 lastPos = str.find_first_not_of(delimiters, pos);
611 // Find next "non-delimiter"
612 pos = str.find_first_of(delimiters, lastPos);
617 void FGTrafficManager::startXML()
619 //cout << "Start XML" << endl;
620 requiredAircraft = "";
624 void FGTrafficManager::endXML()
626 //cout << "End XML" << endl;
629 void FGTrafficManager::startElement(const char *name,
630 const XMLAttributes & atts)
633 //cout << "Start element " << name << endl;
634 //FGTrafficManager temp;
635 //for (int i = 0; i < atts.size(); i++)
636 // if (string(atts.getName(i)) == string("include"))
637 attval = atts.getValue("include");
639 //cout << "including " << attval << endl;
640 SGPath path = globals->get_fg_root();
641 path.append("/Traffic/");
643 readXML(path.str(), *this);
645 elementValueStack.push_back("");
646 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
649 void FGTrafficManager::endElement(const char *name)
651 //cout << "End element " << name << endl;
652 const string & value = elementValueStack.back();
654 if (!strcmp(name, "model"))
656 else if (!strcmp(name, "livery"))
658 else if (!strcmp(name, "home-port"))
660 else if (!strcmp(name, "registration"))
661 registration = value;
662 else if (!strcmp(name, "airline"))
664 else if (!strcmp(name, "actype"))
666 else if (!strcmp(name, "required-aircraft"))
667 requiredAircraft = value;
668 else if (!strcmp(name, "flighttype"))
670 else if (!strcmp(name, "radius"))
671 radius = atoi(value.c_str());
672 else if (!strcmp(name, "offset"))
673 offset = atoi(value.c_str());
674 else if (!strcmp(name, "performance-class"))
676 else if (!strcmp(name, "heavy")) {
677 if (value == string("true"))
681 } else if (!strcmp(name, "callsign"))
683 else if (!strcmp(name, "fltrules"))
685 else if (!strcmp(name, "port"))
687 else if (!strcmp(name, "time"))
689 else if (!strcmp(name, "departure")) {
690 departurePort = port;
691 departureTime = timeString;
692 } else if (!strcmp(name, "cruise-alt"))
693 cruiseAlt = atoi(value.c_str());
694 else if (!strcmp(name, "arrival")) {
696 arrivalTime = timeString;
697 } else if (!strcmp(name, "repeat"))
699 else if (!strcmp(name, "flight")) {
700 // We have loaded and parsed all the information belonging to this flight
701 // so we temporarily store it.
702 //cerr << "Pusing back flight " << callsign << endl;
703 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
704 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
706 //Prioritize aircraft
707 string apt = fgGetString("/sim/presets/airport-id");
708 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
709 //if (departurePort == apt) score++;
710 //flights.push_back(new FGScheduledFlight(callsign,
718 if (requiredAircraft == "") {
720 snprintf(buffer, 16, "%d", acCounter);
721 requiredAircraft = buffer;
723 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
725 << departurePort << " "
726 << arrivalPort << " "
728 << departureTime << " "
729 << arrivalTime << " " << repeat << " " << requiredAircraft);
730 // For database maintainance purposes, it may be convenient to
732 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
733 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
735 << departurePort << ","
736 << arrivalPort << ","
738 << departureTime << ","
739 << arrivalTime << "," << repeat << "," << requiredAircraft);
741 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
750 requiredAircraft = "";
751 } else if (!strcmp(name, "aircraft")) {
755 elementValueStack.pop_back();
758 void FGTrafficManager::endAircraft()
760 string isHeavy = heavy ? "true" : "false";
762 if (missingModels.find(mdl) != missingModels.end()) {
763 // don't stat() or warn again
764 requiredAircraft = homePort = "";
768 if (!FGAISchedule::validModelPath(mdl)) {
769 missingModels.insert(mdl);
770 SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
771 requiredAircraft = homePort = "";
776 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
777 int randval = rand() & 100;
778 if (randval > proportion) {
779 requiredAircraft = homePort = "";
783 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
784 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
785 << "," << acType << "," << livery << ","
786 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
789 if (requiredAircraft == "") {
791 snprintf(buffer, 16, "%d", acCounter);
792 requiredAircraft = buffer;
794 if (homePort == "") {
795 homePort = departurePort;
798 scheduledAircraft.push_back(new FGAISchedule(mdl,
811 requiredAircraft = "";
816 void FGTrafficManager::data(const char *s, int len)
818 string token = string(s, len);
819 //cout << "Character data " << string(s,len) << endl;
820 elementValueStack.back() += token;
823 void FGTrafficManager::pi(const char *target, const char *data)
825 //cout << "Processing instruction " << target << ' ' << data << endl;
828 void FGTrafficManager::warning(const char *message, int line, int column)
830 SG_LOG(SG_IO, SG_WARN,
831 "Warning: " << message << " (" << line << ',' << column << ')');
834 void FGTrafficManager::error(const char *message, int line, int column)
836 SG_LOG(SG_IO, SG_ALERT,
837 "Error: " << message << " (" << line << ',' << column << ')');