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