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