]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
Mark's dynamic sun color changes.
[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 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <iostream>
29 #include <string>
30 #include <sstream>
31
32 #include <simgear/compiler.h>
33 #include <simgear/sg_inlines.h>
34 #include <simgear/math/sg_random.h>
35 #include <simgear/math/vector.hxx>
36
37 #include <Aircraft/aircraft.hxx>
38 #include <Navaids/navlist.hxx>
39
40 #include "navradio.hxx"
41
42 #include <string>
43 SG_USING_STD(string);
44
45
46 // Constructor
47 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
48     lon_node(fgGetNode("/position/longitude-deg", true)),
49     lat_node(fgGetNode("/position/latitude-deg", true)),
50     alt_node(fgGetNode("/position/altitude-ft", true)),
51     is_valid_node(NULL),
52     power_btn_node(NULL),
53     freq_node(NULL),
54     alt_freq_node(NULL),
55     sel_radial_node(NULL),
56     vol_btn_node(NULL),
57     ident_btn_node(NULL),
58     audio_btn_node(NULL),
59     backcourse_node(NULL),
60     nav_serviceable_node(NULL),
61     cdi_serviceable_node(NULL),
62     gs_serviceable_node(NULL),
63     tofrom_serviceable_node(NULL),
64     fmt_freq_node(NULL),
65     fmt_alt_freq_node(NULL),
66     heading_node(NULL),
67     radial_node(NULL),
68     recip_radial_node(NULL),
69     target_radial_true_node(NULL),
70     target_auto_hdg_node(NULL),
71     time_to_intercept(NULL),
72     to_flag_node(NULL),
73     from_flag_node(NULL),
74     inrange_node(NULL),
75     cdi_deflection_node(NULL),
76     cdi_xtrack_error_node(NULL),
77     cdi_xtrack_hdg_err_node(NULL),
78     has_gs_node(NULL),
79     loc_node(NULL),
80     loc_dist_node(NULL),
81     gs_deflection_node(NULL),
82     gs_rate_of_climb_node(NULL),
83     gs_dist_node(NULL),
84     nav_id_node(NULL),
85     id_c1_node(NULL),
86     id_c2_node(NULL),
87     id_c3_node(NULL),
88     id_c4_node(NULL),
89     nav_slaved_to_gps_node(NULL),
90     gps_cdi_deflection_node(NULL),
91     gps_to_flag_node(NULL),
92     gps_from_flag_node(NULL),
93     last_nav_id(""),
94     last_nav_vor(false),
95     play_count(0),
96     last_time(0),
97     radial(0.0),
98     target_radial(0.0),
99     horiz_vel(0.0),
100     last_x(0.0),
101     last_loc_dist(0.0),
102     last_xtrack_error(0.0),
103     name("nav"),
104     num(0),
105     _time_before_search_sec(-1.0)
106 {
107     SGPath path( globals->get_fg_root() );
108     SGPath term = path;
109     term.append( "Navaids/range.term" );
110     SGPath low = path;
111     low.append( "Navaids/range.low" );
112     SGPath high = path;
113     high.append( "Navaids/range.high" );
114
115     term_tbl = new SGInterpTable( term.str() );
116     low_tbl = new SGInterpTable( low.str() );
117     high_tbl = new SGInterpTable( high.str() );
118
119     int i;
120     for ( i = 0; i < node->nChildren(); ++i ) {
121         SGPropertyNode *child = node->getChild(i);
122         string cname = child->getName();
123         string cval = child->getStringValue();
124         if ( cname == "name" ) {
125             name = cval;
126         } else if ( cname == "number" ) {
127             num = child->getIntValue();
128         } else {
129             SG_LOG( SG_INSTR, SG_WARN, 
130                     "Error in nav radio config logic" );
131             if ( name.length() ) {
132                 SG_LOG( SG_INSTR, SG_WARN, "Section = " << name );
133             }
134         }
135     }
136
137 }
138
139
140 // Destructor
141 FGNavRadio::~FGNavRadio() 
142 {
143     delete term_tbl;
144     delete low_tbl;
145     delete high_tbl;
146 }
147
148
149 void
150 FGNavRadio::init ()
151 {
152     morse.init();
153
154     string branch;
155     branch = "/instrumentation/" + name;
156
157     SGPropertyNode *node = fgGetNode(branch.c_str(), num, true );
158
159     bus_power_node = 
160         fgGetNode(("/systems/electrical/outputs/" + name).c_str(), true);
161
162     // inputs
163     is_valid_node = node->getChild("data-is-valid", 0, true);
164     power_btn_node = node->getChild("power-btn", 0, true);
165     power_btn_node->setBoolValue( true );
166     vol_btn_node = node->getChild("volume", 0, true);
167     ident_btn_node = node->getChild("ident", 0, true);
168     ident_btn_node->setBoolValue( true );
169     audio_btn_node = node->getChild("audio-btn", 0, true);
170     audio_btn_node->setBoolValue( true );
171     backcourse_node = node->getChild("back-course-btn", 0, true);
172     backcourse_node->setBoolValue( false );
173     nav_serviceable_node = node->getChild("serviceable", 0, true);
174     cdi_serviceable_node = (node->getChild("cdi", 0, true))
175         ->getChild("serviceable", 0, true);
176     gs_serviceable_node = (node->getChild("gs", 0, true))
177         ->getChild("serviceable");
178     tofrom_serviceable_node = (node->getChild("to-from", 0, true))
179         ->getChild("serviceable", 0, true);
180
181     // frequencies
182     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
183     freq_node = subnode->getChild("selected-mhz", 0, true);
184     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
185     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
186     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
187
188     // radials
189     subnode = node->getChild("radials", 0, true);
190     sel_radial_node = subnode->getChild("selected-deg", 0, true);
191     radial_node = subnode->getChild("actual-deg", 0, true);
192     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
193     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
194     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
195
196     // outputs
197     heading_node = node->getChild("heading-deg", 0, true);
198     time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
199     to_flag_node = node->getChild("to-flag", 0, true);
200     from_flag_node = node->getChild("from-flag", 0, true);
201     inrange_node = node->getChild("in-range", 0, true);
202     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
203     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
204     cdi_xtrack_hdg_err_node
205         = node->getChild("crosstrack-heading-error-deg", 0, true);
206     has_gs_node = node->getChild("has-gs", 0, true);
207     loc_node = node->getChild("nav-loc", 0, true);
208     loc_dist_node = node->getChild("nav-distance", 0, true);
209     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
210     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
211     gs_dist_node = node->getChild("gs-distance", 0, true);
212     nav_id_node = node->getChild("nav-id", 0, true);
213     id_c1_node = node->getChild("nav-id_asc1", 0, true);
214     id_c2_node = node->getChild("nav-id_asc2", 0, true);
215     id_c3_node = node->getChild("nav-id_asc3", 0, true);
216     id_c4_node = node->getChild("nav-id_asc4", 0, true);
217
218     // gps slaving support
219     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
220     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
221     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
222     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
223     
224     std::ostringstream temp;
225     temp << name << "nav-ident" << num;
226     nav_fx_name = temp.str();
227     temp << name << "dme-ident" << num;
228     dme_fx_name = temp.str();
229 }
230
231 void
232 FGNavRadio::bind ()
233 {
234     std::ostringstream temp;
235     string branch;
236     temp << num;
237     branch = "/instrumentation/" + name + "[" + temp.str() + "]";
238 }
239
240
241 void
242 FGNavRadio::unbind ()
243 {
244     std::ostringstream temp;
245     string branch;
246     temp << num;
247     branch = "/instrumentation/" + name + "[" + temp.str() + "]";
248 }
249
250
251 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
252 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
253                                  double nominalRange )
254 {
255     // extend out actual usable range to be 1.3x the published safe range
256     const double usability_factor = 1.3;
257
258     // assumptions we model the standard service volume, plus
259     // ... rather than specifying a cylinder, we model a cone that
260     // contains the cylinder.  Then we put an upside down cone on top
261     // to model diminishing returns at too-high altitudes.
262
263     // altitude difference
264     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
265     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
266     //      << " station elev = " << stationElev << endl;
267
268     if ( nominalRange < 25.0 + SG_EPSILON ) {
269         // Standard Terminal Service Volume
270         return term_tbl->interpolate( alt ) * usability_factor;
271     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
272         // Standard Low Altitude Service Volume
273         // table is based on range of 40, scale to actual range
274         return low_tbl->interpolate( alt ) * nominalRange / 40.0
275             * usability_factor;
276     } else {
277         // Standard High Altitude Service Volume
278         // table is based on range of 130, scale to actual range
279         return high_tbl->interpolate( alt ) * nominalRange / 130.0
280             * usability_factor;
281     }
282 }
283
284
285 // model standard ILS service volumes as per AIM 1-1-9
286 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
287                                  double offsetDegrees, double distance )
288 {
289     // assumptions we model the standard service volume, plus
290
291     // altitude difference
292     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
293 //     double offset = fabs( offsetDegrees );
294
295 //     if ( offset < 10 ) {
296 //      return FG_ILS_DEFAULT_RANGE;
297 //     } else if ( offset < 35 ) {
298 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
299 //     } else if ( offset < 45 ) {
300 //      return (45 - offset);
301 //     } else if ( offset > 170 ) {
302 //         return FG_ILS_DEFAULT_RANGE;
303 //     } else if ( offset > 145 ) {
304 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
305 //     } else if ( offset > 135 ) {
306 //         return (offset - 135);
307 //     } else {
308 //      return 0;
309 //     }
310     return FG_LOC_DEFAULT_RANGE;
311 }
312
313
314 //////////////////////////////////////////////////////////////////////////
315 // Update the various nav values based on position and valid tuned in navs
316 //////////////////////////////////////////////////////////////////////////
317 void 
318 FGNavRadio::update(double dt) 
319 {
320     // Do a nav station search only once a second to reduce
321     // unnecessary work. (Also, make sure to do this before caching
322     // any values!)
323     _time_before_search_sec -= dt;
324     if ( _time_before_search_sec < 0 ) {
325         search();
326     }
327
328     // cache a few strategic values locally for speed
329     SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
330                                    lat_node->getDoubleValue(),
331                                    alt_node->getDoubleValue());
332     bool power_btn = power_btn_node->getBoolValue();
333     bool nav_serviceable = nav_serviceable_node->getBoolValue();
334     bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
335     bool tofrom_serviceable = tofrom_serviceable_node->getBoolValue();
336     bool inrange = inrange_node->getBoolValue();
337     bool has_gs = has_gs_node->getBoolValue();
338     bool is_loc = loc_node->getBoolValue();
339     double loc_dist = loc_dist_node->getDoubleValue();
340
341     double az1, az2, s;
342
343     // Create "formatted" versions of the nav frequencies for
344     // instrument displays.
345     char tmp[16];
346     sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
347     fmt_freq_node->setStringValue(tmp);
348     sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
349     fmt_alt_freq_node->setStringValue(tmp);
350
351     // cout << "is_valid = " << is_valid
352     //      << " power_btn = " << power_btn
353     //      << " bus_power = " << bus_power_node->getDoubleValue()
354     //      << " nav_serviceable = " << nav_serviceable
355     //      << endl;
356
357     if ( is_valid && power_btn && (bus_power_node->getDoubleValue() > 1.0)
358          && nav_serviceable )
359     {
360         SGVec3d aircraft = SGVec3d::fromGeod(pos);
361         loc_dist = dist(aircraft, nav_xyz);
362         loc_dist_node->setDoubleValue( loc_dist );
363         // cout << "dt = " << dt << " dist = " << loc_dist << endl;
364
365         if ( has_gs ) {
366             // find closest distance to the gs base line
367             SGVec3d p = aircraft;
368             double dist = sgdClosestPointToLineDistSquared(p.sg(), gs_xyz.sg(),
369                                                            gs_base_vec.sg());
370             gs_dist_node->setDoubleValue( sqrt( dist ) );
371             // cout << "gs_dist = " << gs_dist_node->getDoubleValue()
372             //      << endl;
373
374             // wgs84 heading to glide slope (to determine sign of distance)
375             geo_inverse_wgs_84( pos, SGGeod::fromDeg(gs_lon, gs_lat),
376                                 &az1, &az2, &s );
377             double r = az1 - target_radial;
378             while ( r >  180.0 ) { r -= 360.0;}
379             while ( r < -180.0 ) { r += 360.0;}
380             if ( r >= -90.0 && r <= 90.0 ) {
381                 gs_dist_signed = gs_dist_node->getDoubleValue();
382             } else {
383                 gs_dist_signed = -gs_dist_node->getDoubleValue();
384             }
385             /* cout << "Target Radial = " << target_radial 
386                  << "  Bearing = " << az1
387                  << "  dist (signed) = " << gs_dist_signed
388                  << endl; */
389             
390         } else {
391             gs_dist_node->setDoubleValue( 0.0 );
392         }
393         
394         //////////////////////////////////////////////////////////
395         // compute forward and reverse wgs84 headings to localizer
396         //////////////////////////////////////////////////////////
397         double hdg;
398         geo_inverse_wgs_84( pos, SGGeod::fromDeg(loc_lon, loc_lat),
399                             &hdg, &az2, &s );
400         // cout << "az1 = " << az1 << " magvar = " << nav_magvar << endl;
401         heading_node->setDoubleValue( hdg );
402         radial = az2 - twist;
403         double recip = radial + 180.0;
404         if ( recip >= 360.0 ) { recip -= 360.0; }
405         radial_node->setDoubleValue( radial );
406         recip_radial_node->setDoubleValue( recip );
407         // cout << " heading = " << heading_node->getDoubleValue()
408         //      << " dist = " << nav_dist << endl;
409
410         //////////////////////////////////////////////////////////
411         // compute the target/selected radial in "true" heading
412         //////////////////////////////////////////////////////////
413         double trtrue = 0.0;
414         if ( is_loc ) {
415             // ILS localizers radials are already "true" in our
416             // database
417             trtrue = target_radial;
418         } else {
419             // VOR radials need to have that vor's offset added in
420             trtrue = target_radial + twist;
421         }
422
423         while ( trtrue < 0.0 ) { trtrue += 360.0; }
424         while ( trtrue > 360.0 ) { trtrue -= 360.0; }
425         target_radial_true_node->setDoubleValue( trtrue );
426
427         //////////////////////////////////////////////////////////
428         // adjust reception range for altitude
429         // FIXME: make sure we are using the navdata range now that
430         //        it is valid in the data file
431         //////////////////////////////////////////////////////////
432         if ( is_loc ) {
433             double offset = radial - target_radial;
434             while ( offset < -180.0 ) { offset += 360.0; }
435             while ( offset > 180.0 ) { offset -= 360.0; }
436             // cout << "ils offset = " << offset << endl;
437             effective_range
438                 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
439                                   loc_dist * SG_METER_TO_NM );
440         } else {
441             effective_range
442                 = adjustNavRange( nav_elev, pos.getElevationM(), range );
443         }
444         // cout << "nav range = " << effective_range
445         //      << " (" << range << ")" << endl;
446
447         if ( loc_dist < effective_range * SG_NM_TO_METER ) {
448             inrange = true;
449         } else if ( loc_dist < 2 * effective_range * SG_NM_TO_METER ) {
450             inrange = sg_random() < ( 2 * effective_range * SG_NM_TO_METER
451                                       - loc_dist )
452                                       / (effective_range * SG_NM_TO_METER);
453         } else {
454             inrange = false;
455         }
456         inrange_node->setBoolValue( inrange );
457
458         if ( !is_loc ) {
459             target_radial = sel_radial_node->getDoubleValue();
460         }
461
462         //////////////////////////////////////////////////////////
463         // compute to/from flag status
464         //////////////////////////////////////////////////////////
465         double value = false;
466         double offset = fabs(radial - target_radial);
467         if ( tofrom_serviceable ) {
468             if ( nav_slaved_to_gps_node->getBoolValue() ) {
469                 value = gps_to_flag_node->getBoolValue();
470             } else if ( inrange ) {
471                 if ( is_loc ) {
472                     value = true;
473                 } else {
474                     value = !(offset <= 90.0 || offset >= 270.0);
475                 }
476             }
477         } else {
478             value = false;
479         }
480         to_flag_node->setBoolValue( value );
481
482         value = false;
483         if ( tofrom_serviceable ) {
484             if ( nav_slaved_to_gps_node->getBoolValue() ) {
485                 value = gps_from_flag_node->getBoolValue();
486             } else if ( inrange ) {
487                 if ( is_loc ) {
488                     value = false;
489                 } else {
490                     value = !(offset > 90.0 && offset < 270.0);
491                 }
492             }
493         } else {
494             value = false;
495         }
496         from_flag_node->setBoolValue( value );
497
498         //////////////////////////////////////////////////////////
499         // compute the deflection of the CDI needle, clamped to the range
500         // of ( -10 , 10 )
501         //////////////////////////////////////////////////////////
502         double r = 0.0;
503         bool loc_backside = false; // an in-code flag indicating that we are
504                                    // on a localizer backcourse.
505         if ( cdi_serviceable ) {
506             if ( nav_slaved_to_gps_node->getBoolValue() ) {
507                 r = gps_cdi_deflection_node->getDoubleValue();
508                 // We want +- 5 dots deflection for the gps, so clamp
509                 // to -12.5/12.5
510                 SG_CLAMP_RANGE( r, -12.5, 12.5 );
511             } else if ( inrange ) {
512                 r = radial - target_radial;
513                 // cout << "Target radial = " << target_radial 
514                 //      << "  Actual radial = " << radial << endl;
515                 
516                 while ( r >  180.0 ) { r -= 360.0;}
517                 while ( r < -180.0 ) { r += 360.0;}
518                 if ( fabs(r) > 90.0 ) {
519                     r = ( r<0.0 ? -r-180.0 : -r+180.0 );
520                 } else {
521                     if ( is_loc ) {
522                         loc_backside = true;
523                     }
524                 }
525
526                 r = -r;         // reverse, since radial is outbound
527                 if ( is_loc ) {
528                     // According to Robin Peel, the ILS is 4x more
529                     // sensitive than a vor
530                     r *= 4.0;
531                 }
532                 SG_CLAMP_RANGE( r, -10.0, 10.0 );
533             }
534         }
535         cdi_deflection_node->setDoubleValue( r );
536
537         //////////////////////////////////////////////////////////
538         // compute the amount of cross track distance error in meters
539         //////////////////////////////////////////////////////////
540         double xtrack_error = 0.0;
541         if ( inrange && nav_serviceable && cdi_serviceable ) {
542             r = radial - target_radial;
543             // cout << "Target radial = " << target_radial 
544             //     << "  Actual radial = " << radial
545             //     << "  r = " << r << endl;
546     
547             while ( r >  180.0 ) { r -= 360.0;}
548             while ( r < -180.0 ) { r += 360.0;}
549             if ( fabs(r) > 90.0 ) {
550                 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
551             }
552
553             r = -r;             // reverse, since radial is outbound
554
555             xtrack_error = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
556         } else {
557             xtrack_error = 0.0;
558         }
559         cdi_xtrack_error_node->setDoubleValue( xtrack_error );
560
561         //////////////////////////////////////////////////////////
562         // compute an approximate ground track heading error
563         //////////////////////////////////////////////////////////
564         double hdg_error = 0.0;
565         if ( inrange && cdi_serviceable ) {
566             double vn = fgGetDouble( "/velocities/speed-north-fps" );
567             double ve = fgGetDouble( "/velocities/speed-east-fps" );
568             double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
569             if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
570
571             SGPropertyNode *true_hdg
572                 = fgGetNode("/orientation/heading-deg", true);
573             hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
574
575             // cout << "ground track = " << gnd_trk_true
576             //      << " orientation = " << true_hdg->getDoubleValue() << endl;
577         }
578         cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
579
580         //////////////////////////////////////////////////////////
581         // compute the time to intercept selected radial (based on
582         // current and last cross track errors and dt
583         //////////////////////////////////////////////////////////
584         double t = 0.0;
585         if ( inrange && cdi_serviceable ) {
586             double xrate_ms = (last_xtrack_error - xtrack_error) / dt;
587             if ( fabs(xrate_ms) > 0.00001 ) {
588                 t = xtrack_error / xrate_ms;
589             } else {
590                 t = 9999.9;
591             }
592         }
593         time_to_intercept->setDoubleValue( t );
594
595         //////////////////////////////////////////////////////////
596         // compute the amount of glide slope needle deflection
597         // (.i.e. the number of degrees we are off the glide slope * 5.0
598         //
599         // CLO - 13 Mar 2006: The glide slope needle should peg at
600         // +/-0.7 degrees off the ideal glideslope.  I'm not sure why
601         // we compute the factor the way we do (5*gs_error), but we
602         // need to compensate for our 'odd' number in the glideslope
603         // needle animation.  This means that the needle should peg
604         // when this values is +/-3.5.
605         //////////////////////////////////////////////////////////
606         r = 0.0;
607         if ( has_gs && gs_serviceable_node->getBoolValue() ) {
608             if ( nav_slaved_to_gps_node->getBoolValue() ) {
609                 // FIXME/FINISHME, what should be set here?
610             } else if ( inrange ) {
611                 double x = gs_dist_node->getDoubleValue();
612                 double y = (fgGetDouble("/position/altitude-ft") - nav_elev)
613                     * SG_FEET_TO_METER;
614                 // cout << "dist = " << x << " height = " << y << endl;
615                 double angle = asin( y / x ) * SGD_RADIANS_TO_DEGREES;
616                 r = (target_gs - angle) * 5.0;
617             }
618         }
619         gs_deflection_node->setDoubleValue( r );
620
621         //////////////////////////////////////////////////////////
622         // Calculate desired rate of climb for intercepting the GS
623         //////////////////////////////////////////////////////////
624         double x = gs_dist_node->getDoubleValue();
625         double y = (alt_node->getDoubleValue() - nav_elev)
626             * SG_FEET_TO_METER;
627         double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
628
629         double target_angle = target_gs;
630         double gs_diff = target_angle - current_angle;
631
632         // convert desired vertical path angle into a climb rate
633         double des_angle = current_angle - 10 * gs_diff;
634
635         // estimate horizontal speed towards ILS in meters per minute
636         double dist = last_x - x;
637         last_x = x;
638         if ( dt > 0.0 ) {
639             // avoid nan
640             double new_vel = ( dist / dt );
641  
642             horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
643             // double horiz_vel = cur_fdm_state->get_V_ground_speed()
644             //    * SG_FEET_TO_METER * 60.0;
645             // double horiz_vel = airspeed_node->getFloatValue()
646             //    * SG_FEET_TO_METER * 60.0;
647
648             gs_rate_of_climb_node
649                 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
650                                   * horiz_vel * SG_METER_TO_FEET );
651         }
652
653         //////////////////////////////////////////////////////////
654         // Calculate a suggested target heading to smoothly intercept
655         // a nav/ils radial.
656         //////////////////////////////////////////////////////////
657
658         // Now that we have cross track heading adjustment built in,
659         // we shouldn't need to overdrive the heading angle within 8km
660         // of the station.
661         //
662         // The cdi deflection should be +/-10 for a full range of deflection
663         // so multiplying this by 3 gives us +/- 30 degrees heading
664         // compensation.
665         double adjustment = cdi_deflection_node->getDoubleValue() * 3.0;
666         SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
667
668         // determine the target heading to fly to intercept the
669         // tgt_radial = target radial (true) + cdi offset adjustmest -
670         // xtrack heading error adjustment
671         double nta_hdg;
672         if ( is_loc && backcourse_node->getBoolValue() ) {
673             // tuned to a localizer and backcourse mode activated
674             trtrue += 180.0;   // reverse the target localizer heading
675             while ( trtrue > 360.0 ) { trtrue -= 360.0; }
676             nta_hdg = trtrue - adjustment - hdg_error;
677         } else {
678             nta_hdg = trtrue + adjustment - hdg_error;
679         }
680
681         while ( nta_hdg <   0.0 ) { nta_hdg += 360.0; }
682         while ( nta_hdg >= 360.0 ) { nta_hdg -= 360.0; }
683         target_auto_hdg_node->setDoubleValue( nta_hdg );
684
685         last_xtrack_error = xtrack_error;
686    } else {
687         inrange_node->setBoolValue( false );
688         cdi_deflection_node->setDoubleValue( 0.0 );
689         cdi_xtrack_error_node->setDoubleValue( 0.0 );
690         cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
691         time_to_intercept->setDoubleValue( 0.0 );
692         gs_deflection_node->setDoubleValue( 0.0 );
693         to_flag_node->setBoolValue( false );
694         from_flag_node->setBoolValue( false );
695         // cout << "not picking up vor. :-(" << endl;
696     }
697
698     // audio effects
699     if ( is_valid && inrange && nav_serviceable ) {
700         // play station ident via audio system if on + ident,
701         // otherwise turn it off
702         if ( power_btn
703              && (bus_power_node->getDoubleValue() > 1.0)
704              && ident_btn_node->getBoolValue()
705              && audio_btn_node->getBoolValue() )
706         {
707             SGSoundSample *sound;
708             sound = globals->get_soundmgr()->find( nav_fx_name );
709             double vol = vol_btn_node->getDoubleValue();
710             if ( vol < 0.0 ) { vol = 0.0; }
711             if ( vol > 1.0 ) { vol = 1.0; }
712             if ( sound != NULL ) {
713                 sound->set_volume( vol );
714             } else {
715                 SG_LOG( SG_COCKPIT, SG_ALERT,
716                         "Can't find nav-vor-ident sound" );
717             }
718             sound = globals->get_soundmgr()->find( dme_fx_name );
719             if ( sound != NULL ) {
720                 sound->set_volume( vol );
721             } else {
722                 SG_LOG( SG_COCKPIT, SG_ALERT,
723                         "Can't find nav-dme-ident sound" );
724             }
725             // cout << "last_time = " << last_time << " ";
726             // cout << "cur_time = "
727             //      << globals->get_time_params()->get_cur_time();
728             if ( last_time <
729                  globals->get_time_params()->get_cur_time() - 30 ) {
730                 last_time = globals->get_time_params()->get_cur_time();
731                 play_count = 0;
732             }
733             // cout << " play_count = " << play_count << endl;
734             // cout << "playing = "
735             //      << globals->get_soundmgr()->is_playing(nav_fx_name)
736             //      << endl;
737             if ( play_count < 4 ) {
738                 // play VOR ident
739                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) ) {
740                     globals->get_soundmgr()->play_once( nav_fx_name );
741                     ++play_count;
742                 }
743             } else if ( play_count < 5 && has_dme ) {
744                 // play DME ident
745                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) &&
746                      !globals->get_soundmgr()->is_playing(dme_fx_name) ) {
747                     globals->get_soundmgr()->play_once( dme_fx_name );
748                     ++play_count;
749                 }
750             }
751         } else {
752             globals->get_soundmgr()->stop( nav_fx_name );
753             globals->get_soundmgr()->stop( dme_fx_name );
754         }
755     }
756
757     last_loc_dist = loc_dist;
758 }
759
760
761 // Update current nav/adf radio stations based on current postition
762 void FGNavRadio::search() 
763 {
764
765     // reset search time
766     _time_before_search_sec = 1.0;
767
768     // cache values locally for speed
769     double lon = lon_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
770     double lat = lat_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
771     double elev = alt_node->getDoubleValue() * SG_FEET_TO_METER;
772
773     FGNavRecord *nav = NULL;
774     FGNavRecord *loc = NULL;
775     FGNavRecord *dme = NULL;
776     FGNavRecord *gs = NULL;
777
778     ////////////////////////////////////////////////////////////////////////
779     // Nav.
780     ////////////////////////////////////////////////////////////////////////
781
782     double freq = freq_node->getDoubleValue();
783     nav = globals->get_navlist()->findByFreq(freq, lon, lat, elev);
784     dme = globals->get_dmelist()->findByFreq(freq, lon, lat, elev);
785     if ( nav == NULL ) {
786         loc = globals->get_loclist()->findByFreq(freq, lon, lat, elev);
787         gs = globals->get_gslist()->findByFreq(freq, lon, lat, elev);
788     }
789
790     string nav_id = "";
791
792     if ( loc != NULL ) {
793         nav_id = loc->get_ident();
794         nav_id_node->setStringValue( nav_id.c_str() );
795         // cout << "localizer = " << nav_id_node->getStringValue() << endl;
796         is_valid = true;
797         if ( last_nav_id != nav_id || last_nav_vor ) {
798             trans_ident = loc->get_trans_ident();
799             target_radial = loc->get_multiuse();
800             while ( target_radial <   0.0 ) { target_radial += 360.0; }
801             while ( target_radial > 360.0 ) { target_radial -= 360.0; }
802             loc_lon = loc->get_lon();
803             loc_lat = loc->get_lat();
804             nav_xyz = loc->get_cart();
805             last_nav_id = nav_id;
806             last_nav_vor = false;
807             loc_node->setBoolValue( true );
808             has_dme = (dme != NULL);
809             if ( gs != NULL ) {
810                 has_gs_node->setBoolValue( true );
811                 gs_lon = gs->get_lon();
812                 gs_lat = gs->get_lat();
813                 nav_elev = gs->get_elev_ft();
814                 int tmp = (int)(gs->get_multiuse() / 1000.0);
815                 target_gs = (double)tmp / 100.0;
816                 gs_xyz = gs->get_cart();
817
818                 // derive GS baseline (perpendicular to the runay
819                 // along the ground)
820                 double tlon, tlat, taz;
821                 geo_direct_wgs_84 ( 0.0, gs_lat, gs_lon,
822                                     target_radial + 90,
823                                     100.0, &tlat, &tlon, &taz );
824                 // cout << "target_radial = " << target_radial << endl;
825                 // cout << "nav_loc = " << loc_node->getBoolValue() << endl;
826                 // cout << gs_lon << "," << gs_lat << "  "
827                 //      << tlon << "," << tlat << "  (" << nav_elev << ")"
828                 //      << endl;
829                 SGGeod tpos = SGGeod::fromDegFt(tlon, tlat, nav_elev);
830                 SGVec3d p1 = SGVec3d::fromGeod(tpos);
831
832                 // cout << gs_xyz << endl;
833                 // cout << p1 << endl;
834                 gs_base_vec = p1 - gs_xyz;
835                 // cout << gs_base_vec << endl;
836             } else {
837                 has_gs_node->setBoolValue( false );
838                 nav_elev = loc->get_elev_ft();
839             }
840             twist = 0;
841             range = FG_LOC_DEFAULT_RANGE;
842             effective_range = range;
843
844             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
845                 globals->get_soundmgr()->remove( nav_fx_name );
846             }
847             SGSoundSample *sound;
848             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
849             sound->set_volume( 0.3 );
850             globals->get_soundmgr()->add( sound, nav_fx_name );
851
852             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
853                 globals->get_soundmgr()->remove( dme_fx_name );
854             }
855             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
856             sound->set_volume( 0.3 );
857             globals->get_soundmgr()->add( sound, dme_fx_name );
858
859             int offset = (int)(sg_random() * 30.0);
860             play_count = offset / 4;
861             last_time = globals->get_time_params()->get_cur_time() -
862                 offset;
863             // cout << "offset = " << offset << " play_count = "
864             //      << play_count
865             //      << " last_time = " << last_time
866             //      << " current time = "
867             //      << globals->get_time_params()->get_cur_time() << endl;
868
869             // cout << "Found an loc station in range" << endl;
870             // cout << " id = " << loc->get_locident() << endl;
871         }
872     } else if ( nav != NULL ) {
873         nav_id = nav->get_ident();
874         nav_id_node->setStringValue( nav_id.c_str() );
875         // cout << "nav = " << nav_id << endl;
876         is_valid = true;
877         if ( last_nav_id != nav_id || !last_nav_vor ) {
878             last_nav_id = nav_id;
879             last_nav_vor = true;
880             trans_ident = nav->get_trans_ident();
881             loc_node->setBoolValue( false );
882             has_dme = (dme != NULL);
883             has_gs_node->setBoolValue( false );
884             loc_lon = nav->get_lon();
885             loc_lat = nav->get_lat();
886             nav_elev = nav->get_elev_ft();
887             twist = nav->get_multiuse();
888             range = nav->get_range();
889             effective_range = adjustNavRange(nav_elev, elev, range);
890             target_gs = 0.0;
891             target_radial = sel_radial_node->getDoubleValue();
892             nav_xyz = nav->get_cart();
893
894             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
895                 globals->get_soundmgr()->remove( nav_fx_name );
896             }
897             try {
898                 SGSoundSample *sound;
899                 sound = morse.make_ident( trans_ident, LO_FREQUENCY );
900                 sound->set_volume( 0.3 );
901                 if ( globals->get_soundmgr()->add( sound, nav_fx_name ) ) {
902                     // cout << "Added nav-vor-ident sound" << endl;
903                 } else {
904                     SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
905                 }
906
907                 if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
908                     globals->get_soundmgr()->remove( dme_fx_name );
909                 }
910                 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
911                 sound->set_volume( 0.3 );
912                 globals->get_soundmgr()->add( sound, dme_fx_name );
913
914                 int offset = (int)(sg_random() * 30.0);
915                 play_count = offset / 4;
916                 last_time = globals->get_time_params()->get_cur_time() - offset;
917                 // cout << "offset = " << offset << " play_count = "
918                 //      << play_count << " last_time = "
919                 //      << last_time << " current time = "
920                 //      << globals->get_time_params()->get_cur_time() << endl;
921
922                 // cout << "Found a vor station in range" << endl;
923                 // cout << " id = " << nav->get_ident() << endl;
924             } catch ( sg_io_exception &e ) {
925                 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());
926             }
927         }
928     } else {
929         is_valid = false;
930         nav_id_node->setStringValue( "" );
931         target_radial = 0;
932         trans_ident = "";
933         last_nav_id = "";
934         if ( ! globals->get_soundmgr()->remove( nav_fx_name ) ) {
935             SG_LOG(SG_COCKPIT, SG_WARN, "Failed to remove nav-vor-ident sound");
936         }
937         globals->get_soundmgr()->remove( dme_fx_name );
938         // cout << "not picking up vor1. :-(" << endl;
939     }
940
941     is_valid_node->setBoolValue( is_valid );
942
943     char tmpid[5];
944     strncpy( tmpid, nav_id.c_str(), 5 );
945     id_c1_node->setIntValue( (int)tmpid[0] );
946     id_c2_node->setIntValue( (int)tmpid[1] );
947     id_c3_node->setIntValue( (int)tmpid[2] );
948     id_c4_node->setIntValue( (int)tmpid[3] );
949 }