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