]> git.mxchange.org Git - flightgear.git/blob - src/ATC/AIMgr.cxx
897f197030227ac12a9cbca932127d9efe424734
[flightgear.git] / src / ATC / AIMgr.cxx
1 // AIMgr.cxx - implementation of FGAIMgr 
2 // - a global management class for FlightGear generated AI traffic
3 //
4 // Written by David Luff, started March 2002.
5 //
6 // Copyright (C) 2002  David C Luff - david.luff@nottingham.ac.uk
7 //
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.
12 //
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.
17 //
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., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22 #include <simgear/misc/sg_path.hxx>
23
24 #include <Main/fg_props.hxx>
25 #include <Main/globals.hxx>
26 #include <simgear/math/sg_random.h>
27
28 #include <list>
29
30 #ifdef _MSC_VER
31 #  include <io.h>
32 #else
33 #  include <sys/types.h>        // for directory reading
34 #  include <dirent.h>           // for directory reading
35 #endif
36
37 #include <Environment/environment_mgr.hxx>
38 #include <Environment/environment.hxx>
39
40 #include "AIMgr.hxx"
41 #include "AILocalTraffic.hxx"
42 #include "AIGAVFRTraffic.hxx"
43 #include "ATCutils.hxx"
44 #include "commlist.hxx"
45
46 SG_USING_STD(list);
47 SG_USING_STD(cout);
48
49 FGAIMgr::FGAIMgr() {
50         ATC = globals->get_ATC_mgr();
51         initDone = false;
52         ai_callsigns_used["CFGFS"] = 1; // so we don't inadvertently use this
53         // TODO - use the proper user callsign when it becomes user settable.
54         removalList.clear();
55         activated.clear();
56 }
57
58 FGAIMgr::~FGAIMgr() {
59 }
60
61 void FGAIMgr::init() {
62         //cout << "AIMgr::init called..." << endl;
63         
64         // Pointers to user's position
65         lon_node = fgGetNode("/position/longitude-deg", true);
66         lat_node = fgGetNode("/position/latitude-deg", true);
67         elev_node = fgGetNode("/position/altitude-ft", true);
68
69         lon = lon_node->getDoubleValue();
70         lat = lat_node->getDoubleValue();
71         elev = elev_node->getDoubleValue();
72         
73         // Load up models at the start to avoid pausing later
74         // Hack alert - Hardwired paths!!
75         string planepath = "Aircraft/c172/Models/c172-dpm.ac";
76         _defaultModel = sgLoad3DModel( globals->get_fg_root(),
77                                           planepath.c_str(),
78                                           globals->get_props(),
79                                           globals->get_sim_time_sec() );
80                                                                           
81         planepath = "Aircraft/pa28-161/Models/pa28-161.ac";
82         _piperModel = sgLoad3DModel( globals->get_fg_root(),
83                                           planepath.c_str(),
84                                           globals->get_props(),
85                                           globals->get_sim_time_sec() );
86                                                                           
87         // go through the $FG_ROOT/ATC directory and find all *.taxi files
88         SGPath path(globals->get_fg_root());
89         path.append("ATC/");
90         string dir = path.dir();
91         string ext;
92         string file, f_ident;
93         int pos;
94         
95         // WARNING - I (DCL) haven't tested this on MSVC - this is simply cribbed from TerraGear
96 #ifdef _MSC_VER 
97         long hfile;
98         struct _finddata_t de;
99         string path_str;
100         
101         path_str = dir + "\\*.*";
102         
103         if ( ( hfile = _findfirst( path.c_str(), &de ) ) == -1 ) {
104                 SG_LOG(SG_ATC, SG_WARN, "cannot open directory " << dir);
105         } else {                
106                 // load all .taxi files
107                 do {
108                         file = de.name;
109                         pos = file.find(".");
110                         ext = file.substr(pos + 1);
111                         if(ext == "taxi") {
112                                 f_ident = file.substr(0, pos);
113                                 FGAirport a;
114                                 if(dclFindAirportID(f_ident, &a)) {
115                                         SGBucket sgb(a.longitude, a.latitude);
116                                         int idx = sgb.gen_index();
117                                         if(facilities.find(idx) != facilities.end()) {
118                                                 facilities[idx]->push_back(f_ident);
119                                         } else {
120                                                 ID_list_type* apts = new ID_list_type;
121                                                 apts->push_back(f_ident);
122                                                 facilities[idx] = apts;
123                                         }
124                                         SG_LOG(SG_ATC, SG_BULK, "Mapping " << f_ident << " to bucket " << idx); 
125                                 }
126                         }
127                 } while ( _findnext( hfile, &de ) == 0 );
128         }
129 #else
130
131     DIR *d;
132     struct dirent *de;
133
134     if ( (d = opendir( dir.c_str() )) == NULL ) {
135                 SG_LOG(SG_ATC, SG_WARN, "cannot open directory " << dir);
136         } else {
137                 // load all .taxi files
138                 while ( (de = readdir(d)) != NULL ) {
139                         file = de->d_name;
140                         pos = file.find(".");
141                         ext = file.substr(pos + 1);
142                         if(ext == "taxi") {
143                                 f_ident = file.substr(0, pos);
144                                 FGAirport a;
145                                 if(dclFindAirportID(f_ident, &a)) {
146                                         SGBucket sgb(a.longitude, a.latitude);
147                                         int idx = sgb.gen_index();
148                                         if(facilities.find(idx) != facilities.end()) {
149                                                 facilities[idx]->push_back(f_ident);
150                                         } else {
151                                                 ID_list_type* apts = new ID_list_type;
152                                                 apts->push_back(f_ident);
153                                                 facilities[idx] = apts;
154                                         }
155                                         SG_LOG(SG_ATC, SG_BULK, "Mapping " << f_ident << " to bucket " << idx);
156                                 }
157                         }
158                 }               
159                 closedir(d);
160         }
161 #endif
162         
163         // See if are in range at startup and activate if necessary
164         SearchByPos(15.0);
165         
166         initDone = true;
167         
168         //cout << "AIMgr::init done..." << endl;
169         
170         /*
171         // TESTING
172         FGATCAlignedProjection ortho;
173         ortho.Init(dclGetAirportPos("KEMT"), 205.0);    // Guess of rwy19 heading
174         //Point3D ip = ortho.ConvertFromLocal(Point3D(6000, 1000, 1000));       // 90 deg entry
175         //Point3D ip = ortho.ConvertFromLocal(Point3D(-7000, 3000, 1000));      // 45 deg entry
176         Point3D ip = ortho.ConvertFromLocal(Point3D(1000, -7000, 1000));        // straight-in
177         ATC->AIRegisterAirport("KEMT");
178         FGAIGAVFRTraffic* p = new FGAIGAVFRTraffic();
179         p->SetModel(_defaultModel);
180         p->Init(ip, "KEMT", GenerateShortForm(GenerateUniqueCallsign()));
181         ai_list.push_back(p);
182         traffic[ident].push_back(p);
183         activated["KEMT"] = 1;
184         */      
185 }
186
187 void FGAIMgr::bind() {
188 }
189
190 void FGAIMgr::unbind() {
191 }
192
193 void FGAIMgr::update(double dt) {
194         if(!initDone) {
195                 init();
196                 SG_LOG(SG_ATC, SG_WARN, "Warning - AIMgr::update(...) called before AIMgr::init()");
197         }
198         
199         //cout << activated.size() << '\n';
200         
201         Point3D userPos = Point3D(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue());
202         
203         // TODO - make these class variables!!
204         static int i = 0;
205         static int j = 0;
206
207         // Don't update any planes for first 50 runs through - this avoids some possible initialisation anomalies
208         // Might not need it now we have fade-in though?
209         if(i < 50) {
210                 ++i;
211                 return;
212         }
213         
214         if(j == 215) {
215                 SearchByPos(25.0);
216                 j = 0;
217         } else if(j == 200) {
218                 // Go through the list of activated airports and remove those out of range
219                 //cout << "The following airports have been activated by the AI system:\n";
220                 ai_activated_map_iterator apt_itr = activated.begin();
221                 while(apt_itr != activated.end()) {
222                         //cout << "FIRST IS " << (*apt_itr).first << '\n';
223                         if(dclGetHorizontalSeparation(userPos, dclGetAirportPos((*apt_itr).first)) > (35.0 * 1600.0)) {
224                                 // Then get rid of it and make sure the iterator is left pointing to the next one!
225                                 string s = (*apt_itr).first;
226                                 if(traffic.find(s) != traffic.end()) {
227                                         //cout << "s = " << s << ", traffic[s].size() = " << traffic[s].size() << '\n';
228                                         if(traffic[s].size()) {
229                                                 apt_itr++;
230                                         } else {
231                                                 //cout << "Erasing " << (*apt_itr).first << " and traffic" << '\n';
232                                                 activated.erase(apt_itr++);
233                                                 traffic.erase(s);
234                                         }
235                                 } else {
236                                                 //cout << "Erasing " << (*apt_itr).first << ' ' << (*apt_itr).second << '\n';
237                                                 activated.erase(apt_itr++);
238                                 }
239                         } else {
240                                 apt_itr++;
241                         }
242                 }
243         } else if(j == 180) {
244                 // Go through the list of activated airports and do the random airplane generation
245                 ai_traffic_map_iterator it = traffic.begin();
246                 while(it != traffic.end()) {
247                         string s = (*it).first;
248                         //cout << "s = " << s << " size = " << (*it).second.size() << '\n';
249                         // Only generate extra traffic if within a certain distance of the user,
250                         // TODO - maybe take users's tuned freq into account as well.
251                         double d = dclGetHorizontalSeparation(userPos, dclGetAirportPos(s)); 
252                         if(d < (15.0 * 1600.0)) {
253                                 double cd = 0.0;
254                                 bool gen = false;
255                                 //cout << "Size of list is " << (*it).second.size() << " at " << s << '\n';
256                                 if((*it).second.size()) {
257                                         FGAIEntity* e = *((*it).second.rbegin());       // Get the last airplane currently scheduled to arrive at this airport.
258                                         cd = dclGetHorizontalSeparation(e->GetPos(), dclGetAirportPos(s));
259                                         if(cd < (d < 5000 ? 10000 : d + 5000)) {
260                                                 gen = true;
261                                         }
262                                 } else {
263                                         gen = true;
264                                         cd = 0.0;
265                                 }
266                                 if(gen) {
267                                         //cout << "Generating extra traffic at airport " << s << ", at least " << cd << " meters out\n";
268                                         //GenerateSimpleAirportTraffic(s, cd);
269                                         GenerateSimpleAirportTraffic(s, cd + 3000.0);   // The random seems a bit wierd - traffic could get far too bunched without the +3000.
270                                         // TODO - make the anti-random constant variable depending on the ai-traffic level.
271                                 }
272                         }
273                         ++it;
274                 }
275         }
276         
277         ++j;
278         
279         //cout << "Size of AI list is " << ai_list.size() << '\n';
280         
281         // TODO - need to add a check of if any activated airports have gone out of range
282         
283         string rs;      // plane to be removed, if one.
284         if(removalList.size()) {
285                 rs = *(removalList.begin());
286                 removalList.pop_front();
287         } else {
288                 rs = "";
289         }
290         
291         // Traverse the list of active planes and run all their update methods
292         // TODO - spread the load - not all planes should need updating every frame.
293         // Note that this will require dt to be calculated for each plane though
294         // since they rely on it to calculate distance travelled.
295         ai_list_itr = ai_list.begin();
296         while(ai_list_itr != ai_list.end()) {
297                 FGAIEntity *e = *ai_list_itr;
298                 if(rs.size() && e->GetCallsign() == rs) {
299                         //cout << "Removing " << rs << " from ai_list\n";
300                         ai_list_itr = ai_list.erase(ai_list_itr);
301                         delete e;
302                         // This is a hack - we should deref this plane from the airport count!
303                 } else {
304                         e->Update(dt);
305                         ++ai_list_itr;
306                 }
307         }
308
309         //cout << "Size of AI list is " << ai_list.size() << '\n';
310 }
311
312 void FGAIMgr::ScheduleRemoval(string s) {
313         //cout << "Scheduling removal of plane " << s << " from AIMgr\n";
314         removalList.push_back(s);
315 }
316
317 // Activate AI traffic at an airport
318 void FGAIMgr::ActivateAirport(string ident) {
319         ATC->AIRegisterAirport(ident);
320         // TODO - need to start the traffic more randomly
321         FGAILocalTraffic* local_traffic = new FGAILocalTraffic;
322         local_traffic->SetModel(_defaultModel); // currently hardwired to cessna.
323         //local_traffic->Init(ident, IN_PATTERN, TAKEOFF_ROLL);
324         local_traffic->Init(GenerateShortForm(GenerateUniqueCallsign()), ident);
325         local_traffic->FlyCircuits(1, true);    // Fly 2 circuits with touch & go in between
326         ai_list.push_back(local_traffic);
327         traffic[ident].push_back(local_traffic);
328         //cout << "******** ACTIVATING AIRPORT, ident = " << ident << '\n';
329         activated[ident] = 1;
330 }
331
332 // Hack - Generate AI traffic at an airport with no facilities file
333 void FGAIMgr::GenerateSimpleAirportTraffic(string ident, double min_dist) {
334         // Ugly hack - don't let VFR Cessnas operate at a hardwired list of major airports
335         // This will go eventually once airport .xml files specify the traffic profile
336         if(ident == "KSFO" || ident == "KDFW" || ident == "EGLL" || ident == "KORD" || ident == "KJFK" 
337                            || ident == "KMSP" || ident == "KLAX" || ident == "KBOS" || ident == "KEDW"
338                                            || ident == "KSEA" || ident == "EHAM") {
339                 return;
340         }
341         
342         /*
343         // TODO - check for military airports - this should be in the current data.
344         // UGGH - there's no point at the moment - everything is labelled civil in basic.dat!
345         FGAirport a;
346         if(dclFindAirportID(ident, &a)) {
347                 cout << "CODE IS " << a.code << '\n';
348         } else {
349                 // UG - can't find the airport!
350                 return;
351         }
352         */
353         
354         Point3D aptpos = dclGetAirportPos(ident);       // TODO - check for elev of -9999
355         //cout << "ident = " << ident << ", elev = " << aptpos.elev() << '\n';
356         
357         // Operate from airports at 3000ft and below only to avoid the default cloud layers and since we don't degrade AI performance with altitude.
358         if(aptpos.elev() > 3000) {
359                 //cout << "High alt airports not yet supported - returning\n";
360                 return;
361         }
362         
363         // Rough hack for plane type - make 70% of the planes cessnas, the rest pipers.
364         bool cessna = true;
365         
366         // Get the time and only operate VFR in the (approximate) daytime.
367         //SGTime *t = globals->get_time_params();
368         string time_str = fgGetString("sim/time/gmt-string");
369         int loc_time = atoi((time_str.substr(0,3)).c_str());
370         //cout << "gmt_time = " << loc_time << '\n';
371         loc_time += (int)((aptpos.lon() / 360.0) * 24.0);
372         while(loc_time < 0) loc_time += 24;
373         while(loc_time > 24) loc_time -= 24;
374         //cout << "loc_time = " << loc_time << '\n';
375         if(loc_time < 7 || loc_time > 19) return;
376         
377         // Check that the visibility is OK for IFR operation.
378         double visibility;
379         FGEnvironment stationweather =
380             ((FGEnvironmentMgr *)globals->get_subsystem("environment"))
381               ->getEnvironment(aptpos.lat(), aptpos.lon(), aptpos.elev());      // TODO - check whether this should take ft or m for elev.
382         visibility = stationweather.get_visibility_m();
383         // Technically we can do VFR down to 1 mile (1600m) but that's pretty murky!
384         //cout << "vis = " << visibility << '\n';
385         if(visibility < 3000) return;
386         
387         ATC->AIRegisterAirport(ident);
388         
389         // Next - get the distance from user to the airport.
390         Point3D userpos = Point3D(lon_node->getDoubleValue(), lat_node->getDoubleValue(), elev_node->getDoubleValue());
391         double d = dclGetHorizontalSeparation(userpos, aptpos); // in meters
392         
393         int lev = fgGetInt("/sim/ai-traffic/level");
394         if(lev < 1 || lev > 3) lev = 2;
395         if(visibility < 6000) lev = 1;
396         //cout << "level = " << lev << '\n';
397         
398         // Next - generate any local / circuit traffic
399
400         /*
401         // --------------------------- THIS BLOCK IS JUST FOR TESTING - COMMENT OUT BEFORE RELEASE ---------------
402         // Finally - generate VFR approaching traffic
403         //if(d > 2000) {
404         if(ident == "KPOC") {
405                 double ad = 2000.0;
406                 double avd = 3000.0;    // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day!
407                 //while(ad < (d < 10000 ? 12000 : d + 2000)) {
408                 for(int i=0; i<8; ++i) {
409                         double dd = sg_random() * avd;
410                         // put a minimum spacing in for now since I don't think tower will cope otherwise!
411                         if(dd < 1500) dd = 1500; 
412                         //ad += dd;
413                         ad += dd;
414                         double dir = int(sg_random() * 36);
415                         if(dir == 36) dir--;
416                         dir *= 10;
417                         //dir = 180;
418                         if(sg_random() < 0.3) cessna = false;
419                         else cessna = true;
420                         string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-"));
421                         FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic();
422                         t->SetModel(cessna ? _defaultModel : _piperModel);
423                         //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n";
424                         Point3D tpos = dclUpdatePosition(aptpos, dir, 6.0, ad);
425                         if(tpos.elev() > (aptpos.elev() + 3000.0)) tpos.setelev(aptpos.elev() + 3000.0);
426                         t->Init(tpos, ident, s);
427                         ai_list.push_back(t);
428                 }
429         }
430         activated[ident] = 1;
431         return;
432         //---------------------------------------------------------------------------------------------------
433         */
434         
435         double ad;   // Minimum distance out of first arriving plane in meters.
436         double mind; // Minimum spacing of traffic in meters
437         double avd;  // average spacing of arriving traffic in meters - relate to airport business and AI density setting one day!
438         // Finally - generate VFR approaching traffic
439         //if(d > 2000) {
440         if(1) {
441                 if(lev == 3) {
442                         ad = 5000.0;
443                         mind = 2000.0;
444                         avd = 6000.0;
445                 } else if(lev == 2) {
446                         ad = 8000.0;
447                         mind = 4000.0;
448                         avd = 10000.0;
449                 } else {
450                         ad = 9000.0;    // Start the first aircraft at least 9K out for now.
451                         mind = 6000.0;
452                         avd = 15000.0;
453                 }
454                 /*
455                 // Check if there is already arriving traffic at this airport
456                 cout << "BING A " << ident << '\n';
457                 if(traffic.find(ident) != traffic.end()) {
458                         cout << "BING B " << ident << '\n';
459                         ai_list_type lst = traffic[ident];
460                         cout << "BING C " << ident << '\n';
461                         if(lst.size()) {
462                                 cout << "BING D " << ident << '\n';
463                                 double cd = dclGetHorizontalSeparation(aptpos, (*lst.rbegin())->GetPos());
464                                 cout << "ident = " << ident << ", cd = " << cd << '\n';
465                                 if(cd > ad) ad = cd;
466                         }
467                 }
468                 */
469                 if(min_dist != 0) ad = min_dist;
470                 //cout << "ident = " << ident << ", ad = " << ad << '\n';
471                 while(ad < (d < 5000 ? 15000 : d + 10000)) {
472                         double dd = mind + (sg_random() * (avd - mind));
473                         ad += dd;
474                         double dir = int(sg_random() * 36);
475                         if(dir == 36) dir--;
476                         dir *= 10;
477                         
478                         if(sg_random() < 0.3) cessna = false;
479                         else cessna = true;
480                         string s = GenerateShortForm(GenerateUniqueCallsign(), (cessna ? "Cessna-" : "Piper-"));
481                         FGAIGAVFRTraffic* t = new FGAIGAVFRTraffic();
482                         t->SetModel(cessna ? _defaultModel : _piperModel);
483                         //cout << "Generating VFR traffic " << s << " inbound to " << ident << " " << ad << " meters out from " << dir << " degrees\n";
484                         Point3D tpos = dclUpdatePosition(aptpos, dir, 6.0, ad);
485                         if(tpos.elev() > (aptpos.elev() + 3000.0)) tpos.setelev(aptpos.elev() + 3000.0);        // FEET yuk :-(
486                         t->Init(tpos, ident, s);
487                         ai_list.push_back(t);
488                         traffic[ident].push_back(t);
489                 }
490         }       
491 }
492
493 /*
494 // Generate a VFR arrival at airport apt, at least distance d (meters) out.
495 void FGAIMgr::GenerateVFRArrival(string apt, double d) {
496 }
497 */
498
499 // Search for valid airports in the vicinity of the user and activate them if necessary
500 void FGAIMgr::SearchByPos(double range) {
501         //cout << "In SearchByPos(...)" << endl;
502         
503         // get bucket number for plane position
504         lon = lon_node->getDoubleValue();
505         lat = lat_node->getDoubleValue();
506         elev = elev_node->getDoubleValue() * SG_FEET_TO_METER;
507         SGBucket buck(lon, lat);
508
509         // get neigboring buckets
510         int bx = (int)( range*SG_NM_TO_METER / buck.get_width_m() / 2);
511         //cout << "bx = " << bx << endl;
512         int by = (int)( range*SG_NM_TO_METER / buck.get_height_m() / 2 );
513         //cout << "by = " << by << endl;
514         
515         // Search for airports with facitities files --------------------------
516         // loop over bucket range 
517         for ( int i=-bx; i<=bx; i++) {
518                 //cout << "i loop\n";
519                 for ( int j=-by; j<=by; j++) {
520                         //cout << "j loop\n";
521                         buck = sgBucketOffset(lon, lat, i, j);
522                         long int bucket = buck.gen_index();
523                         //cout << "bucket is " << bucket << endl;
524                         if(facilities.find(bucket) != facilities.end()) {
525                                 ID_list_type* apts = facilities[bucket];
526                                 ID_list_iterator current = apts->begin();
527                                 ID_list_iterator last = apts->end();
528                                 
529                                 //cout << "Size of apts is " << apts->size() << endl;
530                                 
531                                 //double rlon = lon * SGD_DEGREES_TO_RADIANS;
532                                 //double rlat = lat * SGD_DEGREES_TO_RADIANS;
533                                 //Point3D aircraft = sgGeodToCart( Point3D(rlon, rlat, elev) );
534                                 //Point3D airport;
535                                 for(; current != last; ++current) {
536                                         //cout << "Found " << *current << endl;;
537                                         if(activated.find(*current) == activated.end()) {
538                                                 //cout << "Activating " << *current << endl;
539                                                 //FGAirport a;
540                                                 //if(dclFindAirportID(*current, &a)) {
541                                                         //      // We can do something here based on distance from the user if we wish.
542                                                 //}
543                                                 //string s = *current;
544                                                 //cout << "s = " << s << '\n';
545                                                 ActivateAirport(*current);
546                                                 //ActivateSimpleAirport(*current);      // TODO - put this back to ActivateAirport when that code is done.
547                                                 //cout << "Activation done" << endl;
548                                         } else {
549                                                 //cout << *current << " already activated" << endl;
550                                         }
551                                 }
552                         }
553                 }
554         }
555         //-------------------------------------------------------------
556         
557         // Search for any towered airports in the vicinity ------------
558         comm_list_type towered;
559         comm_list_iterator twd_itr;
560         
561         int num_twd = current_commlist->FindByPos(lon, lat, elev, range, &towered, TOWER);
562         if (num_twd != 0) {
563                 double closest = 1000000;
564                 string s = "";
565                 for(twd_itr = towered.begin(); twd_itr != towered.end(); twd_itr++) {
566                         // Only activate the closest airport not already activated each time.
567                         if(activated.find(twd_itr->ident) == activated.end()) {
568                                 double sep = dclGetHorizontalSeparation(Point3D(lon, lat, elev), dclGetAirportPos(twd_itr->ident));
569                                 if(sep < closest) {
570                                         closest = sep;
571                                         s = twd_itr->ident;
572                                 }
573                                 
574                         }
575                 }
576                 if(s.size()) {
577                         // TODO - find out why empty strings come through here when all in-range airports done.
578                         GenerateSimpleAirportTraffic(s);
579                         //cout << "**************ACTIVATING SIMPLE AIRPORT, ident = " << s << '\n';
580                         activated[s] = 1;
581                 }
582         }
583 }
584
585 string FGAIMgr::GenerateCallsign() {
586         // For now we'll just generate US callsigns until we can regionally identify airports.
587         string s = "N";
588         // Add 3 to 5 numbers and make up to 5 with letters.
589         //sg_srandom_time();
590         double d = sg_random();
591         int n = int(d * 3);
592         if(n == 3) --n;
593         //cout << "First n, n = " << n << '\n';
594         int j = 3 + n;
595         //cout << "j = " << j << '\n';
596         for(int i=0; i<j; ++i) { 
597                 int n = int(sg_random() * 10);
598                 if(n == 10) --n;
599                 s += (char)('0' + n);
600         }
601         for(int i=j; i<5; ++i) {
602                 int n = int(sg_random() * 26);
603                 if(n == 26) --n;
604                 //cout << "Alpha, n = " << n << '\n';
605                 s += (char)('A' + n);
606         }
607         //cout << "s = " << s << '\n';
608         return(s);
609 }
610
611 string FGAIMgr::GenerateUniqueCallsign() {
612         while(1) {
613                 string s = GenerateCallsign();
614                 if(!ai_callsigns_used[s]) {
615                         ai_callsigns_used[s] = 1;
616                         return(s);
617                 }
618         }
619 }
620
621 // This will be moved somewhere else eventually!!!!
622 string FGAIMgr::GenerateShortForm(string callsign, string plane_str, bool local) {
623         //cout << callsign << '\n';
624         string s;
625         if(local) s = "Trainer-";
626         else s = plane_str;
627         for(int i=3; i>0; --i) {
628                 char c = callsign[callsign.size() - i];
629                 //cout << c << '\n';
630                 string tmp = "";
631                 tmp += c;
632                 if(isalpha(c)) s += GetPhoneticIdent(c);
633                 else s += ConvertNumToSpokenDigits(tmp);
634                 if(i > 1) s += '-';
635         }
636         return(s);
637 }