]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/ATCmgr.cxx
Merge branch 'ehofman/atc-sound' into next
[flightgear.git] / src / ATCDCL / ATCmgr.cxx
1 // ATCmgr.cxx - Implementation of FGATCMgr - a global Flightgear ATC manager.
2 //
3 // Written by David Luff, started February 2002.
4 //
5 // Copyright (C) 2002  David C Luff - david.luff@nottingham.ac.uk
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/misc/sg_path.hxx>
26 #include <simgear/debug/logstream.hxx>
27
28 #include <Airports/simple.hxx>
29
30 #include "ATCmgr.hxx"
31 #include "commlist.hxx"
32 #include "ATCDialog.hxx"
33 #include "ATCutils.hxx"
34 #include "transmissionlist.hxx"
35 #include "ground.hxx"
36
37
38 /*
39 // periodic radio station search wrapper
40 static void fgATCSearch( void ) {
41     globals->get_ATC_mgr()->Search();
42 }
43 */ //This wouldn't compile - including Time/event.hxx breaks it :-(
44    // Is this still true?? -EMH-
45
46 AirportATC::AirportATC() :
47     atis_freq(0.0),
48     atis_active(false),
49     tower_freq(0.0),
50     tower_active(false),
51     ground_freq(0.0),
52     ground_active(false),
53     set_by_AI(false),
54     numAI(0)
55     //airport_atc_map.clear();
56 {
57 }
58
59 FGATCMgr::FGATCMgr() :
60     initDone(false),
61     atc_list(new atc_list_type),
62 #ifdef ENABLE_AUDIO_SUPPORT
63     voiceOK(false),
64     voice(true),
65 #else
66     voice(false),
67 #endif
68     last_in_range(false)
69 {
70 }
71
72 FGATCMgr::~FGATCMgr() {
73     delete v1;
74 }
75
76 void FGATCMgr::bind() {
77 }
78
79 void FGATCMgr::unbind() {
80 }
81
82 void FGATCMgr::init() {
83     //cout << "ATCMgr::init called..." << endl;
84     
85     lon_node = fgGetNode("/position/longitude-deg", true);
86     lat_node = fgGetNode("/position/latitude-deg", true);
87     elev_node = fgGetNode("/position/altitude-ft", true);
88     atc_list_itr = atc_list->begin();
89     
90     // Search for connected ATC stations once per 0.8 seconds or so
91     // globals->get_event_mgr()->add( "fgATCSearch()", fgATCSearch,
92         //                                 FGEvent::FG_EVENT_READY, 800);
93         //  
94     // For some reason the above doesn't compile - including Time/event.hxx stops compilation.
95         // Is this still true after the reorganization of the event managar??
96         // -EMH-
97     
98     // Initialise the ATC Dialogs
99     //cout << "Initing Transmissions..." << endl;
100     SG_LOG(SG_ATC, SG_INFO, "  ATC Transmissions");
101     current_transmissionlist = new FGTransmissionList;
102     SGPath p_transmission( globals->get_fg_root() );
103     p_transmission.append( "ATC/default.transmissions" );
104     current_transmissionlist->init( p_transmission );
105     //cout << "Done Transmissions" << endl;
106
107     SG_LOG(SG_ATC, SG_INFO, "  ATC Dialog System");
108     current_atcdialog = new FGATCDialog;
109     current_atcdialog->Init();
110
111     initDone = true;
112     //cout << "ATCmgr::init done!" << endl;
113 }
114
115 void FGATCMgr::update(double dt) {
116     if(!initDone) {
117         init();
118         SG_LOG(SG_ATC, SG_WARN, "Warning - ATCMgr::update(...) called before ATCMgr::init()");
119     }
120     
121     current_atcdialog->Update(dt);
122     
123     //cout << "Entering update..." << endl;
124     //Traverse the list of active stations.
125     //Only update one class per update step to avoid the whole ATC system having to calculate between frames.
126     //Eventually we should only update every so many steps.
127     //cout << "In FGATCMgr::update - atc_list.size = " << atc_list->size() << endl;
128     if(atc_list->size()) {
129         if(atc_list_itr == atc_list->end()) {
130             atc_list_itr = atc_list->begin();
131         }
132         //cout << "Updating " << (*atc_list_itr)->get_ident() << ' ' << (*atc_list_itr)->GetType() << '\n';
133         //cout << "Freq = " << (*atc_list_itr)->get_freq() << '\n';
134         (*atc_list_itr).second->Update(dt * atc_list->size());
135         //cout << "Done ATC update..." << endl;
136         ++atc_list_itr;
137     }
138     
139 #ifdef ATC_TEST
140     cout << "ATC_LIST: " << atc_list->size() << ' ';
141     for(atc_list_iterator it = atc_list->begin(); it != atc_list->end(); it++) {
142         cout << (*it)->get_ident() << ' ';
143     }
144     cout << '\n';
145 #endif
146     
147     // Search the tuned frequencies every now and then - this should be done with the event scheduler
148     static int i = 0;   // Very ugly - but there should only ever be one instance of FGATCMgr.
149     /*** Area search is defeated.  Why?
150     if(i == 7) {
151         //cout << "About to AreaSearch()" << endl;
152         AreaSearch();
153     }
154     ***/
155     if(i == 15) {
156         //cout << "About to search navcomm1" << endl;
157         FreqSearch("comm", 0);
158         FreqSearch("nav", 0);
159     }
160     if(i == 30) {
161         //cout << "About to search navcomm2" << endl;
162         FreqSearch("comm", 1);
163         FreqSearch("nav", 1);
164         i = 0;
165     }
166     ++i;
167     
168     //cout << "comm1 type = " << comm_type[0] << '\n';
169     //cout << "Leaving update..." << endl;
170 }
171
172
173 // Returns frequency in KHz - should I alter this to return in MHz?
174 unsigned short int FGATCMgr::GetFrequency(const string& ident, const atc_type& tp) {
175     ATCData test;
176     bool ok = current_commlist->FindByCode(ident, test, tp);
177     return(ok ? test.freq : 0);
178 }   
179
180
181 // Register the fact that the AI system wants to activate an airport
182 // Might need more sophistication in this in the future - eg registration by aircraft call-sign.
183 bool FGATCMgr::AIRegisterAirport(const string& ident) {
184     SG_LOG(SG_ATC, SG_BULK, "AI registered airport " << ident << " with the ATC system");
185     //cout << "AI registered airport " << ident << " with the ATC system" << '\n';
186     if(airport_atc_map.find(ident) != airport_atc_map.end()) {
187         airport_atc_map[ident]->set_by_AI = true;
188         airport_atc_map[ident]->numAI++;
189         return(true);
190     } else {
191         const FGAirport *ap = fgFindAirportID(ident);
192         if (ap) {
193             //cout << "ident = " << ident << '\n';
194             AirportATC *a = new AirportATC;
195             // I'm not entirely sure that this AirportATC structure business is actually needed - it just duplicates what we can find out anyway!
196             a->geod = ap->geod();
197             a->atis_freq = GetFrequency(ident, ATIS)
198                     || GetFrequency(ident, AWOS);
199             //cout << "ATIS freq = " << a->atis_freq << '\n';
200             a->atis_active = false;
201             a->tower_freq = GetFrequency(ident, TOWER);
202             //cout << "Tower freq = " << a->tower_freq << '\n';
203             a->tower_active = false;
204             a->ground_freq = GetFrequency(ident, GROUND);
205             //cout << "Ground freq = " << a->ground_freq << '\n';
206             a->ground_active = false;
207             // TODO - some airports will have a tower/ground frequency but be inactive overnight.
208             a->set_by_AI = true;
209             a->numAI = 1;
210             airport_atc_map[ident] = a;
211             return(true);
212         } else {
213             SG_LOG(SG_ATC, SG_ALERT, "ERROR - can't find airport " << ident << " in AIRegisterAirport(...)");
214         }
215     }
216     return(false);
217 }
218
219 // Register the fact that the comm radio is tuned to an airport
220 // Channel is zero based
221 bool FGATCMgr::CommRegisterAirport(const string& ident, int chan, const atc_type& tp) {
222     SG_LOG(SG_ATC, SG_BULK, "Comm channel " << chan << " registered airport " << ident);
223     //cout << "Comm channel " << chan << " registered airport " << ident << ' ' << tp << '\n';
224     if(airport_atc_map.find(ident) != airport_atc_map.end()) {
225         //cout << "IN MAP - flagging set by comm..." << endl;
226 //xx        airport_atc_map[ident]->set_by_comm[chan][tp] = true;
227         if(tp == ATIS || tp == AWOS) {
228             airport_atc_map[ident]->atis_active = true;
229         } else if(tp == TOWER) {
230             airport_atc_map[ident]->tower_active = true;
231         } else if(tp == GROUND) {
232             airport_atc_map[ident]->ground_active = true;
233         } else if(tp == APPROACH) {
234             //a->approach_active = true;
235         }   // TODO - there *must* be a better way to do this!!!
236         return(true);
237     } else {
238         //cout << "NOT IN MAP - creating new..." << endl;
239         const FGAirport *ap = fgFindAirportID(ident);
240         if (ap) {
241             AirportATC *a = new AirportATC;
242             // I'm not entirely sure that this AirportATC structure business is actually needed - it just duplicates what we can find out anyway!
243             a->geod = ap->geod();
244             a->atis_freq = GetFrequency(ident, ATIS)
245                     || GetFrequency(ident, AWOS);
246             a->atis_active = false;
247             a->tower_freq = GetFrequency(ident, TOWER);
248             a->tower_active = false;
249             a->ground_freq = GetFrequency(ident, GROUND);
250             a->ground_active = false;
251             if(tp == ATIS || tp == AWOS) {
252                 a->atis_active = true;
253             } else if(tp == TOWER) {
254                 a->tower_active = true;
255             } else if(tp == GROUND) {
256                 a->ground_active = true;
257             } else if(tp == APPROACH) {
258                 //a->approach_active = true;
259             }   // TODO - there *must* be a better way to do this!!!
260             // TODO - some airports will have a tower/ground frequency but be inactive overnight.
261             a->set_by_AI = false;
262             a->numAI = 0;
263 //xx            a->set_by_comm[chan][tp] = true;
264             airport_atc_map[ident] = a;
265             return(true);
266         }
267     }
268     return(false);
269 }
270
271 typedef map<string,int> MSI;
272
273 void FGATCMgr::ZapOtherService(const string ncunit, const string svc_name){
274   for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) {
275     //cout << "Zapping " << navcomm 
276     //  << "[" << unit << "]"  << "  otherthan: " << svc_name << endl;
277     if (svc->first != svc_name) {
278       MSI &actv = svc->second->active_on;
279       // OK, we have found some OTHER service;
280       // see if it is (was) active on our unit:
281       if (!actv.count(ncunit)) continue;
282       // cout << "Eradicating '" << svc->first << "' from: " << ncunit << endl;
283       actv.erase(ncunit);
284       if (!actv.size()) {
285         //cout << "Eradicating service: '" << svc->first << "'" << endl;
286     svc->second->SetNoDisplay();
287     svc->second->Update(0);     // one last update
288     delete svc->second;
289     atc_list->erase(svc);
290 // ALL pointers into the ATC list are now invalid,
291 // so let's reset them:
292     atc_list_itr = atc_list->begin();
293       }
294       break;        // cannot be duplicates in the active list
295     }
296   }
297 }
298
299
300 // Find in list - return a currently active ATC pointer given ICAO code and type
301 // Return NULL if the given service is not in the list
302 // - *** THE CALLING FUNCTION MUST CHECK FOR THIS ***
303 FGATC* FGATCMgr::FindInList(const string& id, const atc_type& tp) {
304   string ndx = id + decimalNumeral(tp);
305   if (!atc_list->count(ndx)) return 0;
306   return (*atc_list)[ndx];
307 }
308
309 // Returns true if the airport is found in the map
310 bool FGATCMgr::GetAirportATCDetails(const string& icao, AirportATC* a) {
311     if(airport_atc_map.find(icao) != airport_atc_map.end()) {
312         *a = *airport_atc_map[icao];
313         return(true);
314     } else {
315         return(false);
316     }
317 }
318
319
320 // Return a pointer to a given sort of ATC at a given airport and activate if necessary
321 // Returns NULL if service doesn't exist - calling function should check for this.
322 // We really ought to make this private and call it from the CommRegisterAirport / AIRegisterAirport functions
323 // - at the moment all these GetATC... functions exposed are just too complicated.
324 FGATC* FGATCMgr::GetATCPointer(const string& icao, const atc_type& type) {
325     if(airport_atc_map.find(icao) == airport_atc_map.end()) {
326         //cout << "Unable to find " << icao << ' ' << type << " in the airport_atc_map" << endl;
327         return NULL;
328     }
329     //cout << "In GetATCPointer, found " << icao << ' ' << type << endl;
330     AirportATC *a = airport_atc_map[icao];
331     //cout << "a->lon = " << a->lon << '\n';
332     //cout << "a->elev = " << a->elev << '\n';
333     //cout << "a->tower_freq = " << a->tower_freq << '\n';
334     switch(type) {
335     case TOWER:
336         if(a->tower_active) {
337             // Get the pointer from the list
338             return(FindInList(icao, type));
339         } else {
340             ATCData data;
341             if(current_commlist->FindByFreq(a->geod, a->tower_freq, &data, TOWER)) {
342                 FGTower* t = new FGTower;
343                 t->SetData(&data);
344                 (*atc_list)[icao+decimalNumeral(type)] = t;
345                 a->tower_active = true;
346                 airport_atc_map[icao] = a;
347                 //cout << "Initing tower " << icao << " in GetATCPointer()\n";
348                 t->Init();
349                 return(t);
350             } else {
351                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - tower that should exist in FGATCMgr::GetATCPointer for airport " << icao << " not found");
352             }
353         }
354         break;
355     case APPROACH:
356         break;
357     case ATIS: case AWOS:
358         SG_LOG(SG_ATC, SG_ALERT, "ERROR - ATIS station should not be requested from FGATCMgr::GetATCPointer");
359         break;
360     case GROUND:
361         //cout << "IN CASE GROUND" << endl;
362         if(a->ground_active) {
363             // Get the pointer from the list
364             return(FindInList(icao, type));
365         } else {
366             ATCData data;
367             if(current_commlist->FindByFreq(a->geod, a->ground_freq, &data, GROUND)) {
368                 FGGround* g = new FGGround;
369                 g->SetData(&data);
370                 (*atc_list)[icao+decimalNumeral(type)] = g;
371                 a->ground_active = true;
372                 airport_atc_map[icao] = a;
373                 g->Init();
374                 return(g);
375             } else {
376                 SG_LOG(SG_ATC, SG_ALERT, "ERROR - ground control that should exist in FGATCMgr::GetATCPointer for airport " << icao << " not found");
377             }
378         }
379         break;
380         case INVALID:
381         break;
382         case ENROUTE:
383         break;
384         case DEPARTURE:
385         break;
386     }
387     
388     SG_LOG(SG_ATC, SG_ALERT, "ERROR IN FGATCMgr - reached end of GetATCPointer");
389     //cout << "ERROR IN FGATCMgr - reached end of GetATCPointer" << endl;
390     
391     return(NULL);
392 }
393
394 // Return a pointer to an appropriate voice for a given type of ATC
395 // creating the voice if necessary - ie. make sure exactly one copy
396 // of every voice in use exists in memory.
397 //
398 // TODO - in the future this will get more complex and dole out country/airport
399 // specific voices, and possible make sure that the same voice doesn't get used
400 // at different airports in quick succession if a large enough selection are available.
401 FGATCVoice* FGATCMgr::GetVoicePointer(const atc_type& type) {
402     // TODO - implement me better - maintain a list of loaded voices and other voices!!
403     if(voice) {
404         switch(type) {
405         case ATIS: case AWOS:
406 #ifdef ENABLE_AUDIO_SUPPORT
407             // Delayed loading fo all available voices, needed because the
408             // soundmanager might not be initialized (at all) at this point.
409             // For now we'll do one hardwired one
410
411             /* I've loaded the voice even if /sim/sound/pause is true
412              *  since I know no way of forcing load of the voice if the user
413              *  subsequently switches /sim/sound/audible to true.
414              *  (which is the right thing to do -- CLO) :-)
415              */
416             if (!voiceOK && fgGetBool("/sim/sound/working")) {
417                 v1 = new FGATCVoice;
418                 try {
419                     voiceOK = v1->LoadVoice("default");
420                     voice = voiceOK;
421                 } catch ( sg_io_exception & e) {
422                     voiceOK  = false;
423                     SG_LOG(SG_ATC, SG_ALERT, "Unable to load default voice : "
424                                             << e.getFormattedMessage().c_str());
425                     voice = false;
426                     delete v1;
427                     v1 = 0;
428                 }
429             }
430 #endif
431             if(voiceOK) {
432                 return(v1);
433             }
434         case TOWER:
435             return(NULL);
436         case APPROACH:
437             return(NULL);
438         case GROUND:
439             return(NULL);
440         default:
441             return(NULL);
442         }
443         return(NULL);
444     } else {
445         return(NULL);
446     }
447 }
448
449 // Search for ATC stations by frequency
450 void FGATCMgr::FreqSearch(const string navcomm, const int unit) {
451
452
453         string ncunit = navcomm + "[" + decimalNumeral(unit) + "]";
454     string commbase = "/instrumentation/" + ncunit;
455     string commfreq = commbase + "/frequencies/selected-mhz";
456         SGPropertyNode_ptr comm_node = fgGetNode(commfreq.c_str(), false);
457
458     //cout << "FreqSearch: " << ncunit
459     //  << "  node: " << comm_node << endl;
460     if (!comm_node) return; // no such radio unit
461
462     ATCData data;   
463     double freq = comm_node->getDoubleValue();
464     _aircraftPos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
465       lat_node->getDoubleValue(), elev_node->getDoubleValue());
466     
467 // Query the data store and get the closest match if any
468     //cout << "Will FindByFreq: " << lat << " " << lon << " " << elev
469     //      << "  freq: " << freq << endl;
470     if(current_commlist->FindByFreq(_aircraftPos, freq, &data)) {
471       //cout << "FoundByFreq: " << freq 
472       //  << "  ident: " << data.ident 
473       //  << "  type: " << data.type << " ***" << endl;
474 // We are in range of something.
475
476
477 // Get rid of any *other* service that was on this radio unit:
478             string svc_name = data.ident+decimalNumeral(data.type);
479         ZapOtherService(ncunit, svc_name);
480 // See if the service already exists, possibly connected to
481 // some other radio unit:
482         if (atc_list->count(svc_name)) {
483           // make sure the service knows it's tuned on this radio:
484           FGATC* svc = (*atc_list)[svc_name];
485           svc->active_on[ncunit] = 1;
486           svc->SetDisplay();
487           if (data.type == APPROACH) svc->AddPlane("Player");
488           return;
489         }
490
491         CommRegisterAirport(data.ident, unit, data.type);
492
493 // This was a switch-case statement but the compiler didn't like 
494 // the new variable creation with it. 
495         if      (data.type == ATIS
496               || data.type == AWOS)     (*atc_list)[svc_name] = new FGATIS;
497         else if (data.type == TOWER)    (*atc_list)[svc_name] = new FGTower;
498         else if (data.type == GROUND)   (*atc_list)[svc_name] = new FGGround;
499         else if (data.type == APPROACH) (*atc_list)[svc_name] = new FGApproach;
500         FGATC* svc = (*atc_list)[svc_name];
501         svc->SetData(&data);
502         svc->active_on[ncunit] = 1;
503         svc->SetDisplay();
504         svc->Init();
505         if (data.type == APPROACH) svc->AddPlane("Player");
506     } else {
507       // No services in range.  Zap any service on this unit.
508       ZapOtherService(ncunit, "x x x");
509     } 
510 }
511
512 #ifdef AREA_SEARCH
513 /* I don't think AreaSearch ever gets called */
514 // Search ATC stations by area in order that we appear 'on the radar'
515 void FGATCMgr::AreaSearch() {
516   const string AREA("AREA");
517   // Search for Approach stations
518   comm_list_type approaches;
519   comm_list_iterator app_itr;
520
521   lon = lon_node->getDoubleValue();
522   lat = lat_node->getDoubleValue();
523   elev = elev_node->getDoubleValue() * SG_FEET_TO_METER;
524   for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) {
525     MSI &actv = svc->second->active_on;
526     if (actv.count(AREA)) actv[AREA] = 0;  // Mark all as maybe not in range
527   }
528
529   // search stations in range
530   int num_app = current_commlist->FindByPos(lon, lat, elev, 100.0, &approaches, APPROACH);
531   if (num_app != 0) {
532     //cout << num_app << " approaches found in area search !!!!" << endl;
533
534     for(app_itr = approaches.begin(); app_itr != approaches.end(); app_itr++) {
535       FGATC* app = FindInList(app_itr->ident, app_itr->type);
536       string svc_name = app_itr->ident+decimalNumeral(app_itr->type);
537       if(app != NULL) {
538     // The station is already in the ATC list
539     app->AddPlane("Player");
540       } else {
541     // Generate the station and put in the ATC list
542     FGApproach* a = new FGApproach;
543     a->SetData(&(*app_itr));
544     a->AddPlane("Player");
545     (*atc_list)[svc_name] = a;
546     //cout << "New area service: " << svc_name << endl;
547       }
548       FGATC* svc = (*atc_list)[svc_name];
549       svc->active_on[AREA] = 1;
550     }
551   }
552
553   for (atc_list_iterator svc = atc_list->begin(); svc != atc_list->end(); svc++) {
554     MSI &actv = svc->second->active_on;
555     if (!actv.count(AREA)) continue;
556     if (!actv[AREA]) actv.erase(AREA);
557     if (!actv.size()) {     // this service no longer active at all
558       cout << "Eradicating area service: " << svc->first << endl;
559       svc->second->SetNoDisplay();
560       svc->second->Update(0);
561       delete (svc->second);
562       atc_list->erase(svc);
563 // Reset the persistent iterator, since any erase() makes it invalid:
564       atc_list_itr = atc_list->begin(); 
565 // Hope we only move out of one approach-area;
566 // others will not be noticed until next update:
567       break;
568     }
569   }
570 }
571 #endif