]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
Check point commit:
[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 #include <string.h>             // strcmp()
32
33 #include <simgear/constants.h>
34 #include <simgear/sg_inlines.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/math/sg_random.h>
38 #include <simgear/route/route.hxx>
39
40 #include <Cockpit/steam.hxx>
41 #include <Cockpit/radiostack.hxx>
42 #include <Controls/controls.hxx>
43 #include <FDM/flight.hxx>
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
46
47 #include "newauto.hxx"
48
49
50 /// These statics will eventually go into the class
51 /// they are just here while I am experimenting -- NHV :-)
52 // AutoPilot Gain Adjuster members
53 static double MaxRollAdjust;        // MaxRollAdjust       = 2 * APData->MaxRoll;
54 static double RollOutAdjust;        // RollOutAdjust       = 2 * APData->RollOut;
55 static double MaxAileronAdjust;     // MaxAileronAdjust    = 2 * APData->MaxAileron;
56 static double RollOutSmoothAdjust;  // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
57
58 static char NewTgtAirportId[16];
59 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID"; 
60
61 extern char *coord_format_lat(float);
62 extern char *coord_format_lon(float);
63                         
64
65 // constructor
66 FGAutopilot::FGAutopilot()
67 {
68 }
69
70 // destructor
71 FGAutopilot::~FGAutopilot() {}
72
73
74 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
75     sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
76     sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
77     sprintf( TargetLatLonStr, "%s  %s", TargetLatitudeStr, TargetLongitudeStr );
78 }
79
80
81 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
82     if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
83         sprintf( TargetAltitudeStr, "APAltitude  %6.0f+", altitude );
84     } else {
85         sprintf( TargetAltitudeStr, "APAltitude  %6.0f", altitude );
86     }
87 }
88
89
90 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
91     if ( bearing < 0. ) {
92         bearing += 360.;
93     } else if (bearing > 360. ) {
94         bearing -= 360.;
95     }
96     sprintf( TargetHeadingStr, "APHeading  %6.1f", bearing );
97 }
98
99
100 static inline double get_speed( void ) {
101     return( cur_fdm_state->get_V_equiv_kts() );
102 }
103
104 static inline double get_ground_speed() {
105     // starts in ft/s so we convert to kts
106     static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
107
108     double ft_s = cur_fdm_state->get_V_ground_speed() 
109         * speedup_node->getIntValue();
110     double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
111
112     return kts;
113 }
114
115
116 void FGAutopilot::MakeTargetWPStr( double distance ) {
117     static time_t last_time = 0;
118     time_t current_time = time(NULL);
119     if ( last_time == current_time ) {
120         return;
121     }
122
123     last_time = current_time;
124
125     double accum = 0.0;
126
127     int size = globals->get_route()->size();
128
129     // start by wiping the strings
130     TargetWP1Str[0] = 0;
131     TargetWP2Str[0] = 0;
132     TargetWP3Str[0] = 0;
133
134     // current route
135     if ( size > 0 ) {
136         SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
137         accum += distance;
138         double eta = accum * SG_METER_TO_NM / get_ground_speed();
139         if ( eta >= 100.0 ) { eta = 99.999; }
140         int major, minor;
141         if ( eta < (1.0/6.0) ) {
142             // within 10 minutes, bump up to min/secs
143             eta *= 60.0;
144         }
145         major = (int)eta;
146         minor = (int)((eta - (int)eta) * 60.0);
147         sprintf( TargetWP1Str, "%s %.2f NM  ETA %d:%02d",
148                  wp1.get_id().c_str(),
149                  accum*SG_METER_TO_NM, major, minor );
150     }
151
152     // next route
153     if ( size > 1 ) {
154         SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
155         accum += wp2.get_distance();
156         
157         double eta = accum * SG_METER_TO_NM / get_ground_speed();
158         if ( eta >= 100.0 ) { eta = 99.999; }
159         int major, minor;
160         if ( eta < (1.0/6.0) ) {
161             // within 10 minutes, bump up to min/secs
162             eta *= 60.0;
163         }
164         major = (int)eta;
165         minor = (int)((eta - (int)eta) * 60.0);
166         sprintf( TargetWP2Str, "%s %.2f NM  ETA %d:%02d",
167                  wp2.get_id().c_str(),
168                  accum*SG_METER_TO_NM, major, minor );
169     }
170
171     // next route
172     if ( size > 2 ) {
173         for ( int i = 2; i < size; ++i ) {
174             accum += globals->get_route()->get_waypoint( i ).get_distance();
175         }
176         
177         SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
178
179         double eta = accum * SG_METER_TO_NM / get_ground_speed();
180         if ( eta >= 100.0 ) { eta = 99.999; }
181         int major, minor;
182         if ( eta < (1.0/6.0) ) {
183             // within 10 minutes, bump up to min/secs
184             eta *= 60.0;
185         }
186         major = (int)eta;
187         minor = (int)((eta - (int)eta) * 60.0);
188         sprintf( TargetWP3Str, "%s %.2f NM  ETA %d:%02d",
189                  wpn.get_id().c_str(),
190                  accum*SG_METER_TO_NM, major, minor );
191     }
192 }
193
194
195 void FGAutopilot::update_old_control_values() {
196     old_aileron = globals->get_controls()->get_aileron();
197     old_elevator = globals->get_controls()->get_elevator();
198     old_elevator_trim = globals->get_controls()->get_elevator_trim();
199     old_rudder = globals->get_controls()->get_rudder();
200 }
201
202
203 // Initialize autopilot subsystem
204
205 void FGAutopilot::init ()
206 {
207     SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
208
209     // bind data input property nodes...
210     latitude_node = fgGetNode("/position/latitude-deg", true);
211     longitude_node = fgGetNode("/position/longitude-deg", true);
212     altitude_node = fgGetNode("/position/altitude-ft", true);
213     altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
214     vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
215     heading_node = fgGetNode("/orientation/heading-deg", true);
216     roll_node = fgGetNode("/orientation/roll-deg", true);
217     pitch_node = fgGetNode("/orientation/pitch-deg", true);
218
219
220
221     // bind config property nodes...
222     TargetClimbRate
223         = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
224     TargetDescentRate
225         = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
226     min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
227     best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
228     elevator_adj_factor
229         = fgGetNode("/autopilot/config/elevator-adj-factor", true);
230     integral_contrib
231         = fgGetNode("/autopilot/config/integral-contribution", true);
232     zero_pitch_throttle
233         = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
234     zero_pitch_trim_full_throttle
235         = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
236     max_aileron_node = fgGetNode("/autopilot/config/max-aileron", true);
237     max_roll_node = fgGetNode("/autopilot/config/max-roll-deg", true);
238     roll_out_node = fgGetNode("/autopilot/config/roll-out-deg", true);
239     roll_out_smooth_node = fgGetNode("/autopilot/config/roll-out-smooth-deg", true);
240
241     current_throttle = fgGetNode("/controls/throttle");
242
243     // initialize config properties with defaults (in case config isn't there)
244     if ( TargetClimbRate->getFloatValue() < 1 )
245         fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
246     if ( TargetDescentRate->getFloatValue() < 1 )
247         fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
248     if ( min_climb->getFloatValue() < 1)
249         fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
250     if (best_climb->getFloatValue() < 1)
251         fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
252     if (elevator_adj_factor->getFloatValue() < 1)
253         fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
254     if ( integral_contrib->getFloatValue() < 0.0000001 )
255         fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
256     if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
257         fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
258     if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
259         fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
260     if ( max_aileron_node->getFloatValue() < 0.0000001 )
261         fgSetFloat( "/autopilot/config/max-aileron", 0.2 );
262     if ( max_roll_node->getFloatValue() < 0.0000001 )
263         fgSetFloat( "/autopilot/config/max-roll-deg", 20 );
264     if ( roll_out_node->getFloatValue() < 0.0000001 )
265         fgSetFloat( "/autopilot/config/roll-out-deg", 20 );
266     if ( roll_out_smooth_node->getFloatValue() < 0.0000001 )
267         fgSetFloat( "/autopilot/config/roll-out-smooth-deg", 10 );
268
269     /* set defaults */
270     heading_hold = false ;      // turn the heading hold off
271     altitude_hold = false ;     // turn the altitude hold off
272     auto_throttle = false ;     // turn the auto throttle off
273     heading_mode = DEFAULT_AP_HEADING_LOCK;
274     altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
275
276     DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
277     TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
278     TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
279
280     // Initialize target location to startup location
281     old_lat = latitude_node->getDoubleValue();
282     old_lon = longitude_node->getDoubleValue();
283     // set_WayPoint( old_lon, old_lat, 0.0, "default" );
284
285     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
286         
287     alt_error_accum = 0.0;
288     climb_error_accum = 0.0;
289
290     MakeTargetAltitudeStr( TargetAltitude );
291     MakeTargetHeadingStr( TargetHeading );
292         
293     // These eventually need to be read from current_aircaft somehow.
294
295     // the maximum roll, in Deg
296     MaxRoll = 20;
297
298     // the deg from heading to start rolling out at, in Deg
299     RollOut = 20;
300
301     // Smoothing distance for alerion control
302     RollOutSmooth = 10;
303
304     // Hardwired for now should be in options
305     // 25% max control variablilty  0.5 / 2.0
306     disengage_threshold = 1.0;
307
308     // set default aileron max deflection
309     MaxAileron = 0.5;
310
311 #if !defined( USING_SLIDER_CLASS )
312     MaxRollAdjust = 2 * MaxRoll;
313     RollOutAdjust = 2 * RollOut;
314     //MaxAileronAdjust = 2 * MaxAileron;
315     RollOutSmoothAdjust = 2 * RollOutSmooth;
316 #endif  // !defined( USING_SLIDER_CLASS )
317
318     update_old_control_values();
319 };
320
321 void
322 FGAutopilot::bind ()
323 {
324     // Autopilot control property get/set bindings
325     fgTie("/autopilot/locks/altitude", this,
326           &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
327     fgSetArchivable("/autopilot/locks/altitude");
328     fgTie("/autopilot/settings/altitude-ft", this,
329           &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
330     fgSetArchivable("/autopilot/settings/altitude-ft");
331     fgTie("/autopilot/locks/glide-slope", this,
332           &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
333     fgSetArchivable("/autopilot/locks/glide-slope");
334     fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
335     fgTie("/autopilot/locks/terrain", this,
336           &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
337     fgSetArchivable("/autopilot/locks/terrain");
338     fgTie("/autopilot/settings/climb-rate-fpm", this,
339           &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
340     fgSetArchivable("/autopilot/settings/climb-rate-fpm");
341     fgTie("/autopilot/locks/heading", this,
342           &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
343     fgSetArchivable("/autopilot/locks/heading");
344     fgTie("/autopilot/settings/heading-bug-deg", this,
345           &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
346     fgSetArchivable("/autopilot/settings/heading-bug-deg");
347     fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
348     fgTie("/autopilot/locks/wing-leveler", this,
349           &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
350     fgSetArchivable("/autopilot/locks/wing-leveler");
351     fgTie("/autopilot/locks/nav[0]", this,
352           &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
353     fgSetArchivable("/autopilot/locks/nav[0]");
354     fgTie("/autopilot/locks/auto-throttle", this,
355           &FGAutopilot::getAPAutoThrottleLock,
356           &FGAutopilot::setAPAutoThrottleLock);
357     fgSetArchivable("/autopilot/locks/auto-throttle");
358     fgTie("/autopilot/control-overrides/rudder", this,
359           &FGAutopilot::getAPRudderControl,
360           &FGAutopilot::setAPRudderControl);
361     fgSetArchivable("/autopilot/control-overrides/rudder");
362     fgTie("/autopilot/control-overrides/elevator", this,
363           &FGAutopilot::getAPElevatorControl,
364           &FGAutopilot::setAPElevatorControl);
365     fgSetArchivable("/autopilot/control-overrides/elevator");
366     fgTie("/autopilot/control-overrides/throttle", this,
367           &FGAutopilot::getAPThrottleControl,
368           &FGAutopilot::setAPThrottleControl);
369     fgSetArchivable("/autopilot/control-overrides/throttle");
370 }
371
372 void
373 FGAutopilot::unbind ()
374 {
375 }
376
377 // Reset the autopilot system
378 void FGAutopilot::reset() {
379
380     heading_hold = false ;      // turn the heading hold off
381     altitude_hold = false ;     // turn the altitude hold off
382     auto_throttle = false ;     // turn the auto throttle off
383     heading_mode = DEFAULT_AP_HEADING_LOCK;
384
385     // TargetHeading = 0.0;     // default direction, due north
386     MakeTargetHeadingStr( TargetHeading );                      
387         
388     // TargetAltitude = 3000;   // default altitude in meters
389     MakeTargetAltitudeStr( TargetAltitude );
390         
391     alt_error_accum = 0.0;
392     climb_error_accum = 0.0;
393         
394     update_old_control_values();
395
396     sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id") );
397         
398     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
399 }
400
401
402 static double NormalizeDegrees( double Input ) {
403     // normalize the input to the range (-180,180]
404     // Input should not be greater than -360 to 360.
405     // Current rules send the output to an undefined state.
406     while ( Input > 180.0 ) { Input -= 360.0; }
407     while ( Input <= -180.0 ) { Input += 360.0; }
408
409     return Input;
410 };
411
412 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
413     // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
414     //assert(x1 != x2); // Divide by zero error.  Cold abort for now
415
416         // Could be
417         // static double y = 0.0;
418         // double dx = x2 -x1;
419         // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
420         // {
421
422     double m, b, y;          // the constants to find in y=mx+b
423     // double m, b;
424
425     m = ( y2 - y1 ) / ( x2 - x1 );   // calculate the m
426
427     b = y1 - m * x1;       // calculate the b
428
429     y = m * x + b;       // the final calculation
430
431     // }
432
433     return ( y );
434
435 };
436
437
438 void
439 FGAutopilot::update (double dt)
440 {
441     // Remove the following lines when the calling funcitons start
442     // passing in the data pointer
443
444     // get control settings 
445         
446     double lat = latitude_node->getDoubleValue();
447     double lon = longitude_node->getDoubleValue();
448     double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
449
450     // get config settings
451     MaxAileron = max_aileron_node->getDoubleValue();
452     MaxRoll = max_roll_node->getDoubleValue();
453     RollOut = roll_out_node->getDoubleValue();
454     RollOutSmooth = roll_out_smooth_node->getDoubleValue();
455
456     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run()  lat = " << lat <<
457             "  lon = " << lon << "  alt = " << alt );
458         
459 #ifdef FG_FORCE_AUTO_DISENGAGE
460     // see if somebody else has changed them
461     if( fabs(aileron - old_aileron) > disengage_threshold ||
462         fabs(elevator - old_elevator) > disengage_threshold ||
463         fabs(elevator_trim - old_elevator_trim) > 
464         disengage_threshold ||          
465         fabs(rudder - old_rudder) > disengage_threshold )
466     {
467         // if controls changed externally turn autopilot off
468         waypoint_hold = false ;   // turn the target hold off
469         heading_hold = false ;    // turn the heading hold off
470         altitude_hold = false ;   // turn the altitude hold off
471         terrain_follow = false;   // turn the terrain_follow hold off
472         // auto_throttle = false; // turn the auto_throttle off
473
474         // stash this runs control settings
475         old_aileron = aileron;
476         old_elevator = elevator;
477         old_elevator_trim = elevator_trim;
478         old_rudder = rudder;
479         
480         return 0;
481     }
482 #endif
483         
484     // heading hold
485     if ( heading_hold == true ) {
486         if ( heading_mode == FG_DG_HEADING_LOCK ) {
487             TargetHeading = DGTargetHeading +
488               globals->get_steam()->get_DG_err();
489             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
490             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
491             MakeTargetHeadingStr( TargetHeading );
492         } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
493             // we don't set a specific target heading in
494             // TC_HEADING_LOCK mode, we instead try to keep the turn
495             // coordinator zero'd
496         } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
497             // leave "true" target heading as is
498             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
499             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
500             MakeTargetHeadingStr( TargetHeading );
501         } else if ( heading_mode == FG_HEADING_NAV1 ) {
502             // track the NAV1 heading needle deflection
503
504             // determine our current radial position relative to the
505             // navaid in "true" heading.
506             double cur_radial = current_radiostack->get_navcom1()->get_nav_heading();
507             if ( current_radiostack->get_navcom1()->get_nav_loc() ) {
508                 // ILS localizers radials are already "true" in our
509                 // database
510             } else {
511                 cur_radial += current_radiostack->get_navcom1()->get_nav_magvar();
512             }
513             if ( current_radiostack->get_navcom1()->get_nav_from_flag() ) {
514                 cur_radial += 180.0;
515                 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
516             }
517
518             // determine the target radial in "true" heading
519             double tgt_radial = current_radiostack->get_navcom1()->get_nav_radial();
520             if ( current_radiostack->get_navcom1()->get_nav_loc() ) {
521                 // ILS localizers radials are already "true" in our
522                 // database
523             } else {
524                 // VOR radials need to have that vor's offset added in
525                 tgt_radial += current_radiostack->get_navcom1()->get_nav_magvar();
526             }
527
528             // determine the heading adjustment needed.
529             double adjustment = 
530                 current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()
531                 * (current_radiostack->get_navcom1()->get_nav_loc_dist() * SG_METER_TO_NM);
532             SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
533
534             // clamp closer when inside cone when beyond 5km...
535             if (current_radiostack->get_navcom1()->get_nav_loc_dist() > 5000) {
536               double clamp_angle = fabs(current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()) * 3;
537               if (clamp_angle < 30)
538                 SG_CLAMP_RANGE( adjustment, -clamp_angle, clamp_angle);
539             }
540
541             // determine the target heading to fly to intercept the
542             // tgt_radial
543             TargetHeading = tgt_radial + adjustment; 
544             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
545             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
546
547             MakeTargetHeadingStr( TargetHeading );
548         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
549             // update target heading to waypoint
550
551             double wp_course, wp_distance;
552
553 #ifdef DO_fgAP_CORRECTED_COURSE
554             // compute course made good
555             // this needs lots of special casing before use
556             double course, reverse, distance, corrected_course;
557             // need to test for iter
558             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
559                                 old_lat,
560                                 old_lon,
561                                 lat,
562                                 lon,
563                                 &course,
564                                 &reverse,
565                                 &distance );
566 #endif // DO_fgAP_CORRECTED_COURSE
567
568             // compute course to way_point
569             // need to test for iter
570             SGWayPoint wp = globals->get_route()->get_first();
571             wp.CourseAndDistance( lon, lat, alt, 
572                                   &wp_course, &wp_distance );
573
574 #ifdef DO_fgAP_CORRECTED_COURSE
575             corrected_course = course - wp_course;
576             if( fabs(corrected_course) > 0.1 )
577                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
578                        course, wp_course, fabs(corrected_course),
579                        distance );
580 #endif // DO_fgAP_CORRECTED_COURSE
581                 
582             if ( wp_distance > 100 ) {
583                 // corrected_course = course - wp_course;
584                 TargetHeading = NormalizeDegrees(wp_course);
585             } else {
586                 // pop off this waypoint from the list
587                 if ( globals->get_route()->size() ) {
588                     globals->get_route()->delete_first();
589                 }
590
591                 // see if there are more waypoints on the list
592                 if ( globals->get_route()->size() ) {
593                     // more waypoints
594                     set_HeadingMode( FG_HEADING_WAYPOINT );
595                 } else {
596                     // end of the line
597                     heading_mode = FG_TRUE_HEADING_LOCK;
598                     // use current heading
599                     TargetHeading = heading_node->getDoubleValue();
600                 }
601             }
602             MakeTargetHeadingStr( TargetHeading );
603             // Force this just in case
604             TargetDistance = wp_distance;
605             MakeTargetWPStr( wp_distance );
606         }
607
608         if ( heading_mode == FG_TC_HEADING_LOCK ) {
609             // drive the turn coordinator to zero
610             double turn = globals->get_steam()->get_TC_std();
611             double AileronSet = -turn / 2.0;
612             SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
613             globals->get_controls()->set_aileron( AileronSet );
614             globals->get_controls()->set_rudder( AileronSet / 4.0 );
615         } else {
616             // steer towards the target heading
617
618             double RelHeading;
619             double TargetRoll;
620             double RelRoll;
621             double AileronSet;
622
623             RelHeading
624                 = NormalizeDegrees( TargetHeading
625                                     - heading_node->getDoubleValue() );
626             // figure out how far off we are from desired heading
627
628             // Now it is time to deterime how far we should be rolled.
629             SG_LOG( SG_AUTOPILOT, SG_DEBUG,
630                     "Heading = " << heading_node->getDoubleValue() <<
631                     " TargetHeading = " << TargetHeading <<
632                     " RelHeading = " << RelHeading );
633
634             // Check if we are further from heading than the roll out point
635             if ( fabs( RelHeading ) > RollOut ) {
636                 // set Target Roll to Max in desired direction
637                 if ( RelHeading < 0 ) {
638                     TargetRoll = 0 - MaxRoll;
639                 } else {
640                     TargetRoll = MaxRoll;
641                 }
642             } else {
643                 // We have to calculate the Target roll
644
645                 // This calculation engine thinks that the Target roll
646                 // should be a line from (RollOut,MaxRoll) to (-RollOut,
647                 // -MaxRoll) I hope this works well.  If I get ambitious
648                 // some day this might become a fancier curve or
649                 // something.
650
651                 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
652                                                 -MaxRoll, RollOut,
653                                                 MaxRoll );
654             }
655
656             // Target Roll has now been Found.
657
658             // Compare Target roll to Current Roll, Generate Rel Roll
659
660             SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
661
662             RelRoll = NormalizeDegrees( TargetRoll 
663                                         - roll_node->getDoubleValue() );
664
665             // Check if we are further from heading than the roll out
666             // smooth point
667             if ( fabs( RelRoll ) > RollOutSmooth ) {
668                 // set Target Roll to Max in desired direction
669                 if ( RelRoll < 0 ) {
670                 AileronSet = 0 - MaxAileron;
671                 } else {
672                     AileronSet = MaxAileron;
673                 }
674             } else {
675                 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
676                                                 -MaxAileron,
677                                                 RollOutSmooth,
678                                                 MaxAileron );
679             }
680
681             globals->get_controls()->set_aileron( AileronSet );
682             globals->get_controls()->set_rudder( AileronSet / 4.0 );
683             // controls.set_rudder( 0.0 );
684         }
685     }
686
687     // altitude hold
688     if ( altitude_hold ) {
689         double climb_rate;
690         double speed, max_climb, error;
691         double prop_error, int_error;
692         double prop_adj, int_adj, total_adj;
693
694         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
695             climb_rate =
696                 ( TargetAltitude -
697                   globals->get_steam()->get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
698         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
699             double x = current_radiostack->get_navcom1()->get_nav_gs_dist();
700             double y = (altitude_node->getDoubleValue()
701                         - current_radiostack->get_navcom1()->get_nav_elev()) * SG_FEET_TO_METER;
702             double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
703
704             double target_angle = current_radiostack->get_navcom1()->get_nav_target_gs();
705
706             double gs_diff = target_angle - current_angle;
707
708             // convert desired vertical path angle into a climb rate
709             double des_angle = current_angle - 10 * gs_diff;
710
711             // convert to meter/min
712             double horiz_vel = cur_fdm_state->get_V_ground_speed()
713                 * SG_FEET_TO_METER * 60.0;
714             climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
715             /* climb_error_accum += gs_diff * 2.0; */
716             /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
717         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
718             // brain dead ground hugging with no look ahead
719             climb_rate =
720                 ( TargetAGL - altitude_agl_node->getDoubleValue()
721                   * SG_FEET_TO_METER ) * 16.0;
722         } else {
723             // just try to zero out rate of climb ...
724             climb_rate = 0.0;
725         }
726
727         speed = get_speed();
728
729         if ( speed < min_climb->getFloatValue() ) {
730             max_climb = 0.0;
731         } else if ( speed < best_climb->getFloatValue() ) {
732             max_climb = ((best_climb->getFloatValue()
733                           - min_climb->getFloatValue())
734                          - (best_climb->getFloatValue() - speed)) 
735                 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) 
736                 / (best_climb->getFloatValue() - min_climb->getFloatValue());
737         } else {                        
738             max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
739                 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
740         }
741
742         // this first one could be optional if we wanted to allow
743         // better climb performance assuming we have the airspeed to
744         // support it.
745         if ( climb_rate >
746              fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
747             climb_rate
748                 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
749         }
750
751         if ( climb_rate > max_climb ) {
752             climb_rate = max_climb;
753         }
754
755         if ( climb_rate <
756              -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
757             climb_rate
758                 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
759         }
760
761         error = vertical_speed_node->getDoubleValue() * 60
762             - climb_rate * SG_METER_TO_FEET;
763
764         // accumulate the error under the curve ... this really should
765         // be *= delta t
766         alt_error_accum += error;
767
768         // calculate integral error, and adjustment amount
769         int_error = alt_error_accum;
770         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
771         
772         // scale elev_adj_factor by speed of aircraft in relation to min climb 
773         double elev_adj_factor = elevator_adj_factor->getFloatValue();
774         elev_adj_factor *=
775           pow(float(speed / min_climb->getFloatValue()), 3.0f);
776
777         int_adj = int_error / elev_adj_factor;
778
779         // caclulate proportional error
780         prop_error = error;
781         prop_adj = prop_error / elev_adj_factor;
782
783         total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
784             + (double) integral_contrib->getFloatValue() * int_adj;
785
786         // stop on autopilot trim at 30% +/-
787 //      if ( total_adj > 0.3 ) {
788 //           total_adj = 0.3;
789 //       } else if ( total_adj < -0.3 ) {
790 //           total_adj = -0.3;
791 //       }
792
793         // adjust for throttle pitch gain
794         total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
795                      / (1 - zero_pitch_throttle->getFloatValue()))
796                      * zero_pitch_trim_full_throttle->getFloatValue();
797
798         globals->get_controls()->set_elevator_trim( total_adj );
799     }
800
801     // auto throttle
802     if ( auto_throttle ) {
803         double error;
804         double prop_error, int_error;
805         double prop_adj, int_adj, total_adj;
806
807         error = TargetSpeed - get_speed();
808
809         // accumulate the error under the curve ... this really should
810         // be *= delta t
811         speed_error_accum += error;
812         if ( speed_error_accum > 2000.0 ) {
813             speed_error_accum = 2000.0;
814         }
815         else if ( speed_error_accum < -2000.0 ) {
816             speed_error_accum = -2000.0;
817         }
818
819         // calculate integral error, and adjustment amount
820         int_error = speed_error_accum;
821
822         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
823         int_adj = int_error / 200.0;
824
825         // caclulate proportional error
826         prop_error = error;
827         prop_adj = 0.5 + prop_error / 50.0;
828
829         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
830         if ( total_adj > 1.0 ) {
831             total_adj = 1.0;
832         }
833         else if ( total_adj < 0.0 ) {
834             total_adj = 0.0;
835         }
836
837         globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
838                                                total_adj );
839     }
840
841 #ifdef THIS_CODE_IS_NOT_USED
842     if (Mode == 2) // Glide slope hold
843         {
844             double RelSlope;
845             double RelElevator;
846
847             // First, calculate Relative slope and normalize it
848             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
849
850             // Now calculate the elevator offset from current angle
851             if ( abs(RelSlope) > SlopeSmooth )
852                 {
853                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
854                         RelElevator = -MaxElevator;
855                     else
856                         RelElevator = MaxElevator;
857                 }
858
859             else
860                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
861
862             // set the elevator
863             fgElevMove(RelElevator);
864
865         }
866 #endif // THIS_CODE_IS_NOT_USED
867
868     // stash this runs control settings
869     //  update_old_control_values();
870     old_aileron = globals->get_controls()->get_aileron();
871     old_elevator = globals->get_controls()->get_elevator();
872     old_elevator_trim = globals->get_controls()->get_elevator_trim();
873     old_rudder = globals->get_controls()->get_rudder();
874
875     // for cross track error
876     old_lat = lat;
877     old_lon = lon;
878         
879     // Ok, we are done
880     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
881 }
882
883
884 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
885     heading_mode = mode;
886
887     if ( heading_mode == FG_DG_HEADING_LOCK ) {
888         // set heading hold to current heading (as read from DG)
889         // ... no, leave target heading along ... just use the current
890         // heading bug value
891         //  DGTargetHeading = FGSteam::get_DG_deg();
892     } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
893         // set autopilot to hold a zero turn (as reported by the TC)
894     } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
895         // set heading hold to current heading
896         TargetHeading = heading_node->getDoubleValue();
897     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
898         if ( globals->get_route()->size() ) {
899             double course, distance;
900
901             old_lat = latitude_node->getDoubleValue();
902             old_lon = longitude_node->getDoubleValue();
903
904             waypoint = globals->get_route()->get_first();
905             waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
906                                         latitude_node->getDoubleValue(),
907                                         altitude_node->getDoubleValue()
908                                         * SG_FEET_TO_METER,
909                                         &course, &distance );
910             TargetHeading = course;
911             TargetDistance = distance;
912             MakeTargetLatLonStr( waypoint.get_target_lat(),
913                                  waypoint.get_target_lon() );
914             MakeTargetWPStr( distance );
915
916             if ( waypoint.get_target_alt() > 0.0 ) {
917                 TargetAltitude = waypoint.get_target_alt();
918                 altitude_mode = FG_ALTITUDE_LOCK;
919                 set_AltitudeEnabled( true );
920                 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
921             }
922
923             SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
924                     << get_TargetLatitude()  << " "
925                     << get_TargetLongitude() << " ) "
926                     );
927         } else {
928             // no more way points, default to heading lock.
929             heading_mode = FG_TC_HEADING_LOCK;
930         }
931     }
932
933     MakeTargetHeadingStr( TargetHeading );                      
934     update_old_control_values();
935 }
936
937
938 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
939     altitude_mode = mode;
940
941     alt_error_accum = 0.0;
942
943
944     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
945         if ( TargetAltitude < altitude_agl_node->getDoubleValue()
946              * SG_FEET_TO_METER ) {
947         }
948
949         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
950             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
951         } else {
952             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
953         }
954     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
955         climb_error_accum = 0.0;
956
957     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
958         TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
959
960         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
961             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
962         } else {
963             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
964         }
965     }
966     
967     update_old_control_values();
968     SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
969 }
970
971
972 void FGAutopilot::AltitudeSet( double new_altitude ) {
973     double target_alt = new_altitude;
974
975     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
976         target_alt = new_altitude * SG_FEET_TO_METER;
977     }
978
979     if( target_alt < globals->get_scenery()->get_cur_elev() ) {
980         target_alt = globals->get_scenery()->get_cur_elev();
981     }
982
983     TargetAltitude = target_alt;
984     altitude_mode = FG_ALTITUDE_LOCK;
985
986     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
987         target_alt *= SG_METER_TO_FEET;
988     }
989     // ApAltitudeDialogInput->setValue((float)target_alt);
990     MakeTargetAltitudeStr( target_alt );
991         
992     update_old_control_values();
993 }
994
995
996 void FGAutopilot::AltitudeAdjust( double inc )
997 {
998     double target_alt, target_agl;
999
1000     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1001         target_alt = TargetAltitude * SG_METER_TO_FEET;
1002         target_agl = TargetAGL * SG_METER_TO_FEET;
1003     } else {
1004         target_alt = TargetAltitude;
1005         target_agl = TargetAGL;
1006     }
1007
1008     if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1009         target_alt += inc;
1010     } else {
1011         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1012     }
1013
1014     if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1015         target_agl += inc;
1016     } else {
1017         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1018     }
1019
1020     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1021         target_alt *= SG_FEET_TO_METER;
1022         target_agl *= SG_FEET_TO_METER;
1023     }
1024
1025     TargetAltitude = target_alt;
1026     TargetAGL = target_agl;
1027         
1028     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1029         target_alt *= SG_METER_TO_FEET;
1030     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1031         target_agl *= SG_METER_TO_FEET;
1032
1033     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
1034         MakeTargetAltitudeStr( target_alt );
1035     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1036         MakeTargetAltitudeStr( target_agl );
1037     }
1038
1039     update_old_control_values();
1040 }
1041
1042
1043 void FGAutopilot::HeadingAdjust( double inc ) {
1044     if ( heading_mode != FG_DG_HEADING_LOCK
1045          && heading_mode != FG_TRUE_HEADING_LOCK )
1046     {
1047         heading_mode = FG_DG_HEADING_LOCK;
1048     }
1049
1050     if ( heading_mode == FG_DG_HEADING_LOCK ) {
1051         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1052         DGTargetHeading = NormalizeDegrees( target );
1053     } else {
1054         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1055         TargetHeading = NormalizeDegrees( target );
1056     }
1057
1058     update_old_control_values();
1059 }
1060
1061
1062 void FGAutopilot::HeadingSet( double new_heading ) {
1063     if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1064         new_heading = NormalizeDegrees( new_heading );
1065         TargetHeading = new_heading;
1066         MakeTargetHeadingStr( TargetHeading );
1067     } else {
1068         heading_mode = FG_DG_HEADING_LOCK;
1069
1070         new_heading = NormalizeDegrees( new_heading );
1071         DGTargetHeading = new_heading;
1072         // following cast needed ambiguous plib
1073         // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1074         MakeTargetHeadingStr( DGTargetHeading );
1075     }
1076     update_old_control_values();
1077 }
1078
1079 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1080     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1081
1082     TargetSpeed = target;
1083 }
1084
1085
1086 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1087     auto_throttle = value;
1088
1089     if ( auto_throttle == true ) {
1090         TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1091         speed_error_accum = 0.0;
1092     }
1093
1094     update_old_control_values();
1095     SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1096             << auto_throttle << ") " << TargetSpeed );
1097 }
1098
1099
1100
1101 \f
1102 ////////////////////////////////////////////////////////////////////////
1103 // Kludged methods for tying to properties.
1104 //
1105 // These should change eventually; they all used to be static
1106 // functions.
1107 ////////////////////////////////////////////////////////////////////////
1108
1109 /**
1110  * Get the autopilot altitude lock (true=on).
1111  */
1112 bool
1113 FGAutopilot::getAPAltitudeLock () const
1114 {
1115     return (get_AltitudeEnabled() &&
1116             get_AltitudeMode()
1117             == FGAutopilot::FG_ALTITUDE_LOCK);
1118 }
1119
1120
1121 /**
1122  * Set the autopilot altitude lock (true=on).
1123  */
1124 void
1125 FGAutopilot::setAPAltitudeLock (bool lock)
1126 {
1127   if (lock)
1128     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_LOCK);
1129   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_LOCK)
1130     set_AltitudeEnabled(lock);
1131 }
1132
1133
1134 /**
1135  * Get the autopilot target altitude in feet.
1136  */
1137 double
1138 FGAutopilot::getAPAltitude () const
1139 {
1140   return get_TargetAltitude() * SG_METER_TO_FEET;
1141 }
1142
1143
1144 /**
1145  * Set the autopilot target altitude in feet.
1146  */
1147 void
1148 FGAutopilot::setAPAltitude (double altitude)
1149 {
1150   set_TargetAltitude( altitude * SG_FEET_TO_METER );
1151 }
1152
1153 /**
1154  * Get the autopilot altitude lock (true=on).
1155  */
1156 bool
1157 FGAutopilot::getAPGSLock () const
1158 {
1159     return (get_AltitudeEnabled() &&
1160             (get_AltitudeMode()
1161              == FGAutopilot::FG_ALTITUDE_GS1));
1162 }
1163
1164
1165 /**
1166  * Set the autopilot altitude lock (true=on).
1167  */
1168 void
1169 FGAutopilot::setAPGSLock (bool lock)
1170 {
1171   if (lock)
1172     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1173   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1174     set_AltitudeEnabled(lock);
1175 }
1176
1177
1178 /**
1179  * Get the autopilot terrain lock (true=on).
1180  */
1181 bool
1182 FGAutopilot::getAPTerrainLock () const
1183 {
1184     return (get_AltitudeEnabled() &&
1185             (get_AltitudeMode()
1186              == FGAutopilot::FG_ALTITUDE_TERRAIN));
1187 }
1188
1189
1190 /**
1191  * Set the autopilot terrain lock (true=on).
1192  */
1193 void
1194 FGAutopilot::setAPTerrainLock (bool lock)
1195 {
1196   if (lock) {
1197     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1198     set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1199                   SG_FEET_TO_METER);
1200   }
1201   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1202     set_AltitudeEnabled(lock);
1203 }
1204
1205
1206 /**
1207  * Get the autopilot target altitude in feet.
1208  */
1209 double
1210 FGAutopilot::getAPClimb () const
1211 {
1212   return get_TargetClimbRate() * SG_METER_TO_FEET;
1213 }
1214
1215
1216 /**
1217  * Set the autopilot target altitude in feet.
1218  */
1219 void
1220 FGAutopilot::setAPClimb (double rate)
1221 {
1222     set_TargetClimbRate( rate * SG_FEET_TO_METER );
1223 }
1224
1225
1226 /**
1227  * Get the autopilot heading lock (true=on).
1228  */
1229 bool
1230 FGAutopilot::getAPHeadingLock () const
1231 {
1232     return
1233       (get_HeadingEnabled() &&
1234        get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1235 }
1236
1237
1238 /**
1239  * Set the autopilot heading lock (true=on).
1240  */
1241 void
1242 FGAutopilot::setAPHeadingLock (bool lock)
1243 {
1244   if (lock)
1245     set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1246   if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1247     set_HeadingEnabled(lock);
1248 }
1249
1250
1251 /**
1252  * Get the autopilot heading bug in degrees.
1253  */
1254 double
1255 FGAutopilot::getAPHeadingBug () const
1256 {
1257   return get_DGTargetHeading();
1258 }
1259
1260
1261 /**
1262  * Set the autopilot heading bug in degrees.
1263  */
1264 void
1265 FGAutopilot::setAPHeadingBug (double heading)
1266 {
1267   set_DGTargetHeading( heading );
1268 }
1269
1270
1271 /**
1272  * Get the autopilot wing leveler lock (true=on).
1273  */
1274 bool
1275 FGAutopilot::getAPWingLeveler () const
1276 {
1277     return
1278       (get_HeadingEnabled() &&
1279        get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1280 }
1281
1282
1283 /**
1284  * Set the autopilot wing leveler lock (true=on).
1285  */
1286 void
1287 FGAutopilot::setAPWingLeveler (bool lock)
1288 {
1289     if (lock)
1290         set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1291     if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1292       set_HeadingEnabled(lock);
1293 }
1294
1295 /**
1296  * Return true if the autopilot is locked to NAV1.
1297  */
1298 bool
1299 FGAutopilot::getAPNAV1Lock () const
1300 {
1301   return
1302     (get_HeadingEnabled() &&
1303      get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1304 }
1305
1306
1307 /**
1308  * Set the autopilot NAV1 lock.
1309  */
1310 void
1311 FGAutopilot::setAPNAV1Lock (bool lock)
1312 {
1313   if (lock)
1314     set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1315   if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1316     set_HeadingEnabled(lock);
1317 }
1318
1319 /**
1320  * Get the autopilot autothrottle lock.
1321  */
1322 bool
1323 FGAutopilot::getAPAutoThrottleLock () const
1324 {
1325   return get_AutoThrottleEnabled();
1326 }
1327
1328
1329 /**
1330  * Set the autothrottle lock.
1331  */
1332 void
1333 FGAutopilot::setAPAutoThrottleLock (bool lock)
1334 {
1335   set_AutoThrottleEnabled(lock);
1336 }
1337
1338
1339 // kludge
1340 double
1341 FGAutopilot::getAPRudderControl () const
1342 {
1343     if (getAPHeadingLock())
1344         return get_TargetHeading();
1345     else
1346         return globals->get_controls()->get_rudder();
1347 }
1348
1349 // kludge
1350 void
1351 FGAutopilot::setAPRudderControl (double value)
1352 {
1353     if (getAPHeadingLock()) {
1354         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1355         value -= get_TargetHeading();
1356         HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1357     } else {
1358         globals->get_controls()->set_rudder(value);
1359     }
1360 }
1361
1362 // kludge
1363 double
1364 FGAutopilot::getAPElevatorControl () const
1365 {
1366   if (getAPAltitudeLock())
1367       return get_TargetAltitude();
1368   else
1369     return globals->get_controls()->get_elevator();
1370 }
1371
1372 // kludge
1373 void
1374 FGAutopilot::setAPElevatorControl (double value)
1375 {
1376     if (value != 0 && getAPAltitudeLock()) {
1377         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1378         value -= get_TargetAltitude();
1379         AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1380     } else {
1381         globals->get_controls()->set_elevator(value);
1382     }
1383 }
1384
1385 // kludge
1386 double
1387 FGAutopilot::getAPThrottleControl () const
1388 {
1389   if (getAPAutoThrottleLock())
1390     return 0.0;                 // always resets
1391   else
1392     return globals->get_controls()->get_throttle(0);
1393 }
1394
1395 // kludge
1396 void
1397 FGAutopilot::setAPThrottleControl (double value)
1398 {
1399   if (getAPAutoThrottleLock())
1400     AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1401   else
1402     globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1403 }
1404
1405 // end of newauto.cxx
1406