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