1 // AIMgr.cxx - implementation of FGAIMgr
2 // - a global management class for FlightGear generated AI traffic
4 // Written by David Luff, started March 2002.
6 // Copyright (C) 2002 David C Luff - david.luff@nottingham.ac.uk
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include <Main/fg_props.hxx>
29 #include <Main/globals.hxx>
30 #include <simgear/misc/sg_path.hxx>
31 #include <simgear/math/sg_random.h>
32 #include <simgear/scene/model/modellib.hxx>
38 # include <sys/types.h> // for directory reading
39 # include <dirent.h> // for directory reading
42 #include <Environment/environment_mgr.hxx>
43 #include <Environment/environment.hxx>
46 #include "AILocalTraffic.hxx"
47 #include "AIGAVFRTraffic.hxx"
48 #include "ATCutils.hxx"
49 #include "commlist.hxx"
54 using namespace simgear;
56 // extern from Airports/simple.cxx
57 extern Point3D fgGetAirportPos( const std::string& id );
60 ATC = globals->get_ATC_mgr();
62 ai_callsigns_used["GFS"] = 1; // so we don't inadvertently use this
63 // TODO - use the proper user callsign when it becomes user settable.
66 _havePiperModel = true;
70 for (ai_list_itr = ai_list.begin(); ai_list_itr != ai_list.end(); ai_list_itr++) {
71 delete (*ai_list_itr);
75 void FGAIMgr::init() {
76 //cout << "AIMgr::init called..." << endl;
78 // Pointers to user's position
79 lon_node = fgGetNode("/position/longitude-deg", true);
80 lat_node = fgGetNode("/position/latitude-deg", true);
81 elev_node = fgGetNode("/position/altitude-ft", true);
83 lon = lon_node->getDoubleValue();
84 lat = lat_node->getDoubleValue();
85 elev = elev_node->getDoubleValue();
87 // Load up models at the start to avoid pausing later
88 // Hack alert - Hardwired paths!!
89 string planepath = "Aircraft/c172p/Models/c172p.xml";
90 bool _loadedDefaultOK = true;
92 _defaultModel = SGModelLib::loadPagedModel(planepath.c_str(), globals->get_props());
93 } catch(sg_exception&) {
94 _loadedDefaultOK = false;
97 if(!_loadedDefaultOK ) {
98 // Just load the same 3D model as the default user plane - that's *bound* to exist!
99 // TODO - implement robust determination of availability of GA AI aircraft models
100 planepath = "Aircraft/c172p/Models/c172p.ac";
101 _defaultModel = SGModelLib::loadPagedModel(planepath.c_str(), globals->get_props());
104 planepath = "Aircraft/pa28-161/Models/pa28-161.ac";
106 _piperModel = SGModelLib::loadPagedModel(planepath.c_str(), globals->get_props());
107 } catch(sg_exception&) {
108 _havePiperModel = false;
111 // go through the $FG_ROOT/ATC directory and find all *.taxi files
112 SGPath path(globals->get_fg_root());
114 string dir = path.dir();
116 string file, f_ident;
122 if ( (d = ulOpenDir( dir.c_str() )) == NULL ) {
123 SG_LOG(SG_ATC, SG_WARN, "cannot open directory " << dir);
125 // load all .taxi files
126 while ( (de = ulReadDir(d)) != NULL ) {
128 pos = file.find(".");
129 ext = file.substr(pos + 1);
131 f_ident = file.substr(0, pos);
132 const FGAirport *a = fgFindAirportID( f_ident);
134 SGBucket sgb(a->getLongitude(), a->getLatitude());
135 int idx = sgb.gen_index();
136 if(facilities.find(idx) != facilities.end()) {
137 facilities[idx]->push_back(f_ident);
139 ID_list_type* apts = new ID_list_type;
140 apts->push_back(f_ident);
141 facilities[idx] = apts;
143 SG_LOG(SG_ATC, SG_BULK, "Mapping " << f_ident << " to bucket " << idx);
150 // See if are in range at startup and activate if necessary
155 //cout << "AIMgr::init done..." << endl;
159 FGATCAlignedProjection ortho;
160 ortho.Init(fgGetAirportPos("KEMT"), 205.0); // Guess of rwy19 heading
161 //Point3D ip = ortho.ConvertFromLocal(Point3D(6000, 1000, 1000)); // 90 deg entry
162 //Point3D ip = ortho.ConvertFromLocal(Point3D(-7000, 3000, 1000)); // 45 deg entry
163 Point3D ip = ortho.ConvertFromLocal(Point3D(1000, -7000, 1000)); // straight-in
164 ATC->AIRegisterAirport("KEMT");
165 FGAIGAVFRTraffic* p = new FGAIGAVFRTraffic();
166 p->SetModel(_defaultModel);
167 p->Init(ip, "KEMT", GenerateShortForm(GenerateUniqueCallsign()));
168 ai_list.push_back(p);
169 traffic[ident].push_back(p);
170 activated["KEMT"] = 1;
174 void FGAIMgr::bind() {
177 void FGAIMgr::unbind() {
180 void FGAIMgr::update(double dt) {
183 SG_LOG(SG_ATC, SG_WARN, "Warning - AIMgr::update(...) called before AIMgr::init()");
186 //cout << activated.size() << '\n';
188 Point3D userPos = Point3D(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue());
190 // TODO - make these class variables!!
194 // Don't update any planes for first 50 runs through - this avoids some possible initialisation anomalies
195 // Might not need it now we have fade-in though?
204 } else if(j == 200) {
205 // Go through the list of activated airports and remove those out of range
206 //cout << "The following airports have been activated by the AI system:\n";
207 ai_activated_map_iterator apt_itr = activated.begin();
208 while(apt_itr != activated.end()) {
209 //cout << "FIRST IS " << (*apt_itr).first << '\n';
210 if(dclGetHorizontalSeparation(userPos, fgGetAirportPos((*apt_itr).first)) > (35.0 * 1600.0)) {
211 // Then get rid of it and make sure the iterator is left pointing to the next one!
212 string s = (*apt_itr).first;
213 if(traffic.find(s) != traffic.end()) {
214 //cout << "s = " << s << ", traffic[s].size() = " << traffic[s].size() << '\n';
215 if(!traffic[s].empty()) {
218 //cout << "Erasing " << (*apt_itr).first << " and traffic" << '\n';
219 activated.erase(apt_itr);
220 apt_itr = activated.upper_bound(s);
224 //cout << "Erasing " << (*apt_itr).first << ' ' << (*apt_itr).second << '\n';
225 activated.erase(apt_itr);
226 apt_itr = activated.upper_bound(s);
232 } else if(j == 180) {
233 // Go through the list of activated airports and do the random airplane generation
234 ai_traffic_map_iterator it = traffic.begin();
235 while(it != traffic.end()) {
236 string s = (*it).first;
237 //cout << "s = " << s << " size = " << (*it).second.size() << '\n';
238 // Only generate extra traffic if within a certain distance of the user,
239 // TODO - maybe take users's tuned freq into account as well.
240 double d = dclGetHorizontalSeparation(userPos, fgGetAirportPos(s));
241 if(d < (15.0 * 1600.0)) {
244 //cout << "Size of list is " << (*it).second.size() << " at " << s << '\n';
245 if((*it).second.size()) {
246 FGAIEntity* e = *((*it).second.rbegin()); // Get the last airplane currently scheduled to arrive at this airport.
247 cd = dclGetHorizontalSeparation(e->GetPos(), fgGetAirportPos(s));
248 if(cd < (d < 5000 ? 10000 : d + 5000)) {
256 //cout << "Generating extra traffic at airport " << s << ", at least " << cd << " meters out\n";
257 //GenerateSimpleAirportTraffic(s, cd);
258 GenerateSimpleAirportTraffic(s, cd + 3000.0); // The random seems a bit wierd - traffic could get far too bunched without the +3000.
259 // TODO - make the anti-random constant variable depending on the ai-traffic level.
268 //cout << "Size of AI list is " << ai_list.size() << '\n';
270 // TODO - need to add a check of if any activated airports have gone out of range
272 string rs; // plane to be removed, if one.
273 if(removalList.size()) {
274 rs = *(removalList.begin());
275 removalList.pop_front();
280 // Traverse the list of active planes and run all their update methods
281 // TODO - spread the load - not all planes should need updating every frame.
282 // Note that this will require dt to be calculated for each plane though
283 // since they rely on it to calculate distance travelled.
284 ai_list_itr = ai_list.begin();
285 while(ai_list_itr != ai_list.end()) {
286 FGAIEntity *e = *ai_list_itr;
287 if(rs.size() && e->GetCallsign() == rs) {
288 //cout << "Removing " << rs << " from ai_list\n";
289 ai_list_itr = ai_list.erase(ai_list_itr);
291 // This is a hack - we should deref this plane from the airport count!
298 //cout << "Size of AI list is " << ai_list.size() << '\n';
301 void FGAIMgr::ScheduleRemoval(const string& s) {
302 //cout << "Scheduling removal of plane " << s << " from AIMgr\n";
303 removalList.push_back(s);
306 // Activate AI traffic at an airport
307 void FGAIMgr::ActivateAirport(const string& ident) {
308 ATC->AIRegisterAirport(ident);
309 // TODO - need to start the traffic more randomly
310 FGAILocalTraffic* local_traffic = new FGAILocalTraffic;
311 local_traffic->SetModel(_defaultModel.get()); // currently hardwired to cessna.
312 //local_traffic->Init(ident, IN_PATTERN, TAKEOFF_ROLL);
313 local_traffic->Init(GenerateShortForm(GenerateUniqueCallsign()), ident);
314 local_traffic->FlyCircuits(1, true); // Fly 2 circuits with touch & go in between
315 ai_list.push_back(local_traffic);
316 traffic[ident].push_back(local_traffic);
317 //cout << "******** ACTIVATING AIRPORT, ident = " << ident << '\n';
318 activated[ident] = 1;
321 // Hack - Generate AI traffic at an airport with no facilities file
322 void FGAIMgr::GenerateSimpleAirportTraffic(const string& ident, double min_dist) {
323 // Ugly hack - don't let VFR Cessnas operate at a hardwired list of major airports
324 // This will go eventually once airport .xml files specify the traffic profile
325 if(ident == "KSFO" || ident == "KDFW" || ident == "EGLL" || ident == "KORD" || ident == "KJFK"
326 || ident == "KMSP" || ident == "KLAX" || ident == "KBOS" || ident == "KEDW"
327 || ident == "KSEA" || ident == "EHAM") {
332 // TODO - check for military airports - this should be in the current data.
333 // UGGH - there's no point at the moment - everything is labelled civil in basic.dat!
334 FGAirport a = fgFindAirportID(ident, &a);
336 cout << "CODE IS " << a.code << '\n';
338 // UG - can't find the airport!
343 Point3D aptpos = fgGetAirportPos(ident); // TODO - check for elev of -9999
344 //cout << "ident = " << ident << ", elev = " << aptpos.elev() << '\n';
346 // Operate from airports at 3000ft and below only to avoid the default cloud layers and since we don't degrade AI performance with altitude.
347 if(aptpos.elev() > 3000) {
348 //cout << "High alt airports not yet supported - returning\n";
352 // Rough hack for plane type - make 70% of the planes cessnas, the rest pipers.
355 // Get the time and only operate VFR in the (approximate) daytime.
356 struct tm *t = globals->get_time_params()->getGmt();
357 int loc_time = t->tm_hour + int(aptpos.lon() / (360.0 / 24.0));
360 while (loc_time >= 24)
363 //cout << "loc_time = " << loc_time << '\n';
364 if(loc_time < 7 || loc_time > 19) return;
366 // Check that the visibility is OK for IFR operation.
368 FGEnvironment stationweather =
369 ((FGEnvironmentMgr *)globals->get_subsystem("environment"))
370 ->getEnvironment(aptpos.lat(), aptpos.lon(), aptpos.elev()); // TODO - check whether this should take ft or m for elev.
371 visibility = stationweather.get_visibility_m();
372 // Technically we can do VFR down to 1 mile (1600m) but that's pretty murky!
373 //cout << "vis = " << visibility << '\n';
374 if(visibility < 3000) return;
376 ATC->AIRegisterAirport(ident);
378 // Next - get the distance from user to the airport.
379 Point3D userpos = Point3D(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue());
380 double d = dclGetHorizontalSeparation(userpos, aptpos); // in meters
382 int lev = fgGetInt("/sim/ai-traffic/level");
387 if(visibility < 6000) lev = 1;
388 //cout << "level = " << lev << '\n';
390 // Next - generate any local / circuit traffic
393 // --------------------------- THIS BLOCK IS JUST FOR TESTING - COMMENT OUT BEFORE RELEASE ---------------
394 // Finally - generate VFR approaching traffic
396 if(ident == "KPOC") {
398 double avd = 3000.0; // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day!
399 //while(ad < (d < 10000 ? 12000 : d + 2000)) {
400 for(int i=0; i<8; ++i) {
401 double dd = sg_random() * avd;
402 // put a minimum spacing in for now since I don't think tower will cope otherwise!
403 if(dd < 1500) dd = 1500;
406 double dir = int(sg_random() * 36);
410 if(sg_random() < 0.3) cessna = false;
412 string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-"));
413 FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic();
414 t->SetModel(cessna ? _defaultModel : _piperModel);
415 //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n";
416 Point3D tpos = dclUpdatePosition(aptpos, dir, 6.0, ad);
417 if(tpos.elev() > (aptpos.elev() + 3000.0)) tpos.setelev(aptpos.elev() + 3000.0);
418 t->Init(tpos, ident, s);
419 ai_list.push_back(t);
422 activated[ident] = 1;
424 //---------------------------------------------------------------------------------------------------
427 double ad; // Minimum distance out of first arriving plane in meters.
428 double mind; // Minimum spacing of traffic in meters
429 double avd; // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day!
430 // Finally - generate VFR approaching traffic
437 } else if(lev == 2) {
442 ad = 9000.0; // Start the first aircraft at least 9K out for now.
447 // Check if there is already arriving traffic at this airport
448 cout << "BING A " << ident << '\n';
449 if(traffic.find(ident) != traffic.end()) {
450 cout << "BING B " << ident << '\n';
451 ai_list_type lst = traffic[ident];
452 cout << "BING C " << ident << '\n';
454 cout << "BING D " << ident << '\n';
455 double cd = dclGetHorizontalSeparation(aptpos, (*lst.rbegin())->GetPos());
456 cout << "ident = " << ident << ", cd = " << cd << '\n';
461 if(min_dist != 0) ad = min_dist;
462 //cout << "ident = " << ident << ", ad = " << ad << '\n';
463 while(ad < (d < 5000 ? 15000 : d + 10000)) {
464 double dd = mind + (sg_random() * (avd - mind));
466 double dir = int(sg_random() * 36);
470 if(sg_random() < 0.3) cessna = false;
472 string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-"));
473 FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic();
474 t->SetModel(cessna ? _defaultModel.get() : (_havePiperModel ? _piperModel.get() : _defaultModel.get()));
475 //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n";
476 Point3D tpos = dclUpdatePosition(aptpos, dir, 6.0, ad);
477 if(tpos.elev() > (aptpos.elev() + 3000.0)) tpos.setelev(aptpos.elev() + 3000.0); // FEET yuk :-(
478 t->Init(tpos, ident, s);
479 ai_list.push_back(t);
480 traffic[ident].push_back(t);
486 // Generate a VFR arrival at airport apt, at least distance d (meters) out.
487 void FGAIMgr::GenerateVFRArrival(const string& apt, double d) {
491 // Search for valid airports in the vicinity of the user and activate them if necessary
492 void FGAIMgr::SearchByPos(double range) {
493 //cout << "In SearchByPos(...)" << endl;
495 // get bucket number for plane position
496 lon = lon_node->getDoubleValue();
497 lat = lat_node->getDoubleValue();
498 elev = elev_node->getDoubleValue() * SG_FEET_TO_METER;
499 SGBucket buck(lon, lat);
501 // get neigboring buckets
502 int bx = (int)( range*SG_NM_TO_METER / buck.get_width_m() / 2);
503 //cout << "bx = " << bx << endl;
504 int by = (int)( range*SG_NM_TO_METER / buck.get_height_m() / 2 );
505 //cout << "by = " << by << endl;
507 // Search for airports with facitities files --------------------------
508 // loop over bucket range
509 for ( int i=-bx; i<=bx; i++) {
510 //cout << "i loop\n";
511 for ( int j=-by; j<=by; j++) {
512 //cout << "j loop\n";
513 buck = sgBucketOffset(lon, lat, i, j);
514 long int bucket = buck.gen_index();
515 //cout << "bucket is " << bucket << endl;
516 if(facilities.find(bucket) != facilities.end()) {
517 ID_list_type* apts = facilities[bucket];
518 ID_list_iterator current = apts->begin();
519 ID_list_iterator last = apts->end();
521 //cout << "Size of apts is " << apts->size() << endl;
523 //double rlon = lon * SGD_DEGREES_TO_RADIANS;
524 //double rlat = lat * SGD_DEGREES_TO_RADIANS;
525 //Point3D aircraft = sgGeodToCart( Point3D(rlon, rlat, elev) );
527 for(; current != last; ++current) {
528 //cout << "Found " << *current << endl;;
529 if(activated.find(*current) == activated.end()) {
530 //cout << "Activating " << *current << endl;
532 //if(dclFindAirportID(*current, &a)) {
533 // // We can do something here based on distance from the user if we wish.
535 //string s = *current;
536 //cout << "s = " << s << '\n';
537 ActivateAirport(*current);
538 //ActivateSimpleAirport(*current); // TODO - put this back to ActivateAirport when that code is done.
539 //cout << "Activation done" << endl;
541 //cout << *current << " already activated" << endl;
547 //-------------------------------------------------------------
549 // Search for any towered airports in the vicinity ------------
550 comm_list_type towered;
551 comm_list_iterator twd_itr;
553 int num_twd = current_commlist->FindByPos(lon, lat, elev, range, &towered, TOWER);
555 double closest = 1000000;
557 for(twd_itr = towered.begin(); twd_itr != towered.end(); twd_itr++) {
558 // Only activate the closest airport not already activated each time.
559 if(activated.find(twd_itr->ident) == activated.end()) {
560 double sep = dclGetHorizontalSeparation(Point3D(lon, lat, elev), fgGetAirportPos(twd_itr->ident));
569 // TODO - find out why empty strings come through here when all in-range airports done.
570 GenerateSimpleAirportTraffic(s);
571 //cout << "**************ACTIVATING SIMPLE AIRPORT, ident = " << s << '\n';
577 string FGAIMgr::GenerateCallsign() {
578 // For now we'll just generate US callsigns until we can regionally identify airports.
580 // Add 3 to 5 numbers and make up to 5 with letters.
582 double d = sg_random();
585 //cout << "First n, n = " << n << '\n';
587 //cout << "j = " << j << '\n';
588 for(int i=0; i<j; ++i) {
589 int n = int(sg_random() * 10);
591 s += (char)('0' + n);
593 for(int i=j; i<5; ++i) {
594 int n = int(sg_random() * 26);
596 //cout << "Alpha, n = " << n << '\n';
597 s += (char)('A' + n);
599 //cout << "s = " << s << '\n';
603 string FGAIMgr::GenerateUniqueCallsign() {
605 string s = GenerateCallsign();
606 if(!ai_callsigns_used[s]) {
607 ai_callsigns_used[s] = 1;
613 // This will be moved somewhere else eventually!!!!
614 string FGAIMgr::GenerateShortForm(const string& callsign, const string& plane_str, bool local) {
615 //cout << callsign << '\n';
617 if(local) s = "Trainer-";
619 for(int i=3; i>0; --i) {
620 char c = callsign[callsign.size() - i];
624 if(isalpha(c)) s += GetPhoneticIdent(c);
625 else s += ConvertNumToSpokenDigits(tmp);