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