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