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