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 metarValid("/environment/metar/valid")
89 FGTrafficManager::~FGTrafficManager()
91 // Save the heuristics data
92 bool saveData = false;
94 if (fgGetBool("/sim/traffic-manager/heuristics")) {
95 SGPath cacheData(fgGetString("/sim/fg-home"));
96 cacheData.append("ai");
97 string airport = fgGetString("/sim/presets/airport-id");
99 if ((airport) != "") {
101 ::snprintf(buffer, 128, "%c/%c/%c/",
102 airport[0], airport[1], airport[2]);
103 cacheData.append(buffer);
104 if (!cacheData.exists()) {
105 cacheData.create_dir(0777);
107 cacheData.append(airport + "-cache.txt");
108 //cerr << "Saving AI traffic heuristics" << endl;
110 cachefile.open(cacheData.str().c_str());
113 for (ScheduleVectorIterator sched = scheduledAircraft.begin();
114 sched != scheduledAircraft.end(); sched++) {
116 cachefile << (*sched)->getRegistration() << " "
117 << (*sched)->getRunCount() << " "
118 << (*sched)->getHits() << endl;
125 scheduledAircraft.clear();
130 void FGTrafficManager::init()
132 if (!enabled || !aiEnabled) {
136 heuristicsVector heuristics;
137 HeuristicMap heurMap;
139 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
140 simgear::Dir trafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
141 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
143 for (unsigned int i=0; i<d.size(); ++i) {
144 simgear::Dir d2(d[i]);
145 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
146 for (unsigned int j=0; j<trafficFiles.size(); ++j) {
147 SGPath curFile = trafficFiles[j];
148 SG_LOG(SG_GENERAL, SG_DEBUG,
149 "Scanning " << curFile.str() << " for traffic");
150 readXML(curFile.str(), *this);
154 fgSetBool("/sim/traffic-manager/heuristics", false);
155 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
156 string ext = path.extension();
157 if (path.extension() == "xml") {
159 readXML(path.str(), *this);
161 } else if (path.extension() == "conf") {
163 readTimeTableFromFile(path);
166 SG_LOG(SG_GENERAL, SG_ALERT,
167 "Unknown data format " << path.str()
172 if (fgGetBool("/sim/traffic-manager/heuristics")) {
173 //cerr << "Processing Heuristics" << endl;
174 // Load the heuristics data
175 SGPath cacheData(fgGetString("/sim/fg-home"));
176 cacheData.append("ai");
177 string airport = fgGetString("/sim/presets/airport-id");
178 if ((airport) != "") {
180 ::snprintf(buffer, 128, "%c/%c/%c/",
181 airport[0], airport[1], airport[2]);
182 cacheData.append(buffer);
183 cacheData.append(airport + "-cache.txt");
184 if (cacheData.exists()) {
185 ifstream data(cacheData.c_str());
187 Heuristic h; // = new Heuristic;
188 data >> h.registration >> h.runCount >> h.hits;
191 HeuristicMapIterator itr = heurMap.find(h.registration);
192 if (itr != heurMap.end()) {
193 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
194 h.registration << " for AI aircraft");
196 heurMap[h.registration] = h;
197 heuristics.push_back(h);
201 for (currAircraft = scheduledAircraft.begin();
202 currAircraft != scheduledAircraft.end(); currAircraft++) {
203 string registration = (*currAircraft)->getRegistration();
204 HeuristicMapIterator itr = heurMap.find(registration);
205 //cerr << "Processing heuristics for" << (*currAircraft)->getRegistration() << endl;
206 if (itr == heurMap.end()) {
207 //cerr << "No heuristics found for " << registration << endl;
209 (*currAircraft)->setrunCount(itr->second.runCount);
210 (*currAircraft)->setHits(itr->second.hits);
211 //cerr <<"Runcount " << itr->second->runCount << ".Hits " << itr->second->hits << endl;
214 //cerr << "Done" << endl;
215 //for (heuristicsVectorIterator hvi = heuristics.begin();
216 // hvi != heuristics.end(); hvi++) {
220 // Do sorting and scoring separately, to take advantage of the "homeport| variable
221 for (currAircraft = scheduledAircraft.begin();
222 currAircraft != scheduledAircraft.end(); currAircraft++) {
223 (*currAircraft)->setScore();
225 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
227 currAircraft = scheduledAircraft.begin();
228 currAircraftClosest = scheduledAircraft.begin();
233 void FGTrafficManager::update(double /*dt */ )
235 if (!enabled || !aiEnabled || !metarValid) {
240 // lazy-initialization, we've been enabled at run-time
241 SG_LOG(SG_GENERAL, SG_INFO, "doing lazy-init of TrafficManager");
245 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
246 if (scheduledAircraft.size() == 0) {
251 SGVec3d::fromGeod(SGGeod::
252 fromDeg(fgGetDouble("/position/longitude-deg"),
253 fgGetDouble("/position/latitude-deg")));
255 if (currAircraft == scheduledAircraft.end()) {
256 currAircraft = scheduledAircraft.begin();
258 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
259 if (!((*currAircraft)->update(now, userCart))) {
260 // NOTE: With traffic manager II, this statement below is no longer true
261 // after proper initialization, we shouldnt get here.
262 // But let's make sure
263 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
268 void FGTrafficManager::release(int id)
270 releaseList.push_back(id);
273 bool FGTrafficManager::isReleased(int id)
275 IdListIterator i = releaseList.begin();
276 while (i != releaseList.end()) {
278 releaseList.erase(i);
287 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
304 vector <string> tokens, depTime,arrTime;
305 vector <string>::iterator it;
306 ifstream infile(infileName.str().c_str());
308 infile.getline(buffer, 256);
312 //cerr << "Read line : " << buffer << endl;
313 buffString = string(buffer);
315 Tokenize(buffString, tokens, " \t");
316 //for (it = tokens.begin(); it != tokens.end(); it++) {
317 // cerr << "Tokens: " << *(it) << endl;
320 if (!tokens.empty()) {
321 if (tokens[0] == string("AC")) {
322 if (tokens.size() != 13) {
323 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
328 homePort = tokens[1];
329 registration = tokens[2];
330 if (tokens[11] == string("false")) {
337 flightReq = tokens[3] + tokens[5];
338 m_class = tokens[10];
339 FlightType = tokens[9];
340 radius = atof(tokens[8].c_str());
341 offset = atof(tokens[7].c_str());;
342 SG_LOG(SG_GENERAL, SG_ALERT, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
343 << registration << " " << flightReq << " " << isHeavy
344 << " " << acType << " " << airline << " " << m_class
345 << " " << FlightType << " " << radius << " " << offset);
346 scheduledAircraft.push_back(new FGAISchedule(model,
359 if (tokens[0] == string("FLIGHT")) {
360 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
361 if (tokens.size() != 10) {
362 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
365 string callsign = tokens[1];
366 string fltrules = tokens[2];
367 string weekdays = tokens[3];
368 string departurePort = tokens[5];
369 string arrivalPort = tokens[7];
370 int cruiseAlt = atoi(tokens[8].c_str());
371 string depTimeGen = tokens[4];
372 string arrTimeGen = tokens[6];
373 string repeat = "WEEK";
374 string requiredAircraft = tokens[9];
376 if (weekdays.size() != 7) {
377 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
382 Tokenize(depTimeGen, depTime, ":");
383 Tokenize(arrTimeGen, arrTime, ":");
384 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
385 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
386 //cerr << "Using " << dep << " " << arr << endl;
387 bool arrivalWeekdayNeedsIncrement = false;
389 arrivalWeekdayNeedsIncrement = true;
391 for (int i = 0; i < 7; i++) {
393 if (weekdays[i] != '.') {
395 snprintf(buffer, 4, "%d/", j);
396 string departureTime = string(buffer) + depTimeGen + string(":00");
398 if (!arrivalWeekdayNeedsIncrement) {
399 arrivalTime = string(buffer) + arrTimeGen + string(":00");
401 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
402 snprintf(buffer, 4, "%d/", j+1);
403 arrivalTime = string(buffer) + arrTimeGen + string(":00");
405 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
406 snprintf(buffer, 4, "%d/", 0);
407 arrivalTime = string(buffer) + arrTimeGen + string(":00");
409 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
411 << departurePort << " "
412 << arrivalPort << " "
414 << departureTime << " "
415 << arrivalTime << " "
417 << requiredAircraft);
419 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
438 void FGTrafficManager::Tokenize(const string& str,
439 vector<string>& tokens,
440 const string& delimiters)
442 // Skip delimiters at beginning.
443 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
444 // Find first "non-delimiter".
445 string::size_type pos = str.find_first_of(delimiters, lastPos);
447 while (string::npos != pos || string::npos != lastPos)
449 // Found a token, add it to the vector.
450 tokens.push_back(str.substr(lastPos, pos - lastPos));
451 // Skip delimiters. Note the "not_of"
452 lastPos = str.find_first_not_of(delimiters, pos);
453 // Find next "non-delimiter"
454 pos = str.find_first_of(delimiters, lastPos);
459 void FGTrafficManager::startXML()
461 //cout << "Start XML" << endl;
462 requiredAircraft = "";
466 void FGTrafficManager::endXML()
468 //cout << "End XML" << endl;
471 void FGTrafficManager::startElement(const char *name,
472 const XMLAttributes & atts)
475 //cout << "Start element " << name << endl;
476 //FGTrafficManager temp;
477 //for (int i = 0; i < atts.size(); i++)
478 // if (string(atts.getName(i)) == string("include"))
479 attval = atts.getValue("include");
481 //cout << "including " << attval << endl;
482 SGPath path = globals->get_fg_root();
483 path.append("/Traffic/");
485 readXML(path.str(), *this);
487 elementValueStack.push_back("");
488 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
491 void FGTrafficManager::endElement(const char *name)
493 //cout << "End element " << name << endl;
494 const string & value = elementValueStack.back();
496 if (!strcmp(name, "model"))
498 else if (!strcmp(name, "livery"))
500 else if (!strcmp(name, "home-port"))
502 else if (!strcmp(name, "registration"))
503 registration = value;
504 else if (!strcmp(name, "airline"))
506 else if (!strcmp(name, "actype"))
508 else if (!strcmp(name, "required-aircraft"))
509 requiredAircraft = value;
510 else if (!strcmp(name, "flighttype"))
512 else if (!strcmp(name, "radius"))
513 radius = atoi(value.c_str());
514 else if (!strcmp(name, "offset"))
515 offset = atoi(value.c_str());
516 else if (!strcmp(name, "performance-class"))
518 else if (!strcmp(name, "heavy")) {
519 if (value == string("true"))
523 } else if (!strcmp(name, "callsign"))
525 else if (!strcmp(name, "fltrules"))
527 else if (!strcmp(name, "port"))
529 else if (!strcmp(name, "time"))
531 else if (!strcmp(name, "departure")) {
532 departurePort = port;
533 departureTime = timeString;
534 } else if (!strcmp(name, "cruise-alt"))
535 cruiseAlt = atoi(value.c_str());
536 else if (!strcmp(name, "arrival")) {
538 arrivalTime = timeString;
539 } else if (!strcmp(name, "repeat"))
541 else if (!strcmp(name, "flight")) {
542 // We have loaded and parsed all the information belonging to this flight
543 // so we temporarily store it.
544 //cerr << "Pusing back flight " << callsign << endl;
545 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
546 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
548 //Prioritize aircraft
549 string apt = fgGetString("/sim/presets/airport-id");
550 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
551 //if (departurePort == apt) score++;
552 //flights.push_back(new FGScheduledFlight(callsign,
560 if (requiredAircraft == "") {
562 snprintf(buffer, 16, "%d", acCounter);
563 requiredAircraft = buffer;
565 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
567 << departurePort << " "
568 << arrivalPort << " "
570 << departureTime << " "
571 << arrivalTime << " " << repeat << " " << requiredAircraft);
572 // For database maintainance purposes, it may be convenient to
574 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
575 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
577 << departurePort << ","
578 << arrivalPort << ","
580 << departureTime << ","
581 << arrivalTime << "," << repeat << "," << requiredAircraft);
583 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
592 requiredAircraft = "";
593 } else if (!strcmp(name, "aircraft")) {
601 cerr << "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
602 << "," << acType << "," << livery << ","
603 << airline << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl << endl;*/
605 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
606 int randval = rand() & 100;
607 if (randval <= proportion) {
608 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
609 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
610 << "," << acType << "," << livery << ","
611 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
613 //scheduledAircraft.push_back(new FGAISchedule(mdl,
625 if (requiredAircraft == "") {
627 snprintf(buffer, 16, "%d", acCounter);
628 requiredAircraft = buffer;
630 if (homePort == "") {
631 homePort = departurePort;
633 scheduledAircraft.push_back(new FGAISchedule(mdl,
645 // while(flights.begin() != flights.end()) {
646 // flights.pop_back();
649 cerr << "Skipping : " << randval;
652 requiredAircraft = "";
654 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
659 SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
660 << registration << " with prioritization score " << score);
663 elementValueStack.pop_back();
666 void FGTrafficManager::data(const char *s, int len)
668 string token = string(s, len);
669 //cout << "Character data " << string(s,len) << endl;
670 elementValueStack.back() += token;
673 void FGTrafficManager::pi(const char *target, const char *data)
675 //cout << "Processing instruction " << target << ' ' << data << endl;
678 void FGTrafficManager::warning(const char *message, int line, int column)
680 SG_LOG(SG_IO, SG_WARN,
681 "Warning: " << message << " (" << line << ',' << column << ')');
684 void FGTrafficManager::error(const char *message, int line, int column)
686 SG_LOG(SG_IO, SG_ALERT,
687 "Error: " << message << " (" << line << ',' << column << ')');