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 *****************************************************************************/
56 #include <simgear/compiler.h>
57 #include <simgear/misc/sg_path.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()
86 FGTrafficManager:: ~FGTrafficManager()
88 // Save the heuristics data
89 bool saveData = false;
91 if (fgGetBool("/sim/traffic-manager/heuristics")) {
92 SGPath cacheData(fgGetString("/sim/fg-home"));
93 cacheData.append("ai");
94 string airport = fgGetString("/sim/presets/airport-id");
96 if ((airport) != "") {
98 ::snprintf(buffer, 128, "%c/%c/%c/",
99 airport[0], airport[1], airport[2]);
100 cacheData.append(buffer);
101 if (!cacheData.exists()) {
102 cacheData.create_dir(0777);
104 cacheData.append(airport + "-cache.txt");
105 //cerr << "Saving AI traffic heuristics" << endl;
107 cachefile.open(cacheData.str().c_str());
110 for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++) {
112 cachefile << (*sched)->getRegistration() << " "
113 << (*sched)-> getRunCount() << " "
114 << (*sched)->getHits() << endl;
121 scheduledAircraft.clear();
126 void FGTrafficManager::init()
129 ulDirEnt* dent, *dent2;
130 SGPath aircraftDir = globals->get_fg_root();
131 SGPath path = aircraftDir;
132 heuristicsVector heuristics;
133 HeuristicMap heurMap;
136 aircraftDir.append("AI/Traffic");
137 if ((d = ulOpenDir(aircraftDir.c_str())) != NULL)
139 while((dent = ulReadDir(d)) != NULL) {
140 if (string(dent->d_name) != string(".") &&
141 string(dent->d_name) != string("..") &&
144 SGPath currACDir = aircraftDir;
145 currACDir.append(dent->d_name);
146 if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
148 while ((dent2 = ulReadDir(d2)) != NULL) {
149 SGPath currFile = currACDir;
150 currFile.append(dent2->d_name);
151 if (currFile.extension() == string("xml"))
153 SGPath currFile = currACDir;
154 currFile.append(dent2->d_name);
155 SG_LOG(SG_GENERAL, SG_DEBUG, "Scanning " << currFile.str() << " for traffic");
156 readXML(currFile.str(),*this);
164 if (fgGetBool("/sim/traffic-manager/heuristics")) {
165 //cerr << "Processing Heuristics" << endl;
166 // Load the heuristics data
167 SGPath cacheData(fgGetString("/sim/fg-home"));
168 cacheData.append("ai");
169 string airport = fgGetString("/sim/presets/airport-id");
170 if ((airport) != "") {
172 ::snprintf(buffer, 128, "%c/%c/%c/",
173 airport[0], airport[1], airport[2]);
174 cacheData.append(buffer);
175 cacheData.append(airport + "-cache.txt");
176 if (cacheData.exists()) {
177 ifstream data(cacheData.c_str());
179 Heuristic *h = new Heuristic;
180 data >> h->registration >> h->runCount >> h->hits;
183 heurMap[h->registration] = h;
184 heuristics.push_back(h);
188 for (currAircraft = scheduledAircraft.begin();
189 currAircraft != scheduledAircraft.end();
191 string registration = (*currAircraft)->getRegistration();
192 HeuristicMapIterator itr = heurMap.find(registration);
193 //cerr << "Processing heuristics for" << (*currAircraft)->getRegistration() << endl;
194 if (itr == heurMap.end()) {
195 //cerr << "No heuristics found for " << registration << endl;
197 (*currAircraft)->setrunCount(itr->second->runCount);
198 (*currAircraft)->setHits (itr->second->hits);
199 (*currAircraft)->setScore();
200 //cerr <<"Runcount " << itr->second->runCount << ".Hits " << itr->second->hits << endl;
203 //cerr << "Done" << endl;
204 for (heuristicsVectorIterator hvi = heuristics.begin();
205 hvi != heuristics.end();
209 sort (scheduledAircraft.begin(), scheduledAircraft.end(), compareSchedules);
211 currAircraft = scheduledAircraft.begin();
212 currAircraftClosest = scheduledAircraft.begin();
215 void FGTrafficManager::update(double /*dt*/)
217 if (fgGetBool("/environment/metar/valid") == false) {
220 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
221 if (scheduledAircraft.size() == 0) {
225 SGVec3d userCart = SGVec3d::fromGeod(SGGeod::fromDeg(
226 fgGetDouble("/position/longitude-deg"),
227 fgGetDouble("/position/latitude-deg")));
229 if(currAircraft == scheduledAircraft.end())
231 currAircraft = scheduledAircraft.begin();
233 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
234 if (!((*currAircraft)->update(now, userCart)))
236 // NOTE: With traffic manager II, this statement below is no longer true
237 // after proper initialization, we shouldnt get here.
238 // But let's make sure
239 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
244 void FGTrafficManager::release(int id)
246 releaseList.push_back(id);
249 bool FGTrafficManager::isReleased(int id)
251 IdListIterator i = releaseList.begin();
252 while (i != releaseList.end())
256 releaseList.erase(i);
264 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
281 vector <string> tokens, depTime,arrTime;
282 vector <string>::iterator it;
283 ifstream infile(infileName.str().c_str());
285 infile.getline(buffer, 256);
289 //cerr << "Read line : " << buffer << endl;
290 buffString = string(buffer);
292 Tokenize(buffString, tokens, " \t");
293 //for (it = tokens.begin(); it != tokens.end(); it++) {
294 // cerr << "Tokens: " << *(it) << endl;
297 if (!tokens.empty()) {
298 if (tokens[0] == string("AC")) {
299 if (tokens.size() != 13) {
300 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
305 homePort = tokens[1];
306 registration = tokens[2];
307 if (tokens[11] == string("false")) {
314 flightReq = tokens[3] + tokens[5];
315 m_class = tokens[10];
316 FlightType = tokens[9];
317 radius = atof(tokens[8].c_str());
318 offset = atof(tokens[7].c_str());;
319 //cerr << "Found AC string " << model << " " << livery << " " << homePort << " "
320 // << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class
321 // << " " << FlightType << " " << radius << " " << offset << endl;
322 scheduledAircraft.push_back(new FGAISchedule(model,
335 if (tokens[0] == string("FLIGHT")) {
336 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
337 if (tokens.size() != 10) {
338 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
341 string callsign = tokens[1];
342 string fltrules = tokens[2];
343 string weekdays = tokens[3];
344 string departurePort = tokens[5];
345 string arrivalPort = tokens[7];
346 int cruiseAlt = atoi(tokens[8].c_str());
347 string depTimeGen = tokens[4];
348 string arrTimeGen = tokens[6];
349 string repeat = "WEEK";
350 string requiredAircraft = tokens[9];
352 if (weekdays.size() != 7) {
353 cerr << "Found misconfigured weekdays string" << weekdays << endl;
358 Tokenize(depTimeGen, depTime, ":");
359 Tokenize(arrTimeGen, arrTime, ":");
360 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
361 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
362 //cerr << "Using " << dep << " " << arr << endl;
363 bool arrivalWeekdayNeedsIncrement = false;
365 arrivalWeekdayNeedsIncrement = true;
367 for (int i = 0; i < 7; i++) {
368 if (weekdays[i] != '.') {
370 snprintf(buffer, 4, "%d/", i);
371 string departureTime = string(buffer) + depTimeGen + string(":00");
373 if (!arrivalWeekdayNeedsIncrement) {
374 arrivalTime = string(buffer) + arrTimeGen + string(":00");
376 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
377 snprintf(buffer, 4, "%d/", i+1);
378 arrivalTime = string(buffer) + arrTimeGen + string(":00");
380 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
381 snprintf(buffer, 4, "%d/", 0);
382 arrivalTime = string(buffer) + arrTimeGen + string(":00");
384 cerr << "Adding flight: " << callsign << " "
386 << departurePort << " "
387 << arrivalPort << " "
389 << departureTime << " "
390 << arrivalTime << " "
392 << requiredAircraft << endl;
394 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
413 void FGTrafficManager::Tokenize(const string& str,
414 vector<string>& tokens,
415 const string& delimiters)
417 // Skip delimiters at beginning.
418 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
419 // Find first "non-delimiter".
420 string::size_type pos = str.find_first_of(delimiters, lastPos);
422 while (string::npos != pos || string::npos != lastPos)
424 // Found a token, add it to the vector.
425 tokens.push_back(str.substr(lastPos, pos - lastPos));
426 // Skip delimiters. Note the "not_of"
427 lastPos = str.find_first_not_of(delimiters, pos);
428 // Find next "non-delimiter"
429 pos = str.find_first_of(delimiters, lastPos);
434 void FGTrafficManager::startXML () {
435 //cout << "Start XML" << endl;
436 requiredAircraft = "";
440 void FGTrafficManager::endXML () {
441 //cout << "End XML" << endl;
444 void FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
446 //cout << "Start element " << name << endl;
447 //FGTrafficManager temp;
448 //for (int i = 0; i < atts.size(); i++)
449 // if (string(atts.getName(i)) == string("include"))
450 attval = atts.getValue("include");
453 //cout << "including " << attval << endl;
455 globals->get_fg_root();
456 path.append("/Traffic/");
458 readXML(path.str(), *this);
460 elementValueStack.push_back( "" );
461 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
464 void FGTrafficManager::endElement (const char * name) {
465 //cout << "End element " << name << endl;
466 const string& value = elementValueStack.back();
468 if (!strcmp(name, "model"))
470 else if (!strcmp(name, "livery"))
472 else if (!strcmp(name, "home-port"))
474 else if (!strcmp(name, "registration"))
475 registration = value;
476 else if (!strcmp(name, "airline"))
478 else if (!strcmp(name, "actype"))
480 else if (!strcmp(name, "required-aircraft"))
481 requiredAircraft = value;
482 else if (!strcmp(name, "flighttype"))
484 else if (!strcmp(name, "radius"))
485 radius = atoi(value.c_str());
486 else if (!strcmp(name, "offset"))
487 offset = atoi(value.c_str());
488 else if (!strcmp(name, "performance-class"))
490 else if (!strcmp(name, "heavy"))
492 if(value == string("true"))
497 else if (!strcmp(name, "callsign"))
499 else if (!strcmp(name, "fltrules"))
501 else if (!strcmp(name, "port"))
503 else if (!strcmp(name, "time"))
505 else if (!strcmp(name, "departure"))
507 departurePort = port;
508 departureTime = timeString;
510 else if (!strcmp(name, "cruise-alt"))
511 cruiseAlt = atoi(value.c_str());
512 else if (!strcmp(name, "arrival"))
515 arrivalTime = timeString;
517 else if (!strcmp(name, "repeat"))
519 else if (!strcmp(name, "flight"))
521 // We have loaded and parsed all the information belonging to this flight
522 // so we temporarily store it.
523 //cerr << "Pusing back flight " << callsign << endl;
524 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
525 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
527 //Prioritize aircraft
528 string apt = fgGetString("/sim/presets/airport-id");
529 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
530 //if (departurePort == apt) score++;
531 //flights.push_back(new FGScheduledFlight(callsign,
539 if (requiredAircraft == "") {
541 snprintf(buffer, 16, "%d", acCounter);
542 requiredAircraft = buffer;
544 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
546 << departurePort << " "
547 << arrivalPort << " "
549 << departureTime << " "
550 << arrivalTime << " "
552 << requiredAircraft);
554 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
563 requiredAircraft = "";
565 else if (!strcmp(name, "aircraft"))
567 int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
568 int randval = rand() & 100;
569 if (randval < proportion) {
570 //scheduledAircraft.push_back(new FGAISchedule(mdl,
582 if (requiredAircraft == "") {
584 snprintf(buffer, 16, "%d", acCounter);
585 requiredAircraft = buffer;
587 if (homePort == "") {
588 homePort = departurePort;
590 scheduledAircraft.push_back(new FGAISchedule(mdl,
603 // while(flights.begin() != flights.end()) {
604 // flights.pop_back();
608 requiredAircraft = "";
610 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
615 SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : "
617 << " with prioritization score "
621 elementValueStack.pop_back();
624 void FGTrafficManager::data (const char * s, int len) {
625 string token = string(s,len);
626 //cout << "Character data " << string(s,len) << endl;
627 elementValueStack.back() += token;
630 void FGTrafficManager::pi (const char * target, const char * data) {
631 //cout << "Processing instruction " << target << ' ' << data << endl;
634 void FGTrafficManager::warning (const char * message, int line, int column) {
635 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
638 void FGTrafficManager::error (const char * message, int line, int column) {
639 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');