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