]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
Add Lee Elliott's per aircraft configurable terrain following factor
[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_heading();
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_magvar();
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 = current_radiostack->get_navcom1()->get_nav_radial();
536             if ( current_radiostack->get_navcom1()->get_nav_loc() ) {
537                 // ILS localizers radials are already "true" in our
538                 // database
539             } else {
540                 // VOR radials need to have that vor's offset added in
541                 tgt_radial += current_radiostack->get_navcom1()->get_nav_magvar();
542             }
543
544             // determine the heading adjustment needed.
545             double adjustment = 
546                 current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()
547                 * (current_radiostack->get_navcom1()->get_nav_loc_dist() * SG_METER_TO_NM);
548             SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
549
550             // clamp closer when inside cone when beyond 5km...
551             if (current_radiostack->get_navcom1()->get_nav_loc_dist() > 5000) {
552               double clamp_angle = fabs(current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()) * 3;
553               if (clamp_angle < 30)
554                 SG_CLAMP_RANGE( adjustment, -clamp_angle, clamp_angle);
555             }
556
557             // determine the target heading to fly to intercept the
558             // tgt_radial
559             TargetHeading = tgt_radial + adjustment; 
560             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
561             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
562
563             MakeTargetHeadingStr( TargetHeading );
564         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
565             // update target heading to waypoint
566
567             double wp_course, wp_distance;
568
569 #ifdef DO_fgAP_CORRECTED_COURSE
570             // compute course made good
571             // this needs lots of special casing before use
572             double course, reverse, distance, corrected_course;
573             // need to test for iter
574             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
575                                 old_lat,
576                                 old_lon,
577                                 lat,
578                                 lon,
579                                 &course,
580                                 &reverse,
581                                 &distance );
582 #endif // DO_fgAP_CORRECTED_COURSE
583
584             // compute course to way_point
585             // need to test for iter
586             SGWayPoint wp = globals->get_route()->get_first();
587             wp.CourseAndDistance( lon, lat, alt, 
588                                   &wp_course, &wp_distance );
589
590 #ifdef DO_fgAP_CORRECTED_COURSE
591             corrected_course = course - wp_course;
592             if( fabs(corrected_course) > 0.1 )
593                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
594                        course, wp_course, fabs(corrected_course),
595                        distance );
596 #endif // DO_fgAP_CORRECTED_COURSE
597                 
598             if ( wp_distance > 100 ) {
599                 // corrected_course = course - wp_course;
600                 TargetHeading = NormalizeDegrees(wp_course);
601             } else {
602                 // pop off this waypoint from the list
603                 if ( globals->get_route()->size() ) {
604                     globals->get_route()->delete_first();
605                 }
606
607                 // see if there are more waypoints on the list
608                 if ( globals->get_route()->size() ) {
609                     // more waypoints
610                     set_HeadingMode( FG_HEADING_WAYPOINT );
611                 } else {
612                     // end of the line
613                     heading_mode = DEFAULT_AP_HEADING_LOCK;
614                     // use current heading
615                     TargetHeading = heading_node->getDoubleValue();
616                 }
617             }
618             MakeTargetHeadingStr( TargetHeading );
619             // Force this just in case
620             TargetDistance = wp_distance;
621             MakeTargetWPStr( wp_distance );
622         }
623
624         if ( heading_mode == FG_TC_HEADING_LOCK ) {
625             // drive the turn coordinator to zero
626             double turn =
627                 fgGetDouble("/instrumentation/turn-indicator/indicated-turn-rate");
628             double AileronSet = -turn / 2.0;
629             SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
630             globals->get_controls()->set_aileron( AileronSet );
631             globals->get_controls()->set_rudder( AileronSet / 4.0 );
632         } else {
633             // steer towards the target heading
634
635             double RelHeading;
636             double TargetRoll;
637             double RelRoll;
638             double AileronSet;
639
640             RelHeading
641                 = NormalizeDegrees( TargetHeading
642                                     - heading_node->getDoubleValue() );
643             // figure out how far off we are from desired heading
644
645             // Now it is time to deterime how far we should be rolled.
646             SG_LOG( SG_AUTOPILOT, SG_DEBUG,
647                     "Heading = " << heading_node->getDoubleValue() <<
648                     " TargetHeading = " << TargetHeading <<
649                     " RelHeading = " << RelHeading );
650
651             // Check if we are further from heading than the roll out point
652             if ( fabs( RelHeading ) > RollOut ) {
653                 // set Target Roll to Max in desired direction
654                 if ( RelHeading < 0 ) {
655                     TargetRoll = 0 - MaxRoll;
656                 } else {
657                     TargetRoll = MaxRoll;
658                 }
659             } else {
660                 // We have to calculate the Target roll
661
662                 // This calculation engine thinks that the Target roll
663                 // should be a line from (RollOut,MaxRoll) to (-RollOut,
664                 // -MaxRoll) I hope this works well.  If I get ambitious
665                 // some day this might become a fancier curve or
666                 // something.
667
668                 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
669                                                 -MaxRoll, RollOut,
670                                                 MaxRoll );
671             }
672
673             // Target Roll has now been Found.
674
675             // Compare Target roll to Current Roll, Generate Rel Roll
676
677             SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
678
679             RelRoll = NormalizeDegrees( TargetRoll 
680                                         - roll_node->getDoubleValue() );
681
682             // Check if we are further from heading than the roll out
683             // smooth point
684             if ( fabs( RelRoll ) > RollOutSmooth ) {
685                 // set Target Roll to Max in desired direction
686                 if ( RelRoll < 0 ) {
687                 AileronSet = 0 - MaxAileron;
688                 } else {
689                     AileronSet = MaxAileron;
690                 }
691             } else {
692                 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
693                                                 -MaxAileron,
694                                                 RollOutSmooth,
695                                                 MaxAileron );
696             }
697
698             globals->get_controls()->set_aileron( AileronSet );
699             globals->get_controls()->set_rudder( AileronSet / 4.0 );
700             // controls.set_rudder( 0.0 );
701         }
702     }
703
704     // altitude hold
705     if ( altitude_hold ) {
706         double climb_rate;
707         double speed, max_climb, error;
708         double prop_error, int_error;
709         double prop_adj, int_adj, total_adj;
710
711         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
712             climb_rate =
713                 ( TargetAltitude -
714                   fgGetDouble("/instrumentation/altimeter/indicated-altitude-ft") * SG_FEET_TO_METER ) * 8.0;
715         } else if ( altitude_mode == FG_TRUE_ALTITUDE_LOCK ) {
716             climb_rate = ( TargetAltitude - alt ) * 8.0;
717         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
718             double x = current_radiostack->get_navcom1()->get_nav_gs_dist();
719             double y = (altitude_node->getDoubleValue()
720                         - current_radiostack->get_navcom1()->get_nav_elev()) * SG_FEET_TO_METER;
721             double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
722
723             double target_angle = current_radiostack->get_navcom1()->get_nav_target_gs();
724
725             double gs_diff = target_angle - current_angle;
726
727             // convert desired vertical path angle into a climb rate
728             double des_angle = current_angle - 10 * gs_diff;
729
730             // convert to meter/min
731             double horiz_vel = cur_fdm_state->get_V_ground_speed()
732                 * SG_FEET_TO_METER * 60.0;
733             climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
734             /* climb_error_accum += gs_diff * 2.0; */
735             /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
736         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
737             // brain dead ground hugging with no look ahead
738             climb_rate =
739                 ( TargetAGL - altitude_agl_node->getDoubleValue()
740                   * SG_FEET_TO_METER )
741                   * terrain_follow_factor->getFloatValue();
742         } else {
743             // just try to zero out rate of climb ...
744             climb_rate = 0.0;
745         }
746
747         speed = get_speed();
748
749         if ( speed < min_climb->getFloatValue() ) {
750             max_climb = 0.0;
751         } else if ( speed < best_climb->getFloatValue() ) {
752             max_climb = ((best_climb->getFloatValue()
753                           - min_climb->getFloatValue())
754                          - (best_climb->getFloatValue() - speed)) 
755                 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) 
756                 / (best_climb->getFloatValue() - min_climb->getFloatValue());
757         } else {                        
758             max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
759                 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
760         }
761
762         // this first one could be optional if we wanted to allow
763         // better climb performance assuming we have the airspeed to
764         // support it.
765         if ( climb_rate >
766              fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
767             climb_rate
768                 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
769         }
770
771         if ( climb_rate > max_climb ) {
772             climb_rate = max_climb;
773         }
774
775         if ( climb_rate <
776              -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
777             climb_rate
778                 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
779         }
780
781         error = vertical_speed_node->getDoubleValue() * 60
782             - climb_rate * SG_METER_TO_FEET;
783
784         // accumulate the error under the curve ... this really should
785         // be *= delta t
786         alt_error_accum += error;
787
788         // calculate integral error, and adjustment amount
789         int_error = alt_error_accum;
790         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
791         
792         // scale elev_adj_factor by speed of aircraft in relation to min climb 
793         double elev_adj_factor = elevator_adj_factor->getFloatValue();
794         elev_adj_factor *=
795           pow(float(speed / min_climb->getFloatValue()), 3.0f);
796
797         int_adj = int_error / elev_adj_factor;
798
799         // caclulate proportional error
800         prop_error = error;
801         prop_adj = prop_error / elev_adj_factor;
802
803         total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
804             + (double) integral_contrib->getFloatValue() * int_adj;
805
806         // stop on autopilot trim at 30% +/-
807 //      if ( total_adj > 0.3 ) {
808 //           total_adj = 0.3;
809 //       } else if ( total_adj < -0.3 ) {
810 //           total_adj = -0.3;
811 //       }
812
813         // adjust for throttle pitch gain
814         total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
815                      / (1 - zero_pitch_throttle->getFloatValue()))
816                      * zero_pitch_trim_full_throttle->getFloatValue();
817
818         globals->get_controls()->set_elevator_trim( total_adj );
819     }
820
821     // auto throttle
822     if ( auto_throttle ) {
823         double error;
824         double prop_error, int_error;
825         double prop_adj, int_adj, total_adj;
826
827         error = TargetSpeed - get_speed();
828
829         // accumulate the error under the curve ... this really should
830         // be *= delta t
831         speed_error_accum += error;
832         if ( speed_error_accum > 2000.0 ) {
833             speed_error_accum = 2000.0;
834         }
835         else if ( speed_error_accum < -2000.0 ) {
836             speed_error_accum = -2000.0;
837         }
838
839         // calculate integral error, and adjustment amount
840         int_error = speed_error_accum;
841
842         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
843         int_adj = int_error / 200.0;
844
845         // caclulate proportional error
846         prop_error = error;
847         prop_adj = 0.5 + prop_error / 50.0;
848
849         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
850         if ( total_adj > 1.0 ) {
851             total_adj = 1.0;
852         }
853         else if ( total_adj < 0.0 ) {
854             total_adj = 0.0;
855         }
856
857         globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
858                                                total_adj );
859     }
860
861 #ifdef THIS_CODE_IS_NOT_USED
862     if (Mode == 2) // Glide slope hold
863         {
864             double RelSlope;
865             double RelElevator;
866
867             // First, calculate Relative slope and normalize it
868             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
869
870             // Now calculate the elevator offset from current angle
871             if ( abs(RelSlope) > SlopeSmooth )
872                 {
873                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
874                         RelElevator = -MaxElevator;
875                     else
876                         RelElevator = MaxElevator;
877                 }
878
879             else
880                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
881
882             // set the elevator
883             fgElevMove(RelElevator);
884
885         }
886 #endif // THIS_CODE_IS_NOT_USED
887
888     // stash this runs control settings
889     //  update_old_control_values();
890     old_aileron = globals->get_controls()->get_aileron();
891     old_elevator = globals->get_controls()->get_elevator();
892     old_elevator_trim = globals->get_controls()->get_elevator_trim();
893     old_rudder = globals->get_controls()->get_rudder();
894
895     // for cross track error
896     old_lat = lat;
897     old_lon = lon;
898         
899     // Ok, we are done
900     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
901 }
902
903
904 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
905     heading_mode = mode;
906
907     if ( heading_mode == FG_DG_HEADING_LOCK ) {
908         // use current heading bug value
909     } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
910         // set autopilot to hold a zero turn (as reported by the TC)
911     } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
912         // set heading hold to current heading
913         TargetHeading = heading_node->getDoubleValue();
914     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
915         if ( globals->get_route()->size() ) {
916             double course, distance;
917
918             old_lat = latitude_node->getDoubleValue();
919             old_lon = longitude_node->getDoubleValue();
920
921             waypoint = globals->get_route()->get_first();
922             waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
923                                         latitude_node->getDoubleValue(),
924                                         altitude_node->getDoubleValue()
925                                         * SG_FEET_TO_METER,
926                                         &course, &distance );
927             TargetHeading = course;
928             TargetDistance = distance;
929             MakeTargetLatLonStr( waypoint.get_target_lat(),
930                                  waypoint.get_target_lon() );
931             MakeTargetWPStr( distance );
932
933             if ( waypoint.get_target_alt() > 0.0 ) {
934                 TargetAltitude = waypoint.get_target_alt();
935                 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
936                 set_AltitudeEnabled( true );
937                 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
938             }
939
940             SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
941                     << get_TargetLatitude()  << " "
942                     << get_TargetLongitude() << " ) "
943                     );
944         } else {
945             // no more way points, default to heading lock.
946             heading_mode = FG_TC_HEADING_LOCK;
947         }
948     }
949
950     MakeTargetHeadingStr( TargetHeading );                      
951     update_old_control_values();
952 }
953
954
955 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
956     altitude_mode = mode;
957
958     alt_error_accum = 0.0;
959
960
961     if ( altitude_mode == DEFAULT_AP_ALTITUDE_LOCK ) {
962         if ( TargetAltitude < altitude_agl_node->getDoubleValue()
963              * SG_FEET_TO_METER ) {
964         }
965
966         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
967             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
968         } else {
969             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
970         }
971     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
972         climb_error_accum = 0.0;
973
974     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
975         TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
976
977         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
978             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
979         } else {
980             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
981         }
982     }
983     
984     update_old_control_values();
985     SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
986 }
987
988
989 void FGAutopilot::AltitudeSet( double new_altitude ) {
990     double target_alt = new_altitude;
991     altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
992
993     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
994         target_alt = new_altitude * SG_FEET_TO_METER;
995     }
996
997     if( target_alt < globals->get_scenery()->get_cur_elev() ) {
998         target_alt = globals->get_scenery()->get_cur_elev();
999     }
1000
1001     TargetAltitude = target_alt;
1002
1003     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1004         target_alt *= SG_METER_TO_FEET;
1005     }
1006     // ApAltitudeDialogInput->setValue((float)target_alt);
1007     MakeTargetAltitudeStr( target_alt );
1008         
1009     update_old_control_values();
1010 }
1011
1012
1013 void FGAutopilot::AltitudeAdjust( double inc )
1014 {
1015     double target_alt, target_agl;
1016
1017     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1018         target_alt = TargetAltitude * SG_METER_TO_FEET;
1019         target_agl = TargetAGL * SG_METER_TO_FEET;
1020     } else {
1021         target_alt = TargetAltitude;
1022         target_agl = TargetAGL;
1023     }
1024
1025     if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1026         target_alt += inc;
1027     } else {
1028         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1029     }
1030
1031     if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1032         target_agl += inc;
1033     } else {
1034         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1035     }
1036
1037     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1038         target_alt *= SG_FEET_TO_METER;
1039         target_agl *= SG_FEET_TO_METER;
1040     }
1041
1042     TargetAltitude = target_alt;
1043     TargetAGL = target_agl;
1044         
1045     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1046         target_alt *= SG_METER_TO_FEET;
1047     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1048         target_agl *= SG_METER_TO_FEET;
1049
1050     if ( altitude_mode == DEFAULT_AP_ALTITUDE_LOCK ) {
1051         MakeTargetAltitudeStr( target_alt );
1052     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1053         MakeTargetAltitudeStr( target_agl );
1054     }
1055
1056     update_old_control_values();
1057 }
1058
1059
1060 void FGAutopilot::HeadingAdjust( double inc ) {
1061     if ( heading_mode != FG_DG_HEADING_LOCK
1062          && heading_mode != FG_TRUE_HEADING_LOCK )
1063     {
1064         heading_mode = DEFAULT_AP_HEADING_LOCK;
1065     }
1066
1067     if ( heading_mode == FG_DG_HEADING_LOCK ) {
1068         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1069         DGTargetHeading = NormalizeDegrees( target );
1070     } else {
1071         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1072         TargetHeading = NormalizeDegrees( target );
1073     }
1074
1075     update_old_control_values();
1076 }
1077
1078
1079 void FGAutopilot::HeadingSet( double new_heading ) {
1080     heading_mode = DEFAULT_AP_HEADING_LOCK;
1081     if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1082         new_heading = NormalizeDegrees( new_heading );
1083         TargetHeading = new_heading;
1084         MakeTargetHeadingStr( TargetHeading );
1085     } else {
1086         heading_mode = FG_DG_HEADING_LOCK;
1087
1088         new_heading = NormalizeDegrees( new_heading );
1089         DGTargetHeading = new_heading;
1090         // following cast needed ambiguous plib
1091         // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1092         MakeTargetHeadingStr( DGTargetHeading );
1093     }
1094     update_old_control_values();
1095 }
1096
1097 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1098     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1099
1100     TargetSpeed = target;
1101 }
1102
1103
1104 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1105     auto_throttle = value;
1106
1107     if ( auto_throttle == true ) {
1108         TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1109         speed_error_accum = 0.0;
1110     }
1111
1112     update_old_control_values();
1113     SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1114             << auto_throttle << ") " << TargetSpeed );
1115 }
1116
1117
1118
1119 \f
1120 ////////////////////////////////////////////////////////////////////////
1121 // Kludged methods for tying to properties.
1122 //
1123 // These should change eventually; they all used to be static
1124 // functions.
1125 ////////////////////////////////////////////////////////////////////////
1126
1127 /**
1128  * Get the autopilot altitude lock (true=on).
1129  */
1130 bool
1131 FGAutopilot::getAPAltitudeLock () const
1132 {
1133     return (get_AltitudeEnabled() &&
1134             get_AltitudeMode()
1135             == DEFAULT_AP_ALTITUDE_LOCK);
1136 }
1137
1138
1139 /**
1140  * Set the autopilot altitude lock (true=on).
1141  */
1142 void
1143 FGAutopilot::setAPAltitudeLock (bool lock)
1144 {
1145   if (lock)
1146     set_AltitudeMode(DEFAULT_AP_ALTITUDE_LOCK);
1147   if (get_AltitudeMode() == DEFAULT_AP_ALTITUDE_LOCK)
1148     set_AltitudeEnabled(lock);
1149 }
1150
1151
1152 /**
1153  * Get the autopilot target altitude in feet.
1154  */
1155 double
1156 FGAutopilot::getAPAltitude () const
1157 {
1158   return get_TargetAltitude() * SG_METER_TO_FEET;
1159 }
1160
1161
1162 /**
1163  * Set the autopilot target altitude in feet.
1164  */
1165 void
1166 FGAutopilot::setAPAltitude (double altitude)
1167 {
1168   set_TargetAltitude( altitude * SG_FEET_TO_METER );
1169 }
1170
1171 /**
1172  * Get the autopilot altitude lock (true=on).
1173  */
1174 bool
1175 FGAutopilot::getAPGSLock () const
1176 {
1177     return (get_AltitudeEnabled() &&
1178             (get_AltitudeMode()
1179              == FGAutopilot::FG_ALTITUDE_GS1));
1180 }
1181
1182
1183 /**
1184  * Set the autopilot altitude lock (true=on).
1185  */
1186 void
1187 FGAutopilot::setAPGSLock (bool lock)
1188 {
1189   if (lock)
1190     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1191   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1192     set_AltitudeEnabled(lock);
1193 }
1194
1195
1196 /**
1197  * Get the autopilot terrain lock (true=on).
1198  */
1199 bool
1200 FGAutopilot::getAPTerrainLock () const
1201 {
1202     return (get_AltitudeEnabled() &&
1203             (get_AltitudeMode()
1204              == FGAutopilot::FG_ALTITUDE_TERRAIN));
1205 }
1206
1207
1208 /**
1209  * Set the autopilot terrain lock (true=on).
1210  */
1211 void
1212 FGAutopilot::setAPTerrainLock (bool lock)
1213 {
1214   if (lock) {
1215     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1216     set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1217                   SG_FEET_TO_METER);
1218   }
1219   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1220     set_AltitudeEnabled(lock);
1221 }
1222
1223
1224 /**
1225  * Get the autopilot target altitude in feet.
1226  */
1227 double
1228 FGAutopilot::getAPClimb () const
1229 {
1230   return get_TargetClimbRate() * SG_METER_TO_FEET;
1231 }
1232
1233
1234 /**
1235  * Set the autopilot target altitude in feet.
1236  */
1237 void
1238 FGAutopilot::setAPClimb (double rate)
1239 {
1240     set_TargetClimbRate( rate * SG_FEET_TO_METER );
1241 }
1242
1243
1244 /**
1245  * Get the autopilot heading lock (true=on).
1246  */
1247 bool
1248 FGAutopilot::getAPHeadingLock () const
1249 {
1250     return
1251       (get_HeadingEnabled() &&
1252        get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1253 }
1254
1255
1256 /**
1257  * Set the autopilot heading lock (true=on).
1258  */
1259 void
1260 FGAutopilot::setAPHeadingLock (bool lock)
1261 {
1262   if (lock)
1263     set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1264   if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1265     set_HeadingEnabled(lock);
1266 }
1267
1268
1269 /**
1270  * Get the autopilot heading bug in degrees.
1271  */
1272 double
1273 FGAutopilot::getAPHeadingBug () const
1274 {
1275   return get_DGTargetHeading();
1276 }
1277
1278
1279 /**
1280  * Set the autopilot heading bug in degrees.
1281  */
1282 void
1283 FGAutopilot::setAPHeadingBug (double heading)
1284 {
1285   set_DGTargetHeading( heading );
1286 }
1287
1288
1289 /**
1290  * return blank-separated string of waypoints
1291  */
1292 const char *
1293 FGAutopilot::getAPwaypoint () const
1294 {
1295   static char wplist[500];
1296   char *p = wplist;
1297   int   WPListsize, i;
1298
1299   // FIXME: This can cause a possible buffer overflow, EMH
1300   if ( globals->get_route()->size() > 0 ) { 
1301       WPListsize = globals->get_route()->size(); 
1302
1303       for (i = 0; i < globals->get_route()->size(); i++ ) {
1304          p += sprintf(p, "%5s ",
1305                 globals->get_route()->get_waypoint(i).get_id().c_str() );
1306       }
1307       return wplist;
1308
1309   } else {
1310     return "none specified";
1311   }    
1312 }
1313
1314
1315 /**
1316  * set next waypoint (if str='0', then delete next(first) waypoint)
1317  */
1318 void
1319 FGAutopilot::setAPwaypoint (const char * apt)
1320 {
1321   if (strcmp(apt, "0")==0)
1322   {
1323     SG_LOG( SG_AUTOPILOT, SG_INFO, "delete of first wp" );
1324     if ( globals->get_route()->size() )
1325                     globals->get_route()->delete_first();
1326     return;
1327   }
1328
1329   if ( NewWaypoint( apt ) == 0)
1330     SG_LOG( SG_AUTOPILOT, SG_INFO, "Waypoint " << apt <<  "not in d.b."  );
1331   else
1332   {
1333     /* SG_LOG( SG_AUTOPILOT, SG_INFO, "GOOD!" ); */
1334   }
1335 }
1336
1337 /**
1338  * Get the autopilot wing leveler lock (true=on).
1339  */
1340 bool
1341 FGAutopilot::getAPWingLeveler () const
1342 {
1343     return
1344       (get_HeadingEnabled() &&
1345        get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1346 }
1347
1348
1349 /**
1350  * Set the autopilot wing leveler lock (true=on).
1351  */
1352 void
1353 FGAutopilot::setAPWingLeveler (bool lock)
1354 {
1355     if (lock)
1356         set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1357     if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1358       set_HeadingEnabled(lock);
1359 }
1360
1361 /**
1362  * Return true if the autopilot is locked to NAV1.
1363  */
1364 bool
1365 FGAutopilot::getAPNAV1Lock () const
1366 {
1367   return
1368     (get_HeadingEnabled() &&
1369      get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1370 }
1371
1372
1373 /**
1374  * Set the autopilot NAV1 lock.
1375  */
1376 void
1377 FGAutopilot::setAPNAV1Lock (bool lock)
1378 {
1379   if (lock)
1380     set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1381   if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1382     set_HeadingEnabled(lock);
1383 }
1384
1385 /**
1386  * Get the autopilot autothrottle lock.
1387  */
1388 bool
1389 FGAutopilot::getAPAutoThrottleLock () const
1390 {
1391   return get_AutoThrottleEnabled();
1392 }
1393
1394
1395 /**
1396  * Set the autothrottle lock.
1397  */
1398 void
1399 FGAutopilot::setAPAutoThrottleLock (bool lock)
1400 {
1401   set_AutoThrottleEnabled(lock);
1402 }
1403
1404
1405 // kludge
1406 double
1407 FGAutopilot::getAPRudderControl () const
1408 {
1409     if (getAPHeadingLock())
1410         return get_TargetHeading();
1411     else
1412         return globals->get_controls()->get_rudder();
1413 }
1414
1415 // kludge
1416 void
1417 FGAutopilot::setAPRudderControl (double value)
1418 {
1419     if (getAPHeadingLock()) {
1420         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1421         value -= get_TargetHeading();
1422         HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1423     } else {
1424         globals->get_controls()->set_rudder(value);
1425     }
1426 }
1427
1428 // kludge
1429 double
1430 FGAutopilot::getAPElevatorControl () const
1431 {
1432   if (getAPAltitudeLock())
1433       return get_TargetAltitude();
1434   else
1435     return globals->get_controls()->get_elevator();
1436 }
1437
1438 // kludge
1439 void
1440 FGAutopilot::setAPElevatorControl (double value)
1441 {
1442     if (value != 0 && getAPAltitudeLock()) {
1443         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1444         value -= get_TargetAltitude();
1445         AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1446     } else {
1447         globals->get_controls()->set_elevator(value);
1448     }
1449 }
1450
1451 // kludge
1452 double
1453 FGAutopilot::getAPThrottleControl () const
1454 {
1455   if (getAPAutoThrottleLock())
1456     return 0.0;                 // always resets
1457   else
1458     return globals->get_controls()->get_throttle(0);
1459 }
1460
1461 // kludge
1462 void
1463 FGAutopilot::setAPThrottleControl (double value)
1464 {
1465   if (getAPAutoThrottleLock())
1466     AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1467   else
1468     globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1469 }
1470
1471 // end of newauto.cxx
1472