]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
Bugfix. The engine thrust is recalculated based on the current N1 value
[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 #if !defined( USING_SLIDER_CLASS )
309     MaxRollAdjust = 2 * MaxRoll;
310     RollOutAdjust = 2 * RollOut;
311     //MaxAileronAdjust = 2 * MaxAileron;
312     RollOutSmoothAdjust = 2 * RollOutSmooth;
313 #endif  // !defined( USING_SLIDER_CLASS )
314
315     update_old_control_values();
316 };
317
318 void
319 FGAutopilot::bind ()
320 {
321     // Autopilot control property get/set bindings
322     fgTie("/autopilot/locks/altitude", this,
323           &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
324     fgSetArchivable("/autopilot/locks/altitude");
325     fgTie("/autopilot/settings/altitude-ft", this,
326           &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
327     fgSetArchivable("/autopilot/settings/altitude-ft");
328     fgTie("/autopilot/locks/glide-slope", this,
329           &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
330     fgSetArchivable("/autopilot/locks/glide-slope");
331     fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
332     fgTie("/autopilot/locks/terrain", this,
333           &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
334     fgSetArchivable("/autopilot/locks/terrain");
335     fgTie("/autopilot/settings/climb-rate-fpm", this,
336           &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
337     fgSetArchivable("/autopilot/settings/climb-rate-fpm");
338     fgTie("/autopilot/locks/heading", this,
339           &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
340     fgSetArchivable("/autopilot/locks/heading");
341     fgTie("/autopilot/settings/heading-bug-deg", this,
342           &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
343     fgSetArchivable("/autopilot/settings/heading-bug-deg");
344     fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
345     fgTie("/autopilot/locks/wing-leveler", this,
346           &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
347     fgSetArchivable("/autopilot/locks/wing-leveler");
348     fgTie("/autopilot/locks/nav[0]", this,
349           &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
350     fgSetArchivable("/autopilot/locks/nav[0]");
351     fgTie("/autopilot/locks/auto-throttle", this,
352           &FGAutopilot::getAPAutoThrottleLock,
353           &FGAutopilot::setAPAutoThrottleLock);
354     fgSetArchivable("/autopilot/locks/auto-throttle");
355     fgTie("/autopilot/control-overrides/rudder", this,
356           &FGAutopilot::getAPRudderControl,
357           &FGAutopilot::setAPRudderControl);
358     fgSetArchivable("/autopilot/control-overrides/rudder");
359     fgTie("/autopilot/control-overrides/elevator", this,
360           &FGAutopilot::getAPElevatorControl,
361           &FGAutopilot::setAPElevatorControl);
362     fgSetArchivable("/autopilot/control-overrides/elevator");
363     fgTie("/autopilot/control-overrides/throttle", this,
364           &FGAutopilot::getAPThrottleControl,
365           &FGAutopilot::setAPThrottleControl);
366     fgSetArchivable("/autopilot/control-overrides/throttle");
367 }
368
369 void
370 FGAutopilot::unbind ()
371 {
372 }
373
374 // Reset the autopilot system
375 void FGAutopilot::reset() {
376
377     heading_hold = false ;      // turn the heading hold off
378     altitude_hold = false ;     // turn the altitude hold off
379     auto_throttle = false ;     // turn the auto throttle off
380     heading_mode = DEFAULT_AP_HEADING_LOCK;
381
382     // TargetHeading = 0.0;     // default direction, due north
383     MakeTargetHeadingStr( TargetHeading );                      
384         
385     // TargetAltitude = 3000;   // default altitude in meters
386     MakeTargetAltitudeStr( TargetAltitude );
387         
388     alt_error_accum = 0.0;
389     climb_error_accum = 0.0;
390         
391     update_old_control_values();
392
393     sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id") );
394         
395     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
396 }
397
398
399 static double NormalizeDegrees( double Input ) {
400     // normalize the input to the range (-180,180]
401     // Input should not be greater than -360 to 360.
402     // Current rules send the output to an undefined state.
403     while ( Input > 180.0 ) { Input -= 360.0; }
404     while ( Input <= -180.0 ) { Input += 360.0; }
405
406     return Input;
407 };
408
409 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
410     // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
411     //assert(x1 != x2); // Divide by zero error.  Cold abort for now
412
413         // Could be
414         // static double y = 0.0;
415         // double dx = x2 -x1;
416         // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
417         // {
418
419     double m, b, y;          // the constants to find in y=mx+b
420     // double m, b;
421
422     m = ( y2 - y1 ) / ( x2 - x1 );   // calculate the m
423
424     b = y1 - m * x1;       // calculate the b
425
426     y = m * x + b;       // the final calculation
427
428     // }
429
430     return ( y );
431
432 };
433
434
435 void
436 FGAutopilot::update (double dt)
437 {
438     // Remove the following lines when the calling funcitons start
439     // passing in the data pointer
440
441     // get control settings 
442         
443     double lat = latitude_node->getDoubleValue();
444     double lon = longitude_node->getDoubleValue();
445     double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
446
447     // get config settings
448     MaxAileron = max_aileron_node->getDoubleValue();
449     MaxRoll = max_roll_node->getDoubleValue();
450     RollOut = roll_out_node->getDoubleValue();
451     RollOutSmooth = roll_out_smooth_node->getDoubleValue();
452
453     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run()  lat = " << lat <<
454             "  lon = " << lon << "  alt = " << alt );
455         
456 #ifdef FG_FORCE_AUTO_DISENGAGE
457     // see if somebody else has changed them
458     if( fabs(aileron - old_aileron) > disengage_threshold ||
459         fabs(elevator - old_elevator) > disengage_threshold ||
460         fabs(elevator_trim - old_elevator_trim) > 
461         disengage_threshold ||          
462         fabs(rudder - old_rudder) > disengage_threshold )
463     {
464         // if controls changed externally turn autopilot off
465         waypoint_hold = false ;   // turn the target hold off
466         heading_hold = false ;    // turn the heading hold off
467         altitude_hold = false ;   // turn the altitude hold off
468         terrain_follow = false;   // turn the terrain_follow hold off
469         // auto_throttle = false; // turn the auto_throttle off
470
471         // stash this runs control settings
472         old_aileron = aileron;
473         old_elevator = elevator;
474         old_elevator_trim = elevator_trim;
475         old_rudder = rudder;
476         
477         return 0;
478     }
479 #endif
480         
481     // heading hold
482     if ( heading_hold == true ) {
483         if ( heading_mode == FG_DG_HEADING_LOCK ) {
484             TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
485             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
486             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
487             MakeTargetHeadingStr( TargetHeading );
488         } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
489             // we don't set a specific target heading in
490             // TC_HEADING_LOCK mode, we instead try to keep the turn
491             // coordinator zero'd
492         } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
493             // leave "true" target heading as is
494             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
495             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
496             MakeTargetHeadingStr( TargetHeading );
497         } else if ( heading_mode == FG_HEADING_NAV1 ) {
498             // track the NAV1 heading needle deflection
499
500             // determine our current radial position relative to the
501             // navaid in "true" heading.
502             double cur_radial = current_radiostack->get_nav1_heading();
503             if ( current_radiostack->get_nav1_loc() ) {
504                 // ILS localizers radials are already "true" in our
505                 // database
506             } else {
507                 cur_radial += current_radiostack->get_nav1_magvar();
508             }
509             if ( current_radiostack->get_nav1_from_flag() ) {
510                 cur_radial += 180.0;
511                 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
512             }
513
514             // determine the target radial in "true" heading
515             double tgt_radial = current_radiostack->get_nav1_radial();
516             if ( current_radiostack->get_nav1_loc() ) {
517                 // ILS localizers radials are already "true" in our
518                 // database
519             } else {
520                 // VOR radials need to have that vor's offset added in
521                 tgt_radial += current_radiostack->get_nav1_magvar();
522             }
523
524             // determine the heading adjustment needed.
525             double adjustment = 
526                 current_radiostack->get_nav1_heading_needle_deflection()
527                 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
528             SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
529
530             // clamp closer when inside cone when beyond 5km...
531             if (current_radiostack->get_nav1_loc_dist() > 5000) {
532               double clamp_angle = fabs(current_radiostack->get_nav1_heading_needle_deflection()) * 3;
533               if (clamp_angle < 30)
534                 SG_CLAMP_RANGE( adjustment, -clamp_angle, clamp_angle);
535             }
536
537             // determine the target heading to fly to intercept the
538             // tgt_radial
539             TargetHeading = tgt_radial + adjustment; 
540             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
541             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
542
543             MakeTargetHeadingStr( TargetHeading );
544         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
545             // update target heading to waypoint
546
547             double wp_course, wp_distance;
548
549 #ifdef DO_fgAP_CORRECTED_COURSE
550             // compute course made good
551             // this needs lots of special casing before use
552             double course, reverse, distance, corrected_course;
553             // need to test for iter
554             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
555                                 old_lat,
556                                 old_lon,
557                                 lat,
558                                 lon,
559                                 &course,
560                                 &reverse,
561                                 &distance );
562 #endif // DO_fgAP_CORRECTED_COURSE
563
564             // compute course to way_point
565             // need to test for iter
566             SGWayPoint wp = globals->get_route()->get_first();
567             wp.CourseAndDistance( lon, lat, alt, 
568                                   &wp_course, &wp_distance );
569
570 #ifdef DO_fgAP_CORRECTED_COURSE
571             corrected_course = course - wp_course;
572             if( fabs(corrected_course) > 0.1 )
573                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
574                        course, wp_course, fabs(corrected_course),
575                        distance );
576 #endif // DO_fgAP_CORRECTED_COURSE
577                 
578             if ( wp_distance > 100 ) {
579                 // corrected_course = course - wp_course;
580                 TargetHeading = NormalizeDegrees(wp_course);
581             } else {
582                 // pop off this waypoint from the list
583                 if ( globals->get_route()->size() ) {
584                     globals->get_route()->delete_first();
585                 }
586
587                 // see if there are more waypoints on the list
588                 if ( globals->get_route()->size() ) {
589                     // more waypoints
590                     set_HeadingMode( FG_HEADING_WAYPOINT );
591                 } else {
592                     // end of the line
593                     heading_mode = FG_TRUE_HEADING_LOCK;
594                     // use current heading
595                     TargetHeading = heading_node->getDoubleValue();
596                 }
597             }
598             MakeTargetHeadingStr( TargetHeading );
599             // Force this just in case
600             TargetDistance = wp_distance;
601             MakeTargetWPStr( wp_distance );
602         }
603
604         if ( heading_mode == FG_TC_HEADING_LOCK ) {
605             // drive the turn coordinator to zero
606             double turn = FGSteam::get_TC_std();
607             double AileronSet = -turn / 2.0;
608             SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
609             globals->get_controls()->set_aileron( AileronSet );
610             globals->get_controls()->set_rudder( AileronSet / 4.0 );
611         } else {
612             // steer towards the target heading
613
614             double RelHeading;
615             double TargetRoll;
616             double RelRoll;
617             double AileronSet;
618
619             RelHeading
620                 = NormalizeDegrees( TargetHeading
621                                     - heading_node->getDoubleValue() );
622             // figure out how far off we are from desired heading
623
624             // Now it is time to deterime how far we should be rolled.
625             SG_LOG( SG_AUTOPILOT, SG_DEBUG,
626                     "Heading = " << heading_node->getDoubleValue() <<
627                     " TargetHeading = " << TargetHeading <<
628                     " RelHeading = " << RelHeading );
629
630             // Check if we are further from heading than the roll out point
631             if ( fabs( RelHeading ) > RollOut ) {
632                 // set Target Roll to Max in desired direction
633                 if ( RelHeading < 0 ) {
634                     TargetRoll = 0 - MaxRoll;
635                 } else {
636                     TargetRoll = MaxRoll;
637                 }
638             } else {
639                 // We have to calculate the Target roll
640
641                 // This calculation engine thinks that the Target roll
642                 // should be a line from (RollOut,MaxRoll) to (-RollOut,
643                 // -MaxRoll) I hope this works well.  If I get ambitious
644                 // some day this might become a fancier curve or
645                 // something.
646
647                 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
648                                                 -MaxRoll, RollOut,
649                                                 MaxRoll );
650             }
651
652             // Target Roll has now been Found.
653
654             // Compare Target roll to Current Roll, Generate Rel Roll
655
656             SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
657
658             RelRoll = NormalizeDegrees( TargetRoll 
659                                         - roll_node->getDoubleValue() );
660
661             // Check if we are further from heading than the roll out
662             // smooth point
663             if ( fabs( RelRoll ) > RollOutSmooth ) {
664                 // set Target Roll to Max in desired direction
665                 if ( RelRoll < 0 ) {
666                 AileronSet = 0 - MaxAileron;
667                 } else {
668                     AileronSet = MaxAileron;
669                 }
670             } else {
671                 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
672                                                 -MaxAileron,
673                                                 RollOutSmooth,
674                                                 MaxAileron );
675             }
676
677             globals->get_controls()->set_aileron( AileronSet );
678             globals->get_controls()->set_rudder( AileronSet / 4.0 );
679             // controls.set_rudder( 0.0 );
680         }
681     }
682
683     // altitude hold
684     if ( altitude_hold ) {
685         double climb_rate;
686         double speed, max_climb, error;
687         double prop_error, int_error;
688         double prop_adj, int_adj, total_adj;
689
690         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
691             climb_rate =
692                 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
693         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
694             double x = current_radiostack->get_nav1_gs_dist();
695             double y = (altitude_node->getDoubleValue()
696                         - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
697             double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
698
699             double target_angle = current_radiostack->get_nav1_target_gs();
700
701             double gs_diff = target_angle - current_angle;
702
703             // convert desired vertical path angle into a climb rate
704             double des_angle = current_angle - 10 * gs_diff;
705
706             // convert to meter/min
707             double horiz_vel = cur_fdm_state->get_V_ground_speed()
708                 * SG_FEET_TO_METER * 60.0;
709             climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
710             /* climb_error_accum += gs_diff * 2.0; */
711             /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
712         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
713             // brain dead ground hugging with no look ahead
714             climb_rate =
715                 ( TargetAGL - altitude_agl_node->getDoubleValue()
716                   * SG_FEET_TO_METER ) * 16.0;
717         } else {
718             // just try to zero out rate of climb ...
719             climb_rate = 0.0;
720         }
721
722         speed = get_speed();
723
724         if ( speed < min_climb->getFloatValue() ) {
725             max_climb = 0.0;
726         } else if ( speed < best_climb->getFloatValue() ) {
727             max_climb = ((best_climb->getFloatValue()
728                           - min_climb->getFloatValue())
729                          - (best_climb->getFloatValue() - speed)) 
730                 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) 
731                 / (best_climb->getFloatValue() - min_climb->getFloatValue());
732         } else {                        
733             max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
734                 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
735         }
736
737         // this first one could be optional if we wanted to allow
738         // better climb performance assuming we have the airspeed to
739         // support it.
740         if ( climb_rate >
741              fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
742             climb_rate
743                 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
744         }
745
746         if ( climb_rate > max_climb ) {
747             climb_rate = max_climb;
748         }
749
750         if ( climb_rate <
751              -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
752             climb_rate
753                 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
754         }
755
756         error = vertical_speed_node->getDoubleValue() * 60
757             - climb_rate * SG_METER_TO_FEET;
758
759         // accumulate the error under the curve ... this really should
760         // be *= delta t
761         alt_error_accum += error;
762
763         // calculate integral error, and adjustment amount
764         int_error = alt_error_accum;
765         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
766         
767         // scale elev_adj_factor by speed of aircraft in relation to min climb 
768         double elev_adj_factor = elevator_adj_factor->getFloatValue();
769         elev_adj_factor *=
770           pow(float(speed / min_climb->getFloatValue()), 3.0f);
771
772         int_adj = int_error / elev_adj_factor;
773
774         // caclulate proportional error
775         prop_error = error;
776         prop_adj = prop_error / elev_adj_factor;
777
778         total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
779             + (double) integral_contrib->getFloatValue() * int_adj;
780
781         // stop on autopilot trim at 30% +/-
782 //      if ( total_adj > 0.3 ) {
783 //           total_adj = 0.3;
784 //       } else if ( total_adj < -0.3 ) {
785 //           total_adj = -0.3;
786 //       }
787
788         // adjust for throttle pitch gain
789         total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
790                      / (1 - zero_pitch_throttle->getFloatValue()))
791                      * zero_pitch_trim_full_throttle->getFloatValue();
792
793         globals->get_controls()->set_elevator_trim( total_adj );
794     }
795
796     // auto throttle
797     if ( auto_throttle ) {
798         double error;
799         double prop_error, int_error;
800         double prop_adj, int_adj, total_adj;
801
802         error = TargetSpeed - get_speed();
803
804         // accumulate the error under the curve ... this really should
805         // be *= delta t
806         speed_error_accum += error;
807         if ( speed_error_accum > 2000.0 ) {
808             speed_error_accum = 2000.0;
809         }
810         else if ( speed_error_accum < -2000.0 ) {
811             speed_error_accum = -2000.0;
812         }
813
814         // calculate integral error, and adjustment amount
815         int_error = speed_error_accum;
816
817         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
818         int_adj = int_error / 200.0;
819
820         // caclulate proportional error
821         prop_error = error;
822         prop_adj = 0.5 + prop_error / 50.0;
823
824         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
825         if ( total_adj > 1.0 ) {
826             total_adj = 1.0;
827         }
828         else if ( total_adj < 0.0 ) {
829             total_adj = 0.0;
830         }
831
832         globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
833                                                total_adj );
834     }
835
836 #ifdef THIS_CODE_IS_NOT_USED
837     if (Mode == 2) // Glide slope hold
838         {
839             double RelSlope;
840             double RelElevator;
841
842             // First, calculate Relative slope and normalize it
843             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
844
845             // Now calculate the elevator offset from current angle
846             if ( abs(RelSlope) > SlopeSmooth )
847                 {
848                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
849                         RelElevator = -MaxElevator;
850                     else
851                         RelElevator = MaxElevator;
852                 }
853
854             else
855                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
856
857             // set the elevator
858             fgElevMove(RelElevator);
859
860         }
861 #endif // THIS_CODE_IS_NOT_USED
862
863     // stash this runs control settings
864     //  update_old_control_values();
865     old_aileron = globals->get_controls()->get_aileron();
866     old_elevator = globals->get_controls()->get_elevator();
867     old_elevator_trim = globals->get_controls()->get_elevator_trim();
868     old_rudder = globals->get_controls()->get_rudder();
869
870     // for cross track error
871     old_lat = lat;
872     old_lon = lon;
873         
874     // Ok, we are done
875     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
876 }
877
878
879 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
880     heading_mode = mode;
881
882     if ( heading_mode == FG_DG_HEADING_LOCK ) {
883         // set heading hold to current heading (as read from DG)
884         // ... no, leave target heading along ... just use the current
885         // heading bug value
886         //  DGTargetHeading = FGSteam::get_DG_deg();
887     } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
888         // set autopilot to hold a zero turn (as reported by the TC)
889     } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
890         // set heading hold to current heading
891         TargetHeading = heading_node->getDoubleValue();
892     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
893         if ( globals->get_route()->size() ) {
894             double course, distance;
895
896             old_lat = latitude_node->getDoubleValue();
897             old_lon = longitude_node->getDoubleValue();
898
899             waypoint = globals->get_route()->get_first();
900             waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
901                                         latitude_node->getDoubleValue(),
902                                         altitude_node->getDoubleValue()
903                                         * SG_FEET_TO_METER,
904                                         &course, &distance );
905             TargetHeading = course;
906             TargetDistance = distance;
907             MakeTargetLatLonStr( waypoint.get_target_lat(),
908                                  waypoint.get_target_lon() );
909             MakeTargetWPStr( distance );
910
911             if ( waypoint.get_target_alt() > 0.0 ) {
912                 TargetAltitude = waypoint.get_target_alt();
913                 altitude_mode = FG_ALTITUDE_LOCK;
914                 set_AltitudeEnabled( true );
915                 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
916             }
917
918             SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
919                     << get_TargetLatitude()  << " "
920                     << get_TargetLongitude() << " ) "
921                     );
922         } else {
923             // no more way points, default to heading lock.
924             heading_mode = FG_TC_HEADING_LOCK;
925         }
926     }
927
928     MakeTargetHeadingStr( TargetHeading );                      
929     update_old_control_values();
930 }
931
932
933 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
934     altitude_mode = mode;
935
936     alt_error_accum = 0.0;
937
938
939     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
940         if ( TargetAltitude < altitude_agl_node->getDoubleValue()
941              * SG_FEET_TO_METER ) {
942         }
943
944         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
945             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
946         } else {
947             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
948         }
949     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
950         climb_error_accum = 0.0;
951
952     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
953         TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
954
955         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
956             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
957         } else {
958             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
959         }
960     }
961     
962     update_old_control_values();
963     SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
964 }
965
966
967 void FGAutopilot::AltitudeSet( double new_altitude ) {
968     double target_alt = new_altitude;
969
970     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
971         target_alt = new_altitude * SG_FEET_TO_METER;
972     }
973
974     if( target_alt < globals->get_scenery()->get_cur_elev() ) {
975         target_alt = globals->get_scenery()->get_cur_elev();
976     }
977
978     TargetAltitude = target_alt;
979     altitude_mode = FG_ALTITUDE_LOCK;
980
981     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
982         target_alt *= SG_METER_TO_FEET;
983     }
984     // ApAltitudeDialogInput->setValue((float)target_alt);
985     MakeTargetAltitudeStr( target_alt );
986         
987     update_old_control_values();
988 }
989
990
991 void FGAutopilot::AltitudeAdjust( double inc )
992 {
993     double target_alt, target_agl;
994
995     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
996         target_alt = TargetAltitude * SG_METER_TO_FEET;
997         target_agl = TargetAGL * SG_METER_TO_FEET;
998     } else {
999         target_alt = TargetAltitude;
1000         target_agl = TargetAGL;
1001     }
1002
1003     if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1004         target_alt += inc;
1005     } else {
1006         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1007     }
1008
1009     if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1010         target_agl += inc;
1011     } else {
1012         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1013     }
1014
1015     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1016         target_alt *= SG_FEET_TO_METER;
1017         target_agl *= SG_FEET_TO_METER;
1018     }
1019
1020     TargetAltitude = target_alt;
1021     TargetAGL = target_agl;
1022         
1023     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1024         target_alt *= SG_METER_TO_FEET;
1025     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1026         target_agl *= SG_METER_TO_FEET;
1027
1028     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
1029         MakeTargetAltitudeStr( target_alt );
1030     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1031         MakeTargetAltitudeStr( target_agl );
1032     }
1033
1034     update_old_control_values();
1035 }
1036
1037
1038 void FGAutopilot::HeadingAdjust( double inc ) {
1039     if ( heading_mode != FG_DG_HEADING_LOCK
1040          && heading_mode != FG_TRUE_HEADING_LOCK )
1041     {
1042         heading_mode = FG_DG_HEADING_LOCK;
1043     }
1044
1045     if ( heading_mode == FG_DG_HEADING_LOCK ) {
1046         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1047         DGTargetHeading = NormalizeDegrees( target );
1048     } else {
1049         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1050         TargetHeading = NormalizeDegrees( target );
1051     }
1052
1053     update_old_control_values();
1054 }
1055
1056
1057 void FGAutopilot::HeadingSet( double new_heading ) {
1058     if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1059         new_heading = NormalizeDegrees( new_heading );
1060         TargetHeading = new_heading;
1061         MakeTargetHeadingStr( TargetHeading );
1062     } else {
1063         heading_mode = FG_DG_HEADING_LOCK;
1064
1065         new_heading = NormalizeDegrees( new_heading );
1066         DGTargetHeading = new_heading;
1067         // following cast needed ambiguous plib
1068         // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1069         MakeTargetHeadingStr( DGTargetHeading );
1070     }
1071     update_old_control_values();
1072 }
1073
1074 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1075     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1076
1077     TargetSpeed = target;
1078 }
1079
1080
1081 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1082     auto_throttle = value;
1083
1084     if ( auto_throttle == true ) {
1085         TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1086         speed_error_accum = 0.0;
1087     }
1088
1089     update_old_control_values();
1090     SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1091             << auto_throttle << ") " << TargetSpeed );
1092 }
1093
1094
1095
1096 \f
1097 ////////////////////////////////////////////////////////////////////////
1098 // Kludged methods for tying to properties.
1099 //
1100 // These should change eventually; they all used to be static
1101 // functions.
1102 ////////////////////////////////////////////////////////////////////////
1103
1104 /**
1105  * Get the autopilot altitude lock (true=on).
1106  */
1107 bool
1108 FGAutopilot::getAPAltitudeLock () const
1109 {
1110     return (get_AltitudeEnabled() &&
1111             get_AltitudeMode()
1112             == FGAutopilot::FG_ALTITUDE_LOCK);
1113 }
1114
1115
1116 /**
1117  * Set the autopilot altitude lock (true=on).
1118  */
1119 void
1120 FGAutopilot::setAPAltitudeLock (bool lock)
1121 {
1122   if (lock)
1123     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_LOCK);
1124   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_LOCK)
1125     set_AltitudeEnabled(lock);
1126 }
1127
1128
1129 /**
1130  * Get the autopilot target altitude in feet.
1131  */
1132 double
1133 FGAutopilot::getAPAltitude () const
1134 {
1135   return get_TargetAltitude() * SG_METER_TO_FEET;
1136 }
1137
1138
1139 /**
1140  * Set the autopilot target altitude in feet.
1141  */
1142 void
1143 FGAutopilot::setAPAltitude (double altitude)
1144 {
1145   set_TargetAltitude( altitude * SG_FEET_TO_METER );
1146 }
1147
1148 /**
1149  * Get the autopilot altitude lock (true=on).
1150  */
1151 bool
1152 FGAutopilot::getAPGSLock () const
1153 {
1154     return (get_AltitudeEnabled() &&
1155             (get_AltitudeMode()
1156              == FGAutopilot::FG_ALTITUDE_GS1));
1157 }
1158
1159
1160 /**
1161  * Set the autopilot altitude lock (true=on).
1162  */
1163 void
1164 FGAutopilot::setAPGSLock (bool lock)
1165 {
1166   if (lock)
1167     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1168   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1169     set_AltitudeEnabled(lock);
1170 }
1171
1172
1173 /**
1174  * Get the autopilot terrain lock (true=on).
1175  */
1176 bool
1177 FGAutopilot::getAPTerrainLock () const
1178 {
1179     return (get_AltitudeEnabled() &&
1180             (get_AltitudeMode()
1181              == FGAutopilot::FG_ALTITUDE_TERRAIN));
1182 }
1183
1184
1185 /**
1186  * Set the autopilot terrain lock (true=on).
1187  */
1188 void
1189 FGAutopilot::setAPTerrainLock (bool lock)
1190 {
1191   if (lock) {
1192     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1193     set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1194                   SG_FEET_TO_METER);
1195   }
1196   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1197     set_AltitudeEnabled(lock);
1198 }
1199
1200
1201 /**
1202  * Get the autopilot target altitude in feet.
1203  */
1204 double
1205 FGAutopilot::getAPClimb () const
1206 {
1207   return get_TargetClimbRate() * SG_METER_TO_FEET;
1208 }
1209
1210
1211 /**
1212  * Set the autopilot target altitude in feet.
1213  */
1214 void
1215 FGAutopilot::setAPClimb (double rate)
1216 {
1217     set_TargetClimbRate( rate * SG_FEET_TO_METER );
1218 }
1219
1220
1221 /**
1222  * Get the autopilot heading lock (true=on).
1223  */
1224 bool
1225 FGAutopilot::getAPHeadingLock () const
1226 {
1227     return
1228       (get_HeadingEnabled() &&
1229        get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1230 }
1231
1232
1233 /**
1234  * Set the autopilot heading lock (true=on).
1235  */
1236 void
1237 FGAutopilot::setAPHeadingLock (bool lock)
1238 {
1239   if (lock)
1240     set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1241   if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1242     set_HeadingEnabled(lock);
1243 }
1244
1245
1246 /**
1247  * Get the autopilot heading bug in degrees.
1248  */
1249 double
1250 FGAutopilot::getAPHeadingBug () const
1251 {
1252   return get_DGTargetHeading();
1253 }
1254
1255
1256 /**
1257  * Set the autopilot heading bug in degrees.
1258  */
1259 void
1260 FGAutopilot::setAPHeadingBug (double heading)
1261 {
1262   set_DGTargetHeading( heading );
1263 }
1264
1265
1266 /**
1267  * Get the autopilot wing leveler lock (true=on).
1268  */
1269 bool
1270 FGAutopilot::getAPWingLeveler () const
1271 {
1272     return
1273       (get_HeadingEnabled() &&
1274        get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1275 }
1276
1277
1278 /**
1279  * Set the autopilot wing leveler lock (true=on).
1280  */
1281 void
1282 FGAutopilot::setAPWingLeveler (bool lock)
1283 {
1284     if (lock)
1285         set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1286     if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1287       set_HeadingEnabled(lock);
1288 }
1289
1290 /**
1291  * Return true if the autopilot is locked to NAV1.
1292  */
1293 bool
1294 FGAutopilot::getAPNAV1Lock () const
1295 {
1296   return
1297     (get_HeadingEnabled() &&
1298      get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1299 }
1300
1301
1302 /**
1303  * Set the autopilot NAV1 lock.
1304  */
1305 void
1306 FGAutopilot::setAPNAV1Lock (bool lock)
1307 {
1308   if (lock)
1309     set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1310   if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1311     set_HeadingEnabled(lock);
1312 }
1313
1314 /**
1315  * Get the autopilot autothrottle lock.
1316  */
1317 bool
1318 FGAutopilot::getAPAutoThrottleLock () const
1319 {
1320   return get_AutoThrottleEnabled();
1321 }
1322
1323
1324 /**
1325  * Set the autothrottle lock.
1326  */
1327 void
1328 FGAutopilot::setAPAutoThrottleLock (bool lock)
1329 {
1330   set_AutoThrottleEnabled(lock);
1331 }
1332
1333
1334 // kludge
1335 double
1336 FGAutopilot::getAPRudderControl () const
1337 {
1338     if (getAPHeadingLock())
1339         return get_TargetHeading();
1340     else
1341         return globals->get_controls()->get_rudder();
1342 }
1343
1344 // kludge
1345 void
1346 FGAutopilot::setAPRudderControl (double value)
1347 {
1348     if (getAPHeadingLock()) {
1349         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1350         value -= get_TargetHeading();
1351         HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1352     } else {
1353         globals->get_controls()->set_rudder(value);
1354     }
1355 }
1356
1357 // kludge
1358 double
1359 FGAutopilot::getAPElevatorControl () const
1360 {
1361   if (getAPAltitudeLock())
1362       return get_TargetAltitude();
1363   else
1364     return globals->get_controls()->get_elevator();
1365 }
1366
1367 // kludge
1368 void
1369 FGAutopilot::setAPElevatorControl (double value)
1370 {
1371     if (value != 0 && getAPAltitudeLock()) {
1372         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1373         value -= get_TargetAltitude();
1374         AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1375     } else {
1376         globals->get_controls()->set_elevator(value);
1377     }
1378 }
1379
1380 // kludge
1381 double
1382 FGAutopilot::getAPThrottleControl () const
1383 {
1384   if (getAPAutoThrottleLock())
1385     return 0.0;                 // always resets
1386   else
1387     return globals->get_controls()->get_throttle(0);
1388 }
1389
1390 // kludge
1391 void
1392 FGAutopilot::setAPThrottleControl (double value)
1393 {
1394   if (getAPAutoThrottleLock())
1395     AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1396   else
1397     globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1398 }
1399
1400 // end of newauto.cxx
1401