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