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