]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
Autopilot now honors tunable altitude hold parameters which are defined in
[flightgear.git] / src / Autopilot / newauto.cxx
1 // newauto.cxx -- autopilot defines and prototypes (very alpha)
2 // 
3 // Started April 1998  Copyright (C) 1998
4 //
5 // Contributions by Jeff Goeke-Smith <jgoeke@voyager.net>
6 //                  Norman Vine <nhv@cape.com>
7 //                  Curtis Olson <curt@flightgear.org>
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 // General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 #include <stdio.h>              // sprintf()
31
32 #include <simgear/constants.h>
33 #include <simgear/debug/logstream.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/math/sg_random.h>
36
37 #include <Cockpit/steam.hxx>
38 #include <Cockpit/radiostack.hxx>
39 #include <Controls/controls.hxx>
40 #include <FDM/flight.hxx>
41 #include <Main/globals.hxx>
42 #include <Scenery/scenery.hxx>
43
44 #include "newauto.hxx"
45
46
47 FGAutopilot *current_autopilot;
48
49
50 // Climb speed constants
51 // const double min_climb = 70.0;       // kts
52 // const double best_climb = 75.0;      // kts
53 // const double ideal_climb_rate = 500.0 * SG_FEET_TO_METER; // fpm -> mpm
54 // const double ideal_decent_rate = 1000.0 * SG_FEET_TO_METER; // fpm -> mpm
55
56 /// These statics will eventually go into the class
57 /// they are just here while I am experimenting -- NHV :-)
58 // AutoPilot Gain Adjuster members
59 static double MaxRollAdjust;        // MaxRollAdjust       = 2 * APData->MaxRoll;
60 static double RollOutAdjust;        // RollOutAdjust       = 2 * APData->RollOut;
61 static double MaxAileronAdjust;     // MaxAileronAdjust    = 2 * APData->MaxAileron;
62 static double RollOutSmoothAdjust;  // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
63
64 static char NewTgtAirportId[16];
65 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID"; 
66
67 extern char *coord_format_lat(float);
68 extern char *coord_format_lon(float);
69                         
70
71 // constructor
72 FGAutopilot::FGAutopilot()
73 {
74     TargetClimbRate
75         = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
76     TargetDescentRate
77         = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
78     min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
79     best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
80     elevator_adj_factor
81         = fgGetNode("/autopilot/config/elevator-adj-factor", true);
82     integral_contrib
83         = fgGetNode("/autopilot/config/integral-contribution", true);
84     cout << "elevadj = " << elevator_adj_factor->getFloatValue() << endl;
85     // initialize with defaults (in case config isn't there)
86     if ( TargetClimbRate->getFloatValue() < 1 )
87         fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
88     if ( TargetDescentRate->getFloatValue() < 1 )
89         fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
90     if ( min_climb->getFloatValue() < 1)
91         fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
92     if (best_climb->getFloatValue() < 1)
93         fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
94     if (elevator_adj_factor->getFloatValue() < 1)
95         fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
96     if ( integral_contrib->getFloatValue() < 0.0000001 )
97         fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
98 }
99
100 // destructor
101 FGAutopilot::~FGAutopilot() {}
102
103
104 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
105     sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
106     sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
107     sprintf( TargetLatLonStr, "%s  %s", TargetLatitudeStr, TargetLongitudeStr );
108 }
109
110
111 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
112     if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
113         sprintf( TargetAltitudeStr, "APAltitude  %6.0f+", altitude );
114     } else {
115         sprintf( TargetAltitudeStr, "APAltitude  %6.0f", altitude );
116     }
117 }
118
119
120 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
121     if( bearing < 0. ) {
122         bearing += 360.;
123     } else if (bearing > 360. ) {
124         bearing -= 360.;
125     }
126     sprintf( TargetHeadingStr, "APHeading  %6.1f", bearing );
127 }
128
129
130 static inline double get_speed( void ) {
131     return( cur_fdm_state->get_V_equiv_kts() );
132 }
133
134 static inline double get_ground_speed() {
135     // starts in ft/s so we convert to kts
136     static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
137
138     double ft_s = cur_fdm_state->get_V_ground_speed() 
139         * speedup_node->getIntValue();
140     double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
141
142     return kts;
143 }
144
145
146 void FGAutopilot::MakeTargetWPStr( double distance ) {
147     static time_t last_time = 0;
148     time_t current_time = time(NULL);
149     if ( last_time == current_time ) {
150         return;
151     }
152
153     last_time = current_time;
154
155     double accum = 0.0;
156
157     int size = globals->get_route()->size();
158
159     // start by wiping the strings
160     TargetWP1Str[0] = 0;
161     TargetWP2Str[0] = 0;
162     TargetWP3Str[0] = 0;
163
164     // current route
165     if ( size > 0 ) {
166         SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
167         accum += distance;
168         double eta = accum * SG_METER_TO_NM / get_ground_speed();
169         if ( eta >= 100.0 ) { eta = 99.999; }
170         int major, minor;
171         if ( eta < (1.0/6.0) ) {
172             // within 10 minutes, bump up to min/secs
173             eta *= 60.0;
174         }
175         major = (int)eta;
176         minor = (int)((eta - (int)eta) * 60.0);
177         sprintf( TargetWP1Str, "%s %.2f NM  ETA %d:%02d",
178                  wp1.get_id().c_str(),
179                  accum*SG_METER_TO_NM, major, minor );
180         // cout << "distance = " << distance*SG_METER_TO_NM
181         //      << "  gndsp = " << get_ground_speed() 
182         //      << "  time = " << eta
183         //      << "  major = " << major
184         //      << "  minor = " << minor
185         //      << endl;
186     }
187
188     // next route
189     if ( size > 1 ) {
190         SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
191         accum += wp2.get_distance();
192         
193         double eta = accum * SG_METER_TO_NM / get_ground_speed();
194         if ( eta >= 100.0 ) { eta = 99.999; }
195         int major, minor;
196         if ( eta < (1.0/6.0) ) {
197             // within 10 minutes, bump up to min/secs
198             eta *= 60.0;
199         }
200         major = (int)eta;
201         minor = (int)((eta - (int)eta) * 60.0);
202         sprintf( TargetWP2Str, "%s %.2f NM  ETA %d:%02d",
203                  wp2.get_id().c_str(),
204                  accum*SG_METER_TO_NM, major, minor );
205     }
206
207     // next route
208     if ( size > 2 ) {
209         for ( int i = 2; i < size; ++i ) {
210             accum += globals->get_route()->get_waypoint( i ).get_distance();
211         }
212         
213         SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
214
215         double eta = accum * SG_METER_TO_NM / get_ground_speed();
216         if ( eta >= 100.0 ) { eta = 99.999; }
217         int major, minor;
218         if ( eta < (1.0/6.0) ) {
219             // within 10 minutes, bump up to min/secs
220             eta *= 60.0;
221         }
222         major = (int)eta;
223         minor = (int)((eta - (int)eta) * 60.0);
224         sprintf( TargetWP3Str, "%s %.2f NM  ETA %d:%02d",
225                  wpn.get_id().c_str(),
226                  accum*SG_METER_TO_NM, major, minor );
227     }
228 }
229
230
231 void FGAutopilot::update_old_control_values() {
232     old_aileron = globals->get_controls()->get_aileron();
233     old_elevator = globals->get_controls()->get_elevator();
234     old_elevator_trim = globals->get_controls()->get_elevator_trim();
235     old_rudder = globals->get_controls()->get_rudder();
236 }
237
238
239 // Initialize autopilot subsystem
240 void FGAutopilot::init() {
241     SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
242
243     latitude_node = fgGetNode("/position/latitude-deg", true);
244     longitude_node = fgGetNode("/position/longitude-deg", true);
245     altitude_node = fgGetNode("/position/altitude-ft", true);
246     altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
247     vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
248     heading_node = fgGetNode("/orientation/heading-deg", true);
249     roll_node = fgGetNode("/orientation/roll-deg", true);
250
251     heading_hold = false ;      // turn the heading hold off
252     altitude_hold = false ;     // turn the altitude hold off
253     auto_throttle = false ;     // turn the auto throttle off
254     heading_mode = DEFAULT_AP_HEADING_LOCK;
255
256     sg_srandom_time();
257     DGTargetHeading = sg_random() * 360.0;
258
259     // Initialize target location to startup location
260     old_lat = latitude_node->getDoubleValue();
261     old_lon = longitude_node->getDoubleValue();
262     // set_WayPoint( old_lon, old_lat, 0.0, "default" );
263
264     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
265         
266     TargetHeading = 0.0;        // default direction, due north
267     TargetAltitude = 3000;      // default altitude in meters
268     alt_error_accum = 0.0;
269     climb_error_accum = 0.0;
270
271     MakeTargetAltitudeStr( TargetAltitude );
272     MakeTargetHeadingStr( TargetHeading );
273         
274     // These eventually need to be read from current_aircaft somehow.
275
276     // the maximum roll, in Deg
277     MaxRoll = 20;
278
279     // the deg from heading to start rolling out at, in Deg
280     RollOut = 20;
281
282     // how far can I move the aleron from center.
283     MaxAileron = .2;
284
285     // Smoothing distance for alerion control
286     RollOutSmooth = 10;
287
288     // Hardwired for now should be in options
289     // 25% max control variablilty  0.5 / 2.0
290     disengage_threshold = 1.0;
291
292 #if !defined( USING_SLIDER_CLASS )
293     MaxRollAdjust = 2 * MaxRoll;
294     RollOutAdjust = 2 * RollOut;
295     MaxAileronAdjust = 2 * MaxAileron;
296     RollOutSmoothAdjust = 2 * RollOutSmooth;
297 #endif  // !defined( USING_SLIDER_CLASS )
298
299     update_old_control_values();
300         
301     // Initialize GUI components of autopilot
302     // NewTgtAirportInit();
303     // fgAPAdjustInit() ;
304     // NewHeadingInit();
305     // NewAltitudeInit();
306 };
307
308
309 // Reset the autopilot system
310 void FGAutopilot::reset() {
311
312     heading_hold = false ;      // turn the heading hold off
313     altitude_hold = false ;     // turn the altitude hold off
314     auto_throttle = false ;     // turn the auto throttle off
315     heading_mode = DEFAULT_AP_HEADING_LOCK;
316
317     // TargetHeading = 0.0;     // default direction, due north
318     MakeTargetHeadingStr( TargetHeading );                      
319         
320     // TargetAltitude = 3000;   // default altitude in meters
321     MakeTargetAltitudeStr( TargetAltitude );
322         
323     alt_error_accum = 0.0;
324     climb_error_accum = 0.0;
325         
326     update_old_control_values();
327
328     sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id").c_str() );
329         
330     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
331 }
332
333
334 static double NormalizeDegrees( double Input ) {
335     // normalize the input to the range (-180,180]
336     // Input should not be greater than -360 to 360.
337     // Current rules send the output to an undefined state.
338     if ( Input > 180 )
339         while(Input > 180 )
340             Input -= 360;
341     else if ( Input <= -180 )
342         while ( Input <= -180 )
343             Input += 360;
344     return ( Input );
345 };
346
347 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
348     // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
349     //assert(x1 != x2); // Divide by zero error.  Cold abort for now
350
351         // Could be
352         // static double y = 0.0;
353         // double dx = x2 -x1;
354         // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
355         // {
356
357     double m, b, y;          // the constants to find in y=mx+b
358     // double m, b;
359
360     m = ( y2 - y1 ) / ( x2 - x1 );   // calculate the m
361
362     b = y1 - m * x1;       // calculate the b
363
364     y = m * x + b;       // the final calculation
365
366     // }
367
368     return ( y );
369
370 };
371
372
373 int FGAutopilot::run() {
374     // Remove the following lines when the calling funcitons start
375     // passing in the data pointer
376
377     // get control settings 
378         
379     double lat = latitude_node->getDoubleValue();
380     double lon = longitude_node->getDoubleValue();
381     double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
382
383     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run()  lat = " << lat <<
384             "  lon = " << lon << "  alt = " << alt );
385         
386 #ifdef FG_FORCE_AUTO_DISENGAGE
387     // see if somebody else has changed them
388     if( fabs(aileron - old_aileron) > disengage_threshold ||
389         fabs(elevator - old_elevator) > disengage_threshold ||
390         fabs(elevator_trim - old_elevator_trim) > 
391         disengage_threshold ||          
392         fabs(rudder - old_rudder) > disengage_threshold )
393     {
394         // if controls changed externally turn autopilot off
395         waypoint_hold = false ;   // turn the target hold off
396         heading_hold = false ;    // turn the heading hold off
397         altitude_hold = false ;   // turn the altitude hold off
398         terrain_follow = false;   // turn the terrain_follow hold off
399         // auto_throttle = false; // turn the auto_throttle off
400
401         // stash this runs control settings
402         old_aileron = aileron;
403         old_elevator = elevator;
404         old_elevator_trim = elevator_trim;
405         old_rudder = rudder;
406         
407         return 0;
408     }
409 #endif
410         
411     // heading hold
412     if ( heading_hold == true ) {
413         if ( heading_mode == FG_DG_HEADING_LOCK ) {
414             // cout << "DG heading = " << FGSteam::get_DG_deg()
415             //      << " DG error = " << FGSteam::get_DG_err() << endl;
416
417             TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
418             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
419             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
420             MakeTargetHeadingStr( TargetHeading );
421         } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
422             // we don't set a specific target heading in
423             // TC_HEADING_LOCK mode, we instead try to keep the turn
424             // coordinator zero'd
425         } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
426             // leave "true" target heading as is
427             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
428             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
429             MakeTargetHeadingStr( TargetHeading );
430         } else if ( heading_mode == FG_HEADING_NAV1 ) {
431             // track the NAV1 heading needle deflection
432
433             // determine our current radial position relative to the
434             // navaid in "true" heading.
435             double cur_radial = current_radiostack->get_nav1_heading();
436             if ( current_radiostack->get_nav1_loc() ) {
437                 // ILS localizers radials are already "true" in our
438                 // database
439             } else {
440                 cur_radial += current_radiostack->get_nav1_magvar();
441             }
442             if ( current_radiostack->get_nav1_from_flag() ) {
443                 cur_radial += 180.0;
444                 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
445             }
446
447             // determine the target radial in "true" heading
448             double tgt_radial = current_radiostack->get_nav1_radial();
449             if ( current_radiostack->get_nav1_loc() ) {
450                 // ILS localizers radials are already "true" in our
451                 // database
452             } else {
453                 // VOR radials need to have that vor's offset added in
454                 tgt_radial += current_radiostack->get_nav1_magvar();
455             }
456
457             // determine the heading adjustment needed.
458             double adjustment = 
459                 current_radiostack->get_nav1_heading_needle_deflection()
460                 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
461             if ( adjustment < -30.0 ) { adjustment = -30.0; }
462             if ( adjustment >  30.0 ) { adjustment =  30.0; }
463
464             // determine the target heading to fly to intercept the
465             // tgt_radial
466             TargetHeading = tgt_radial + adjustment; 
467             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
468             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
469
470             MakeTargetHeadingStr( TargetHeading );
471             // cout << "target course (true) = " << TargetHeading << endl;
472         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
473             // update target heading to waypoint
474
475             double wp_course, wp_distance;
476
477 #ifdef DO_fgAP_CORRECTED_COURSE
478             // compute course made good
479             // this needs lots of special casing before use
480             double course, reverse, distance, corrected_course;
481             // need to test for iter
482             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
483                                 old_lat,
484                                 old_lon,
485                                 lat,
486                                 lon,
487                                 &course,
488                                 &reverse,
489                                 &distance );
490 #endif // DO_fgAP_CORRECTED_COURSE
491
492             // compute course to way_point
493             // need to test for iter
494             SGWayPoint wp = globals->get_route()->get_first();
495             wp.CourseAndDistance( lon, lat, alt, 
496                                   &wp_course, &wp_distance );
497
498 #ifdef DO_fgAP_CORRECTED_COURSE
499             corrected_course = course - wp_course;
500             if( fabs(corrected_course) > 0.1 )
501                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
502                        course, wp_course, fabs(corrected_course),
503                        distance );
504 #endif // DO_fgAP_CORRECTED_COURSE
505                 
506             if ( wp_distance > 100 ) {
507                 // corrected_course = course - wp_course;
508                 TargetHeading = NormalizeDegrees(wp_course);
509             } else {
510                 cout << "Reached waypoint within " << wp_distance << "meters"
511                      << endl;
512
513                 // pop off this waypoint from the list
514                 if ( globals->get_route()->size() ) {
515                     globals->get_route()->delete_first();
516                 }
517
518                 // see if there are more waypoints on the list
519                 if ( globals->get_route()->size() ) {
520                     // more waypoints
521                     set_HeadingMode( FG_HEADING_WAYPOINT );
522                 } else {
523                     // end of the line
524                     heading_mode = FG_TRUE_HEADING_LOCK;
525                     // use current heading
526                     TargetHeading = heading_node->getDoubleValue();
527                 }
528             }
529             MakeTargetHeadingStr( TargetHeading );
530             // Force this just in case
531             TargetDistance = wp_distance;
532             MakeTargetWPStr( wp_distance );
533         }
534
535         if ( heading_mode == FG_TC_HEADING_LOCK ) {
536             // drive the turn coordinator to zero
537             double turn = FGSteam::get_TC_std();
538             // cout << "turn rate = " << turn << endl;
539             double AileronSet = -turn / 2.0;
540             if ( AileronSet < -1.0 ) { AileronSet = -1.0; }
541             if ( AileronSet >  1.0 ) { AileronSet =  1.0; }
542             globals->get_controls()->set_aileron( AileronSet );
543             globals->get_controls()->set_rudder( AileronSet / 4.0 );
544         } else {
545             // steer towards the target heading
546
547             double RelHeading;
548             double TargetRoll;
549             double RelRoll;
550             double AileronSet;
551
552             RelHeading
553                 = NormalizeDegrees( TargetHeading
554                                     - heading_node->getDoubleValue() );
555             // figure out how far off we are from desired heading
556
557             // Now it is time to deterime how far we should be rolled.
558             SG_LOG( SG_AUTOPILOT, SG_DEBUG, "RelHeading: " << RelHeading );
559
560
561             // Check if we are further from heading than the roll out point
562             if ( fabs( RelHeading ) > RollOut ) {
563                 // set Target Roll to Max in desired direction
564                 if ( RelHeading < 0 ) {
565                     TargetRoll = 0 - MaxRoll;
566                 } else {
567                     TargetRoll = MaxRoll;
568                 }
569             } else {
570                 // We have to calculate the Target roll
571
572                 // This calculation engine thinks that the Target roll
573                 // should be a line from (RollOut,MaxRoll) to (-RollOut,
574                 // -MaxRoll) I hope this works well.  If I get ambitious
575                 // some day this might become a fancier curve or
576                 // something.
577
578                 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
579                                                 -MaxRoll, RollOut,
580                                                 MaxRoll );
581             }
582
583             // Target Roll has now been Found.
584
585             // Compare Target roll to Current Roll, Generate Rel Roll
586
587             SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
588
589             RelRoll = NormalizeDegrees( TargetRoll 
590                                         - roll_node->getDoubleValue() );
591
592             // Check if we are further from heading than the roll out
593             // smooth point
594             if ( fabs( RelRoll ) > RollOutSmooth ) {
595                 // set Target Roll to Max in desired direction
596                 if ( RelRoll < 0 ) {
597                 AileronSet = 0 - MaxAileron;
598                 } else {
599                     AileronSet = MaxAileron;
600                 }
601             } else {
602                 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
603                                                 -MaxAileron,
604                                                 RollOutSmooth,
605                                                 MaxAileron );
606             }
607
608             globals->get_controls()->set_aileron( AileronSet );
609             globals->get_controls()->set_rudder( AileronSet / 4.0 );
610             // controls.set_rudder( 0.0 );
611         }
612     }
613
614     // altitude hold
615     if ( altitude_hold ) {
616         double climb_rate;
617         double speed, max_climb, error;
618         double prop_error, int_error;
619         double prop_adj, int_adj, total_adj;
620
621         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
622             climb_rate =
623                 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
624         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
625             double x = current_radiostack->get_nav1_gs_dist();
626             double y = (altitude_node->getDoubleValue()
627                         - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
628             double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
629             // cout << "current angle = " << current_angle << endl;
630
631             double target_angle = current_radiostack->get_nav1_target_gs();
632             // cout << "target angle = " << target_angle << endl;
633
634             double gs_diff = target_angle - current_angle;
635             // cout << "difference from desired = " << gs_diff << endl;
636
637             // convert desired vertical path angle into a climb rate
638             double des_angle = current_angle - 10 * gs_diff;
639             // cout << "desired angle = " << des_angle << endl;
640
641             // convert to meter/min
642             // cout << "raw ground speed = " << cur_fdm_state->get_V_ground_speed() << endl;
643             double horiz_vel = cur_fdm_state->get_V_ground_speed()
644                 * SG_FEET_TO_METER * 60.0;
645             // cout << "Horizontal vel = " << horiz_vel << endl;
646             climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
647             // cout << "climb_rate = " << climb_rate << endl;
648             /* climb_error_accum += gs_diff * 2.0; */
649             /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
650         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
651             // brain dead ground hugging with no look ahead
652             climb_rate =
653                 ( TargetAGL - altitude_agl_node->getDoubleValue()
654                   * SG_FEET_TO_METER ) * 16.0;
655             // cout << "target agl = " << TargetAGL 
656             //      << "  current agl = " << fgAPget_agl() 
657             //      << "  target climb rate = " << climb_rate 
658             //      << endl;
659         } else {
660             // just try to zero out rate of climb ...
661             climb_rate = 0.0;
662         }
663
664         speed = get_speed();
665
666         if ( speed < min_climb->getFloatValue() ) {
667             max_climb = 0.0;
668         } else if ( speed < best_climb->getFloatValue() ) {
669             max_climb = ((best_climb->getFloatValue()
670                           - min_climb->getFloatValue())
671                          - (best_climb->getFloatValue() - speed)) 
672                 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) 
673                 / (best_climb->getFloatValue() - min_climb->getFloatValue());
674         } else {                        
675             max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
676                 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
677         }
678
679         // this first one could be optional if we wanted to allow
680         // better climb performance assuming we have the airspeed to
681         // support it.
682         if ( climb_rate >
683              fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
684             climb_rate
685                 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
686         }
687
688         if ( climb_rate > max_climb ) {
689             climb_rate = max_climb;
690         }
691
692         if ( climb_rate <
693              -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
694             climb_rate
695                 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
696         }
697
698         // cout << "Target climb rate = " << TargetClimbRate << endl;
699         // cout << "given our speed, modified desired climb rate = "
700         //      << climb_rate * SG_METER_TO_FEET 
701         //      << " fpm" << endl;
702         // cout << "Current climb rate = "
703         //      << vertical_speed_node->getDoubleValue() * 60 << " fpm" << endl;
704
705         error = vertical_speed_node->getDoubleValue() * 60
706             - climb_rate * SG_METER_TO_FEET;
707
708         // accumulate the error under the curve ... this really should
709         // be *= delta t
710         alt_error_accum += error;
711
712         // calculate integral error, and adjustment amount
713         int_error = alt_error_accum;
714         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
715         int_adj = int_error / elevator_adj_factor->getFloatValue();
716
717         // caclulate proportional error
718         prop_error = error;
719         prop_adj = prop_error / elevator_adj_factor->getFloatValue();
720
721         total_adj = (1.0 - integral_contrib->getFloatValue()) * prop_adj
722             + integral_contrib->getFloatValue() * int_adj;
723         // if ( total_adj > 0.6 ) {
724         //     total_adj = 0.6;
725         // } else if ( total_adj < -0.2 ) {
726         //     total_adj = -0.2;
727         // }
728         if ( total_adj > 1.0 ) {
729             total_adj = 1.0;
730         } else if ( total_adj < -1.0 ) {
731             total_adj = -1.0;
732         }
733
734         globals->get_controls()->set_elevator_trim( total_adj );
735     }
736
737     // auto throttle
738     if ( auto_throttle ) {
739         double error;
740         double prop_error, int_error;
741         double prop_adj, int_adj, total_adj;
742
743         error = TargetSpeed - get_speed();
744
745         // accumulate the error under the curve ... this really should
746         // be *= delta t
747         speed_error_accum += error;
748         if ( speed_error_accum > 2000.0 ) {
749             speed_error_accum = 2000.0;
750         }
751         else if ( speed_error_accum < -2000.0 ) {
752             speed_error_accum = -2000.0;
753         }
754
755         // calculate integral error, and adjustment amount
756         int_error = speed_error_accum;
757
758         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
759         int_adj = int_error / 200.0;
760
761         // caclulate proportional error
762         prop_error = error;
763         prop_adj = 0.5 + prop_error / 50.0;
764
765         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
766         if ( total_adj > 1.0 ) {
767             total_adj = 1.0;
768         }
769         else if ( total_adj < 0.0 ) {
770             total_adj = 0.0;
771         }
772
773         globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
774                                                total_adj );
775     }
776
777 #ifdef THIS_CODE_IS_NOT_USED
778     if (Mode == 2) // Glide slope hold
779         {
780             double RelSlope;
781             double RelElevator;
782
783             // First, calculate Relative slope and normalize it
784             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
785
786             // Now calculate the elevator offset from current angle
787             if ( abs(RelSlope) > SlopeSmooth )
788                 {
789                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
790                         RelElevator = -MaxElevator;
791                     else
792                         RelElevator = MaxElevator;
793                 }
794
795             else
796                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
797
798             // set the elevator
799             fgElevMove(RelElevator);
800
801         }
802 #endif // THIS_CODE_IS_NOT_USED
803
804     // stash this runs control settings
805     //  update_old_control_values();
806     old_aileron = globals->get_controls()->get_aileron();
807     old_elevator = globals->get_controls()->get_elevator();
808     old_elevator_trim = globals->get_controls()->get_elevator_trim();
809     old_rudder = globals->get_controls()->get_rudder();
810
811     // for cross track error
812     old_lat = lat;
813     old_lon = lon;
814         
815     // Ok, we are done
816     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
817
818     return 0;
819 }
820
821
822 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
823     heading_mode = mode;
824
825     if ( heading_mode == FG_DG_HEADING_LOCK ) {
826         // set heading hold to current heading (as read from DG)
827         // ... no, leave target heading along ... just use the current
828         // heading bug value
829         //  DGTargetHeading = FGSteam::get_DG_deg();
830     } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
831         // set autopilot to hold a zero turn (as reported by the TC)
832     } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
833         // set heading hold to current heading
834         TargetHeading = heading_node->getDoubleValue();
835     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
836         if ( globals->get_route()->size() ) {
837             double course, distance;
838
839             old_lat = latitude_node->getDoubleValue();
840             old_lon = longitude_node->getDoubleValue();
841
842             waypoint = globals->get_route()->get_first();
843             waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
844                                         latitude_node->getDoubleValue(),
845                                         altitude_node->getDoubleValue()
846                                         * SG_FEET_TO_METER,
847                                         &course, &distance );
848             TargetHeading = course;
849             TargetDistance = distance;
850             MakeTargetLatLonStr( waypoint.get_target_lat(),
851                                  waypoint.get_target_lon() );
852             MakeTargetWPStr( distance );
853
854             if ( waypoint.get_target_alt() > 0.0 ) {
855                 TargetAltitude = waypoint.get_target_alt();
856                 altitude_mode = FG_ALTITUDE_LOCK;
857                 set_AltitudeEnabled( true );
858                 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
859             }
860
861             SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
862                     << get_TargetLatitude()  << " "
863                     << get_TargetLongitude() << " ) "
864                     );
865         } else {
866             // no more way points, default to heading lock.
867             heading_mode = FG_TC_HEADING_LOCK;
868         }
869     }
870
871     MakeTargetHeadingStr( TargetHeading );                      
872     update_old_control_values();
873 }
874
875
876 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
877     altitude_mode = mode;
878
879     alt_error_accum = 0.0;
880
881     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
882         if ( TargetAltitude < altitude_agl_node->getDoubleValue()
883              * SG_FEET_TO_METER ) {
884         }
885
886         if ( fgGetString("/sim/startup/units") == "feet" ) {
887             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
888         } else {
889             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
890         }
891     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
892         climb_error_accum = 0.0;
893
894     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
895         TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
896
897         if ( fgGetString("/sim/startup/units") == "feet" ) {
898             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
899         } else {
900             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
901         }
902     }
903     
904     update_old_control_values();
905     SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
906 }
907
908
909 #if 0
910 static inline double get_aoa( void ) {
911     return( cur_fdm_state->get_Gamma_vert_rad() * SGD_RADIANS_TO_DEGREES );
912 }
913
914 static inline double fgAPget_latitude( void ) {
915     return( cur_fdm_state->get_Latitude() * SGD_RADIANS_TO_DEGREES );
916 }
917
918 static inline double fgAPget_longitude( void ) {
919     return( cur_fdm_state->get_Longitude() * SGD_RADIANS_TO_DEGREES );
920 }
921
922 static inline double fgAPget_roll( void ) {
923     return( cur_fdm_state->get_Phi() * SGD_RADIANS_TO_DEGREES );
924 }
925
926 static inline double get_pitch( void ) {
927     return( cur_fdm_state->get_Theta() );
928 }
929
930 double fgAPget_heading( void ) {
931     return( cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES );
932 }
933
934 static inline double fgAPget_altitude( void ) {
935     return( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
936 }
937
938 static inline double fgAPget_climb( void ) {
939     // return in meters per minute
940     return( cur_fdm_state->get_Climb_Rate() * SG_FEET_TO_METER * 60 );
941 }
942
943 static inline double get_sideslip( void ) {
944     return( cur_fdm_state->get_Beta() );
945 }
946
947 static inline double fgAPget_agl( void ) {
948     double agl;
949
950     agl = cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
951         - scenery.get_cur_elev();
952
953     return( agl );
954 }
955 #endif
956
957
958 void FGAutopilot::AltitudeSet( double new_altitude ) {
959     double target_alt = new_altitude;
960
961     // cout << "new altitude = " << new_altitude << endl;
962
963     if ( fgGetString("/sim/startup/units") == "feet" ) {
964         target_alt = new_altitude * SG_FEET_TO_METER;
965     }
966
967     if( target_alt < scenery.get_cur_elev() ) {
968         target_alt = scenery.get_cur_elev();
969     }
970
971     TargetAltitude = target_alt;
972     altitude_mode = FG_ALTITUDE_LOCK;
973
974     // cout << "TargetAltitude = " << TargetAltitude << endl;
975
976     if ( fgGetString("/sim/startup/units") == "feet" ) {
977         target_alt *= SG_METER_TO_FEET;
978     }
979     // ApAltitudeDialogInput->setValue((float)target_alt);
980     MakeTargetAltitudeStr( target_alt );
981         
982     update_old_control_values();
983 }
984
985
986 void FGAutopilot::AltitudeAdjust( double inc )
987 {
988     double target_alt, target_agl;
989
990     if ( fgGetString("/sim/startup/units") == "feet" ) {
991         target_alt = TargetAltitude * SG_METER_TO_FEET;
992         target_agl = TargetAGL * SG_METER_TO_FEET;
993     } else {
994         target_alt = TargetAltitude;
995         target_agl = TargetAGL;
996     }
997
998     // cout << "target_agl = " << target_agl << endl;
999     // cout << "target_agl / inc = " << target_agl / inc << endl;
1000     // cout << "(int)(target_agl / inc) = " << (int)(target_agl / inc) << endl;
1001
1002     if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1003         target_alt += inc;
1004     } else {
1005         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1006     }
1007
1008     if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1009         target_agl += inc;
1010     } else {
1011         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1012     }
1013
1014     if ( fgGetString("/sim/startup/units") == "feet" ) {
1015         target_alt *= SG_FEET_TO_METER;
1016         target_agl *= SG_FEET_TO_METER;
1017     }
1018
1019     TargetAltitude = target_alt;
1020     TargetAGL = target_agl;
1021         
1022     if ( fgGetString("/sim/startup/units") == "feet" )
1023         target_alt *= SG_METER_TO_FEET;
1024     if ( fgGetString("/sim/startup/units") == "feet" )
1025         target_agl *= SG_METER_TO_FEET;
1026
1027     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
1028         MakeTargetAltitudeStr( target_alt );
1029     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1030         MakeTargetAltitudeStr( target_agl );
1031     }
1032
1033     update_old_control_values();
1034 }
1035
1036
1037 void FGAutopilot::HeadingAdjust( double inc ) {
1038     if ( heading_mode != FG_DG_HEADING_LOCK
1039          && heading_mode != FG_TRUE_HEADING_LOCK )
1040     {
1041         heading_mode = FG_DG_HEADING_LOCK;
1042     }
1043
1044     if ( heading_mode == FG_DG_HEADING_LOCK ) {
1045         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1046         DGTargetHeading = NormalizeDegrees( target );
1047     } else {
1048         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1049         TargetHeading = NormalizeDegrees( target );
1050     }
1051
1052     update_old_control_values();
1053 }
1054
1055
1056 void FGAutopilot::HeadingSet( double new_heading ) {
1057     if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1058         new_heading = NormalizeDegrees( new_heading );
1059         TargetHeading = new_heading;
1060         MakeTargetHeadingStr( TargetHeading );
1061     } else {
1062         heading_mode = FG_DG_HEADING_LOCK;
1063
1064         new_heading = NormalizeDegrees( new_heading );
1065         DGTargetHeading = new_heading;
1066         // following cast needed ambiguous plib
1067         // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1068         MakeTargetHeadingStr( DGTargetHeading );
1069     }
1070     update_old_control_values();
1071 }
1072
1073 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1074     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1075
1076     TargetSpeed = target;
1077 }
1078
1079
1080 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1081     auto_throttle = value;
1082
1083     if ( auto_throttle == true ) {
1084         TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1085         speed_error_accum = 0.0;
1086     }
1087
1088     update_old_control_values();
1089     SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1090             << auto_throttle << ") " << TargetSpeed );
1091 }