]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/newnavradio.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[flightgear.git] / src / Instrumentation / newnavradio.cxx
1 // navradio.cxx -- class to manage a nav radio instance
2 //
3 // Written by Curtis Olson, started April 2000.
4 // Rewritten by Torsten Dreyer, August 2011
5 //
6 // Copyright (C) 2000 - 2011  Curtis L. Olson - http://www.flightgear.org/~curt
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
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include "newnavradio.hxx"
28
29 #include <assert.h>
30 #include <boost/foreach.hpp>
31
32 #include <simgear/math/SGMath.hxx>
33 #include <simgear/math/interpolater.hxx>
34 #include <simgear/sg_inlines.h>
35 #include <simgear/props/propertyObject.hxx>
36 #include <simgear/misc/strutils.hxx>
37
38 #include <Main/fg_props.hxx>
39 #include <Navaids/navlist.hxx>
40 #include <Sound/audioident.hxx>
41
42 #include "navradio.hxx"
43
44
45 namespace Instrumentation {
46
47 using simgear::PropertyObject;
48
49 /* --------------The Navigation Indicator ----------------------------- */
50
51 class NavIndicator {
52 public:
53     NavIndicator( SGPropertyNode * rootNode ) :
54       _cdi( rootNode->getNode("heading-needle-deflection", true ) ),
55       _cdiNorm( rootNode->getNode("heading-needle-deflection-norm", true ) ),
56       _course( rootNode->getNode("radials/selected-deg", true ) ),
57       _toFlag( rootNode->getNode("to-flag", true ) ),
58       _fromFlag( rootNode->getNode("from-flag", true ) ),
59       _signalQuality( rootNode->getNode("signal-quality-norm", true ) ),
60       _hasGS( rootNode->getNode("has-gs", true ) ),
61       _gsDeflection(rootNode->getNode("gs-needle-deflection", true )),
62       _gsDeflectionDeg(rootNode->getNode("gs-needle-deflection-deg", true )),
63       _gsDeflectionNorm(rootNode->getNode("gs-needle-deflection-norm", true ))
64   {
65   }
66
67   virtual ~NavIndicator() {}
68
69   /**
70    * set the normalized CDI deflection
71    * @param norm the cdi deflection normalized [-1..1]
72    */
73   void setCDI( double norm )
74   {
75       _cdi = norm * 10.0;
76       _cdiNorm = norm;
77   }
78
79   /**
80    * set the normalized GS deflection
81    * @param norm the gs deflection normalized to [-1..1]
82    */
83   void setGS( double norm )
84   {
85       _gsDeflectionNorm = norm;
86       _gsDeflectionDeg = norm * 0.7;
87       _gsDeflection = norm * 3.5;
88   }
89
90   void setGS( bool enabled )
91   {
92       _hasGS = enabled;
93       if( !enabled ) {
94         setGS( 0.0 );
95       }
96   }
97
98   void showFrom( bool on )
99   {
100       _fromFlag = on;
101   }
102
103   void showTo( bool on )
104   {
105       _toFlag = on;
106   }
107       
108   void setSelectedCourse( double course )
109   {
110       _course = course;
111   }
112
113   double getSelectedCourse() const
114   {
115       return SGMiscd::normalizePeriodic(0.0, 360.0, _course );
116   }
117
118   void setSignalQuality( double signalQuality )
119   {
120       _signalQuality = signalQuality;
121   }
122
123 private:
124   PropertyObject<double> _cdi;
125   PropertyObject<double> _cdiNorm;
126   PropertyObject<double> _course;
127   PropertyObject<double> _toFlag;
128   PropertyObject<double> _fromFlag;
129   PropertyObject<double> _signalQuality;
130   PropertyObject<double> _hasGS;
131   PropertyObject<double> _gsDeflection;
132   PropertyObject<double> _gsDeflectionDeg;
133   PropertyObject<double> _gsDeflectionNorm;
134 };
135
136 /* ---------------------------------------------------------------- */
137
138 class NavRadioComponent {
139 public:
140   NavRadioComponent( const std::string & name, SGPropertyNode_ptr rootNode );
141   virtual ~NavRadioComponent();
142
143   virtual void   update( double dt, const SGGeod & aircraftPosition );
144   virtual void   search( double frequency, const SGGeod & aircraftPosition );
145   virtual double getRange_nm( const SGGeod & aircraftPosition );
146   virtual void   display( NavIndicator & navIndicator ) = 0;
147   virtual bool   valid() const { return NULL != _navRecord && true == _serviceable; }
148   virtual const std::string getIdent() const { return _ident; }
149
150 protected:
151   virtual double computeSignalQuality_norm( const SGGeod & aircraftPosition );
152   virtual FGNavList * getNavaidList() = 0;
153
154   // General-purpose sawtooth function.  Graph looks like this:
155   //         /\                                    .
156   //       \/
157   // Odd symmetry, inversion symmetry about the origin.
158   // Unit slope at the origin.
159   // Max 1, min -1, period 4.
160   // Two zero-crossings per period, one with + slope, one with - slope.
161   // Useful for false localizer courses.
162   static double sawtooth(double xx)
163   {
164     return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
165   }
166
167   SGPropertyNode_ptr _rootNode;
168   const std::string _name;
169   FGNavRecord * _navRecord;
170   PropertyObject<bool>   _serviceable;
171   PropertyObject<double> _signalQuality_norm;
172   PropertyObject<double> _trueBearingTo_deg;
173   PropertyObject<double> _trueBearingFrom_deg;
174   PropertyObject<double> _trackDistance_m;
175   PropertyObject<double> _slantDistance_m;
176   PropertyObject<double> _heightAboveStation_ft;
177   PropertyObject<string> _ident;
178   PropertyObject<bool>   _inRange;
179   PropertyObject<double> _range_nm;
180 };
181
182 class NavRadioComponentWithIdent : public NavRadioComponent {
183 public:
184   NavRadioComponentWithIdent( const std::string & name, SGPropertyNode_ptr rootNode, AudioIdent * audioIdent );
185   virtual ~NavRadioComponentWithIdent();
186   void update( double dt, const SGGeod & aircraftPosition );
187 protected:
188   static std::string getIdentString( const std::string & name, int index );
189 private:
190   AudioIdent * _audioIdent;
191   PropertyObject<double> _identVolume;
192   PropertyObject<bool>   _identEnabled;
193 };
194
195 std::string NavRadioComponentWithIdent::getIdentString( const std::string & name, int index )
196 {
197   std::ostringstream temp;
198   temp << name << "-ident-" << index;
199   return temp.str();
200 }
201
202 NavRadioComponentWithIdent::NavRadioComponentWithIdent( const std::string & name, SGPropertyNode_ptr rootNode, AudioIdent * audioIdent ) :
203   NavRadioComponent( name, rootNode ),
204   _audioIdent( audioIdent ),
205   _identVolume( rootNode->getNode(name,true)->getNode("ident-volume",true) ),
206   _identEnabled( rootNode->getNode(name,true)->getNode("ident-enabled",true) )
207 {
208   _audioIdent->init();
209
210 }
211 NavRadioComponentWithIdent::~NavRadioComponentWithIdent()
212 {
213   delete _audioIdent;
214 }
215
216 void NavRadioComponentWithIdent::update( double dt, const SGGeod & aircraftPosition )
217 {
218   NavRadioComponent::update( dt, aircraftPosition );
219   _audioIdent->update( dt );
220
221   if( false == ( valid() && _identEnabled && _signalQuality_norm > 0.1 ) ) {
222       _audioIdent->setIdent("", 0.0 );
223       return;
224   }
225   _audioIdent->setIdent( _ident, SGMiscd::clip(_identVolume, 0.0, 1.0) );
226 }
227
228 NavRadioComponent::NavRadioComponent( const std::string & name, SGPropertyNode_ptr rootNode ) :
229   _rootNode(rootNode),
230   _name(name),
231   _navRecord(NULL),
232   _serviceable( rootNode->getNode(name,true)->getNode("serviceable",true) ),
233   _signalQuality_norm( rootNode->getNode(name,true)->getNode("signal-quality-norm",true) ),
234   _trueBearingTo_deg( rootNode->getNode(name,true)->getNode("true-bearing-to-deg",true) ),
235   _trueBearingFrom_deg( rootNode->getNode(name,true)->getNode("true-bearing-from-deg",true) ),
236   _trackDistance_m( rootNode->getNode(name,true)->getNode("track-distance-m",true) ),
237   _slantDistance_m( rootNode->getNode(name,true)->getNode("slant-distance-m",true) ),
238   _heightAboveStation_ft( rootNode->getNode(name,true)->getNode("height-above-station-ft",true) ),
239   _ident( rootNode->getNode(name,true)->getNode("ident",true) ),
240   _inRange( rootNode->getNode(name,true)->getNode("in-range",true) ),
241   _range_nm( rootNode->getNode(_name,true)->getNode("range-nm",true) )
242 {
243   simgear::props::Type typ = _serviceable.node()->getType();
244   if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED))
245     _serviceable = true;
246 }
247
248 NavRadioComponent::~NavRadioComponent()
249 {
250 }
251
252 double NavRadioComponent::getRange_nm( const SGGeod & aircraftPosition )
253
254   if( _navRecord == NULL ) return 0.0; // no station: no range
255   double d = _navRecord->get_range();
256   if( d <= SGLimitsd::min() ) return 25.0; // no configured range: arbitrary number
257   return d; // configured range
258 }
259
260 void NavRadioComponent::search( double frequency, const SGGeod & aircraftPosition )
261 {
262   if( NULL == (_navRecord = getNavaidList()->findByFreq(frequency, aircraftPosition )) ) {
263     SG_LOG(SG_INSTR,SG_ALERT, "No " << _name << " available at " << frequency );
264     _ident = "";
265     return;
266   }
267   SG_LOG(SG_INSTR,SG_ALERT, "Using " << _name << "'" << _navRecord->get_ident() << "' for " << frequency );
268   _ident = _navRecord->ident();
269 }
270
271 double NavRadioComponent::computeSignalQuality_norm( const SGGeod & aircraftPosition )
272 {
273   if( false == valid() ) return 0.0;
274
275   double distance_nm = _slantDistance_m * SG_METER_TO_NM;
276   double range_nm = _range_nm;
277
278   // assume signal quality is 100% up to the published range and 
279   // decay with the distance squared further out
280   if ( distance_nm <= range_nm ) return 1.0;
281   return range_nm*range_nm/(distance_nm*distance_nm);
282 }
283
284 void NavRadioComponent::update( double dt, const SGGeod & aircraftPosition )
285 {
286     if( false == valid() ) {
287       _signalQuality_norm = 0.0;
288       _trueBearingTo_deg = 0.0;
289       _trueBearingFrom_deg = 0.0;
290       _trackDistance_m = 0.0;
291       _slantDistance_m = 0.0;
292       return;
293     } 
294
295     _slantDistance_m = dist(_navRecord->cart(), SGVec3d::fromGeod(aircraftPosition));
296
297     double az1 = 0.0, az2 = 0.0, dist = 0.0;
298     SGGeodesy::inverse(aircraftPosition, _navRecord->geod(), az1, az2, dist );
299     _trueBearingTo_deg = az1; _trueBearingFrom_deg = az2; _trackDistance_m = dist;
300     _heightAboveStation_ft = SGMiscd::max(0.0, aircraftPosition.getElevationFt() - _navRecord->get_elev_ft());
301
302     _range_nm = getRange_nm(aircraftPosition);
303     _signalQuality_norm = computeSignalQuality_norm( aircraftPosition );
304     _inRange = _signalQuality_norm > 0.2;
305 }
306
307 /* ---------------------------------------------------------------- */
308
309 static std::string VORTablePath( const char * name )
310 {
311     SGPath path( globals->get_fg_root() );
312     path.append( "Navaids" );
313     path.append(name);
314     return path.str();
315 }
316
317 class VOR : public NavRadioComponentWithIdent {
318 public:
319   VOR( SGPropertyNode_ptr rootNode);
320   virtual ~VOR();
321   virtual void update( double dt, const SGGeod & aircraftPosition );
322   virtual void display( NavIndicator & navIndicator );
323   virtual double getRange_nm(const SGGeod & aircraftPosition);
324 protected:
325   virtual double computeSignalQuality_norm( const SGGeod & aircraftPosition );
326   virtual FGNavList * getNavaidList();
327
328 private:
329   double _totalTime;
330   class ServiceVolume {
331   public:
332     ServiceVolume() :
333       term_tbl(VORTablePath("range.term")),
334       low_tbl(VORTablePath("range.low")),
335       high_tbl(VORTablePath("range.high")) {
336     }
337     double adjustRange( double height_ft, double nominalRange_nm );
338
339   private:
340     SGInterpTable term_tbl;
341     SGInterpTable low_tbl;
342     SGInterpTable high_tbl;
343   } _serviceVolume;
344
345   PropertyObject<double> _radial;
346   PropertyObject<double> _radialInbound;
347 };
348
349 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
350 double VOR::ServiceVolume::adjustRange( double height_ft, double nominalRange_nm )
351 {
352     if (nominalRange_nm < SGLimitsd::min() )
353       nominalRange_nm = FG_NAV_DEFAULT_RANGE;
354     
355     // extend out actual usable range to be 1.3x the published safe range
356     const double usability_factor = 1.3;
357
358     // assumptions we model the standard service volume, plus
359     // ... rather than specifying a cylinder, we model a cone that
360     // contains the cylinder.  Then we put an upside down cone on top
361     // to model diminishing returns at too-high altitudes.
362
363     if ( nominalRange_nm < 25.0 + SG_EPSILON ) {
364         // Standard Terminal Service Volume
365         return term_tbl.interpolate( height_ft ) * usability_factor;
366     } else if ( nominalRange_nm < 50.0 + SG_EPSILON ) {
367         // Standard Low Altitude Service Volume
368         // table is based on range of 40, scale to actual range
369         return low_tbl.interpolate( height_ft ) * nominalRange_nm / 40.0
370             * usability_factor;
371     } else {
372         // Standard High Altitude Service Volume
373         // table is based on range of 130, scale to actual range
374         return high_tbl.interpolate( height_ft ) * nominalRange_nm / 130.0
375             * usability_factor;
376     }
377 }
378
379 VOR::VOR( SGPropertyNode_ptr rootNode) :
380   NavRadioComponentWithIdent("vor", rootNode, new VORAudioIdent(getIdentString(string("vor"), rootNode->getIndex()))),
381   _totalTime(0.0),
382   _radial( rootNode->getNode(_name,true)->getNode("radial",true) ),
383   _radialInbound( rootNode->getNode(_name,true)->getNode("radial-inbound",true) )
384 {
385 }
386
387 VOR::~VOR()
388 {
389 }
390
391 double VOR::getRange_nm( const SGGeod & aircraftPosition )
392 {
393   return _serviceVolume.adjustRange( _heightAboveStation_ft, _navRecord->get_range() );
394 }
395
396 FGNavList * VOR::getNavaidList()
397 {
398   return globals->get_navlist();
399 }
400
401 double VOR::computeSignalQuality_norm( const SGGeod & aircraftPosition )
402 {
403   // apply cone of confusion. Some sources say it's opening angle is 53deg, others estimate
404   // a diameter of 1NM per 6000ft (approx. 45deg). ICAO Annex 10 says minimum 40deg.
405   // We use 1NM@6000ft and a distance-squared
406   // function to make signal-quality=100% 0.5NM@6000ft from the center and zero overhead
407   double cone_of_confusion_width = 0.5 * _heightAboveStation_ft / 6000.0 * SG_NM_TO_METER;
408   if( _trackDistance_m < cone_of_confusion_width ) {
409     double d = cone_of_confusion_width <= SGLimitsd::min() ? 1 : 
410               (1 - _trackDistance_m/cone_of_confusion_width);
411     return 1-d*d;
412   } 
413
414   // use default decay function outside the cone of confusion
415   return NavRadioComponentWithIdent::computeSignalQuality_norm( aircraftPosition );
416 }
417
418 void VOR::update( double dt, const SGGeod & aircraftPosition )
419 {
420   _totalTime += dt;
421   NavRadioComponentWithIdent::update( dt, aircraftPosition );
422
423   if( false == valid() ) {
424       _radial = 0.0;
425       return;
426   }
427
428   // an arbitrary error function
429   double error = 0.5*(sin(_totalTime/11.0) + sin(_totalTime/23.0));
430
431   // add 1% error at 100% signal-quality
432   // add 50% error at  0% signal-quality
433   // of full deflection (+/-10deg)
434   double e = 10.0 * ( 0.01 + (1-_signalQuality_norm) * 0.49 ) * error;
435
436   // compute magnetic bearing from the station (aka current radial)
437   double r = SGMiscd::normalizePeriodic(0.0, 360.0, _trueBearingFrom_deg - _navRecord->get_multiuse() + e );
438
439   _radial = r;
440   _radialInbound = SGMiscd::normalizePeriodic(0.0,360.0, 180.0 + _radial);
441 }
442
443 void VOR::display( NavIndicator & navIndicator )
444 {
445   if( false == valid() ) return;
446
447   double offset = SGMiscd::normalizePeriodic(-180.0,180.0,_radial - navIndicator.getSelectedCourse());
448   bool to = fabs(offset) >= 90.0;
449
450   if( to ) offset = -offset + copysign(180.0,offset);
451
452   navIndicator.showTo( to );
453   navIndicator.showFrom( !to );
454   // normalize to +/- 1.0 for +/- 10deg, decrease deflection with decreasing signal
455   navIndicator.setCDI( SGMiscd::clip( -offset/10.0, -1.0, 1.0 ) * _signalQuality_norm );
456   navIndicator.setSignalQuality( _signalQuality_norm );
457 }
458
459 /* ---------------------------------------------------------------- */
460 class LOC : public NavRadioComponentWithIdent {
461 public:
462   LOC( SGPropertyNode_ptr rootNode );
463   virtual ~LOC();
464   virtual void update( double dt, const SGGeod & aircraftPosition );
465   virtual void search( double frequency, const SGGeod & aircraftPosition );
466   virtual void display( NavIndicator & navIndicator );
467   virtual double getRange_nm(const SGGeod & aircraftPosition);
468
469 protected:
470   virtual double computeSignalQuality_norm( const SGGeod & aircraftPosition );
471   virtual FGNavList * getNavaidList();
472
473 private:
474   class ServiceVolume {
475   public:
476       ServiceVolume();
477       double adjustRange( double azimuthAngle_deg, double elevationAngle_deg );
478   private:
479       SGInterpTable _azimuthTable;
480       SGInterpTable _elevationTable;
481   } _serviceVolume;
482   PropertyObject<double> _localizerOffset_norm;
483   PropertyObject<double> _localizerWidth_deg;
484 };
485
486 LOC::ServiceVolume::ServiceVolume()
487 {
488 // maybe this: http://www.tpub.com/content/aviation2/P-1244/P-12440125.htm
489   // ICAO Annex 10 - 3.1.3.2.2: The emission from the localizer
490   // shall be horizontally polarized
491   // very rough abstraction of a 5-element yagi antenna's
492   // E-plane radiation diagram
493   _azimuthTable.addEntry(   0.0, 1.0 );
494   _azimuthTable.addEntry(  10.0, 1.0 );
495   _azimuthTable.addEntry(  30.0, 0.75 );
496   _azimuthTable.addEntry(  40.0, 0.50 );
497   _azimuthTable.addEntry(  50.0, 0.20 );
498   _azimuthTable.addEntry(  60.0, 0.10 );
499   _azimuthTable.addEntry(  70.0, 0.20 );
500   _azimuthTable.addEntry(  80.0, 0.10 );
501   _azimuthTable.addEntry(  90.0, 0.05 );
502   _azimuthTable.addEntry( 105.0, 0.10 );
503   _azimuthTable.addEntry( 130.0, 0.05 );
504   _azimuthTable.addEntry( 150.0, 0.30 );
505   _azimuthTable.addEntry( 160.0, 0.40 );
506   _azimuthTable.addEntry( 170.0, 0.50 );
507   _azimuthTable.addEntry( 180.0, 0.50 );
508
509   _elevationTable.addEntry(   0.0, 0.1 );
510   _elevationTable.addEntry(  1.05, 1.0 );
511   _elevationTable.addEntry(  7.00, 1.0 );
512   _elevationTable.addEntry(  45.0, 0.3 );
513   _elevationTable.addEntry(  90.0, 0.1 );
514   _elevationTable.addEntry( 180.0, 0.01 );
515 }
516
517 double LOC::ServiceVolume::adjustRange( double azimuthAngle_deg, double elevationAngle_deg )
518 {
519     return _azimuthTable.interpolate( fabs(azimuthAngle_deg) ) * 
520         _elevationTable.interpolate( fabs(elevationAngle_deg) );
521 }
522
523 LOC::LOC( SGPropertyNode_ptr rootNode) :
524   NavRadioComponentWithIdent("loc", rootNode, new LOCAudioIdent(getIdentString(string("loc"), rootNode->getIndex()))),
525   _serviceVolume(),
526   _localizerOffset_norm( rootNode->getNode(_name,true)->getNode("offset-norm",true) ),
527   _localizerWidth_deg( rootNode->getNode(_name,true)->getNode("width-deg",true) )
528 {
529 }
530
531 LOC::~LOC()
532 {
533 }
534
535 FGNavList * LOC::getNavaidList()
536 {
537   return globals->get_loclist();
538 }
539
540 void LOC::search( double frequency, const SGGeod & aircraftPosition )
541 {
542   NavRadioComponentWithIdent::search( frequency, aircraftPosition );
543   if( false == valid() ) {
544       _localizerWidth_deg = 0.0;
545       return;
546   }
547
548   // cache slightly expensive value, 
549   // sanitized in FGNavRecord::localizerWidth() to  never become zero
550   _localizerWidth_deg = _navRecord->localizerWidth();
551 }
552
553 /* Localizer coverage (ICAO Annex 10 Volume I 3.1.3.3 
554   25NM within +/-10 deg from the front course line
555   17NM between 10 and 35deg from the front course line
556   10NM outside of +/- 35deg  if coverage is provided
557   at and above a height of 2000ft above threshold or
558   1000ft above the highest point within intermediate
559   and final approach areas. Upper limit is a surface
560   extending outward from the localizer and inclined at
561   7 degrees above the horizontal
562  */
563 double LOC::getRange_nm(const SGGeod & aircraftPosition)
564 {
565   double elevationAngle = ::atan2(_heightAboveStation_ft*SG_FEET_TO_METER, _trackDistance_m)*SG_RADIANS_TO_DEGREES;
566   double azimuthAngle = SGMiscd::normalizePeriodic( -180.0, 180.0, _trueBearingFrom_deg + 180.0 - _navRecord->get_multiuse() );
567
568   // looks like our navrecord declared range is based on 10NM?
569   return  _navRecord->get_range() * _serviceVolume.adjustRange( azimuthAngle, elevationAngle );
570 }
571
572 double LOC::computeSignalQuality_norm( const SGGeod & aircraftPosition )
573 {
574   return NavRadioComponentWithIdent::computeSignalQuality_norm( aircraftPosition );
575 }
576
577 void LOC::update( double dt, const SGGeod & aircraftPosition )
578 {
579   NavRadioComponentWithIdent::update( dt, aircraftPosition );
580
581   if( false == valid() ) {
582     _localizerOffset_norm = 0.0;
583     return;
584   }
585
586   double offset = SGMiscd::normalizePeriodic( -180.0, 180.0, _trueBearingFrom_deg + 180.0 - _navRecord->get_multiuse() );
587
588   // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six 
589   // zeros i.e. six courses: one front course, one back course, and four 
590   // false courses. Three of the six are reverse sensing.
591   offset = 30.0 * sawtooth(offset / 30.0);
592
593   // normalize offset to the localizer width, scale and clip to [-1..1]
594   offset = SGMiscd::clip( 2.0 * offset / _localizerWidth_deg, -1.0, 1.0 );
595   
596   _localizerOffset_norm = offset;
597 }
598
599 void LOC::display( NavIndicator & navIndicator )
600 {
601   if( false == valid() ) 
602     return;
603
604   navIndicator.showTo( true );
605   navIndicator.showFrom( false );
606
607   navIndicator.setCDI( _localizerOffset_norm * _signalQuality_norm );
608   navIndicator.setSignalQuality( _signalQuality_norm );
609 }
610
611 class GS : public NavRadioComponent {
612 public:
613   GS( SGPropertyNode_ptr rootNode);
614   virtual ~GS();
615   virtual void update( double dt, const SGGeod & aircraftPosition );
616   virtual void search( double frequency, const SGGeod & aircraftPosition );
617   virtual void display( NavIndicator & navIndicator );
618
619   virtual double getRange_nm(const SGGeod & aircraftPosition);
620 protected:
621   virtual FGNavList * getNavaidList();
622
623 private:
624   class ServiceVolume {
625   public:
626       ServiceVolume();
627       double adjustRange( double azimuthAngle_deg, double elevationAngle_deg );
628   private:
629       SGInterpTable _azimuthTable;
630       SGInterpTable _elevationTable;
631   } _serviceVolume;
632   static SGVec3d tangentVector(const SGGeod& midpoint, const double heading);
633
634   PropertyObject<double>  _targetGlideslope_deg;
635   PropertyObject<double>  _glideslopeOffset_norm;
636   SGVec3d _gsAxis;
637   SGVec3d _gsVertical;
638 };
639
640 GS::ServiceVolume::ServiceVolume()
641 {
642 // maybe this: http://www.tpub.com/content/aviation2/P-1244/P-12440125.htm
643   // ICAO Annex 10 - 3.1.5.2.2: The emission from the glide path equipment
644   // shall be horizontally polarized
645   // very rough abstraction of a 5-element yagi antenna's
646   // E-plane radiation diagram
647   _azimuthTable.addEntry(   0.0, 1.0 );
648   _azimuthTable.addEntry(  10.0, 1.0 );
649   _azimuthTable.addEntry(  30.0, 0.75 );
650   _azimuthTable.addEntry(  40.0, 0.50 );
651   _azimuthTable.addEntry(  50.0, 0.20 );
652   _azimuthTable.addEntry(  60.0, 0.10 );
653   _azimuthTable.addEntry(  70.0, 0.20 );
654   _azimuthTable.addEntry(  80.0, 0.10 );
655   _azimuthTable.addEntry(  90.0, 0.05 );
656   _azimuthTable.addEntry( 105.0, 0.10 );
657   _azimuthTable.addEntry( 130.0, 0.05 );
658   _azimuthTable.addEntry( 150.0, 0.30 );
659   _azimuthTable.addEntry( 160.0, 0.40 );
660   _azimuthTable.addEntry( 170.0, 0.50 );
661   _azimuthTable.addEntry( 180.0, 0.50 );
662
663   _elevationTable.addEntry(   0.0, 0.1 );
664   _elevationTable.addEntry(  1.05, 1.0 );
665   _elevationTable.addEntry(  7.00, 1.0 );
666   _elevationTable.addEntry(  45.0, 0.3 );
667   _elevationTable.addEntry(  90.0, 0.1 );
668   _elevationTable.addEntry( 180.0, 0.01 );
669 }
670
671 double GS::ServiceVolume::adjustRange( double azimuthAngle_deg, double elevationAngle_deg )
672 {
673     return _azimuthTable.interpolate( fabs(azimuthAngle_deg) ) * 
674         _elevationTable.interpolate( fabs(elevationAngle_deg) );
675 }
676
677 GS::GS( SGPropertyNode_ptr rootNode) :
678   NavRadioComponent("gs", rootNode ),
679   _targetGlideslope_deg( rootNode->getNode(_name,true)->getNode("slope",true) ),
680   _glideslopeOffset_norm( rootNode->getNode(_name,true)->getNode("offset-norm",true) ),
681   _gsAxis(SGVec3d::zeros()),
682   _gsVertical(SGVec3d::zeros())
683 {
684 }
685
686 GS::~GS()
687 {
688 }
689
690 FGNavList * GS::getNavaidList()
691 {
692   return globals->get_gslist();
693 }
694
695 double GS::getRange_nm(const SGGeod & aircraftPosition)
696 {
697   double elevationAngle = ::atan2(_heightAboveStation_ft*SG_FEET_TO_METER, _trackDistance_m)*SG_RADIANS_TO_DEGREES;
698   double azimuthAngle = SGMiscd::normalizePeriodic( -180.0, 180.0, _trueBearingFrom_deg + 180.0 - fmod(_navRecord->get_multiuse(), 1000.0) );
699   return  _navRecord->get_range() * _serviceVolume.adjustRange( azimuthAngle, elevationAngle );
700 }
701
702 // Calculate a Cartesian unit vector in the
703 // local horizontal plane, i.e. tangent to the 
704 // surface of the earth at the local ground zero.
705 // The tangent vector passes through the given  <midpoint> 
706 // and points forward along the given <heading>.
707 // The <heading> is given in degrees.
708 SGVec3d GS::tangentVector(const SGGeod& midpoint, const double heading)
709 {
710   // move 100m away from the midpoint - arbitrary number
711   const double delta(100.0);
712   SGGeod head, tail;
713   double az2;                   // ignored
714   SGGeodesy::direct(midpoint, heading,     delta, head, az2);
715   SGGeodesy::direct(midpoint, 180+heading, delta, tail, az2);
716   head.setElevationM(midpoint.getElevationM());
717   tail.setElevationM(midpoint.getElevationM());
718   SGVec3d head_xyz = SGVec3d::fromGeod(head);
719   SGVec3d tail_xyz = SGVec3d::fromGeod(tail);
720 // Awkward formula here, needed because vector-by-scalar
721 // multiplication is defined, but not vector-by-scalar division.
722   return (head_xyz - tail_xyz) * (0.5/delta);
723 }
724
725 void GS::search( double frequency, const SGGeod & aircraftPosition )
726 {
727   NavRadioComponent::search( frequency, aircraftPosition );
728   if( false == valid() ) {
729       _gsAxis = SGVec3d::zeros();
730       _gsVertical = SGVec3d::zeros();
731       _targetGlideslope_deg = 3.0;
732       return;
733   }
734   
735   double gs_radial = SGMiscd::normalizePeriodic(0.0, 360.0, fmod(_navRecord->get_multiuse(), 1000.0) );
736
737   _gsAxis = tangentVector(_navRecord->geod(), gs_radial);
738   SGVec3d gsBaseline = tangentVector(_navRecord->geod(), gs_radial + 90.0);
739   _gsVertical = cross(gsBaseline, _gsAxis);
740
741   int tmp = (int)(_navRecord->get_multiuse() / 1000.0);
742   // catch unconfigured glideslopes here, they will cause nan later
743   _targetGlideslope_deg = SGMiscd::max( 1.0, (double)tmp / 100.0 );
744 }
745
746 void GS::update( double dt, const SGGeod & aircraftPosition )
747 {
748   NavRadioComponent::update( dt, aircraftPosition );
749   if( false == valid() ) {
750       _glideslopeOffset_norm = 0.0;
751       return;
752   }
753   
754   SGVec3d pos = SGVec3d::fromGeod(aircraftPosition) - _navRecord->cart(); // relative vector from gs antenna to aircraft
755   // The positive GS axis points along the runway in the landing direction,
756   // toward the far end, not toward the approach area, so we need a - sign here:
757   double comp_h = -dot(pos, _gsAxis);      // component in horiz direction
758   double comp_v = dot(pos, _gsVertical);   // component in vertical direction
759   //double comp_b = dot(pos, _gsBaseline);   // component in baseline direction
760   //if (comp_b) {}                           // ... (useful for debugging)
761
762 // _gsDirect represents the angle of elevation of the aircraft
763 // as seen by the GS transmitter.
764   double gsDirect = atan2(comp_v, comp_h) * SGD_RADIANS_TO_DEGREES;
765 // At this point, if the aircraft is centered on the glide slope,
766 // _gsDirect will be a small positive number, e.g. 3.0 degrees
767
768 // Aim the branch cut straight down 
769 // into the ground below the GS transmitter:
770   if (gsDirect < -90.0) gsDirect += 360.0;
771
772   double offset = _targetGlideslope_deg - gsDirect;
773   if( offset < 0.0 )
774     offset = _targetGlideslope_deg/2 * sawtooth(2.0*offset/_targetGlideslope_deg);
775   assert( false == isnan(offset) );
776 // GS is documented to be 1.4 degrees thick, 
777 // i.e. plus or minus 0.7 degrees from the midline:
778   _glideslopeOffset_norm = SGMiscd::clip(offset/0.7, -1.0, 1.0);
779 }
780
781 void GS::display( NavIndicator & navIndicator )
782 {
783   if( false == valid() ) {
784     navIndicator.setGS( false );
785     return;
786   }
787   navIndicator.setGS( true );
788   navIndicator.setGS( _glideslopeOffset_norm );
789 }
790
791 /* ------------- A NAV/COMM Frequency formatter ---------------------- */
792
793 class FrequencyFormatter : public SGPropertyChangeListener {
794 public:
795   FrequencyFormatter( SGPropertyNode_ptr freqNode, SGPropertyNode_ptr fmtFreqNode, double channelSpacing ) :
796     _freqNode( freqNode ),
797     _fmtFreqNode( fmtFreqNode ),
798     _channelSpacing(channelSpacing)
799   {
800     _freqNode->addChangeListener( this );
801     valueChanged(_freqNode);
802   }
803   ~FrequencyFormatter()
804   {
805     _freqNode->removeChangeListener( this );
806   }
807
808   void valueChanged (SGPropertyNode * prop)
809   {
810     // format as fixed decimal "nnn.nn"
811     std::ostringstream buf;
812     buf << std::fixed 
813         << std::setw(5) 
814         << std::setfill('0') 
815         << std::setprecision(2)
816         << getFrequency();
817     _fmtFreqNode->setStringValue( buf.str() );
818   }
819
820   double getFrequency() const 
821   {
822     double d = SGMiscd::roundToInt(_freqNode->getDoubleValue() / _channelSpacing) * _channelSpacing;
823     // strip last digit, do not round
824     return ((int)(d*100))/100.0;
825   }
826
827 private:
828   SGPropertyNode_ptr _freqNode;
829   SGPropertyNode_ptr _fmtFreqNode;
830   double _channelSpacing;
831 };
832
833
834 /* ------------- The NavRadio implementation ---------------------- */
835
836 class NavRadioImpl : public NavRadio {
837 public:
838   NavRadioImpl( SGPropertyNode_ptr node );
839   virtual ~NavRadioImpl();
840
841   virtual void update( double dt );
842   virtual void init();
843 private:
844   void search();
845
846   class Legacy {
847   public:
848       Legacy( NavRadioImpl * navRadioImpl ) : _navRadioImpl( navRadioImpl ) {}
849
850       void init();
851       void update( double dt );
852   private:
853       NavRadioImpl * _navRadioImpl;
854       SGPropertyNode_ptr is_valid_node;
855       SGPropertyNode_ptr nav_serviceable_node;
856       SGPropertyNode_ptr nav_id_node;
857       SGPropertyNode_ptr id_c1_node;
858       SGPropertyNode_ptr id_c2_node;
859       SGPropertyNode_ptr id_c3_node;
860       SGPropertyNode_ptr id_c4_node;
861   } _legacy;
862
863   const static int VOR_COMPONENT = 0;
864   const static int LOC_COMPONENT = 1;
865   const static int GS_COMPONENT  = 2;
866
867   std::string _name;
868   int         _num;
869   SGPropertyNode_ptr _rootNode;
870   FrequencyFormatter _useFrequencyFormatter;
871   FrequencyFormatter _stbyFrequencyFormatter;
872   std::vector<NavRadioComponent*> _components;
873   NavIndicator _navIndicator;
874   double _stationTTL;
875   double _frequency;
876   PropertyObject<bool> _cdiDisconnected;
877 };
878
879 NavRadioImpl::NavRadioImpl( SGPropertyNode_ptr node ) :
880   _legacy( this ),
881   _name(node->getStringValue("name", "nav")),
882   _num(node->getIntValue("number", 0)),
883   _rootNode(fgGetNode( string("/instrumentation/") + _name, _num, true)),
884   _useFrequencyFormatter( _rootNode->getNode("frequencies/selected-mhz",true), _rootNode->getNode("frequencies/selected-mhz-fmt",true), 0.05 ),
885   _stbyFrequencyFormatter( _rootNode->getNode("frequencies/standby-mhz",true), _rootNode->getNode("frequencies/standby-mhz-fmt",true), 0.05 ),
886   _navIndicator(_rootNode),
887   _stationTTL(0.0),
888   _frequency(-1.0),
889   _cdiDisconnected(_rootNode->getNode("cdi-disconnected",true))
890 {
891 }
892
893 NavRadioImpl::~NavRadioImpl()
894 {
895   BOOST_FOREACH( NavRadioComponent * p, _components ) {
896     delete p;
897   }
898 }
899
900 void NavRadioImpl::init()
901 {
902   if( 0 < _components.size() )
903     return;
904
905   _components.push_back( new VOR(_rootNode) );
906   _components.push_back( new LOC(_rootNode) );
907   _components.push_back( new GS(_rootNode) );
908
909   _legacy.init();
910 }
911
912 void NavRadioImpl::search()
913 {
914 }
915
916 void NavRadioImpl::update( double dt )
917 {
918   if( dt < SGLimitsd::min() ) return;
919
920   SGGeod position;
921
922   try {
923     position = globals->get_aircraft_position();
924   }
925   catch( std::exception & ) {
926     return;
927   }
928
929   _stationTTL -= dt;
930   if( _frequency != _useFrequencyFormatter.getFrequency() ) {
931       _frequency = _useFrequencyFormatter.getFrequency();
932       _stationTTL = 0.0;
933   }
934
935   BOOST_FOREACH( NavRadioComponent * p, _components ) {
936       if( _stationTTL <= 0.0 )
937           p->search( _frequency, position );
938       p->update( dt, position );
939
940       if( false == _cdiDisconnected )
941           p->display( _navIndicator );
942   }
943
944   if( _stationTTL <= 0.0 )
945       _stationTTL = 30.0;
946
947   _legacy.update( dt );
948 }
949
950 void NavRadioImpl::Legacy::init()
951 {
952     is_valid_node = _navRadioImpl->_rootNode->getChild("data-is-valid", 0, true);
953     nav_serviceable_node = _navRadioImpl->_rootNode->getChild("serviceable", 0, true);
954
955     nav_id_node = _navRadioImpl->_rootNode->getChild("nav-id", 0, true );
956     id_c1_node = _navRadioImpl->_rootNode->getChild("nav-id_asc1", 0, true );
957     id_c2_node = _navRadioImpl->_rootNode->getChild("nav-id_asc2", 0, true );
958     id_c3_node = _navRadioImpl->_rootNode->getChild("nav-id_asc3", 0, true );
959     id_c4_node = _navRadioImpl->_rootNode->getChild("nav-id_asc4", 0, true );
960
961 }
962
963 void NavRadioImpl::Legacy::update( double dt )
964 {
965     is_valid_node->setBoolValue( 
966         _navRadioImpl->_components[VOR_COMPONENT]->valid() || _navRadioImpl->_components[LOC_COMPONENT]->valid()  
967         );
968
969     string ident = _navRadioImpl->_components[VOR_COMPONENT]->getIdent();
970     if( ident.empty() )
971         ident = _navRadioImpl->_components[LOC_COMPONENT]->getIdent();
972
973     nav_id_node->setStringValue( ident );
974
975     ident = simgear::strutils::rpad( ident, 4, ' ' );
976     id_c1_node->setIntValue( (int)ident[0] );
977     id_c2_node->setIntValue( (int)ident[1] );
978     id_c3_node->setIntValue( (int)ident[2] );
979     id_c4_node->setIntValue( (int)ident[3] );
980 }
981
982
983 SGSubsystem * NavRadio::createInstance( SGPropertyNode_ptr rootNode )
984 {
985     // use old navradio code by default
986     if( fgGetBool( "/instrumentation/use-new-navradio", false ) )
987         return new NavRadioImpl( rootNode );
988
989     return new FGNavRadio( rootNode );
990 }
991
992 } // namespace Instrumentation
993