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 for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++)
92 scheduledAircraft.clear();
97 void FGTrafficManager::init()
100 ulDirEnt* dent, *dent2;
101 SGPath aircraftDir = globals->get_fg_root();
103 SGPath path = aircraftDir;
105 aircraftDir.append("AI/Traffic");
106 if ((d = ulOpenDir(aircraftDir.c_str())) != NULL)
108 while((dent = ulReadDir(d)) != NULL) {
109 if (string(dent->d_name) != string(".") &&
110 string(dent->d_name) != string("..") &&
113 SGPath currACDir = aircraftDir;
114 currACDir.append(dent->d_name);
115 if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
117 while ((dent2 = ulReadDir(d2)) != NULL) {
118 SGPath currFile = currACDir;
119 currFile.append(dent2->d_name);
120 if (currFile.extension() == string("xml"))
122 SGPath currFile = currACDir;
123 currFile.append(dent2->d_name);
124 SG_LOG(SG_GENERAL, SG_DEBUG, "Scanning " << currFile.str() << " for traffic");
125 readXML(currFile.str(),*this);
134 currAircraft = scheduledAircraft.begin();
135 currAircraftClosest = scheduledAircraft.begin();
138 void FGTrafficManager::update(double /*dt*/)
141 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
142 if (scheduledAircraft.size() == 0) {
145 if(currAircraft == scheduledAircraft.end())
147 currAircraft = scheduledAircraft.begin();
149 if (!((*currAircraft)->update(now)))
151 // NOTE: With traffic manager II, this statement below is no longer true
152 // after proper initialization, we shouldnt get here.
153 // But let's make sure
154 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
159 void FGTrafficManager::release(int id)
161 releaseList.push_back(id);
164 bool FGTrafficManager::isReleased(int id)
166 IdListIterator i = releaseList.begin();
167 while (i != releaseList.end())
171 releaseList.erase(i);
179 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
196 vector <string> tokens, depTime,arrTime;
197 vector <string>::iterator it;
198 ifstream infile(infileName.str().c_str());
200 infile.getline(buffer, 256);
204 //cerr << "Read line : " << buffer << endl;
205 buffString = string(buffer);
207 Tokenize(buffString, tokens, " \t");
208 //for (it = tokens.begin(); it != tokens.end(); it++) {
209 // cerr << "Tokens: " << *(it) << endl;
212 if (!tokens.empty()) {
213 if (tokens[0] == string("AC")) {
214 if (tokens.size() != 13) {
215 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
220 homePort = tokens[1];
221 registration = tokens[2];
222 if (tokens[11] == string("false")) {
229 flightReq = tokens[3] + tokens[5];
230 m_class = tokens[10];
231 FlightType = tokens[9];
232 radius = atof(tokens[8].c_str());
233 offset = atof(tokens[7].c_str());;
234 //cerr << "Found AC string " << model << " " << livery << " " << homePort << " "
235 // << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class
236 // << " " << FlightType << " " << radius << " " << offset << endl;
237 scheduledAircraft.push_back(new FGAISchedule(model,
250 if (tokens[0] == string("FLIGHT")) {
251 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
252 if (tokens.size() != 10) {
253 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
256 string callsign = tokens[1];
257 string fltrules = tokens[2];
258 string weekdays = tokens[3];
259 string departurePort = tokens[5];
260 string arrivalPort = tokens[7];
261 int cruiseAlt = atoi(tokens[8].c_str());
262 string depTimeGen = tokens[4];
263 string arrTimeGen = tokens[6];
264 string repeat = "WEEK";
265 string requiredAircraft = tokens[9];
267 if (weekdays.size() != 7) {
268 cerr << "Found misconfigured weekdays string" << weekdays << endl;
273 Tokenize(depTimeGen, depTime, ":");
274 Tokenize(arrTimeGen, arrTime, ":");
275 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
276 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
277 //cerr << "Using " << dep << " " << arr << endl;
278 bool arrivalWeekdayNeedsIncrement = false;
280 arrivalWeekdayNeedsIncrement = true;
282 for (int i = 0; i < 7; i++) {
283 if (weekdays[i] != '.') {
285 snprintf(buffer, 4, "%d/", i);
286 string departureTime = string(buffer) + depTimeGen + string(":00");
288 if (!arrivalWeekdayNeedsIncrement) {
289 arrivalTime = string(buffer) + arrTimeGen + string(":00");
291 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
292 snprintf(buffer, 4, "%d/", i+1);
293 arrivalTime = string(buffer) + arrTimeGen + string(":00");
295 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
296 snprintf(buffer, 4, "%d/", 0);
297 arrivalTime = string(buffer) + arrTimeGen + string(":00");
299 cerr << "Adding flight: " << callsign << " "
301 << departurePort << " "
302 << arrivalPort << " "
304 << departureTime << " "
305 << arrivalTime << " "
307 << requiredAircraft << endl;
309 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
328 void FGTrafficManager::Tokenize(const string& str,
329 vector<string>& tokens,
330 const string& delimiters)
332 // Skip delimiters at beginning.
333 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
334 // Find first "non-delimiter".
335 string::size_type pos = str.find_first_of(delimiters, lastPos);
337 while (string::npos != pos || string::npos != lastPos)
339 // Found a token, add it to the vector.
340 tokens.push_back(str.substr(lastPos, pos - lastPos));
341 // Skip delimiters. Note the "not_of"
342 lastPos = str.find_first_not_of(delimiters, pos);
343 // Find next "non-delimiter"
344 pos = str.find_first_of(delimiters, lastPos);
349 void FGTrafficManager::startXML () {
350 //cout << "Start XML" << endl;
351 requiredAircraft = "";
355 void FGTrafficManager::endXML () {
356 //cout << "End XML" << endl;
359 void FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
361 //cout << "Start element " << name << endl;
362 //FGTrafficManager temp;
363 //for (int i = 0; i < atts.size(); i++)
364 // if (string(atts.getName(i)) == string("include"))
365 attval = atts.getValue("include");
368 //cout << "including " << attval << endl;
370 globals->get_fg_root();
371 path.append("/Traffic/");
373 readXML(path.str(), *this);
375 elementValueStack.push_back( "" );
376 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
379 void FGTrafficManager::endElement (const char * name) {
380 //cout << "End element " << name << endl;
381 const string& value = elementValueStack.back();
383 if (!strcmp(name, "model"))
385 else if (!strcmp(name, "livery"))
387 else if (!strcmp(name, "home-port"))
389 else if (!strcmp(name, "registration"))
390 registration = value;
391 else if (!strcmp(name, "airline"))
393 else if (!strcmp(name, "actype"))
395 else if (!strcmp(name, "required-aircraft"))
396 requiredAircraft = value;
397 else if (!strcmp(name, "flighttype"))
399 else if (!strcmp(name, "radius"))
400 radius = atoi(value.c_str());
401 else if (!strcmp(name, "offset"))
402 offset = atoi(value.c_str());
403 else if (!strcmp(name, "performance-class"))
405 else if (!strcmp(name, "heavy"))
407 if(value == string("true"))
412 else if (!strcmp(name, "callsign"))
414 else if (!strcmp(name, "fltrules"))
416 else if (!strcmp(name, "port"))
418 else if (!strcmp(name, "time"))
420 else if (!strcmp(name, "departure"))
422 departurePort = port;
423 departureTime = timeString;
425 else if (!strcmp(name, "cruise-alt"))
426 cruiseAlt = atoi(value.c_str());
427 else if (!strcmp(name, "arrival"))
430 arrivalTime = timeString;
432 else if (!strcmp(name, "repeat"))
434 else if (!strcmp(name, "flight"))
436 // We have loaded and parsed all the information belonging to this flight
437 // so we temporarily store it.
438 //cerr << "Pusing back flight " << callsign << endl;
439 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
440 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
442 //Prioritize aircraft
443 string apt = fgGetString("/sim/presets/airport-id");
444 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
445 //if (departurePort == apt) score++;
446 //flights.push_back(new FGScheduledFlight(callsign,
454 if (requiredAircraft == "") {
456 snprintf(buffer, 16, "%d", acCounter);
457 requiredAircraft = buffer;
459 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
461 << departurePort << " "
462 << arrivalPort << " "
464 << departureTime << " "
465 << arrivalTime << " "
467 << requiredAircraft);
469 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
478 requiredAircraft = "";
480 else if (!strcmp(name, "aircraft"))
482 int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
483 int randval = rand() & 100;
484 if (randval < proportion) {
485 //scheduledAircraft.push_back(new FGAISchedule(mdl,
497 if (requiredAircraft == "") {
499 snprintf(buffer, 16, "%d", acCounter);
500 requiredAircraft = buffer;
502 if (homePort == "") {
503 homePort = departurePort;
505 scheduledAircraft.push_back(new FGAISchedule(mdl,
518 // while(flights.begin() != flights.end()) {
519 // flights.pop_back();
523 requiredAircraft = "";
525 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
530 SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : "
532 << " with prioritization score "
536 elementValueStack.pop_back();
539 void FGTrafficManager::data (const char * s, int len) {
540 string token = string(s,len);
541 //cout << "Character data " << string(s,len) << endl;
542 elementValueStack.back() += token;
545 void FGTrafficManager::pi (const char * target, const char * data) {
546 //cout << "Processing instruction " << target << ' ' << data << endl;
549 void FGTrafficManager::warning (const char * message, int line, int column) {
550 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
553 void FGTrafficManager::error (const char * message, int line, int column) {
554 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');