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