]> git.mxchange.org Git - flightgear.git/blob - src/ATCDCL/ATC.cxx
89cb5527302f99208a9ff03d7acecbe6674790ac
[flightgear.git] / src / ATCDCL / ATC.cxx
1 // Implementation of FGATC - ATC subsystem base class.
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 "ATC.hxx"
26
27 #include <iostream>
28
29 #include <simgear/sound/soundmgr_openal.hxx>
30 #include <simgear/sound/sample_group.hxx>
31 #include <simgear/structure/exception.hxx>
32
33 #include <Main/globals.hxx>
34 #include <Main/fg_props.hxx>
35 #include <ATC/CommStation.hxx>
36 #include <Airports/simple.hxx>
37
38 FGATC::FGATC() :
39     freq(0),
40     _currentStation(NULL),
41     range(0),
42     _voice(true),
43     _playing(false),
44     _vPtr(NULL),
45     _sgr(NULL),
46     _type(INVALID),
47     _display(false)
48 #ifdef OLD_ATC_MGR
49     ,freqClear(true),
50     receiving(false),
51     respond(false),
52     responseID(""),
53     runResponseCounter(false),
54     _runReleaseCounter(false),
55     responseReqd(false),
56     // Transmission timing stuff
57     pending_transmission(""),
58     _timeout(0),
59     _pending(false),
60     _transmit(false),
61     _transmitting(false),
62     _counter(0.0),
63     _max_count(5.0)
64 #endif
65 {
66     SGSoundMgr *smgr = globals->get_soundmgr();
67     _sgr = smgr->find("atc", true);
68     _sgr->tie_to_listener();
69
70     _masterVolume = fgGetNode("/sim/sound/atc/volume", true);
71     _enabled = fgGetNode("/sim/sound/atc/enabled", true);
72     _atc_external = fgGetNode("/sim/sound/atc/external-view", true);
73     _internal = fgGetNode("/sim/current-view/internal", true);
74 }
75
76 FGATC::~FGATC() {
77 }
78
79 #ifndef OLD_ATC_MGR
80 // Derived classes wishing to use the response counter should 
81 // call this from their own Update(...).
82 void FGATC::update(double dt) {
83
84     // TODO This doesn't really do anything specific to this instance.
85     // All FGATCs share the same "_sgr" sound group. So this really should
86     // only be done once for all FGATCs.
87 #ifdef ENABLE_AUDIO_SUPPORT
88     bool active = _atc_external->getBoolValue() ||
89               _internal->getBoolValue();
90
91     if ( active && _enabled->getBoolValue() ) {
92         _sgr->set_volume( _masterVolume->getFloatValue() );
93         _sgr->resume(); // no-op if already in resumed state
94     } else {
95         _sgr->suspend();
96     }
97 #endif
98 }
99 #endif
100
101 void FGATC::SetStation(flightgear::CommStation* sta) {
102     if (_currentStation == sta)
103         return;
104     _currentStation = sta;
105
106     if (sta)
107     {
108         switch (sta->type()) {
109             case FGPositioned::FREQ_ATIS:   _type = ATIS; break;
110             case FGPositioned::FREQ_AWOS:   _type = AWOS; break;
111             default:
112                 sta = NULL;
113                 break;
114         }
115     }
116
117     if (sta == NULL)
118     {
119         range = 0;
120         ident = "";
121         name = "";
122         freq = 0;
123
124         SetNoDisplay();
125         update(0);     // one last update
126     }
127     else
128     {
129         _geod = sta->geod();
130         _cart = sta->cart();
131
132         range = sta->rangeNm();
133         ident = sta->airport()->ident();
134         name = sta->airport()->name();
135         freq = sta->freqKHz();
136         SetDisplay();
137     }
138 }
139
140 // Render a transmission
141 // Outputs the transmission either on screen or as audio depending on user preference
142 // The refname is a string to identify this sample to the sound manager
143 // The repeating flag indicates whether the message should be repeated continuously or played once.
144 void FGATC::Render(std::string& msg, const float volume,
145                    const std::string& refname, const bool repeating) {
146     if ((!_display) ||(volume < 0.05))
147     {
148         NoRender(refname);
149         return;
150     }
151
152     if (repeating)
153         fgSetString("/sim/messages/atis", msg.c_str());
154     else
155         fgSetString("/sim/messages/atc", msg.c_str());
156
157 #ifdef ENABLE_AUDIO_SUPPORT
158     bool useVoice = _voice && fgGetBool("/sim/sound/voice") && fgGetBool("/sim/sound/atc/enabled");
159     SGSoundSample *simple = _sgr->find(refname);
160     if(useVoice) {
161         if (simple && (_currentMsg == msg))
162         {
163             simple->set_volume(volume);
164         }
165         else
166         {
167             _currentMsg = msg;
168             size_t len;
169             void* buf = NULL;
170             if (!_vPtr)
171                 _vPtr = GetVoicePointer();
172             if (_vPtr)
173                 buf = _vPtr->WriteMessage((char*)msg.c_str(), &len);
174             NoRender(refname);
175             if(buf) {
176                 try {
177 // >>> Beware: must pass a (new) object to the (add) method,
178 // >>> because the (remove) method is going to do a (delete)
179 // >>> whether that's what you want or not.
180                     simple = new SGSoundSample(&buf, len, 8000);
181                     simple->set_volume(volume);
182                     _sgr->add(simple, refname);
183                     _sgr->play(refname, repeating);
184                 } catch ( sg_io_exception &e ) {
185                     SG_LOG(SG_ATC, SG_ALERT, e.getFormattedMessage());
186                 }
187             }
188         }
189     }
190     else
191     if (simple)
192     {
193         NoRender(refname);
194     }
195 #else
196     bool useVoice = false;
197 #endif    // ENABLE_AUDIO_SUPPORT
198
199     if (!useVoice)
200     {
201         // first rip the underscores and the pause hints out of the string - these are for the convenience of the voice parser
202         for(unsigned int i = 0; i < msg.length(); ++i) {
203             if((msg.substr(i,1) == "_") || (msg.substr(i,1) == "/")) {
204                 msg[i] = ' ';
205             }
206         }
207     }
208     _playing = true;
209 }
210
211
212 // Cease rendering a transmission.
213 void FGATC::NoRender(const std::string& refname) {
214     if(_playing) {
215         if(_voice) {
216 #ifdef ENABLE_AUDIO_SUPPORT
217             _sgr->stop(refname);
218             _sgr->remove(refname);
219 #endif
220         }
221         _playing = false;
222     }
223 }
224
225 #ifdef OLD_ATC_MGR
226 // Derived classes wishing to use the response counter should
227 // call this from their own Update(...).
228 void FGATC::Update(double dt) {
229
230 #ifdef ENABLE_AUDIO_SUPPORT
231     bool active = _atc_external->getBoolValue() ||
232               _internal->getBoolValue();
233
234     if ( active && _enabled->getBoolValue() ) {
235         _sgr->set_volume( _masterVolume->getFloatValue() );
236         _sgr->resume(); // no-op if already in resumed state
237     } else {
238         _sgr->suspend();
239     }
240 #endif
241
242     if(runResponseCounter) {
243         //cout << responseCounter << '\t' << responseTime << '\n';
244         if(responseCounter >= responseTime) {
245             runResponseCounter = false;
246             respond = true;
247             //cout << "RESPOND\n";
248         } else {
249             responseCounter += dt;
250         }
251     }
252
253     if(_runReleaseCounter) {
254         if(_releaseCounter >= _releaseTime) {
255             freqClear = true;
256             _runReleaseCounter = false;
257         } else {
258             _releaseCounter += dt;
259         }
260     }
261
262     // Transmission stuff cribbed from AIPlane.cxx
263     if(_pending) {
264         if(GetFreqClear()) {
265             //cout << "TUNED STATION FREQ CLEAR\n";
266             SetFreqInUse();
267             _pending = false;
268             _transmit = true;
269             _transmitting = false;
270         } else {
271             if(_timeout > 0.0) {    // allows count down to be avoided by initially setting it to zero
272                 _timeout -= dt;
273                 if(_timeout <= 0.0) {
274                     _timeout = 0.0;
275                     _pending = false;
276                     // timed out - don't render.
277                 }
278             }
279         }
280     }
281
282     if(_transmit) {
283         _counter = 0.0;
284         _max_count = 5.0;        // FIXME - hardwired length of message - need to calculate it!
285
286         //cout << "Transmission = " << pending_transmission << '\n';
287         if(_display) {
288             //Render(pending_transmission, ident, false);
289             Render(pending_transmission);
290         }
291         _transmit = false;
292         _transmitting = true;
293     } else if(_transmitting) {
294         if(_counter >= _max_count) {
295             //NoRender(plane.callsign);  commented out since at the moment NoRender is designed just to stop repeating messages,
296             // and this will be primarily used on single messages.
297             _transmitting = false;
298             //if(tuned_station) tuned_station->NotifyTransmissionFinished(plane.callsign);
299             // TODO - need to let the plane the transmission is aimed at that it's finished.
300             // However, for now we'll just release the frequency since if we don't it all goes pear-shaped
301             _releaseCounter = 0.0;
302             _releaseTime = 0.9;
303             _runReleaseCounter = true;
304         }
305         _counter += dt;
306     }
307 }
308
309 void FGATC::ReceiveUserCallback(int code) {
310     SG_LOG(SG_ATC, SG_WARN, "WARNING - whichever ATC class was intended to receive callback code " << code << " didn't get it!!!");
311 }
312
313 void FGATC::SetResponseReqd(const string& rid) {
314     receiving = false;
315     responseReqd = true;
316     respond = false;    // TODO - this ignores the fact that more than one plane could call this before response
317                         // Shouldn't happen with AI only, but user could confuse things??
318     responseID = rid;
319     runResponseCounter = true;
320     responseCounter = 0.0;
321     responseTime = 1.8;        // TODO - randomize this slightly.
322 }
323
324 void FGATC::NotifyTransmissionFinished(const string& rid) {
325     //cout << "Transmission finished, callsign = " << rid << '\n';
326     receiving = false;
327     responseID = rid;
328     if(responseReqd) {
329         runResponseCounter = true;
330         responseCounter = 0.0;
331         responseTime = 1.2;    // TODO - randomize this slightly, and allow it to be dependent on the transmission and how busy the ATC is.
332         respond = false;    // TODO - this ignores the fact that more than one plane could call this before response
333                             // Shouldn't happen with AI only, but user could confuse things??
334     } else {
335         freqClear = true;
336     }
337 }
338
339 // Generate the text of a message from its parameters and the current context.
340 string FGATC::GenText(const string& m, int c) {
341     return("");
342 }
343
344 ostream& operator << (ostream& os, atc_type atc) {
345     switch(atc) {
346         case(AWOS):       return(os << "AWOS");
347         case(ATIS):       return(os << "ATIS");
348         case(GROUND):     return(os << "GROUND");
349         case(TOWER):      return(os << "TOWER");
350         case(APPROACH):   return(os << "APPROACH");
351         case(DEPARTURE):  return(os << "DEPARTURE");
352         case(ENROUTE):    return(os << "ENROUTE");
353         case(INVALID):    return(os << "INVALID");
354     }
355     return(os << "ERROR - Unknown switch in atc_type operator << ");
356 }
357
358 std::istream& operator >> ( std::istream& fin, ATCData& a )
359 {
360     double f;
361     char ch;
362     char tp;
363
364     fin >> tp;
365
366     switch(tp) {
367     case 'I':
368         a.type = ATIS;
369         break;
370     case 'T':
371         a.type = TOWER;
372         break;
373     case 'G':
374         a.type = GROUND;
375         break;
376     case 'A':
377         a.type = APPROACH;
378         break;
379     case '[':
380         a.type = INVALID;
381         return fin >> skipeol;
382     default:
383         SG_LOG(SG_ATC, SG_ALERT, "Warning - unknown type \'" << tp << "\' found whilst reading ATC frequency data!\n");
384         a.type = INVALID;
385         return fin >> skipeol;
386     }
387
388     double lat, lon, elev;
389
390     fin >> lat >> lon >> elev >> f >> a.range >> a.ident;
391     a.geod = SGGeod::fromDegM(lon, lat, elev);
392     a.name = "";
393     fin >> ch;
394     if(ch != '"') a.name += ch;
395     while(1) {
396         //in >> noskipws
397         fin.unsetf(std::ios::skipws);
398         fin >> ch;
399         if((ch == '"') || (ch == 0x0A)) {
400             break;
401         }   // we shouldn't need the 0x0A but it makes a nice safely in case someone leaves off the "
402         a.name += ch;
403     }
404     fin.setf(std::ios::skipws);
405     //cout << "Comm name = " << a.name << '\n';
406
407     a.freq = (int)(f*100.0 + 0.5);
408
409     // cout << a.ident << endl;
410
411     // generate cartesian coordinates
412     a.cart = SGVec3d::fromGeod(a.geod);
413     return fin >> skipeol;
414 }
415 #endif