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