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