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