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