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