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 *****************************************************************************/
54 #include <simgear/compiler.h>
55 #include <simgear/misc/sg_path.hxx>
56 #include <simgear/misc/sg_dir.hxx>
57 #include <simgear/props/props.hxx>
58 #include <simgear/route/waypoint.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() :
80 enabled("/sim/traffic-manager/enabled"),
81 aiEnabled("/sim/ai/enabled"),
82 realWxEnabled("/environment/realwx/enabled"),
83 metarValid("/environment/metar/valid")
90 FGTrafficManager::~FGTrafficManager()
92 // Save the heuristics data
93 bool saveData = false;
95 if (fgGetBool("/sim/traffic-manager/heuristics")) {
96 SGPath cacheData(fgGetString("/sim/fg-home"));
97 cacheData.append("ai");
98 string airport = fgGetString("/sim/presets/airport-id");
100 if ((airport) != "") {
102 ::snprintf(buffer, 128, "%c/%c/%c/",
103 airport[0], airport[1], airport[2]);
104 cacheData.append(buffer);
105 if (!cacheData.exists()) {
106 cacheData.create_dir(0777);
108 cacheData.append(airport + "-cache.txt");
109 //cerr << "Saving AI traffic heuristics" << endl;
111 cachefile.open(cacheData.str().c_str());
114 for (ScheduleVectorIterator sched = scheduledAircraft.begin();
115 sched != scheduledAircraft.end(); sched++) {
117 cachefile << (*sched)->getRegistration() << " "
118 << (*sched)->getRunCount() << " "
119 << (*sched)->getHits() << endl;
126 scheduledAircraft.clear();
131 void FGTrafficManager::init()
133 if (!enabled || !aiEnabled) {
137 heuristicsVector heuristics;
138 HeuristicMap heurMap;
140 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
141 simgear::Dir trafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
142 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
144 for (unsigned int i=0; i<d.size(); ++i) {
145 simgear::Dir d2(d[i]);
146 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
147 for (unsigned int j=0; j<trafficFiles.size(); ++j) {
148 SGPath curFile = trafficFiles[j];
149 SG_LOG(SG_GENERAL, SG_DEBUG,
150 "Scanning " << curFile.str() << " for traffic");
151 readXML(curFile.str(), *this);
155 fgSetBool("/sim/traffic-manager/heuristics", false);
156 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
157 string ext = path.extension();
158 if (path.extension() == "xml") {
160 readXML(path.str(), *this);
162 } else if (path.extension() == "conf") {
164 readTimeTableFromFile(path);
167 SG_LOG(SG_GENERAL, SG_ALERT,
168 "Unknown data format " << path.str()
173 if (fgGetBool("/sim/traffic-manager/heuristics")) {
174 //cerr << "Processing Heuristics" << endl;
175 // Load the heuristics data
176 SGPath cacheData(fgGetString("/sim/fg-home"));
177 cacheData.append("ai");
178 string airport = fgGetString("/sim/presets/airport-id");
179 if ((airport) != "") {
181 ::snprintf(buffer, 128, "%c/%c/%c/",
182 airport[0], airport[1], airport[2]);
183 cacheData.append(buffer);
184 cacheData.append(airport + "-cache.txt");
185 if (cacheData.exists()) {
186 ifstream data(cacheData.c_str());
188 Heuristic h; // = new Heuristic;
189 data >> h.registration >> h.runCount >> h.hits;
192 HeuristicMapIterator itr = heurMap.find(h.registration);
193 if (itr != heurMap.end()) {
194 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
195 h.registration << " for AI aircraft");
197 heurMap[h.registration] = h;
198 heuristics.push_back(h);
202 for (currAircraft = scheduledAircraft.begin();
203 currAircraft != scheduledAircraft.end(); currAircraft++) {
204 string registration = (*currAircraft)->getRegistration();
205 HeuristicMapIterator itr = heurMap.find(registration);
206 //cerr << "Processing heuristics for" << (*currAircraft)->getRegistration() << endl;
207 if (itr == heurMap.end()) {
208 //cerr << "No heuristics found for " << registration << endl;
210 (*currAircraft)->setrunCount(itr->second.runCount);
211 (*currAircraft)->setHits(itr->second.hits);
212 //cerr <<"Runcount " << itr->second->runCount << ".Hits " << itr->second->hits << endl;
215 //cerr << "Done" << endl;
216 //for (heuristicsVectorIterator hvi = heuristics.begin();
217 // hvi != heuristics.end(); hvi++) {
221 // Do sorting and scoring separately, to take advantage of the "homeport| variable
222 for (currAircraft = scheduledAircraft.begin();
223 currAircraft != scheduledAircraft.end(); currAircraft++) {
224 (*currAircraft)->setScore();
226 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
228 currAircraft = scheduledAircraft.begin();
229 currAircraftClosest = scheduledAircraft.begin();
234 void FGTrafficManager::update(double /*dt */ )
236 if (!enabled || !aiEnabled || (realWxEnabled && !metarValid)) {
241 // lazy-initialization, we've been enabled at run-time
242 SG_LOG(SG_GENERAL, SG_INFO, "doing lazy-init of TrafficManager");
246 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
247 if (scheduledAircraft.size() == 0) {
252 SGVec3d::fromGeod(SGGeod::
253 fromDeg(fgGetDouble("/position/longitude-deg"),
254 fgGetDouble("/position/latitude-deg")));
256 if (currAircraft == scheduledAircraft.end()) {
257 currAircraft = scheduledAircraft.begin();
259 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
260 if (!((*currAircraft)->update(now, userCart))) {
261 (*currAircraft)->taint();
262 // NOTE: With traffic manager II, this statement below is no longer true
263 // after proper initialization, we shouldnt get here.
264 // But let's make sure
265 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
270 void FGTrafficManager::release(int id)
272 releaseList.push_back(id);
275 bool FGTrafficManager::isReleased(int id)
277 IdListIterator i = releaseList.begin();
278 while (i != releaseList.end()) {
280 releaseList.erase(i);
289 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
306 vector <string> tokens, depTime,arrTime;
307 vector <string>::iterator it;
308 ifstream infile(infileName.str().c_str());
310 infile.getline(buffer, 256);
314 //cerr << "Read line : " << buffer << endl;
315 buffString = string(buffer);
317 Tokenize(buffString, tokens, " \t");
318 //for (it = tokens.begin(); it != tokens.end(); it++) {
319 // cerr << "Tokens: " << *(it) << endl;
322 if (!tokens.empty()) {
323 if (tokens[0] == string("AC")) {
324 if (tokens.size() != 13) {
325 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
330 homePort = tokens[1];
331 registration = tokens[2];
332 if (tokens[11] == string("false")) {
339 flightReq = tokens[3] + tokens[5];
340 m_class = tokens[10];
341 FlightType = tokens[9];
342 radius = atof(tokens[8].c_str());
343 offset = atof(tokens[7].c_str());;
344 SG_LOG(SG_GENERAL, SG_ALERT, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
345 << registration << " " << flightReq << " " << isHeavy
346 << " " << acType << " " << airline << " " << m_class
347 << " " << FlightType << " " << radius << " " << offset);
348 scheduledAircraft.push_back(new FGAISchedule(model,
361 if (tokens[0] == string("FLIGHT")) {
362 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
363 if (tokens.size() != 10) {
364 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
367 string callsign = tokens[1];
368 string fltrules = tokens[2];
369 string weekdays = tokens[3];
370 string departurePort = tokens[5];
371 string arrivalPort = tokens[7];
372 int cruiseAlt = atoi(tokens[8].c_str());
373 string depTimeGen = tokens[4];
374 string arrTimeGen = tokens[6];
375 string repeat = "WEEK";
376 string requiredAircraft = tokens[9];
378 if (weekdays.size() != 7) {
379 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
384 Tokenize(depTimeGen, depTime, ":");
385 Tokenize(arrTimeGen, arrTime, ":");
386 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
387 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
388 //cerr << "Using " << dep << " " << arr << endl;
389 bool arrivalWeekdayNeedsIncrement = false;
391 arrivalWeekdayNeedsIncrement = true;
393 for (int i = 0; i < 7; i++) {
395 if (weekdays[i] != '.') {
397 snprintf(buffer, 4, "%d/", j);
398 string departureTime = string(buffer) + depTimeGen + string(":00");
400 if (!arrivalWeekdayNeedsIncrement) {
401 arrivalTime = string(buffer) + arrTimeGen + string(":00");
403 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
404 snprintf(buffer, 4, "%d/", j+1);
405 arrivalTime = string(buffer) + arrTimeGen + string(":00");
407 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
408 snprintf(buffer, 4, "%d/", 0);
409 arrivalTime = string(buffer) + arrTimeGen + string(":00");
411 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
413 << departurePort << " "
414 << arrivalPort << " "
416 << departureTime << " "
417 << arrivalTime << " "
419 << requiredAircraft);
421 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
440 void FGTrafficManager::Tokenize(const string& str,
441 vector<string>& tokens,
442 const string& delimiters)
444 // Skip delimiters at beginning.
445 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
446 // Find first "non-delimiter".
447 string::size_type pos = str.find_first_of(delimiters, lastPos);
449 while (string::npos != pos || string::npos != lastPos)
451 // Found a token, add it to the vector.
452 tokens.push_back(str.substr(lastPos, pos - lastPos));
453 // Skip delimiters. Note the "not_of"
454 lastPos = str.find_first_not_of(delimiters, pos);
455 // Find next "non-delimiter"
456 pos = str.find_first_of(delimiters, lastPos);
461 void FGTrafficManager::startXML()
463 //cout << "Start XML" << endl;
464 requiredAircraft = "";
468 void FGTrafficManager::endXML()
470 //cout << "End XML" << endl;
473 void FGTrafficManager::startElement(const char *name,
474 const XMLAttributes & atts)
477 //cout << "Start element " << name << endl;
478 //FGTrafficManager temp;
479 //for (int i = 0; i < atts.size(); i++)
480 // if (string(atts.getName(i)) == string("include"))
481 attval = atts.getValue("include");
483 //cout << "including " << attval << endl;
484 SGPath path = globals->get_fg_root();
485 path.append("/Traffic/");
487 readXML(path.str(), *this);
489 elementValueStack.push_back("");
490 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
493 void FGTrafficManager::endElement(const char *name)
495 //cout << "End element " << name << endl;
496 const string & value = elementValueStack.back();
498 if (!strcmp(name, "model"))
500 else if (!strcmp(name, "livery"))
502 else if (!strcmp(name, "home-port"))
504 else if (!strcmp(name, "registration"))
505 registration = value;
506 else if (!strcmp(name, "airline"))
508 else if (!strcmp(name, "actype"))
510 else if (!strcmp(name, "required-aircraft"))
511 requiredAircraft = value;
512 else if (!strcmp(name, "flighttype"))
514 else if (!strcmp(name, "radius"))
515 radius = atoi(value.c_str());
516 else if (!strcmp(name, "offset"))
517 offset = atoi(value.c_str());
518 else if (!strcmp(name, "performance-class"))
520 else if (!strcmp(name, "heavy")) {
521 if (value == string("true"))
525 } else if (!strcmp(name, "callsign"))
527 else if (!strcmp(name, "fltrules"))
529 else if (!strcmp(name, "port"))
531 else if (!strcmp(name, "time"))
533 else if (!strcmp(name, "departure")) {
534 departurePort = port;
535 departureTime = timeString;
536 } else if (!strcmp(name, "cruise-alt"))
537 cruiseAlt = atoi(value.c_str());
538 else if (!strcmp(name, "arrival")) {
540 arrivalTime = timeString;
541 } else if (!strcmp(name, "repeat"))
543 else if (!strcmp(name, "flight")) {
544 // We have loaded and parsed all the information belonging to this flight
545 // so we temporarily store it.
546 //cerr << "Pusing back flight " << callsign << endl;
547 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
548 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
550 //Prioritize aircraft
551 string apt = fgGetString("/sim/presets/airport-id");
552 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
553 //if (departurePort == apt) score++;
554 //flights.push_back(new FGScheduledFlight(callsign,
562 if (requiredAircraft == "") {
564 snprintf(buffer, 16, "%d", acCounter);
565 requiredAircraft = buffer;
567 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
569 << departurePort << " "
570 << arrivalPort << " "
572 << departureTime << " "
573 << arrivalTime << " " << repeat << " " << requiredAircraft);
574 // For database maintainance purposes, it may be convenient to
576 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
577 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
579 << departurePort << ","
580 << arrivalPort << ","
582 << departureTime << ","
583 << arrivalTime << "," << repeat << "," << requiredAircraft);
585 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
594 requiredAircraft = "";
595 } else if (!strcmp(name, "aircraft")) {
603 cerr << "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
604 << "," << acType << "," << livery << ","
605 << airline << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl << endl;*/
607 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
608 int randval = rand() & 100;
609 if (randval <= proportion) {
610 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
611 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
612 << "," << acType << "," << livery << ","
613 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
615 //scheduledAircraft.push_back(new FGAISchedule(mdl,
627 if (requiredAircraft == "") {
629 snprintf(buffer, 16, "%d", acCounter);
630 requiredAircraft = buffer;
632 if (homePort == "") {
633 homePort = departurePort;
635 scheduledAircraft.push_back(new FGAISchedule(mdl,
647 // while(flights.begin() != flights.end()) {
648 // flights.pop_back();
651 cerr << "Skipping : " << randval;
654 requiredAircraft = "";
656 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
661 SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
662 << registration << " with prioritization score " << score);
665 elementValueStack.pop_back();
668 void FGTrafficManager::data(const char *s, int len)
670 string token = string(s, len);
671 //cout << "Character data " << string(s,len) << endl;
672 elementValueStack.back() += token;
675 void FGTrafficManager::pi(const char *target, const char *data)
677 //cout << "Processing instruction " << target << ' ' << data << endl;
680 void FGTrafficManager::warning(const char *message, int line, int column)
682 SG_LOG(SG_IO, SG_WARN,
683 "Warning: " << message << " (" << line << ',' << column << ')');
686 void FGTrafficManager::error(const char *message, int line, int column)
688 SG_LOG(SG_IO, SG_ALERT,
689 "Error: " << message << " (" << line << ',' << column << ')');