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