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