]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
1f3b670ba7828c09be849233fe2c8e5fb080f2e1
[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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <iostream>
29 #include <string>
30 #include <sstream>
31
32 #include <simgear/compiler.h>
33 #include <simgear/sg_inlines.h>
34 #include <simgear/math/sg_random.h>
35 #include <simgear/math/vector.hxx>
36
37 #include <Aircraft/aircraft.hxx>
38 #include <Navaids/navlist.hxx>
39
40 #include "navradio.hxx"
41
42 #include <string>
43 SG_USING_STD(string);
44
45
46 // Constructor
47 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
48     lon_node(fgGetNode("/position/longitude-deg", true)),
49     lat_node(fgGetNode("/position/latitude-deg", true)),
50     alt_node(fgGetNode("/position/altitude-ft", true)),
51     power_btn_node(NULL),
52     freq_node(NULL),
53     alt_freq_node(NULL),
54     fmt_freq_node(NULL),
55     fmt_alt_freq_node(NULL),
56     sel_radial_node(NULL),
57     vol_btn_node(NULL),
58     ident_btn_node(NULL),
59     audio_btn_node(NULL),
60     nav_serviceable_node(NULL),
61     cdi_serviceable_node(NULL),
62     gs_serviceable_node(NULL),
63     tofrom_serviceable_node(NULL),
64     heading_node(NULL),
65     radial_node(NULL),
66     recip_radial_node(NULL),
67     target_radial_true_node(NULL),
68     target_auto_hdg_node(NULL),
69     to_flag_node(NULL),
70     from_flag_node(NULL),
71     inrange_node(NULL),
72     cdi_deflection_node(NULL),
73     cdi_xtrack_error_node(NULL),
74     has_gs_node(NULL),
75     loc_node(NULL),
76     loc_dist_node(NULL),
77     gs_deflection_node(NULL),
78     gs_rate_of_climb_node(NULL),
79     gs_dist_node(NULL),
80     nav_id_node(NULL),
81     id_c1_node(NULL),
82     id_c2_node(NULL),
83     id_c3_node(NULL),
84     id_c4_node(NULL),
85     nav_slaved_to_gps_node(NULL),
86     gps_cdi_deflection_node(NULL),
87     gps_to_flag_node(NULL),
88     gps_from_flag_node(NULL),
89     last_nav_id(""),
90     last_nav_vor(false),
91     play_count(0),
92     last_time(0),
93     radial(0.0),
94     target_radial(0.0),
95     horiz_vel(0.0),
96     last_x(0.0),
97     name("nav"),
98     num(0),
99     _time_before_search_sec(-1.0)
100 {
101     SGPath path( globals->get_fg_root() );
102     SGPath term = path;
103     term.append( "Navaids/range.term" );
104     SGPath low = path;
105     low.append( "Navaids/range.low" );
106     SGPath high = path;
107     high.append( "Navaids/range.high" );
108
109     term_tbl = new SGInterpTable( term.str() );
110     low_tbl = new SGInterpTable( low.str() );
111     high_tbl = new SGInterpTable( high.str() );
112
113     int i;
114     for ( i = 0; i < node->nChildren(); ++i ) {
115         SGPropertyNode *child = node->getChild(i);
116         string cname = child->getName();
117         string cval = child->getStringValue();
118         if ( cname == "name" ) {
119             name = cval;
120         } else if ( cname == "number" ) {
121             num = child->getIntValue();
122         } else {
123             SG_LOG( SG_INSTR, SG_WARN, 
124                     "Error in nav radio config logic" );
125             if ( name.length() ) {
126                 SG_LOG( SG_INSTR, SG_WARN, "Section = " << name );
127             }
128         }
129     }
130
131 }
132
133
134 // Destructor
135 FGNavRadio::~FGNavRadio() 
136 {
137     delete term_tbl;
138     delete low_tbl;
139     delete high_tbl;
140 }
141
142
143 void
144 FGNavRadio::init ()
145 {
146     morse.init();
147
148     string branch;
149     branch = "/instrumentation/" + name;
150
151     SGPropertyNode *node = fgGetNode(branch.c_str(), num, true );
152
153     bus_power_node = 
154         fgGetNode(("/systems/electrical/outputs/" + name).c_str(), true);
155
156     // inputs
157     power_btn_node = node->getChild("power-btn", 0, true);
158     power_btn_node->setBoolValue( true );
159     vol_btn_node = node->getChild("volume", 0, true);
160     ident_btn_node = node->getChild("ident", 0, true);
161     ident_btn_node->setBoolValue( true );
162     audio_btn_node = node->getChild("audio-btn", 0, true);
163     audio_btn_node->setBoolValue( true );
164     nav_serviceable_node = node->getChild("serviceable", 0, true);
165     cdi_serviceable_node = (node->getChild("cdi", 0, true))
166         ->getChild("serviceable", 0, true);
167     gs_serviceable_node = (node->getChild("gs", 0, true))
168         ->getChild("serviceable");
169     tofrom_serviceable_node = (node->getChild("to-from", 0, true))
170         ->getChild("serviceable", 0, true);
171
172     // frequencies
173     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
174     freq_node = subnode->getChild("selected-mhz", 0, true);
175     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
176     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
177     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
178
179     // radials
180     subnode = node->getChild("radials", 0, true);
181     sel_radial_node = subnode->getChild("selected-deg", 0, true);
182     radial_node = subnode->getChild("actual-deg", 0, true);
183     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
184     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
185     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
186
187     // outputs
188     heading_node = node->getChild("heading-deg", 0, true);
189     to_flag_node = node->getChild("to-flag", 0, true);
190     from_flag_node = node->getChild("from-flag", 0, true);
191     inrange_node = node->getChild("in-range", 0, true);
192     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
193     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
194     has_gs_node = node->getChild("has-gs", 0, true);
195     loc_node = node->getChild("nav-loc", 0, true);
196     loc_dist_node = node->getChild("nav-distance", 0, true);
197     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
198     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
199     gs_dist_node = node->getChild("gs-distance", 0, true);
200     nav_id_node = node->getChild("nav-id", 0, true);
201     id_c1_node = node->getChild("nav-id_asc1", 0, true);
202     id_c2_node = node->getChild("nav-id_asc2", 0, true);
203     id_c3_node = node->getChild("nav-id_asc3", 0, true);
204     id_c4_node = node->getChild("nav-id_asc4", 0, true);
205
206     // gps slaving support
207     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
208     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
209     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
210     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
211     
212     std::ostringstream temp;
213     temp << name << "nav-ident" << num;
214     nav_fx_name = temp.str();
215     temp << name << "dme-ident" << num;
216     dme_fx_name = temp.str();
217 }
218
219 void
220 FGNavRadio::bind ()
221 {
222     std::ostringstream temp;
223     string branch;
224     temp << num;
225     branch = "/instrumentation/" + name + "[" + temp.str() + "]";
226 }
227
228
229 void
230 FGNavRadio::unbind ()
231 {
232     std::ostringstream temp;
233     string branch;
234     temp << num;
235     branch = "/instrumentation/" + name + "[" + temp.str() + "]";
236 }
237
238
239 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
240 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
241                                  double nominalRange )
242 {
243     // extend out actual usable range to be 1.3x the published safe range
244     const double usability_factor = 1.3;
245
246     // assumptions we model the standard service volume, plus
247     // ... rather than specifying a cylinder, we model a cone that
248     // contains the cylinder.  Then we put an upside down cone on top
249     // to model diminishing returns at too-high altitudes.
250
251     // altitude difference
252     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
253     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
254     //      << " station elev = " << stationElev << endl;
255
256     if ( nominalRange < 25.0 + SG_EPSILON ) {
257         // Standard Terminal Service Volume
258         return term_tbl->interpolate( alt ) * usability_factor;
259     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
260         // Standard Low Altitude Service Volume
261         // table is based on range of 40, scale to actual range
262         return low_tbl->interpolate( alt ) * nominalRange / 40.0
263             * usability_factor;
264     } else {
265         // Standard High Altitude Service Volume
266         // table is based on range of 130, scale to actual range
267         return high_tbl->interpolate( alt ) * nominalRange / 130.0
268             * usability_factor;
269     }
270 }
271
272
273 // model standard ILS service volumes as per AIM 1-1-9
274 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
275                                  double offsetDegrees, double distance )
276 {
277     // assumptions we model the standard service volume, plus
278
279     // altitude difference
280     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
281 //     double offset = fabs( offsetDegrees );
282
283 //     if ( offset < 10 ) {
284 //      return FG_ILS_DEFAULT_RANGE;
285 //     } else if ( offset < 35 ) {
286 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
287 //     } else if ( offset < 45 ) {
288 //      return (45 - offset);
289 //     } else if ( offset > 170 ) {
290 //         return FG_ILS_DEFAULT_RANGE;
291 //     } else if ( offset > 145 ) {
292 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
293 //     } else if ( offset > 135 ) {
294 //         return (offset - 135);
295 //     } else {
296 //      return 0;
297 //     }
298     return FG_LOC_DEFAULT_RANGE;
299 }
300
301
302 // Update the various nav values based on position and valid tuned in navs
303 void 
304 FGNavRadio::update(double dt) 
305 {
306     // cache values locally for speed
307     double lon = lon_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
308     double lat = lat_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
309     double elev = alt_node->getDoubleValue() * SG_FEET_TO_METER;
310     bool power_btn = power_btn_node->getBoolValue();
311     bool nav_serviceable = nav_serviceable_node->getBoolValue();
312     bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
313     bool tofrom_serviceable = tofrom_serviceable_node->getBoolValue();
314     bool inrange = inrange_node->getBoolValue();
315     bool has_gs = has_gs_node->getBoolValue();
316     bool is_loc = loc_node->getBoolValue();
317     double loc_dist = loc_dist_node->getDoubleValue();
318
319     // SGPropertyNode *node = fgGetNode(branch.c_str(), num, true );
320
321     Point3D aircraft = sgGeodToCart( Point3D( lon, lat, elev ) );
322     Point3D station;
323     double az1, az2, s;
324
325     // Create "formatted" versions of the nav frequencies for
326     // consistant display output.
327     char tmp[16];
328     sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
329     fmt_freq_node->setStringValue(tmp);
330     sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
331     fmt_alt_freq_node->setStringValue(tmp);
332
333     // On timeout, scan again
334     _time_before_search_sec -= dt;
335     if ( _time_before_search_sec < 0 ) {
336         search();
337     }
338
339     ////////////////////////////////////////////////////////////////////////
340     // Nav.
341     ////////////////////////////////////////////////////////////////////////
342
343     // cout << "is_valid = " << is_valid
344     //      << " power_btn = " << power_btn
345     //      << " bus_power = " << bus_power_node->getDoubleValue()
346     //      << " nav_serviceable = " << nav_serviceable
347     //      << endl;
348
349     if ( is_valid && power_btn
350          && (bus_power_node->getDoubleValue() > 1.0)
351          && nav_serviceable )
352     {
353         station = Point3D( nav_x, nav_y, nav_z );
354         loc_dist = aircraft.distance3D( station );
355         loc_dist_node->setDoubleValue( loc_dist );
356         // cout << "station = " << station << " dist = " << loc_dist << endl;
357
358         if ( has_gs ) {
359             // find closest distance to the gs base line
360             sgdVec3 p;
361             sgdSetVec3( p, aircraft.x(), aircraft.y(), aircraft.z() );
362             sgdVec3 p0;
363             sgdSetVec3( p0, gs_x, gs_y, gs_z );
364             double dist = sgdClosestPointToLineDistSquared( p, p0,
365                                                             gs_base_vec );
366             gs_dist_node->setDoubleValue( sqrt( dist ) );
367             // cout << "gs_dist = " << gs_dist_node->getDoubleValue()
368             //      << endl;
369
370             Point3D tmp( gs_x, gs_y, gs_z );
371             // cout << " (" << aircraft.distance3D( tmp ) << ")" << endl;
372
373             // wgs84 heading to glide slope (to determine sign of distance)
374             geo_inverse_wgs_84( elev,
375                                 lat * SGD_RADIANS_TO_DEGREES,
376                                 lon * SGD_RADIANS_TO_DEGREES, 
377                                 gs_lat, gs_lon,
378                                 &az1, &az2, &s );
379             double r = az1 - target_radial;
380             while ( r >  180.0 ) { r -= 360.0;}
381             while ( r < -180.0 ) { r += 360.0;}
382             if ( r >= -90.0 && r <= 90.0 ) {
383                 gs_dist_signed = gs_dist_node->getDoubleValue();
384             } else {
385                 gs_dist_signed = -gs_dist_node->getDoubleValue();
386             }
387             /* cout << "Target Radial = " << target_radial 
388                  << "  Bearing = " << az1
389                  << "  dist (signed) = " << gs_dist_signed
390                  << endl; */
391             
392         } else {
393             gs_dist_node->setDoubleValue( 0.0 );
394         }
395         
396         // wgs84 heading to localizer
397         double hdg;
398         geo_inverse_wgs_84( elev,
399                             lat * SGD_RADIANS_TO_DEGREES,
400                             lon * SGD_RADIANS_TO_DEGREES, 
401                             loc_lat, loc_lon,
402                             &hdg, &az2, &s );
403         // cout << "az1 = " << az1 << " magvar = " << nav_magvar << endl;
404         heading_node->setDoubleValue( hdg );
405         radial = az2 - twist;
406         double recip = radial + 180.0;
407         if ( recip >= 360.0 ) { recip -= 360.0; }
408         radial_node->setDoubleValue( radial );
409         recip_radial_node->setDoubleValue( recip );
410         // cout << " heading = " << heading_node->getDoubleValue()
411         //      << " dist = " << nav_dist << endl;
412
413         if ( is_loc ) {
414             double offset = radial - target_radial;
415             while ( offset < -180.0 ) { offset += 360.0; }
416             while ( offset > 180.0 ) { offset -= 360.0; }
417             // cout << "ils offset = " << offset << endl;
418             effective_range
419                 = adjustILSRange( nav_elev, elev, offset,
420                                   loc_dist * SG_METER_TO_NM );
421         } else {
422             effective_range = adjustNavRange( nav_elev, elev, range );
423         }
424         // cout << "nav range = " << effective_range
425         //      << " (" << range << ")" << endl;
426
427         if ( loc_dist < effective_range * SG_NM_TO_METER ) {
428             inrange = true;
429         } else if ( loc_dist < 2 * effective_range * SG_NM_TO_METER ) {
430             inrange = sg_random() < ( 2 * effective_range * SG_NM_TO_METER
431                                       - loc_dist )
432                                       / (effective_range * SG_NM_TO_METER);
433         } else {
434             inrange = false;
435         }
436         inrange_node->setBoolValue( inrange );
437
438         if ( !is_loc ) {
439             target_radial = sel_radial_node->getDoubleValue();
440         }
441
442         // Calculate some values for the nav/ils hold autopilot
443
444         double cur_radial = recip;
445         if ( is_loc ) {
446             // ILS localizers radials are already "true" in our
447             // database
448         } else {
449             cur_radial += twist;
450         }
451         if ( from_flag_node->getBoolValue() ) {
452             cur_radial += 180.0;
453             while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
454         }
455         
456         // AUTOPILOT/FLIGHT-DIRECTOR HELPERS
457
458         // determine the target radial in "true" heading
459         double trtrue = 0.0;
460         if ( is_loc ) {
461             // ILS localizers radials are already "true" in our
462             // database
463             trtrue = target_radial;
464         } else {
465             // VOR radials need to have that vor's offset added in
466             trtrue = target_radial + twist;
467         }
468
469         while ( trtrue < 0.0 ) { trtrue += 360.0; }
470         while ( trtrue > 360.0 ) { trtrue -= 360.0; }
471         target_radial_true_node->setDoubleValue( trtrue );
472
473         // FIXME: this smells odd, there must be a better (or more
474         // linear) solution
475         //
476         // determine the heading adjustment needed.
477         // over 8km scale by 3.0 
478         //    (3 is chosen because max deflection is 10
479         //    and 30 is clamped angle to radial)
480         // under 8km scale by 10.0
481         //    because the overstated error helps drive it to the radial in a 
482         //    moderate cross wind.
483         double adjustment = 0.0;
484         if ( loc_dist > 8000 ) {
485             adjustment = cdi_deflection_node->getDoubleValue() * 3.0;
486         } else {
487             adjustment = cdi_deflection_node->getDoubleValue() * 10.0;
488         }
489         SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
490         
491         // determine the target heading to fly to intercept the
492         // tgt_radial
493         double nta_hdg = trtrue + adjustment; 
494         while ( nta_hdg <   0.0 ) { nta_hdg += 360.0; }
495         while ( nta_hdg > 360.0 ) { nta_hdg -= 360.0; }
496         target_auto_hdg_node->setDoubleValue( nta_hdg );
497
498         // cross track error
499         // ????
500
501         // Calculate desired rate of climb for intercepting the GS
502         double x = gs_dist_node->getDoubleValue();
503         double y = (alt_node->getDoubleValue() - nav_elev)
504             * SG_FEET_TO_METER;
505         double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
506
507         double target_angle = target_gs;
508         double gs_diff = target_angle - current_angle;
509
510         // convert desired vertical path angle into a climb rate
511         double des_angle = current_angle - 10 * gs_diff;
512
513         // estimate horizontal speed towards ILS in meters per minute
514         double dist = last_x - x;
515         last_x = x;
516         if ( dt > 0.0 ) {
517             // avoid nan
518             double new_vel = ( dist / dt );
519  
520             horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
521             // double horiz_vel = cur_fdm_state->get_V_ground_speed()
522             //    * SG_FEET_TO_METER * 60.0;
523             // double horiz_vel = airspeed_node->getFloatValue()
524             //    * SG_FEET_TO_METER * 60.0;
525
526             gs_rate_of_climb_node
527                 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
528                                   * horiz_vel * SG_METER_TO_FEET );
529         }
530     } else {
531         inrange_node->setBoolValue( false );
532         // cout << "not picking up vor. :-(" << endl;
533     }
534
535     // compute to/from flag status
536     double value = false;
537     double offset = fabs(radial - target_radial);
538     if ( nav_slaved_to_gps_node->getBoolValue() ) {
539         value = gps_to_flag_node->getBoolValue();
540     } else if ( inrange && nav_serviceable && tofrom_serviceable ) {
541         if ( is_loc ) {
542             value = true;
543         } else {
544             value = !(offset <= 90.0 || offset >= 270.0);
545         }
546     }
547     to_flag_node->setBoolValue( value );
548
549     value = false;
550     if ( nav_slaved_to_gps_node->getBoolValue() ) {
551         value = gps_from_flag_node->getBoolValue();
552     } else if ( inrange && nav_serviceable && tofrom_serviceable ) {
553         if ( is_loc ) {
554             value = false;
555         } else {
556             value = !(offset > 90.0 && offset < 270.0);
557         }
558     }
559     from_flag_node->setBoolValue( value );
560
561     // compute the deflection of the CDI needle, clamped to the range
562     // of ( -10 , 10 )
563     double r = 0.0;
564     if ( nav_slaved_to_gps_node->getBoolValue() ) {
565         r = gps_cdi_deflection_node->getDoubleValue();
566         // We want +- 5 dots deflection for the gps, so clamp to -12.5/12.5
567         if ( r < -12.5 ) { r = -12.5; }
568         if ( r >  12.5 ) { r =  12.5; }
569     } else if ( inrange && nav_serviceable && cdi_serviceable ) {
570         r = radial - target_radial;
571         // cout << "Target radial = " << target_radial 
572         //      << "  Actual radial = " << radial << endl;
573     
574         while ( r >  180.0 ) { r -= 360.0;}
575         while ( r < -180.0 ) { r += 360.0;}
576         if ( fabs(r) > 90.0 ) {
577             r = ( r<0.0 ? -r-180.0 : -r+180.0 );
578         }
579
580         // According to Robin Peel, the ILS is 4x more sensitive than a vor
581         r = -r;                 // reverse, since radial is outbound
582         if ( is_loc ) { r *= 4.0; }
583         if ( r < -10.0 ) { r = -10.0; }
584         if ( r >  10.0 ) { r =  10.0; }
585     } else {
586         r = 0.0;
587     }
588     cdi_deflection_node->setDoubleValue( r );
589
590     // compute the amount of cross track distance error in meters
591     double m = 0.0;
592     if ( inrange && nav_serviceable && cdi_serviceable ) {
593         r = radial - target_radial;
594         // cout << "Target radial = " << target_radial 
595         //     << "  Actual radial = " << radial
596         //     << "  r = " << r << endl;
597     
598         while ( r >  180.0 ) { r -= 360.0;}
599         while ( r < -180.0 ) { r += 360.0;}
600         if ( fabs(r) > 90.0 ) {
601             r = ( r<0.0 ? -r-180.0 : -r+180.0 );
602         }
603
604         r = -r;                 // reverse, since radial is outbound
605
606         m = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
607
608     } else {
609         m = 0.0;
610     }
611     cdi_xtrack_error_node->setDoubleValue( m );
612
613     // compute the amount of glide slope needle deflection (.i.e. the
614     // number of degrees we are off the glide slope * 5.0
615     r = 0.0;
616     if ( nav_slaved_to_gps_node->getBoolValue() ) {
617         // FIXME, what should be set here?
618     } else if ( inrange && nav_serviceable 
619                 && has_gs && gs_serviceable_node->getBoolValue() )
620     {
621         double x = gs_dist_node->getDoubleValue();
622         double y = (fgGetDouble("/position/altitude-ft") - nav_elev)
623             * SG_FEET_TO_METER;
624         // cout << "dist = " << x << " height = " << y << endl;
625         double angle = asin( y / x ) * SGD_RADIANS_TO_DEGREES;
626         r = (target_gs - angle) * 5.0;
627     }
628     gs_deflection_node->setDoubleValue( r );
629
630     // audio effects
631     if ( is_valid && inrange && nav_serviceable ) {
632         // play station ident via audio system if on + ident,
633         // otherwise turn it off
634         if ( power_btn
635              && (bus_power_node->getDoubleValue() > 1.0)
636              && ident_btn_node->getBoolValue()
637              && audio_btn_node->getBoolValue() )
638         {
639             SGSoundSample *sound;
640             sound = globals->get_soundmgr()->find( nav_fx_name );
641             double vol = vol_btn_node->getDoubleValue();
642             if ( vol < 0.0 ) { vol = 0.0; }
643             if ( vol > 1.0 ) { vol = 1.0; }
644             if ( sound != NULL ) {
645                 sound->set_volume( vol );
646             } else {
647                 SG_LOG( SG_COCKPIT, SG_ALERT,
648                         "Can't find nav-vor-ident sound" );
649             }
650             sound = globals->get_soundmgr()->find( dme_fx_name );
651             if ( sound != NULL ) {
652                 sound->set_volume( vol );
653             } else {
654                 SG_LOG( SG_COCKPIT, SG_ALERT,
655                         "Can't find nav-dme-ident sound" );
656             }
657             // cout << "last_time = " << last_time << " ";
658             // cout << "cur_time = "
659             //      << globals->get_time_params()->get_cur_time();
660             if ( last_time <
661                  globals->get_time_params()->get_cur_time() - 30 ) {
662                 last_time = globals->get_time_params()->get_cur_time();
663                 play_count = 0;
664             }
665             // cout << " play_count = " << play_count << endl;
666             // cout << "playing = "
667             //      << globals->get_soundmgr()->is_playing(nav_fx_name)
668             //      << endl;
669             if ( play_count < 4 ) {
670                 // play VOR ident
671                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) ) {
672                     globals->get_soundmgr()->play_once( nav_fx_name );
673                     ++play_count;
674                 }
675             } else if ( play_count < 5 && has_dme ) {
676                 // play DME ident
677                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) &&
678                      !globals->get_soundmgr()->is_playing(dme_fx_name) ) {
679                     globals->get_soundmgr()->play_once( dme_fx_name );
680                     ++play_count;
681                 }
682             }
683         } else {
684             globals->get_soundmgr()->stop( nav_fx_name );
685             globals->get_soundmgr()->stop( dme_fx_name );
686         }
687     }
688 }
689
690
691 // Update current nav/adf radio stations based on current postition
692 void FGNavRadio::search() 
693 {
694
695     // reset search time
696     _time_before_search_sec = 1.0;
697
698     // cache values locally for speed
699     double lon = lon_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
700     double lat = lat_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
701     double elev = alt_node->getDoubleValue() * SG_FEET_TO_METER;
702
703     FGNavRecord *nav = NULL;
704     FGNavRecord *loc = NULL;
705     FGNavRecord *dme = NULL;
706     FGNavRecord *gs = NULL;
707
708     ////////////////////////////////////////////////////////////////////////
709     // Nav.
710     ////////////////////////////////////////////////////////////////////////
711
712     double freq = freq_node->getDoubleValue();
713     nav = globals->get_navlist()->findByFreq(freq, lon, lat, elev);
714     dme = globals->get_dmelist()->findByFreq(freq, lon, lat, elev);
715     if ( nav == NULL ) {
716         loc = globals->get_loclist()->findByFreq(freq, lon, lat, elev);
717         gs = globals->get_gslist()->findByFreq(freq, lon, lat, elev);
718     }
719
720     string nav_id = "";
721
722     if ( loc != NULL ) {
723         nav_id = loc->get_ident();
724         nav_id_node->setStringValue( nav_id.c_str() );
725         // cout << "localizer = " << nav_id_node->getStringValue() << endl;
726         is_valid = true;
727         if ( last_nav_id != nav_id || last_nav_vor ) {
728             trans_ident = loc->get_trans_ident();
729             target_radial = loc->get_multiuse();
730             while ( target_radial <   0.0 ) { target_radial += 360.0; }
731             while ( target_radial > 360.0 ) { target_radial -= 360.0; }
732             loc_lon = loc->get_lon();
733             loc_lat = loc->get_lat();
734             nav_x = loc->get_x();
735             nav_y = loc->get_y();
736             nav_z = loc->get_z();
737             last_nav_id = nav_id;
738             last_nav_vor = false;
739             loc_node->setBoolValue( true );
740             has_dme = (dme != NULL);
741             if ( gs != NULL ) {
742                 has_gs_node->setBoolValue( true );
743                 gs_lon = gs->get_lon();
744                 gs_lat = gs->get_lat();
745                 nav_elev = gs->get_elev_ft();
746                 int tmp = (int)(gs->get_multiuse() / 1000.0);
747                 target_gs = (double)tmp / 100.0;
748                 gs_x = gs->get_x();
749                 gs_y = gs->get_y();
750                 gs_z = gs->get_z();
751
752                 // derive GS baseline (perpendicular to the runay
753                 // along the ground)
754                 double tlon, tlat, taz;
755                 geo_direct_wgs_84 ( 0.0, gs_lat, gs_lon,
756                                     target_radial + 90,  
757                                     100.0, &tlat, &tlon, &taz );
758                 // cout << "target_radial = " << target_radial << endl;
759                 // cout << "nav_loc = " << loc_node->getBoolValue() << endl;
760                 // cout << gs_lon << "," << gs_lat << "  "
761                 //      << tlon << "," << tlat << "  (" << nav_elev << ")"
762                 //      << endl;
763                 Point3D p1 = sgGeodToCart( Point3D(tlon*SGD_DEGREES_TO_RADIANS,
764                                                    tlat*SGD_DEGREES_TO_RADIANS,
765                                                    nav_elev*SG_FEET_TO_METER)
766                                            );
767                 // cout << gs_x << "," << gs_y << "," << gs_z
768                 //      << endl;
769                 // cout << p1 << endl;
770                 sgdSetVec3( gs_base_vec,
771                             p1.x()-gs_x, p1.y()-gs_y, p1.z()-gs_z );
772                 // cout << gs_base_vec[0] << "," << gs_base_vec[1] << ","
773                 //      << gs_base_vec[2] << endl;
774             } else {
775                 has_gs_node->setBoolValue( false );
776                 nav_elev = loc->get_elev_ft();
777             }
778             twist = 0;
779             range = FG_LOC_DEFAULT_RANGE;
780             effective_range = range;
781
782             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
783                 globals->get_soundmgr()->remove( nav_fx_name );
784             }
785             SGSoundSample *sound;
786             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
787             sound->set_volume( 0.3 );
788             globals->get_soundmgr()->add( sound, nav_fx_name );
789
790             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
791                 globals->get_soundmgr()->remove( dme_fx_name );
792             }
793             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
794             sound->set_volume( 0.3 );
795             globals->get_soundmgr()->add( sound, dme_fx_name );
796
797             int offset = (int)(sg_random() * 30.0);
798             play_count = offset / 4;
799             last_time = globals->get_time_params()->get_cur_time() -
800                 offset;
801             // cout << "offset = " << offset << " play_count = "
802             //      << play_count
803             //      << " last_time = " << last_time
804             //      << " current time = "
805             //      << globals->get_time_params()->get_cur_time() << endl;
806
807             // cout << "Found an loc station in range" << endl;
808             // cout << " id = " << loc->get_locident() << endl;
809         }
810     } else if ( nav != NULL ) {
811         nav_id = nav->get_ident();
812         nav_id_node->setStringValue( nav_id.c_str() );
813         // cout << "nav = " << nav_id << endl;
814         is_valid = true;
815         if ( last_nav_id != nav_id || !last_nav_vor ) {
816             last_nav_id = nav_id;
817             last_nav_vor = true;
818             trans_ident = nav->get_trans_ident();
819             loc_node->setBoolValue( false );
820             has_dme = (dme != NULL);
821             has_gs_node->setBoolValue( false );
822             loc_lon = nav->get_lon();
823             loc_lat = nav->get_lat();
824             nav_elev = nav->get_elev_ft();
825             twist = nav->get_multiuse();
826             range = nav->get_range();
827             effective_range = adjustNavRange(nav_elev, elev, range);
828             target_gs = 0.0;
829             target_radial = sel_radial_node->getDoubleValue();
830             nav_x = nav->get_x();
831             nav_y = nav->get_y();
832             nav_z = nav->get_z();
833
834             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
835                 globals->get_soundmgr()->remove( nav_fx_name );
836             }
837             SGSoundSample *sound;
838             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
839             sound->set_volume( 0.3 );
840             if ( globals->get_soundmgr()->add( sound, nav_fx_name ) ) {
841                 // cout << "Added nav-vor-ident sound" << endl;
842             } else {
843                 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
844             }
845
846             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
847                 globals->get_soundmgr()->remove( dme_fx_name );
848             }
849             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
850             sound->set_volume( 0.3 );
851             globals->get_soundmgr()->add( sound, dme_fx_name );
852
853             int offset = (int)(sg_random() * 30.0);
854             play_count = offset / 4;
855             last_time = globals->get_time_params()->get_cur_time() - offset;
856             // cout << "offset = " << offset << " play_count = "
857             //      << play_count << " last_time = "
858             //      << last_time << " current time = "
859             //      << globals->get_time_params()->get_cur_time() << endl;
860
861             // cout << "Found a vor station in range" << endl;
862             // cout << " id = " << nav->get_ident() << endl;
863         }
864     } else {
865         is_valid = false;
866         nav_id_node->setStringValue( "" );
867         target_radial = 0;
868         trans_ident = "";
869         last_nav_id = "";
870         if ( ! globals->get_soundmgr()->remove( nav_fx_name ) ) {
871             SG_LOG(SG_COCKPIT, SG_WARN, "Failed to remove nav-vor-ident sound");
872         }
873         globals->get_soundmgr()->remove( dme_fx_name );
874         // cout << "not picking up vor1. :-(" << endl;
875     }
876
877     char tmpid[5];
878     strncpy( tmpid, nav_id.c_str(), 5 );
879     id_c1_node->setIntValue( (int)tmpid[0] );
880     id_c2_node->setIntValue( (int)tmpid[1] );
881     id_c3_node->setIntValue( (int)tmpid[2] );
882     id_c4_node->setIntValue( (int)tmpid[3] );
883 }