]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
Latest JSBSim changes.
[flightgear.git] / src / Autopilot / newauto.cxx
1 // newauto.cxx -- autopilot defines and prototypes (very alpha)
2 // 
3 // Started April 1998  Copyright (C) 1998
4 //
5 // Contributions by Jeff Goeke-Smith <jgoeke@voyager.net>
6 //                  Norman Vine <nhv@cape.com>
7 //                  Curtis Olson <curt@flightgear.org>
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 // General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 #include <stdio.h>              // sprintf()
31
32 #include <simgear/constants.h>
33 #include <simgear/debug/logstream.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/math/sg_random.h>
36
37 #include <Cockpit/steam.hxx>
38 #include <Cockpit/radiostack.hxx>
39 #include <Controls/controls.hxx>
40 #include <FDM/flight.hxx>
41 #include <Main/globals.hxx>
42 #include <Scenery/scenery.hxx>
43
44 #include "newauto.hxx"
45
46
47 FGAutopilot *current_autopilot;
48
49
50 // Climb speed constants
51 const double min_climb = 70.0;  // kts
52 const double best_climb = 75.0; // kts
53 // const double ideal_climb_rate = 500.0 * SG_FEET_TO_METER; // fpm -> mpm
54 // const double ideal_decent_rate = 1000.0 * SG_FEET_TO_METER; // fpm -> mpm
55
56 /// These statics will eventually go into the class
57 /// they are just here while I am experimenting -- NHV :-)
58 // AutoPilot Gain Adjuster members
59 static double MaxRollAdjust;        // MaxRollAdjust       = 2 * APData->MaxRoll;
60 static double RollOutAdjust;        // RollOutAdjust       = 2 * APData->RollOut;
61 static double MaxAileronAdjust;     // MaxAileronAdjust    = 2 * APData->MaxAileron;
62 static double RollOutSmoothAdjust;  // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
63
64 static char NewTgtAirportId[16];
65 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID"; 
66
67 extern char *coord_format_lat(float);
68 extern char *coord_format_lon(float);
69                         
70
71 // constructor
72 FGAutopilot::FGAutopilot():
73 TargetClimbRate(500 * SG_FEET_TO_METER),
74 TargetDecentRate(1000 * SG_FEET_TO_METER)
75 {
76 }
77
78 // destructor
79 FGAutopilot::~FGAutopilot() {}
80
81
82 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
83     sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
84     sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
85     sprintf( TargetLatLonStr, "%s  %s", TargetLatitudeStr, TargetLongitudeStr );
86 }
87
88
89 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
90     if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
91         sprintf( TargetAltitudeStr, "APAltitude  %6.0f+", altitude );
92     } else {
93         sprintf( TargetAltitudeStr, "APAltitude  %6.0f", altitude );
94     }
95 }
96
97
98 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
99     if( bearing < 0. ) {
100         bearing += 360.;
101     } else if (bearing > 360. ) {
102         bearing -= 360.;
103     }
104     sprintf( TargetHeadingStr, "APHeading  %6.1f", bearing );
105 }
106
107
108 static inline double get_speed( void ) {
109     return( cur_fdm_state->get_V_equiv_kts() );
110 }
111
112 static inline double get_ground_speed() {
113     // starts in ft/s so we convert to kts
114     static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
115
116     double ft_s = cur_fdm_state->get_V_ground_speed() 
117         * speedup_node->getIntValue();
118     double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
119
120     return kts;
121 }
122
123
124 void FGAutopilot::MakeTargetWPStr( double distance ) {
125     static time_t last_time = 0;
126     time_t current_time = time(NULL);
127     if ( last_time == current_time ) {
128         return;
129     }
130
131     last_time = current_time;
132
133     double accum = 0.0;
134
135     int size = globals->get_route()->size();
136
137     // start by wiping the strings
138     TargetWP1Str[0] = 0;
139     TargetWP2Str[0] = 0;
140     TargetWP3Str[0] = 0;
141
142     // current route
143     if ( size > 0 ) {
144         SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
145         accum += distance;
146         double eta = accum * SG_METER_TO_NM / get_ground_speed();
147         if ( eta >= 100.0 ) { eta = 99.999; }
148         int major, minor;
149         if ( eta < (1.0/6.0) ) {
150             // within 10 minutes, bump up to min/secs
151             eta *= 60.0;
152         }
153         major = (int)eta;
154         minor = (int)((eta - (int)eta) * 60.0);
155         sprintf( TargetWP1Str, "%s %.2f NM  ETA %d:%02d",
156                  wp1.get_id().c_str(),
157                  accum*SG_METER_TO_NM, major, minor );
158         // cout << "distance = " << distance*SG_METER_TO_NM
159         //      << "  gndsp = " << get_ground_speed() 
160         //      << "  time = " << eta
161         //      << "  major = " << major
162         //      << "  minor = " << minor
163         //      << endl;
164     }
165
166     // next route
167     if ( size > 1 ) {
168         SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
169         accum += wp2.get_distance();
170         
171         double eta = accum * SG_METER_TO_NM / get_ground_speed();
172         if ( eta >= 100.0 ) { eta = 99.999; }
173         int major, minor;
174         if ( eta < (1.0/6.0) ) {
175             // within 10 minutes, bump up to min/secs
176             eta *= 60.0;
177         }
178         major = (int)eta;
179         minor = (int)((eta - (int)eta) * 60.0);
180         sprintf( TargetWP2Str, "%s %.2f NM  ETA %d:%02d",
181                  wp2.get_id().c_str(),
182                  accum*SG_METER_TO_NM, major, minor );
183     }
184
185     // next route
186     if ( size > 2 ) {
187         for ( int i = 2; i < size; ++i ) {
188             accum += globals->get_route()->get_waypoint( i ).get_distance();
189         }
190         
191         SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
192
193         double eta = accum * SG_METER_TO_NM / get_ground_speed();
194         if ( eta >= 100.0 ) { eta = 99.999; }
195         int major, minor;
196         if ( eta < (1.0/6.0) ) {
197             // within 10 minutes, bump up to min/secs
198             eta *= 60.0;
199         }
200         major = (int)eta;
201         minor = (int)((eta - (int)eta) * 60.0);
202         sprintf( TargetWP3Str, "%s %.2f NM  ETA %d:%02d",
203                  wpn.get_id().c_str(),
204                  accum*SG_METER_TO_NM, major, minor );
205     }
206 }
207
208
209 void FGAutopilot::update_old_control_values() {
210     old_aileron = globals->get_controls()->get_aileron();
211     old_elevator = globals->get_controls()->get_elevator();
212     old_elevator_trim = globals->get_controls()->get_elevator_trim();
213     old_rudder = globals->get_controls()->get_rudder();
214 }
215
216
217 // Initialize autopilot subsystem
218 void FGAutopilot::init() {
219     SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
220
221     latitude_node = fgGetNode("/position/latitude-deg", true);
222     longitude_node = fgGetNode("/position/longitude-deg", true);
223     altitude_node = fgGetNode("/position/altitude-ft", true);
224     altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
225     vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
226     heading_node = fgGetNode("/orientation/heading-deg", true);
227     roll_node = fgGetNode("/orientation/roll-deg", true);
228
229     heading_hold = false ;      // turn the heading hold off
230     altitude_hold = false ;     // turn the altitude hold off
231     auto_throttle = false ;     // turn the auto throttle off
232     heading_mode = DEFAULT_AP_HEADING_LOCK;
233
234     sg_srandom_time();
235     DGTargetHeading = sg_random() * 360.0;
236
237     // Initialize target location to startup location
238     old_lat = latitude_node->getDoubleValue();
239     old_lon = longitude_node->getDoubleValue();
240     // set_WayPoint( old_lon, old_lat, 0.0, "default" );
241
242     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
243         
244     TargetHeading = 0.0;        // default direction, due north
245     TargetAltitude = 3000;      // default altitude in meters
246     alt_error_accum = 0.0;
247     climb_error_accum = 0.0;
248
249     MakeTargetAltitudeStr( TargetAltitude );
250     MakeTargetHeadingStr( TargetHeading );
251         
252     // These eventually need to be read from current_aircaft somehow.
253
254     // the maximum roll, in Deg
255     MaxRoll = 20;
256
257     // the deg from heading to start rolling out at, in Deg
258     RollOut = 20;
259
260     // how far can I move the aleron from center.
261     MaxAileron = .2;
262
263     // Smoothing distance for alerion control
264     RollOutSmooth = 10;
265
266     // Hardwired for now should be in options
267     // 25% max control variablilty  0.5 / 2.0
268     disengage_threshold = 1.0;
269
270 #if !defined( USING_SLIDER_CLASS )
271     MaxRollAdjust = 2 * MaxRoll;
272     RollOutAdjust = 2 * RollOut;
273     MaxAileronAdjust = 2 * MaxAileron;
274     RollOutSmoothAdjust = 2 * RollOutSmooth;
275 #endif  // !defined( USING_SLIDER_CLASS )
276
277     update_old_control_values();
278         
279     // Initialize GUI components of autopilot
280     // NewTgtAirportInit();
281     // fgAPAdjustInit() ;
282     // NewHeadingInit();
283     // NewAltitudeInit();
284 };
285
286
287 // Reset the autopilot system
288 void FGAutopilot::reset() {
289
290     heading_hold = false ;      // turn the heading hold off
291     altitude_hold = false ;     // turn the altitude hold off
292     auto_throttle = false ;     // turn the auto throttle off
293     heading_mode = DEFAULT_AP_HEADING_LOCK;
294
295     // TargetHeading = 0.0;     // default direction, due north
296     MakeTargetHeadingStr( TargetHeading );                      
297         
298     // TargetAltitude = 3000;   // default altitude in meters
299     MakeTargetAltitudeStr( TargetAltitude );
300         
301     alt_error_accum = 0.0;
302     climb_error_accum = 0.0;
303         
304     update_old_control_values();
305
306     sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id").c_str() );
307         
308     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
309 }
310
311
312 static double NormalizeDegrees( double Input ) {
313     // normalize the input to the range (-180,180]
314     // Input should not be greater than -360 to 360.
315     // Current rules send the output to an undefined state.
316     if ( Input > 180 )
317         while(Input > 180 )
318             Input -= 360;
319     else if ( Input <= -180 )
320         while ( Input <= -180 )
321             Input += 360;
322     return ( Input );
323 };
324
325 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
326     // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
327     //assert(x1 != x2); // Divide by zero error.  Cold abort for now
328
329         // Could be
330         // static double y = 0.0;
331         // double dx = x2 -x1;
332         // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
333         // {
334
335     double m, b, y;          // the constants to find in y=mx+b
336     // double m, b;
337
338     m = ( y2 - y1 ) / ( x2 - x1 );   // calculate the m
339
340     b = y1 - m * x1;       // calculate the b
341
342     y = m * x + b;       // the final calculation
343
344     // }
345
346     return ( y );
347
348 };
349
350
351 int FGAutopilot::run() {
352     // Remove the following lines when the calling funcitons start
353     // passing in the data pointer
354
355     // get control settings 
356         
357     double lat = latitude_node->getDoubleValue();
358     double lon = longitude_node->getDoubleValue();
359     double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
360
361     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run()  lat = " << lat <<
362             "  lon = " << lon << "  alt = " << alt );
363         
364 #ifdef FG_FORCE_AUTO_DISENGAGE
365     // see if somebody else has changed them
366     if( fabs(aileron - old_aileron) > disengage_threshold ||
367         fabs(elevator - old_elevator) > disengage_threshold ||
368         fabs(elevator_trim - old_elevator_trim) > 
369         disengage_threshold ||          
370         fabs(rudder - old_rudder) > disengage_threshold )
371     {
372         // if controls changed externally turn autopilot off
373         waypoint_hold = false ;   // turn the target hold off
374         heading_hold = false ;    // turn the heading hold off
375         altitude_hold = false ;   // turn the altitude hold off
376         terrain_follow = false;   // turn the terrain_follow hold off
377         // auto_throttle = false; // turn the auto_throttle off
378
379         // stash this runs control settings
380         old_aileron = aileron;
381         old_elevator = elevator;
382         old_elevator_trim = elevator_trim;
383         old_rudder = rudder;
384         
385         return 0;
386     }
387 #endif
388         
389     // heading hold
390     if ( heading_hold == true ) {
391         if ( heading_mode == FG_DG_HEADING_LOCK ) {
392             // cout << "DG heading = " << FGSteam::get_DG_deg()
393             //      << " DG error = " << FGSteam::get_DG_err() << endl;
394
395             TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
396             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
397             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
398             MakeTargetHeadingStr( TargetHeading );
399         } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
400             // we don't set a specific target heading in
401             // TC_HEADING_LOCK mode, we instead try to keep the turn
402             // coordinator zero'd
403         } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
404             // leave "true" target heading as is
405             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
406             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
407             MakeTargetHeadingStr( TargetHeading );
408         } else if ( heading_mode == FG_HEADING_NAV1 ) {
409             // track the NAV1 heading needle deflection
410
411             // determine our current radial position relative to the
412             // navaid in "true" heading.
413             double cur_radial = current_radiostack->get_nav1_heading();
414             if ( current_radiostack->get_nav1_loc() ) {
415                 // ILS localizers radials are already "true" in our
416                 // database
417             } else {
418                 cur_radial += current_radiostack->get_nav1_magvar();
419             }
420             if ( current_radiostack->get_nav1_from_flag() ) {
421                 cur_radial += 180.0;
422                 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
423             }
424
425             // determine the target radial in "true" heading
426             double tgt_radial = current_radiostack->get_nav1_radial();
427             if ( current_radiostack->get_nav1_loc() ) {
428                 // ILS localizers radials are already "true" in our
429                 // database
430             } else {
431                 // VOR radials need to have that vor's offset added in
432                 tgt_radial += current_radiostack->get_nav1_magvar();
433             }
434
435             // determine the heading adjustment needed.
436             double adjustment = 
437                 current_radiostack->get_nav1_heading_needle_deflection()
438                 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
439             if ( adjustment < -30.0 ) { adjustment = -30.0; }
440             if ( adjustment >  30.0 ) { adjustment =  30.0; }
441
442             // determine the target heading to fly to intercept the
443             // tgt_radial
444             TargetHeading = tgt_radial + adjustment; 
445             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
446             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
447
448             MakeTargetHeadingStr( TargetHeading );
449             // cout << "target course (true) = " << TargetHeading << endl;
450         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
451             // update target heading to waypoint
452
453             double wp_course, wp_distance;
454
455 #ifdef DO_fgAP_CORRECTED_COURSE
456             // compute course made good
457             // this needs lots of special casing before use
458             double course, reverse, distance, corrected_course;
459             // need to test for iter
460             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
461                                 old_lat,
462                                 old_lon,
463                                 lat,
464                                 lon,
465                                 &course,
466                                 &reverse,
467                                 &distance );
468 #endif // DO_fgAP_CORRECTED_COURSE
469
470             // compute course to way_point
471             // need to test for iter
472             SGWayPoint wp = globals->get_route()->get_first();
473             wp.CourseAndDistance( lon, lat, alt, 
474                                   &wp_course, &wp_distance );
475
476 #ifdef DO_fgAP_CORRECTED_COURSE
477             corrected_course = course - wp_course;
478             if( fabs(corrected_course) > 0.1 )
479                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
480                        course, wp_course, fabs(corrected_course),
481                        distance );
482 #endif // DO_fgAP_CORRECTED_COURSE
483                 
484             if ( wp_distance > 100 ) {
485                 // corrected_course = course - wp_course;
486                 TargetHeading = NormalizeDegrees(wp_course);
487             } else {
488                 cout << "Reached waypoint within " << wp_distance << "meters"
489                      << endl;
490
491                 // pop off this waypoint from the list
492                 if ( globals->get_route()->size() ) {
493                     globals->get_route()->delete_first();
494                 }
495
496                 // see if there are more waypoints on the list
497                 if ( globals->get_route()->size() ) {
498                     // more waypoints
499                     set_HeadingMode( FG_HEADING_WAYPOINT );
500                 } else {
501                     // end of the line
502                     heading_mode = FG_TRUE_HEADING_LOCK;
503                     // use current heading
504                     TargetHeading = heading_node->getDoubleValue();
505                 }
506             }
507             MakeTargetHeadingStr( TargetHeading );
508             // Force this just in case
509             TargetDistance = wp_distance;
510             MakeTargetWPStr( wp_distance );
511         }
512
513         if ( heading_mode == FG_TC_HEADING_LOCK ) {
514             // drive the turn coordinator to zero
515             double turn = FGSteam::get_TC_std();
516             // cout << "turn rate = " << turn << endl;
517             double AileronSet = -turn / 2.0;
518             if ( AileronSet < -1.0 ) { AileronSet = -1.0; }
519             if ( AileronSet >  1.0 ) { AileronSet =  1.0; }
520             globals->get_controls()->set_aileron( AileronSet );
521             globals->get_controls()->set_rudder( AileronSet / 4.0 );
522         } else {
523             // steer towards the target heading
524
525             double RelHeading;
526             double TargetRoll;
527             double RelRoll;
528             double AileronSet;
529
530             RelHeading
531                 = NormalizeDegrees( TargetHeading
532                                     - heading_node->getDoubleValue() );
533             // figure out how far off we are from desired heading
534
535             // Now it is time to deterime how far we should be rolled.
536             SG_LOG( SG_AUTOPILOT, SG_DEBUG, "RelHeading: " << RelHeading );
537
538
539             // Check if we are further from heading than the roll out point
540             if ( fabs( RelHeading ) > RollOut ) {
541                 // set Target Roll to Max in desired direction
542                 if ( RelHeading < 0 ) {
543                     TargetRoll = 0 - MaxRoll;
544                 } else {
545                     TargetRoll = MaxRoll;
546                 }
547             } else {
548                 // We have to calculate the Target roll
549
550                 // This calculation engine thinks that the Target roll
551                 // should be a line from (RollOut,MaxRoll) to (-RollOut,
552                 // -MaxRoll) I hope this works well.  If I get ambitious
553                 // some day this might become a fancier curve or
554                 // something.
555
556                 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
557                                                 -MaxRoll, RollOut,
558                                                 MaxRoll );
559             }
560
561             // Target Roll has now been Found.
562
563             // Compare Target roll to Current Roll, Generate Rel Roll
564
565             SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
566
567             RelRoll = NormalizeDegrees( TargetRoll 
568                                         - roll_node->getDoubleValue() );
569
570             // Check if we are further from heading than the roll out
571             // smooth point
572             if ( fabs( RelRoll ) > RollOutSmooth ) {
573                 // set Target Roll to Max in desired direction
574                 if ( RelRoll < 0 ) {
575                 AileronSet = 0 - MaxAileron;
576                 } else {
577                     AileronSet = MaxAileron;
578                 }
579             } else {
580                 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
581                                                 -MaxAileron,
582                                                 RollOutSmooth,
583                                                 MaxAileron );
584             }
585
586             globals->get_controls()->set_aileron( AileronSet );
587             globals->get_controls()->set_rudder( AileronSet / 4.0 );
588             // controls.set_rudder( 0.0 );
589         }
590     }
591
592     // altitude hold
593     if ( altitude_hold ) {
594         double climb_rate;
595         double speed, max_climb, error;
596         double prop_error, int_error;
597         double prop_adj, int_adj, total_adj;
598
599         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
600             climb_rate =
601                 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
602         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
603             double x = current_radiostack->get_nav1_gs_dist();
604             double y = (altitude_node->getDoubleValue()
605                         - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
606             double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
607             // cout << "current angle = " << current_angle << endl;
608
609             double target_angle = current_radiostack->get_nav1_target_gs();
610             // cout << "target angle = " << target_angle << endl;
611
612             double gs_diff = target_angle - current_angle;
613             // cout << "difference from desired = " << gs_diff << endl;
614
615             // convert desired vertical path angle into a climb rate
616             double des_angle = current_angle - 10 * gs_diff;
617             // cout << "desired angle = " << des_angle << endl;
618
619             // convert to meter/min
620             // cout << "raw ground speed = " << cur_fdm_state->get_V_ground_speed() << endl;
621             double horiz_vel = cur_fdm_state->get_V_ground_speed()
622                 * SG_FEET_TO_METER * 60.0;
623             // cout << "Horizontal vel = " << horiz_vel << endl;
624             climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
625             // cout << "climb_rate = " << climb_rate << endl;
626             /* climb_error_accum += gs_diff * 2.0; */
627             /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
628         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
629             // brain dead ground hugging with no look ahead
630             climb_rate =
631                 ( TargetAGL - altitude_agl_node->getDoubleValue()
632                   * SG_FEET_TO_METER ) * 16.0;
633             // cout << "target agl = " << TargetAGL 
634             //      << "  current agl = " << fgAPget_agl() 
635             //      << "  target climb rate = " << climb_rate 
636             //      << endl;
637         } else {
638             // just try to zero out rate of climb ...
639             climb_rate = 0.0;
640         }
641
642         speed = get_speed();
643
644         if ( speed < min_climb ) {
645             max_climb = 0.0;
646         } else if ( speed < best_climb ) {
647             max_climb = ((best_climb - min_climb) - (best_climb - speed)) 
648                 * fabs(TargetClimbRate) 
649                 / (best_climb - min_climb);
650         } else {                        
651             max_climb = ( speed - best_climb ) * 10.0 + fabs(TargetClimbRate);
652         }
653
654         // this first one could be optional if we wanted to allow
655         // better climb performance assuming we have the airspeed to
656         // support it.
657         if ( climb_rate > fabs(TargetClimbRate) ) {
658             climb_rate = fabs(TargetClimbRate);
659         }
660
661         if ( climb_rate > max_climb ) {
662             climb_rate = max_climb;
663         }
664
665         if ( climb_rate < -fabs(TargetDecentRate) ) {
666             climb_rate = -fabs(TargetDecentRate);
667         }
668
669         // cout << "Target climb rate = " << TargetClimbRate << endl;
670         // cout << "given our speed, modified desired climb rate = "
671         //      << climb_rate * SG_METER_TO_FEET 
672         //      << " fpm" << endl;
673         // cout << "Current climb rate = "
674         //      << vertical_speed_node->getDoubleValue() * 60 << " fpm" << endl;
675
676         error = vertical_speed_node->getDoubleValue() * 60
677             - climb_rate * SG_METER_TO_FEET;
678
679         // accumulate the error under the curve ... this really should
680         // be *= delta t
681         alt_error_accum += error;
682
683         // calculate integral error, and adjustment amount
684         int_error = alt_error_accum;
685         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
686         int_adj = int_error / 20000.0;
687
688         // caclulate proportional error
689         prop_error = error;
690         prop_adj = prop_error / 2000.0;
691
692         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
693         // if ( total_adj > 0.6 ) {
694         //     total_adj = 0.6;
695         // } else if ( total_adj < -0.2 ) {
696         //     total_adj = -0.2;
697         // }
698         if ( total_adj > 1.0 ) {
699             total_adj = 1.0;
700         } else if ( total_adj < -1.0 ) {
701             total_adj = -1.0;
702         }
703
704         globals->get_controls()->set_elevator_trim( total_adj );
705     }
706
707     // auto throttle
708     if ( auto_throttle ) {
709         double error;
710         double prop_error, int_error;
711         double prop_adj, int_adj, total_adj;
712
713         error = TargetSpeed - get_speed();
714
715         // accumulate the error under the curve ... this really should
716         // be *= delta t
717         speed_error_accum += error;
718         if ( speed_error_accum > 2000.0 ) {
719             speed_error_accum = 2000.0;
720         }
721         else if ( speed_error_accum < -2000.0 ) {
722             speed_error_accum = -2000.0;
723         }
724
725         // calculate integral error, and adjustment amount
726         int_error = speed_error_accum;
727
728         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
729         int_adj = int_error / 200.0;
730
731         // caclulate proportional error
732         prop_error = error;
733         prop_adj = 0.5 + prop_error / 50.0;
734
735         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
736         if ( total_adj > 1.0 ) {
737             total_adj = 1.0;
738         }
739         else if ( total_adj < 0.0 ) {
740             total_adj = 0.0;
741         }
742
743         globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
744                                                total_adj );
745     }
746
747 #ifdef THIS_CODE_IS_NOT_USED
748     if (Mode == 2) // Glide slope hold
749         {
750             double RelSlope;
751             double RelElevator;
752
753             // First, calculate Relative slope and normalize it
754             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
755
756             // Now calculate the elevator offset from current angle
757             if ( abs(RelSlope) > SlopeSmooth )
758                 {
759                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
760                         RelElevator = -MaxElevator;
761                     else
762                         RelElevator = MaxElevator;
763                 }
764
765             else
766                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
767
768             // set the elevator
769             fgElevMove(RelElevator);
770
771         }
772 #endif // THIS_CODE_IS_NOT_USED
773
774     // stash this runs control settings
775     //  update_old_control_values();
776     old_aileron = globals->get_controls()->get_aileron();
777     old_elevator = globals->get_controls()->get_elevator();
778     old_elevator_trim = globals->get_controls()->get_elevator_trim();
779     old_rudder = globals->get_controls()->get_rudder();
780
781     // for cross track error
782     old_lat = lat;
783     old_lon = lon;
784         
785     // Ok, we are done
786     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
787
788     return 0;
789 }
790
791
792 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
793     heading_mode = mode;
794
795     if ( heading_mode == FG_DG_HEADING_LOCK ) {
796         // set heading hold to current heading (as read from DG)
797         // ... no, leave target heading along ... just use the current
798         // heading bug value
799         //  DGTargetHeading = FGSteam::get_DG_deg();
800     } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
801         // set autopilot to hold a zero turn (as reported by the TC)
802     } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
803         // set heading hold to current heading
804         TargetHeading = heading_node->getDoubleValue();
805     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
806         if ( globals->get_route()->size() ) {
807             double course, distance;
808
809             old_lat = latitude_node->getDoubleValue();
810             old_lon = longitude_node->getDoubleValue();
811
812             waypoint = globals->get_route()->get_first();
813             waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
814                                         latitude_node->getDoubleValue(),
815                                         altitude_node->getDoubleValue()
816                                         * SG_FEET_TO_METER,
817                                         &course, &distance );
818             TargetHeading = course;
819             TargetDistance = distance;
820             MakeTargetLatLonStr( waypoint.get_target_lat(),
821                                  waypoint.get_target_lon() );
822             MakeTargetWPStr( distance );
823
824             if ( waypoint.get_target_alt() > 0.0 ) {
825                 TargetAltitude = waypoint.get_target_alt();
826                 altitude_mode = FG_ALTITUDE_LOCK;
827                 set_AltitudeEnabled( true );
828                 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
829             }
830
831             SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
832                     << get_TargetLatitude()  << " "
833                     << get_TargetLongitude() << " ) "
834                     );
835         } else {
836             // no more way points, default to heading lock.
837             heading_mode = FG_TC_HEADING_LOCK;
838         }
839     }
840
841     MakeTargetHeadingStr( TargetHeading );                      
842     update_old_control_values();
843 }
844
845
846 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
847     altitude_mode = mode;
848
849     alt_error_accum = 0.0;
850
851     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
852         if ( TargetAltitude < altitude_agl_node->getDoubleValue()
853              * SG_FEET_TO_METER ) {
854         }
855
856         if ( fgGetString("/sim/startup/units") == "feet" ) {
857             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
858         } else {
859             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
860         }
861     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
862         climb_error_accum = 0.0;
863
864     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
865         TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
866
867         if ( fgGetString("/sim/startup/units") == "feet" ) {
868             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
869         } else {
870             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
871         }
872     }
873     
874     update_old_control_values();
875     SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
876 }
877
878
879 #if 0
880 static inline double get_aoa( void ) {
881     return( cur_fdm_state->get_Gamma_vert_rad() * SGD_RADIANS_TO_DEGREES );
882 }
883
884 static inline double fgAPget_latitude( void ) {
885     return( cur_fdm_state->get_Latitude() * SGD_RADIANS_TO_DEGREES );
886 }
887
888 static inline double fgAPget_longitude( void ) {
889     return( cur_fdm_state->get_Longitude() * SGD_RADIANS_TO_DEGREES );
890 }
891
892 static inline double fgAPget_roll( void ) {
893     return( cur_fdm_state->get_Phi() * SGD_RADIANS_TO_DEGREES );
894 }
895
896 static inline double get_pitch( void ) {
897     return( cur_fdm_state->get_Theta() );
898 }
899
900 double fgAPget_heading( void ) {
901     return( cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES );
902 }
903
904 static inline double fgAPget_altitude( void ) {
905     return( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
906 }
907
908 static inline double fgAPget_climb( void ) {
909     // return in meters per minute
910     return( cur_fdm_state->get_Climb_Rate() * SG_FEET_TO_METER * 60 );
911 }
912
913 static inline double get_sideslip( void ) {
914     return( cur_fdm_state->get_Beta() );
915 }
916
917 static inline double fgAPget_agl( void ) {
918     double agl;
919
920     agl = cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
921         - scenery.get_cur_elev();
922
923     return( agl );
924 }
925 #endif
926
927
928 void FGAutopilot::AltitudeSet( double new_altitude ) {
929     double target_alt = new_altitude;
930
931     // cout << "new altitude = " << new_altitude << endl;
932
933     if ( fgGetString("/sim/startup/units") == "feet" ) {
934         target_alt = new_altitude * SG_FEET_TO_METER;
935     }
936
937     if( target_alt < scenery.get_cur_elev() ) {
938         target_alt = scenery.get_cur_elev();
939     }
940
941     TargetAltitude = target_alt;
942     altitude_mode = FG_ALTITUDE_LOCK;
943
944     // cout << "TargetAltitude = " << TargetAltitude << endl;
945
946     if ( fgGetString("/sim/startup/units") == "feet" ) {
947         target_alt *= SG_METER_TO_FEET;
948     }
949     // ApAltitudeDialogInput->setValue((float)target_alt);
950     MakeTargetAltitudeStr( target_alt );
951         
952     update_old_control_values();
953 }
954
955
956 void FGAutopilot::AltitudeAdjust( double inc )
957 {
958     double target_alt, target_agl;
959
960     if ( fgGetString("/sim/startup/units") == "feet" ) {
961         target_alt = TargetAltitude * SG_METER_TO_FEET;
962         target_agl = TargetAGL * SG_METER_TO_FEET;
963     } else {
964         target_alt = TargetAltitude;
965         target_agl = TargetAGL;
966     }
967
968     // cout << "target_agl = " << target_agl << endl;
969     // cout << "target_agl / inc = " << target_agl / inc << endl;
970     // cout << "(int)(target_agl / inc) = " << (int)(target_agl / inc) << endl;
971
972     if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
973         target_alt += inc;
974     } else {
975         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
976     }
977
978     if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
979         target_agl += inc;
980     } else {
981         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
982     }
983
984     if ( fgGetString("/sim/startup/units") == "feet" ) {
985         target_alt *= SG_FEET_TO_METER;
986         target_agl *= SG_FEET_TO_METER;
987     }
988
989     TargetAltitude = target_alt;
990     TargetAGL = target_agl;
991         
992     if ( fgGetString("/sim/startup/units") == "feet" )
993         target_alt *= SG_METER_TO_FEET;
994     if ( fgGetString("/sim/startup/units") == "feet" )
995         target_agl *= SG_METER_TO_FEET;
996
997     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
998         MakeTargetAltitudeStr( target_alt );
999     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1000         MakeTargetAltitudeStr( target_agl );
1001     }
1002
1003     update_old_control_values();
1004 }
1005
1006
1007 void FGAutopilot::HeadingAdjust( double inc ) {
1008     if ( heading_mode != FG_DG_HEADING_LOCK
1009          && heading_mode != FG_TRUE_HEADING_LOCK )
1010     {
1011         heading_mode = FG_DG_HEADING_LOCK;
1012     }
1013
1014     if ( heading_mode == FG_DG_HEADING_LOCK ) {
1015         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1016         DGTargetHeading = NormalizeDegrees( target );
1017     } else {
1018         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1019         TargetHeading = NormalizeDegrees( target );
1020     }
1021
1022     update_old_control_values();
1023 }
1024
1025
1026 void FGAutopilot::HeadingSet( double new_heading ) {
1027     if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1028         new_heading = NormalizeDegrees( new_heading );
1029         TargetHeading = new_heading;
1030         MakeTargetHeadingStr( TargetHeading );
1031     } else {
1032         heading_mode = FG_DG_HEADING_LOCK;
1033
1034         new_heading = NormalizeDegrees( new_heading );
1035         DGTargetHeading = new_heading;
1036         // following cast needed ambiguous plib
1037         // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1038         MakeTargetHeadingStr( DGTargetHeading );
1039     }
1040     update_old_control_values();
1041 }
1042
1043 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1044     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1045
1046     TargetSpeed = target;
1047 }
1048
1049
1050 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1051     auto_throttle = value;
1052
1053     if ( auto_throttle == true ) {
1054         TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1055         speed_error_accum = 0.0;
1056     }
1057
1058     update_old_control_values();
1059     SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1060             << auto_throttle << ") " << TargetSpeed );
1061 }