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