]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
Fix max-metar-age, bug #1076.
[flightgear.git] / src / Instrumentation / navradio.cxx
1 // navradio.cxx -- class to manage a nav radio instance
2 //
3 // Written by Curtis Olson, started April 2000.
4 //
5 // Copyright (C) 2000 - 2002  Curtis L. Olson - http://www.flightgear.org/~curt
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
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #include <sstream>
27 #include <cstring>
28 #include <cstdio>
29
30 #include <simgear/sg_inlines.h>
31 #include <simgear/timing/sg_time.hxx>
32 #include <simgear/math/sg_random.h>
33 #include <simgear/misc/sg_path.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/structure/exception.hxx>
36 #include <simgear/math/interpolater.hxx>
37 #include <simgear/misc/strutils.hxx>
38 #include <simgear/sound/sample_group.hxx>
39
40 #include <Navaids/navrecord.hxx>
41 #include <Sound/audioident.hxx>
42 #include <Airports/runways.hxx>
43 #include <Navaids/navlist.hxx>
44 #include <Main/util.hxx>
45
46 #include "navradio.hxx"
47
48 using std::string;
49
50 // General-purpose sawtooth function.  Graph looks like this:
51 //         /\                                    .
52 //       \/
53 // Odd symmetry, inversion symmetry about the origin.
54 // Unit slope at the origin.
55 // Max 1, min -1, period 4.
56 // Two zero-crossings per period, one with + slope, one with - slope.
57 // Useful for false localizer courses.
58 static double sawtooth(double xx)
59 {
60   return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
61 }
62
63 // Calculate a Cartesian unit vector in the
64 // local horizontal plane, i.e. tangent to the 
65 // surface of the earth at the local ground zero.
66 // The tangent vector passes through the given  <midpoint> 
67 // and points forward along the given <heading>.
68 // The <heading> is given in degrees.
69 static SGVec3d tangentVector(const SGGeod& midpoint, const double heading)
70 {
71 // The size of the delta is presumably chosen to give
72 // numerical stability.  I don't know how the value was chosen.
73 // It probably doesn't matter much.  It gets divided out.
74   double delta(100.0);          // in meters
75   SGGeod head, tail;
76   double az2;                   // ignored
77   SGGeodesy::direct(midpoint, heading,     delta, head, az2);
78   SGGeodesy::direct(midpoint, 180+heading, delta, tail, az2);
79   head.setElevationM(midpoint.getElevationM());
80   tail.setElevationM(midpoint.getElevationM());
81   SGVec3d head_xyz = SGVec3d::fromGeod(head);
82   SGVec3d tail_xyz = SGVec3d::fromGeod(tail);
83 // Awkward formula here, needed because vector-by-scalar
84 // multiplication is defined, but not vector-by-scalar division.
85   return (head_xyz - tail_xyz) * (0.5/delta);
86 }
87
88 // Create a "serviceable" node with a default value of "true"
89 SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent, 
90         const char* aName)
91 {
92   SGPropertyNode_ptr n = 
93      aParent->getChild(aName, 0, true)->getChild("serviceable", 0, true);
94   simgear::props::Type typ = n->getType();
95   if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED)) {
96     n->setBoolValue(true);
97   }
98   return n;  
99 }
100
101 static std::auto_ptr<SGInterpTable> static_terminalRangeInterp,
102   static_lowRangeInterp, static_highRangeInterp;
103
104 // Constructor
105 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
106     _operable(false),
107     play_count(0),
108     _last_freq(0.0),
109     target_radial(0.0),
110     effective_range(0.0),
111     target_gs(0.0),
112     twist(0.0),
113     horiz_vel(0.0),
114     last_x(0.0),
115     last_xtrack_error(0.0),
116     xrate_ms(0.0),
117     _localizerWidth(5.0),
118     _name(node->getStringValue("name", "nav")),
119     _num(node->getIntValue("number", 0)),
120     _time_before_search_sec(-1.0),
121     _gsCart(SGVec3d::zeros()),
122     _gsAxis(SGVec3d::zeros()),
123     _gsVertical(SGVec3d::zeros()),
124     _toFlag(false),
125     _fromFlag(false),
126     _cdiDeflection(0.0),
127     _cdiCrossTrackErrorM(0.0),
128     _gsNeedleDeflection(0.0),
129     _gsNeedleDeflectionNorm(0.0),
130     _audioIdent(NULL)
131 {
132     if (!static_terminalRangeInterp.get()) {
133     // one-time interpolator init
134       SGPath path( globals->get_fg_root() );
135       SGPath term = path;
136       term.append( "Navaids/range.term" );
137       SGPath low = path;
138       low.append( "Navaids/range.low" );
139       SGPath high = path;
140       high.append( "Navaids/range.high" );
141       
142       static_terminalRangeInterp.reset(new SGInterpTable(term.str()));
143       static_lowRangeInterp.reset(new SGInterpTable(low.str()));
144       static_highRangeInterp.reset(new SGInterpTable(high.str()));
145     }
146   
147     string branch("/instrumentation/" + _name);
148     _radio_node = fgGetNode(branch.c_str(), _num, true);
149 }
150
151
152 // Destructor
153 FGNavRadio::~FGNavRadio() 
154 {
155     if (gps_course_node) {
156       gps_course_node->removeChangeListener(this);
157     }
158     
159     if (nav_slaved_to_gps_node) {
160       nav_slaved_to_gps_node->removeChangeListener(this);
161     }
162     
163     delete _audioIdent;
164 }
165
166
167 void
168 FGNavRadio::init ()
169 {
170     SGPropertyNode* node = _radio_node.get();
171     bus_power_node = 
172         fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
173
174     // inputs
175     is_valid_node = node->getChild("data-is-valid", 0, true);
176     power_btn_node = node->getChild("power-btn", 0, true);
177     power_btn_node->setBoolValue( true );
178     vol_btn_node = node->getChild("volume", 0, true);
179     ident_btn_node = node->getChild("ident", 0, true);
180     ident_btn_node->setBoolValue( true );
181     audio_btn_node = node->getChild("audio-btn", 0, true);
182     audio_btn_node->setBoolValue( true );
183     backcourse_node = node->getChild("back-course-btn", 0, true);
184     backcourse_node->setBoolValue( false );
185     
186     nav_serviceable_node = node->getChild("serviceable", 0, true);
187     cdi_serviceable_node = createServiceableProp(node, "cdi");
188     gs_serviceable_node = createServiceableProp(node, "gs");
189     tofrom_serviceable_node = createServiceableProp(node, "to-from");
190     
191     falseCoursesEnabledNode = 
192       fgGetNode("/sim/realism/false-radio-courses-enabled");
193     if (!falseCoursesEnabledNode) {
194       falseCoursesEnabledNode = 
195         fgGetNode("/sim/realism/false-radio-courses-enabled", true);
196       falseCoursesEnabledNode->setBoolValue(true);
197     }
198
199     // frequencies
200     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
201     freq_node = subnode->getChild("selected-mhz", 0, true);
202     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
203     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
204     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
205     is_loc_freq_node = subnode->getChild("is-localizer-frequency", 0, true );
206
207     // radials
208     subnode = node->getChild("radials", 0, true);
209     sel_radial_node = subnode->getChild("selected-deg", 0, true);
210     radial_node = subnode->getChild("actual-deg", 0, true);
211     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
212     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
213     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
214
215     // outputs
216     heading_node = node->getChild("heading-deg", 0, true);
217     time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
218     to_flag_node = node->getChild("to-flag", 0, true);
219     from_flag_node = node->getChild("from-flag", 0, true);
220     inrange_node = node->getChild("in-range", 0, true);
221     signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
222     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
223     cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
224     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
225     cdi_xtrack_hdg_err_node
226         = node->getChild("crosstrack-heading-error-deg", 0, true);
227     has_gs_node = node->getChild("has-gs", 0, true);
228     loc_node = node->getChild("nav-loc", 0, true);
229     loc_dist_node = node->getChild("nav-distance", 0, true);
230     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
231     gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
232     gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
233     gs_direct_node = node->getChild("gs-direct-deg", 0, true);
234     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
235     gs_rate_of_climb_fpm_node = node->getChild("gs-rate-of-climb-fpm", 0, true);
236     gs_dist_node = node->getChild("gs-distance", 0, true);
237     gs_inrange_node = node->getChild("gs-in-range", 0, true);
238     
239     nav_id_node = node->getChild("nav-id", 0, true);
240     id_c1_node = node->getChild("nav-id_asc1", 0, true);
241     id_c2_node = node->getChild("nav-id_asc2", 0, true);
242     id_c3_node = node->getChild("nav-id_asc3", 0, true);
243     id_c4_node = node->getChild("nav-id_asc4", 0, true);
244
245     // gps slaving support
246     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
247     nav_slaved_to_gps_node->addChangeListener(this);
248     
249     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
250     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
251     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
252     gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
253     gps_course_node = fgGetNode("/instrumentation/gps/desired-course-deg", true);
254     gps_course_node->addChangeListener(this);
255     
256     gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
257     _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
258     
259     std::ostringstream temp;
260     temp << _name << "-ident-" << _num;
261     if( NULL == _audioIdent ) 
262         _audioIdent = new VORAudioIdent( temp.str() );
263     _audioIdent->init();
264
265     // dme-in-range is deprecated,
266     // temporarily create dme-in-range alias for instrumentation/dme[0]/in-range
267     // remove after flightgear 2.6.0
268     node->getNode( "dme-in-range", true )->alias( fgGetNode("/instrumentation/dme[0]/in-range", true ) );
269 }
270
271 void
272 FGNavRadio::reinit ()
273 {
274     _time_before_search_sec = -1.0;
275 }
276
277 void
278 FGNavRadio::bind ()
279 {
280     _radio_node->tie( "operable", SGRawValueMethods<FGNavRadio,bool>( *this, &FGNavRadio::isOperable ) );
281 }
282
283
284 void
285 FGNavRadio::unbind ()
286 {
287     _radio_node->untie("operable");
288 }
289
290
291 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
292 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
293                                  double nominalRange )
294 {
295     if (nominalRange <= 0.0) {
296       nominalRange = FG_NAV_DEFAULT_RANGE;
297     }
298     
299     // extend out actual usable range to be 1.3x the published safe range
300     const double usability_factor = 1.3;
301
302     // assumptions we model the standard service volume, plus
303     // ... rather than specifying a cylinder, we model a cone that
304     // contains the cylinder.  Then we put an upside down cone on top
305     // to model diminishing returns at too-high altitudes.
306
307     // altitude difference
308     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
309     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
310     //      << " station elev = " << stationElev << endl;
311
312     if ( nominalRange < 25.0 + SG_EPSILON ) {
313       // Standard Terminal Service Volume
314       return static_terminalRangeInterp->interpolate( alt ) * usability_factor;
315     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
316         // Standard Low Altitude Service Volume
317         // table is based on range of 40, scale to actual range
318       return static_lowRangeInterp->interpolate( alt ) * nominalRange / 40.0
319             * usability_factor;
320     } else {
321         // Standard High Altitude Service Volume
322         // table is based on range of 130, scale to actual range
323       return static_highRangeInterp->interpolate( alt ) * nominalRange / 130.0
324             * usability_factor;
325     }
326 }
327
328
329 // model standard ILS service volumes as per AIM 1-1-9
330 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
331                                  double offsetDegrees, double distance )
332 {
333     // assumptions we model the standard service volume, plus
334
335     // altitude difference
336     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
337 //     double offset = fabs( offsetDegrees );
338
339 //     if ( offset < 10 ) {
340 //      return FG_ILS_DEFAULT_RANGE;
341 //     } else if ( offset < 35 ) {
342 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
343 //     } else if ( offset < 45 ) {
344 //      return (45 - offset);
345 //     } else if ( offset > 170 ) {
346 //         return FG_ILS_DEFAULT_RANGE;
347 //     } else if ( offset > 145 ) {
348 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
349 //     } else if ( offset > 135 ) {
350 //         return (offset - 135);
351 //     } else {
352 //      return 0;
353 //     }
354     return FG_LOC_DEFAULT_RANGE;
355 }
356
357 // Frequencies with odd 100kHz numbers in the range from 108.00 - 111.95
358 // are LOC/GS (ILS) frequency pairs
359 // (108.00, 108.05, 108.20, 108.25.. =VOR)
360 // (108.10, 108.15, 108.30, 108.35.. =ILS)
361 static inline bool IsLocalizerFrequency( double f )
362 {
363   if( f < 108.0 || f >= 112.00 ) return false;
364   return (((SGMiscd::roundToInt(f * 100.0) % 100)/10) % 2) != 0;
365 }
366
367
368 //////////////////////////////////////////////////////////////////////////
369 // Update the various nav values based on position and valid tuned in navs
370 //////////////////////////////////////////////////////////////////////////
371 void 
372 FGNavRadio::update(double dt) 
373 {
374   if (dt <= 0.0) {
375     return; // paused
376   }
377     
378   // Create "formatted" versions of the nav frequencies for
379   // instrument displays.
380   char tmp[16];
381   sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
382   fmt_freq_node->setStringValue(tmp);
383   sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
384   fmt_alt_freq_node->setStringValue(tmp);
385   is_loc_freq_node->setBoolValue( IsLocalizerFrequency( freq_node->getDoubleValue() ));
386
387   if (power_btn_node->getBoolValue() 
388       && (bus_power_node->getDoubleValue() > 1.0)
389       && nav_serviceable_node->getBoolValue() )
390   {
391     _operable = true;
392     updateReceiver(dt);
393     updateCDI(dt);
394   } else {
395     clearOutputs();
396   }
397   
398   updateAudio( dt );
399 }
400
401 void FGNavRadio::clearOutputs()
402 {
403   inrange_node->setBoolValue( false );
404   signal_quality_norm_node->setDoubleValue( 0.0 );
405   cdi_deflection_node->setDoubleValue( 0.0 );
406   cdi_deflection_norm_node->setDoubleValue( 0.0 );
407   cdi_xtrack_error_node->setDoubleValue( 0.0 );
408   cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
409   time_to_intercept->setDoubleValue( 0.0 );
410   heading_node->setDoubleValue(0.0);
411   gs_deflection_node->setDoubleValue( 0.0 );
412   gs_deflection_deg_node->setDoubleValue(0.0);
413   gs_deflection_norm_node->setDoubleValue(0.0);
414   gs_direct_node->setDoubleValue(0.0);
415   gs_inrange_node->setBoolValue( false );
416   loc_node->setBoolValue( false );
417   has_gs_node->setBoolValue(false);
418   
419   to_flag_node->setBoolValue( false );
420   from_flag_node->setBoolValue( false );
421   is_valid_node->setBoolValue(false);
422   nav_id_node->setStringValue("");
423   
424   _operable = false;
425   _navaid = NULL;
426 }
427
428 void FGNavRadio::updateReceiver(double dt)
429 {
430   SGVec3d aircraft = SGVec3d::fromGeod(globals->get_aircraft_position());
431   double loc_dist = 0;
432
433   // Do a nav station search only once a second to reduce
434   // unnecessary work. (Also, make sure to do this before caching
435   // any values!)
436   _time_before_search_sec -= dt;
437   if ( _time_before_search_sec < 0 ) {
438    search();
439   }
440
441   if (_navaid)
442   {
443       loc_dist = dist(aircraft, _navaid->cart());
444       loc_dist_node->setDoubleValue( loc_dist );
445   }
446
447   if (nav_slaved_to_gps_node->getBoolValue()) {
448     // when slaved to GPS: only allow stuff above: tune NAV station
449     // All other data driven by GPS only.
450     updateGPSSlaved();
451     return;
452   }
453
454   if (!_navaid) {
455     _cdiDeflection = 0.0;
456     _cdiCrossTrackErrorM = 0.0;
457     _toFlag = _fromFlag = false;
458     _gsNeedleDeflection = 0.0;
459     _gsNeedleDeflectionNorm = 0.0;
460     heading_node->setDoubleValue(0.0);
461     inrange_node->setBoolValue(false);
462     signal_quality_norm_node->setDoubleValue(0.0);
463     gs_dist_node->setDoubleValue( 0.0 );
464     gs_inrange_node->setBoolValue(false);
465     return;
466   }
467
468   double nav_elev = _navaid->get_elev_ft();
469
470   bool is_loc = loc_node->getBoolValue();
471   double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
472   
473   double az2, s;
474   //////////////////////////////////////////////////////////
475         // compute forward and reverse wgs84 headings to localizer
476   //////////////////////////////////////////////////////////
477   double hdg;
478   SGGeodesy::inverse(globals->get_aircraft_position(), _navaid->geod(), hdg, az2, s);
479   heading_node->setDoubleValue(hdg);
480   double radial = az2 - twist;
481   double recip = radial + 180.0;
482   SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
483   radial_node->setDoubleValue( radial );
484   recip_radial_node->setDoubleValue( recip );
485   
486   //////////////////////////////////////////////////////////
487   // compute the target/selected radial in "true" heading
488   //////////////////////////////////////////////////////////
489   if (!is_loc) {
490     target_radial = sel_radial_node->getDoubleValue();
491   }
492   
493   // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
494   double trtrue = target_radial + twist;
495   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
496   target_radial_true_node->setDoubleValue( trtrue );
497
498   //////////////////////////////////////////////////////////
499   // adjust reception range for altitude
500   // FIXME: make sure we are using the navdata range now that
501   //        it is valid in the data file
502   //////////////////////////////////////////////////////////
503         if ( is_loc ) {
504             double offset = radial - target_radial;
505       SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
506             effective_range
507                 = adjustILSRange( nav_elev, globals->get_aircraft_position().getElevationM(), offset,
508                                   loc_dist * SG_METER_TO_NM );
509         } else {
510             effective_range
511                 = adjustNavRange( nav_elev, globals->get_aircraft_position().getElevationM(), _navaid->get_range() );
512         }
513   
514   double effective_range_m = effective_range * SG_NM_TO_METER;
515
516   //////////////////////////////////////////////////////////
517   // compute signal quality
518   // 100% within effective_range
519   // decreases 1/x^2 further out
520   //////////////////////////////////////////////////////////  
521   double last_signal_quality_norm = signal_quality_norm;
522
523   if ( loc_dist < effective_range_m ) {
524     signal_quality_norm = 1.0;
525   } else {
526     double range_exceed_norm = loc_dist/effective_range_m;
527     signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
528   }
529
530   signal_quality_norm = fgGetLowPass( last_signal_quality_norm, 
531            signal_quality_norm, dt );
532   
533   signal_quality_norm_node->setDoubleValue( signal_quality_norm );
534   bool inrange = signal_quality_norm > 0.2;
535   inrange_node->setBoolValue( inrange );
536   
537   //////////////////////////////////////////////////////////
538   // compute to/from flag status
539   //////////////////////////////////////////////////////////
540   if (inrange) {
541     if (is_loc) {
542       _toFlag = true;
543     } else {
544       double offset = fabs(radial - target_radial);
545       _toFlag = (offset > 90.0 && offset < 270.0);
546     }
547     _fromFlag = !_toFlag;
548   } else {
549     _toFlag = _fromFlag = false;
550   }
551   
552   // CDI deflection
553   double r = target_radial - radial;
554   SG_NORMALIZE_RANGE(r, -180.0, 180.0);
555   
556   if ( is_loc ) {
557     if (falseCoursesEnabledNode->getBoolValue()) {
558       // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six 
559       // zeros i.e. six courses: one front course, one back course, and four 
560       // false courses. Three of the six are reverse sensing.
561       _cdiDeflection = 30.0 * sawtooth(r / 30.0);
562     } else {
563       // no false courses, but we do need to create a back course
564       if (fabs(r) > 90.0) { // front course
565         _cdiDeflection = r - copysign(180.0, r);
566       } else {
567         _cdiDeflection = r; // back course
568       }
569       
570       _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
571     } // of false courses disabled
572     
573     const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
574     _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localizer sensitivity
575     
576     if (backcourse_node->getBoolValue()) {
577       _cdiDeflection = -_cdiDeflection;
578     }
579   } else {
580     // handle the TO side of the VOR
581     if (fabs(r) > 90.0) {
582       r = ( r<0.0 ? -r-180.0 : -r+180.0 );
583     }
584     _cdiDeflection = r;
585   } // of non-localizer case
586   
587   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
588   _cdiDeflection *= signal_quality_norm;
589   
590   // cross-track error (in meters)
591   _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
592   
593   updateGlideSlope(dt, aircraft, signal_quality_norm);
594 }
595
596 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
597 {
598   bool gsInRange = (_gs && inrange_node->getBoolValue());
599   double gsDist = 0;
600
601   if (gsInRange)
602   {
603     gsDist = dist(aircraft, _gsCart);
604     gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
605   }
606
607   gs_inrange_node->setBoolValue(gsInRange);
608   gs_dist_node->setDoubleValue( gsDist );
609
610   if (!gsInRange)
611   {
612     _gsNeedleDeflection = 0.0;
613     _gsNeedleDeflectionNorm = 0.0;
614     return;
615   }
616   
617   SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
618   // The positive GS axis points along the runway in the landing direction,
619   // toward the far end, not toward the approach area, so we need a - sign here:
620   double comp_h = -dot(pos, _gsAxis);      // component in horiz direction
621   double comp_v = dot(pos, _gsVertical);   // component in vertical direction
622   //double comp_b = dot(pos, _gsBaseline);   // component in baseline direction
623   //if (comp_b) {}                           // ... (useful for debugging)
624
625 // _gsDirect represents the angle of elevation of the aircraft
626 // as seen by the GS transmitter.
627   _gsDirect = atan2(comp_v, comp_h) * SGD_RADIANS_TO_DEGREES;
628 // At this point, if the aircraft is centered on the glide slope,
629 // _gsDirect will be a small positive number, e.g. 3.0 degrees
630
631 // Aim the branch cut straight down 
632 // into the ground below the GS transmitter:
633   if (_gsDirect < -90.0) _gsDirect += 360.0;
634
635   double deflectionAngle = target_gs - _gsDirect;
636   
637   if (falseCoursesEnabledNode->getBoolValue()) {
638     // Construct false glideslopes.  The scale factor of 1.5 
639     // in the sawtooth gives a period of 6 degrees.
640     // There will be zeros at 3, 6r, 9, 12r et cetera
641     // where "r" indicates reverse sensing.
642     // This is is consistent with conventional pilot lore
643     // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
644     // but inconsistent with
645     // http://www.freepatentsonline.com/3757338.html
646     //
647     // It may be that some of each exist.
648     if (deflectionAngle < 0) {
649       deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
650     } else {
651       // no false GS below the true GS
652     }
653   }
654   
655 // GS is documented to be 1.4 degrees thick, 
656 // i.e. plus or minus 0.7 degrees from the midline:
657   SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
658
659 // Many older instrument xml frontends depend on
660 // the un-normalized gs-needle-deflection.
661 // Apparently the interface standard is plus or minus 3.5 "volts"
662 // for a full-scale deflection:
663   _gsNeedleDeflection = deflectionAngle * 5.0;
664   _gsNeedleDeflection *= signal_quality_norm;
665   
666   _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
667   
668   //////////////////////////////////////////////////////////
669   // Calculate desired rate of climb for intercepting the GS
670   //////////////////////////////////////////////////////////
671   double gs_diff = target_gs - _gsDirect;
672   // convert desired vertical path angle into a climb rate
673   double des_angle = _gsDirect - 10 * gs_diff;
674   /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
675      target_gs, _gsDirect, gs_diff, des_angle); */
676
677   // estimate horizontal speed towards ILS in meters per minute
678   double elapsedDistance = last_x - gsDist;
679   last_x = gsDist;
680       
681   double new_vel = ( elapsedDistance / dt );
682   horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
683   /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
684
685   gs_rate_of_climb_node
686       ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
687                         * horiz_vel * SG_METER_TO_FEET );
688   gs_rate_of_climb_fpm_node
689       ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
690 }
691
692 void FGNavRadio::valueChanged (SGPropertyNode* prop)
693 {
694   if (prop == gps_course_node) {
695     if (!nav_slaved_to_gps_node->getBoolValue()) {
696       return;
697     }
698   
699     // GPS desired course has changed, sync up our selected-course
700     double v = prop->getDoubleValue();
701     if (v != sel_radial_node->getDoubleValue()) {
702       sel_radial_node->setDoubleValue(v);
703     }
704   } else if (prop == nav_slaved_to_gps_node) {
705     if (prop->getBoolValue()) {
706       // slaved-to-GPS activated, clear obsolete NAV outputs and sync up selected course
707       clearOutputs();
708       sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
709     }
710     // slave-to-GPS enabled/disabled, resync NAV station (update all outputs)
711     _navaid = NULL;
712     _time_before_search_sec = 0;
713   }
714 }
715
716 void FGNavRadio::updateGPSSlaved()
717 {
718   has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
719  
720   _toFlag = gps_to_flag_node->getBoolValue();
721   _fromFlag = gps_from_flag_node->getBoolValue();
722
723   bool gpsValid = (_toFlag | _fromFlag);
724   inrange_node->setBoolValue(gpsValid);
725   if (!gpsValid) {
726     signal_quality_norm_node->setDoubleValue(0.0);
727     _cdiDeflection = 0.0;
728     _cdiCrossTrackErrorM = 0.0;
729     _gsNeedleDeflection = 0.0;
730     _gsNeedleDeflectionNorm = 0.0;
731     return;
732   }
733   
734   // this is unfortunate, but panel instruments use this value to decide
735   // if the navradio output is valid.
736   signal_quality_norm_node->setDoubleValue(1.0);
737   
738   _cdiDeflection =  gps_cdi_deflection_node->getDoubleValue();
739   // clmap to some range (+/- 10 degrees) as the regular deflection
740   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
741   
742   _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
743   _gsNeedleDeflection = 0.0; // FIXME, supply this
744   
745   double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
746   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
747   target_radial_true_node->setDoubleValue( trtrue );
748 }
749
750 void FGNavRadio::updateCDI(double dt)
751 {
752   bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
753   bool inrange = inrange_node->getBoolValue();
754                                
755   if (tofrom_serviceable_node->getBoolValue()) {
756     to_flag_node->setBoolValue(_toFlag);
757     from_flag_node->setBoolValue(_fromFlag);
758   } else {
759     to_flag_node->setBoolValue(false);
760     from_flag_node->setBoolValue(false);
761   }
762   
763   if (!cdi_serviceable) {
764     _cdiDeflection = 0.0;
765     _cdiCrossTrackErrorM = 0.0;
766   }
767   
768   cdi_deflection_node->setDoubleValue(_cdiDeflection);
769   cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
770   cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
771
772   //////////////////////////////////////////////////////////
773   // compute an approximate ground track heading error
774   //////////////////////////////////////////////////////////
775   double hdg_error = 0.0;
776   if ( inrange && cdi_serviceable ) {
777     double vn = fgGetDouble( "/velocities/speed-north-fps" );
778     double ve = fgGetDouble( "/velocities/speed-east-fps" );
779     double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
780     if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
781
782     SGPropertyNode *true_hdg
783         = fgGetNode("/orientation/heading-deg", true);
784     hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
785
786     // cout << "ground track = " << gnd_trk_true
787     //      << " orientation = " << true_hdg->getDoubleValue() << endl;
788   }
789   cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
790
791   //////////////////////////////////////////////////////////
792   // Calculate a suggested target heading to smoothly intercept
793   // a nav/ils radial.
794   //////////////////////////////////////////////////////////
795
796   // Now that we have cross track heading adjustment built in,
797   // we shouldn't need to overdrive the heading angle within 8km
798   // of the station.
799   //
800   // The cdi deflection should be +/-10 for a full range of deflection
801   // so multiplying this by 3 gives us +/- 30 degrees heading
802   // compensation.
803   double adjustment = _cdiDeflection * 3.0;
804   SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
805
806   // determine the target heading to fly to intercept the
807   // tgt_radial = target radial (true) + cdi offset adjustment -
808   // xtrack heading error adjustment
809   double nta_hdg;
810   double trtrue = target_radial_true_node->getDoubleValue();
811   if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
812       // tuned to a localizer and backcourse mode activated
813       trtrue += 180.0;   // reverse the target localizer heading
814       SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
815       nta_hdg = trtrue - adjustment - hdg_error;
816   } else {
817       nta_hdg = trtrue + adjustment - hdg_error;
818   }
819
820   SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
821   target_auto_hdg_node->setDoubleValue( nta_hdg );
822
823   //////////////////////////////////////////////////////////
824   // compute the time to intercept selected radial (based on
825   // current and last cross track errors and dt)
826   //////////////////////////////////////////////////////////
827   double t = 0.0;
828   if ( inrange && cdi_serviceable ) {
829     double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
830     xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
831     if ( fabs(xrate_ms) > 0.00001 ) {
832         t = _cdiCrossTrackErrorM / xrate_ms;
833     } else {
834         t = 9999.9;
835     }
836   }
837   time_to_intercept->setDoubleValue( t );
838
839   if (!gs_serviceable_node->getBoolValue() ) {
840     _gsNeedleDeflection = 0.0;
841     _gsNeedleDeflectionNorm = 0.0;
842   }
843   gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
844   gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
845   gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
846   gs_direct_node->setDoubleValue(_gsDirect);
847   
848   last_xtrack_error = _cdiCrossTrackErrorM;
849 }
850
851 void FGNavRadio::updateAudio( double dt )
852 {
853   if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
854     _audioIdent->setIdent("", 0.0 );
855     return;
856   }
857   
858         // play station ident via audio system if on + ident,
859         // otherwise turn it off
860   if (!power_btn_node->getBoolValue()
861       || !(bus_power_node->getDoubleValue() > 1.0)
862       || !ident_btn_node->getBoolValue()
863       || !audio_btn_node->getBoolValue() ) {
864     _audioIdent->setIdent("", 0.0 );
865     return;
866   }
867
868   _audioIdent->setIdent( _navaid->get_trans_ident(), vol_btn_node->getFloatValue() );
869
870   _audioIdent->update( dt );
871 }
872
873 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
874 {
875   return FGNavList::findByFreq(aFreqMHz, aPos, FGNavList::navFilter());
876 }
877
878 // Update current nav/adf radio stations based on current position
879 void FGNavRadio::search() 
880 {
881   // set delay for next search
882   _time_before_search_sec = 1.0;
883
884   double freq = freq_node->getDoubleValue();
885
886   // immediate NAV search when frequency has changed (toggle between nav and g/s search otherwise)
887   _nav_search |= (_last_freq != freq);
888
889   // do we need to search a new NAV station in this iteration?
890   if (_nav_search)
891   {
892       _last_freq = freq;
893       FGNavRecord* nav = findPrimaryNavaid(globals->get_aircraft_position(), freq);
894       if (nav == _navaid) {
895         if (nav && (nav->type() != FGPositioned::VOR))
896             _nav_search = false;  // search glideslope on next iteration
897         return; // nav hasn't changed, we're done
898       }
899       // remember new navaid station
900       _navaid = nav;
901   }
902
903   // search glideslope station
904   if ((_navaid.valid()) && (_navaid->type() != FGPositioned::VOR))
905   {
906     FGNavList::TypeFilter gsFilter(FGPositioned::GS);
907     FGNavRecord* gs = FGNavList::findByFreq(freq, globals->get_aircraft_position(),
908                                            &gsFilter);
909       if ((!_nav_search) && (gs == _gs))
910       {
911           _nav_search = true; // search NAV on next iteration
912           return; // g/s hasn't changed, neither has nav - we're done
913       }
914       // remember new glideslope station
915       _gs = gs;
916   }
917
918   _nav_search = true; // search NAV on next iteration
919
920   // nav or gs station has changed
921   updateNav();
922 }
923
924 // Update current nav/adf/glideslope outputs when station has changed
925 void FGNavRadio::updateNav()
926 {
927   // update necessary, nav and/or gs has changed
928   FGNavRecord* nav = _navaid;
929   string identBuffer(4, ' ');
930   if (nav) {
931     nav_id_node->setStringValue(nav->get_ident());
932     identBuffer =  simgear::strutils::rpad( nav->ident(), 4, ' ' );
933     
934     effective_range = adjustNavRange(nav->get_elev_ft(), globals->get_aircraft_position().getElevationM(), nav->get_range());
935     loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
936     twist = nav->get_multiuse();
937
938     if (nav->type() == FGPositioned::VOR) {
939       target_radial = sel_radial_node->getDoubleValue();
940       _gs = NULL;
941     } else { // ILS or LOC
942       _localizerWidth = nav->localizerWidth();
943       twist = 0.0;
944       effective_range = nav->get_range();
945       
946       target_radial = nav->get_multiuse();
947       SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
948
949       if (_gs) {
950         int tmp = (int)(_gs->get_multiuse() / 1000.0);
951         target_gs = (double)tmp / 100.0;
952
953         double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
954         SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
955         _gsCart = _gs->cart();
956                 
957         // GS axis unit tangent vector 
958         // (along the runway):
959         _gsAxis = tangentVector(_gs->geod(), gs_radial);
960
961         // GS baseline unit tangent vector
962         // (transverse to the runway along the ground)
963         _gsBaseline = tangentVector(_gs->geod(), gs_radial + 90.0);
964         _gsVertical = cross(_gsBaseline, _gsAxis);
965       } // of have glideslope
966     } // of found LOC or ILS
967     
968   } else { // found nothing
969     _gs = NULL;
970     nav_id_node->setStringValue("");
971     loc_node->setBoolValue(false);
972     _audioIdent->setIdent("", 0.0 );
973   }
974
975   has_gs_node->setBoolValue(_gs != NULL);
976   is_valid_node->setBoolValue(nav != NULL);
977   id_c1_node->setIntValue( (int)identBuffer[0] );
978   id_c2_node->setIntValue( (int)identBuffer[1] );
979   id_c3_node->setIntValue( (int)identBuffer[2] );
980   id_c4_node->setIntValue( (int)identBuffer[3] );
981 }