1 // newauto.cxx -- autopilot defines and prototypes (very alpha)
3 // Started April 1998 Copyright (C) 1998
5 // Contributions by Jeff Goeke-Smith <jgoeke@voyager.net>
6 // Norman Vine <nhv@cape.com>
7 // Curtis Olson <curt@flightgear.org>
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.
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.
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.
30 #include <stdio.h> // sprintf()
31 #include <string.h> // strcmp()
33 #include <simgear/constants.h>
34 #include <simgear/sg_inlines.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/math/sg_random.h>
38 #include <simgear/route/route.hxx>
40 #include <Cockpit/steam.hxx>
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>
47 #include "newauto.hxx"
50 /// These statics will eventually go into the class
51 /// they are just here while I am experimenting -- NHV :-)
52 // AutoPilot Gain Adjuster members
53 static double MaxRollAdjust; // MaxRollAdjust = 2 * APData->MaxRoll;
54 static double RollOutAdjust; // RollOutAdjust = 2 * APData->RollOut;
55 static double MaxAileronAdjust; // MaxAileronAdjust = 2 * APData->MaxAileron;
56 static double RollOutSmoothAdjust; // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
58 static char NewTgtAirportId[16];
59 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID";
61 extern char *coord_format_lat(float);
62 extern char *coord_format_lon(float);
66 FGAutopilot::FGAutopilot()
71 FGAutopilot::~FGAutopilot() {}
74 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
75 sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
76 sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
77 sprintf( TargetLatLonStr, "%s %s", TargetLatitudeStr, TargetLongitudeStr );
81 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
82 if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
83 sprintf( TargetAltitudeStr, "APAltitude %6.0f+", altitude );
85 sprintf( TargetAltitudeStr, "APAltitude %6.0f", altitude );
90 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
93 } else if (bearing > 360. ) {
96 sprintf( TargetHeadingStr, "APHeading %6.1f", bearing );
100 static inline double get_speed( void ) {
101 return( cur_fdm_state->get_V_equiv_kts() );
104 static inline double get_ground_speed() {
105 // starts in ft/s so we convert to kts
106 static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
108 double ft_s = cur_fdm_state->get_V_ground_speed()
109 * speedup_node->getIntValue();
110 double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
116 void FGAutopilot::MakeTargetWPStr( double distance ) {
117 static time_t last_time = 0;
118 time_t current_time = time(NULL);
119 if ( last_time == current_time ) {
123 last_time = current_time;
127 int size = globals->get_route()->size();
129 // start by wiping the strings
136 SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
138 double eta = accum * SG_METER_TO_NM / get_ground_speed();
139 if ( eta >= 100.0 ) { eta = 99.999; }
141 if ( eta < (1.0/6.0) ) {
142 // within 10 minutes, bump up to min/secs
146 minor = (int)((eta - (int)eta) * 60.0);
147 sprintf( TargetWP1Str, "%s %.2f NM ETA %d:%02d",
148 wp1.get_id().c_str(),
149 accum*SG_METER_TO_NM, major, minor );
154 SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
155 accum += wp2.get_distance();
157 double eta = accum * SG_METER_TO_NM / get_ground_speed();
158 if ( eta >= 100.0 ) { eta = 99.999; }
160 if ( eta < (1.0/6.0) ) {
161 // within 10 minutes, bump up to min/secs
165 minor = (int)((eta - (int)eta) * 60.0);
166 sprintf( TargetWP2Str, "%s %.2f NM ETA %d:%02d",
167 wp2.get_id().c_str(),
168 accum*SG_METER_TO_NM, major, minor );
173 for ( int i = 2; i < size; ++i ) {
174 accum += globals->get_route()->get_waypoint( i ).get_distance();
177 SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
179 double eta = accum * SG_METER_TO_NM / get_ground_speed();
180 if ( eta >= 100.0 ) { eta = 99.999; }
182 if ( eta < (1.0/6.0) ) {
183 // within 10 minutes, bump up to min/secs
187 minor = (int)((eta - (int)eta) * 60.0);
188 sprintf( TargetWP3Str, "%s %.2f NM ETA %d:%02d",
189 wpn.get_id().c_str(),
190 accum*SG_METER_TO_NM, major, minor );
195 void FGAutopilot::update_old_control_values() {
196 old_aileron = globals->get_controls()->get_aileron();
197 old_elevator = globals->get_controls()->get_elevator();
198 old_elevator_trim = globals->get_controls()->get_elevator_trim();
199 old_rudder = globals->get_controls()->get_rudder();
203 // Initialize autopilot subsystem
205 void FGAutopilot::init ()
207 SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
209 // bind data input property nodes...
210 latitude_node = fgGetNode("/position/latitude-deg", true);
211 longitude_node = fgGetNode("/position/longitude-deg", true);
212 altitude_node = fgGetNode("/position/altitude-ft", true);
213 altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
214 vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
215 heading_node = fgGetNode("/orientation/heading-deg", true);
216 roll_node = fgGetNode("/orientation/roll-deg", true);
217 pitch_node = fgGetNode("/orientation/pitch-deg", true);
219 // bind config property nodes...
221 = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
223 = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
224 min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
225 best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
227 = fgGetNode("/autopilot/config/elevator-adj-factor", true);
229 = fgGetNode("/autopilot/config/integral-contribution", true);
231 = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
232 zero_pitch_trim_full_throttle
233 = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
234 current_throttle = fgGetNode("/controls/throttle");
236 // initialize config properties with defaults (in case config isn't there)
237 if ( TargetClimbRate->getFloatValue() < 1 )
238 fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
239 if ( TargetDescentRate->getFloatValue() < 1 )
240 fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
241 if ( min_climb->getFloatValue() < 1)
242 fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
243 if (best_climb->getFloatValue() < 1)
244 fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
245 if (elevator_adj_factor->getFloatValue() < 1)
246 fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
247 if ( integral_contrib->getFloatValue() < 0.0000001 )
248 fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
249 if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
250 fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
251 if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
252 fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
255 heading_hold = false ; // turn the heading hold off
256 altitude_hold = false ; // turn the altitude hold off
257 auto_throttle = false ; // turn the auto throttle off
258 heading_mode = DEFAULT_AP_HEADING_LOCK;
259 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
261 DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
262 TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
263 TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
265 // Initialize target location to startup location
266 old_lat = latitude_node->getDoubleValue();
267 old_lon = longitude_node->getDoubleValue();
268 // set_WayPoint( old_lon, old_lat, 0.0, "default" );
270 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
272 alt_error_accum = 0.0;
273 climb_error_accum = 0.0;
275 MakeTargetAltitudeStr( TargetAltitude );
276 MakeTargetHeadingStr( TargetHeading );
278 // These eventually need to be read from current_aircaft somehow.
280 // the maximum roll, in Deg
283 // the deg from heading to start rolling out at, in Deg
286 // how far can I move the aleron from center.
289 // Smoothing distance for alerion control
292 // Hardwired for now should be in options
293 // 25% max control variablilty 0.5 / 2.0
294 disengage_threshold = 1.0;
296 #if !defined( USING_SLIDER_CLASS )
297 MaxRollAdjust = 2 * MaxRoll;
298 RollOutAdjust = 2 * RollOut;
299 MaxAileronAdjust = 2 * MaxAileron;
300 RollOutSmoothAdjust = 2 * RollOutSmooth;
301 #endif // !defined( USING_SLIDER_CLASS )
303 update_old_control_values();
309 // Autopilot control property get/set bindings
310 fgTie("/autopilot/locks/altitude", this,
311 &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
312 fgSetArchivable("/autopilot/locks/altitude");
313 fgTie("/autopilot/settings/altitude-ft", this,
314 &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
315 fgSetArchivable("/autopilot/settings/altitude-ft");
316 fgTie("/autopilot/locks/glide-slope", this,
317 &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
318 fgSetArchivable("/autopilot/locks/glide-slope");
319 fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
320 fgTie("/autopilot/locks/terrain", this,
321 &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
322 fgSetArchivable("/autopilot/locks/terrain");
323 fgTie("/autopilot/settings/climb-rate-fpm", this,
324 &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
325 fgSetArchivable("/autopilot/settings/climb-rate-fpm");
326 fgTie("/autopilot/locks/heading", this,
327 &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
328 fgSetArchivable("/autopilot/locks/heading");
329 fgTie("/autopilot/settings/heading-bug-deg", this,
330 &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
331 fgSetArchivable("/autopilot/settings/heading-bug-deg");
332 fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
333 fgTie("/autopilot/locks/wing-leveler", this,
334 &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
335 fgSetArchivable("/autopilot/locks/wing-leveler");
336 fgTie("/autopilot/locks/nav[0]", this,
337 &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
338 fgSetArchivable("/autopilot/locks/nav[0]");
339 fgTie("/autopilot/locks/auto-throttle", this,
340 &FGAutopilot::getAPAutoThrottleLock,
341 &FGAutopilot::setAPAutoThrottleLock);
342 fgSetArchivable("/autopilot/locks/auto-throttle");
343 fgTie("/autopilot/control-overrides/rudder", this,
344 &FGAutopilot::getAPRudderControl,
345 &FGAutopilot::setAPRudderControl);
346 fgSetArchivable("/autopilot/control-overrides/rudder");
347 fgTie("/autopilot/control-overrides/elevator", this,
348 &FGAutopilot::getAPElevatorControl,
349 &FGAutopilot::setAPElevatorControl);
350 fgSetArchivable("/autopilot/control-overrides/elevator");
351 fgTie("/autopilot/control-overrides/throttle", this,
352 &FGAutopilot::getAPThrottleControl,
353 &FGAutopilot::setAPThrottleControl);
354 fgSetArchivable("/autopilot/control-overrides/throttle");
358 FGAutopilot::unbind ()
362 // Reset the autopilot system
363 void FGAutopilot::reset() {
365 heading_hold = false ; // turn the heading hold off
366 altitude_hold = false ; // turn the altitude hold off
367 auto_throttle = false ; // turn the auto throttle off
368 heading_mode = DEFAULT_AP_HEADING_LOCK;
370 // TargetHeading = 0.0; // default direction, due north
371 MakeTargetHeadingStr( TargetHeading );
373 // TargetAltitude = 3000; // default altitude in meters
374 MakeTargetAltitudeStr( TargetAltitude );
376 alt_error_accum = 0.0;
377 climb_error_accum = 0.0;
379 update_old_control_values();
381 sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id") );
383 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
387 static double NormalizeDegrees( double Input ) {
388 // normalize the input to the range (-180,180]
389 // Input should not be greater than -360 to 360.
390 // Current rules send the output to an undefined state.
391 while ( Input > 180.0 ) { Input -= 360.0; }
392 while ( Input <= -180.0 ) { Input += 360.0; }
397 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
398 // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
399 //assert(x1 != x2); // Divide by zero error. Cold abort for now
402 // static double y = 0.0;
403 // double dx = x2 -x1;
404 // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
407 double m, b, y; // the constants to find in y=mx+b
410 m = ( y2 - y1 ) / ( x2 - x1 ); // calculate the m
412 b = y1 - m * x1; // calculate the b
414 y = m * x + b; // the final calculation
424 FGAutopilot::update (int dt)
426 // Remove the following lines when the calling funcitons start
427 // passing in the data pointer
429 // get control settings
431 double lat = latitude_node->getDoubleValue();
432 double lon = longitude_node->getDoubleValue();
433 double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
435 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run() lat = " << lat <<
436 " lon = " << lon << " alt = " << alt );
438 #ifdef FG_FORCE_AUTO_DISENGAGE
439 // see if somebody else has changed them
440 if( fabs(aileron - old_aileron) > disengage_threshold ||
441 fabs(elevator - old_elevator) > disengage_threshold ||
442 fabs(elevator_trim - old_elevator_trim) >
443 disengage_threshold ||
444 fabs(rudder - old_rudder) > disengage_threshold )
446 // if controls changed externally turn autopilot off
447 waypoint_hold = false ; // turn the target hold off
448 heading_hold = false ; // turn the heading hold off
449 altitude_hold = false ; // turn the altitude hold off
450 terrain_follow = false; // turn the terrain_follow hold off
451 // auto_throttle = false; // turn the auto_throttle off
453 // stash this runs control settings
454 old_aileron = aileron;
455 old_elevator = elevator;
456 old_elevator_trim = elevator_trim;
464 if ( heading_hold == true ) {
465 if ( heading_mode == FG_DG_HEADING_LOCK ) {
466 TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
467 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
468 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
469 MakeTargetHeadingStr( TargetHeading );
470 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
471 // we don't set a specific target heading in
472 // TC_HEADING_LOCK mode, we instead try to keep the turn
473 // coordinator zero'd
474 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
475 // leave "true" target heading as is
476 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
477 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
478 MakeTargetHeadingStr( TargetHeading );
479 } else if ( heading_mode == FG_HEADING_NAV1 ) {
480 // track the NAV1 heading needle deflection
482 // determine our current radial position relative to the
483 // navaid in "true" heading.
484 double cur_radial = current_radiostack->get_nav1_heading();
485 if ( current_radiostack->get_nav1_loc() ) {
486 // ILS localizers radials are already "true" in our
489 cur_radial += current_radiostack->get_nav1_magvar();
491 if ( current_radiostack->get_nav1_from_flag() ) {
493 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
496 // determine the target radial in "true" heading
497 double tgt_radial = current_radiostack->get_nav1_radial();
498 if ( current_radiostack->get_nav1_loc() ) {
499 // ILS localizers radials are already "true" in our
502 // VOR radials need to have that vor's offset added in
503 tgt_radial += current_radiostack->get_nav1_magvar();
506 // determine the heading adjustment needed.
508 current_radiostack->get_nav1_heading_needle_deflection()
509 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
510 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
512 // determine the target heading to fly to intercept the
514 TargetHeading = tgt_radial + adjustment;
515 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
516 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
518 MakeTargetHeadingStr( TargetHeading );
519 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
520 // update target heading to waypoint
522 double wp_course, wp_distance;
524 #ifdef DO_fgAP_CORRECTED_COURSE
525 // compute course made good
526 // this needs lots of special casing before use
527 double course, reverse, distance, corrected_course;
528 // need to test for iter
529 geo_inverse_wgs_84( 0, //fgAPget_altitude(),
537 #endif // DO_fgAP_CORRECTED_COURSE
539 // compute course to way_point
540 // need to test for iter
541 SGWayPoint wp = globals->get_route()->get_first();
542 wp.CourseAndDistance( lon, lat, alt,
543 &wp_course, &wp_distance );
545 #ifdef DO_fgAP_CORRECTED_COURSE
546 corrected_course = course - wp_course;
547 if( fabs(corrected_course) > 0.1 )
548 printf("fgAP: course %f wp_course %f %f %f\n",
549 course, wp_course, fabs(corrected_course),
551 #endif // DO_fgAP_CORRECTED_COURSE
553 if ( wp_distance > 100 ) {
554 // corrected_course = course - wp_course;
555 TargetHeading = NormalizeDegrees(wp_course);
557 // pop off this waypoint from the list
558 if ( globals->get_route()->size() ) {
559 globals->get_route()->delete_first();
562 // see if there are more waypoints on the list
563 if ( globals->get_route()->size() ) {
565 set_HeadingMode( FG_HEADING_WAYPOINT );
568 heading_mode = FG_TRUE_HEADING_LOCK;
569 // use current heading
570 TargetHeading = heading_node->getDoubleValue();
573 MakeTargetHeadingStr( TargetHeading );
574 // Force this just in case
575 TargetDistance = wp_distance;
576 MakeTargetWPStr( wp_distance );
579 if ( heading_mode == FG_TC_HEADING_LOCK ) {
580 // drive the turn coordinator to zero
581 double turn = FGSteam::get_TC_std();
582 double AileronSet = -turn / 2.0;
583 SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
584 globals->get_controls()->set_aileron( AileronSet );
585 globals->get_controls()->set_rudder( AileronSet / 4.0 );
587 // steer towards the target heading
595 = NormalizeDegrees( TargetHeading
596 - heading_node->getDoubleValue() );
597 // figure out how far off we are from desired heading
599 // Now it is time to deterime how far we should be rolled.
600 SG_LOG( SG_AUTOPILOT, SG_DEBUG,
601 "Heading = " << heading_node->getDoubleValue() <<
602 " TargetHeading = " << TargetHeading <<
603 " RelHeading = " << RelHeading );
605 // Check if we are further from heading than the roll out point
606 if ( fabs( RelHeading ) > RollOut ) {
607 // set Target Roll to Max in desired direction
608 if ( RelHeading < 0 ) {
609 TargetRoll = 0 - MaxRoll;
611 TargetRoll = MaxRoll;
614 // We have to calculate the Target roll
616 // This calculation engine thinks that the Target roll
617 // should be a line from (RollOut,MaxRoll) to (-RollOut,
618 // -MaxRoll) I hope this works well. If I get ambitious
619 // some day this might become a fancier curve or
622 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
627 // Target Roll has now been Found.
629 // Compare Target roll to Current Roll, Generate Rel Roll
631 SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
633 RelRoll = NormalizeDegrees( TargetRoll
634 - roll_node->getDoubleValue() );
636 // Check if we are further from heading than the roll out
638 if ( fabs( RelRoll ) > RollOutSmooth ) {
639 // set Target Roll to Max in desired direction
641 AileronSet = 0 - MaxAileron;
643 AileronSet = MaxAileron;
646 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
652 globals->get_controls()->set_aileron( AileronSet );
653 globals->get_controls()->set_rudder( AileronSet / 4.0 );
654 // controls.set_rudder( 0.0 );
659 if ( altitude_hold ) {
661 double speed, max_climb, error;
662 double prop_error, int_error;
663 double prop_adj, int_adj, total_adj;
665 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
667 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
668 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
669 double x = current_radiostack->get_nav1_gs_dist();
670 double y = (altitude_node->getDoubleValue()
671 - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
672 double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
674 double target_angle = current_radiostack->get_nav1_target_gs();
676 double gs_diff = target_angle - current_angle;
678 // convert desired vertical path angle into a climb rate
679 double des_angle = current_angle - 10 * gs_diff;
681 // convert to meter/min
682 double horiz_vel = cur_fdm_state->get_V_ground_speed()
683 * SG_FEET_TO_METER * 60.0;
684 climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
685 /* climb_error_accum += gs_diff * 2.0; */
686 /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
687 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
688 // brain dead ground hugging with no look ahead
690 ( TargetAGL - altitude_agl_node->getDoubleValue()
691 * SG_FEET_TO_METER ) * 16.0;
693 // just try to zero out rate of climb ...
699 if ( speed < min_climb->getFloatValue() ) {
701 } else if ( speed < best_climb->getFloatValue() ) {
702 max_climb = ((best_climb->getFloatValue()
703 - min_climb->getFloatValue())
704 - (best_climb->getFloatValue() - speed))
705 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER)
706 / (best_climb->getFloatValue() - min_climb->getFloatValue());
708 max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
709 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
712 // this first one could be optional if we wanted to allow
713 // better climb performance assuming we have the airspeed to
716 fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
718 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
721 if ( climb_rate > max_climb ) {
722 climb_rate = max_climb;
726 -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
728 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
731 error = vertical_speed_node->getDoubleValue() * 60
732 - climb_rate * SG_METER_TO_FEET;
734 // accumulate the error under the curve ... this really should
736 alt_error_accum += error;
738 // calculate integral error, and adjustment amount
739 int_error = alt_error_accum;
740 // printf("error = %.2f int_error = %.2f\n", error, int_error);
741 int_adj = int_error / elevator_adj_factor->getFloatValue();
743 // caclulate proportional error
745 prop_adj = prop_error / elevator_adj_factor->getDoubleValue();
747 total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
748 + (double) integral_contrib->getFloatValue() * int_adj;
750 // stop on autopilot trim at 30% +/-
751 // if ( total_adj > 0.3 ) {
753 // } else if ( total_adj < -0.3 ) {
757 // adjust for throttle pitch gain
758 total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
759 / (1 - zero_pitch_throttle->getFloatValue()))
760 * zero_pitch_trim_full_throttle->getFloatValue();
762 globals->get_controls()->set_elevator_trim( total_adj );
766 if ( auto_throttle ) {
768 double prop_error, int_error;
769 double prop_adj, int_adj, total_adj;
771 error = TargetSpeed - get_speed();
773 // accumulate the error under the curve ... this really should
775 speed_error_accum += error;
776 if ( speed_error_accum > 2000.0 ) {
777 speed_error_accum = 2000.0;
779 else if ( speed_error_accum < -2000.0 ) {
780 speed_error_accum = -2000.0;
783 // calculate integral error, and adjustment amount
784 int_error = speed_error_accum;
786 // printf("error = %.2f int_error = %.2f\n", error, int_error);
787 int_adj = int_error / 200.0;
789 // caclulate proportional error
791 prop_adj = 0.5 + prop_error / 50.0;
793 total_adj = 0.9 * prop_adj + 0.1 * int_adj;
794 if ( total_adj > 1.0 ) {
797 else if ( total_adj < 0.0 ) {
801 globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
805 #ifdef THIS_CODE_IS_NOT_USED
806 if (Mode == 2) // Glide slope hold
811 // First, calculate Relative slope and normalize it
812 RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
814 // Now calculate the elevator offset from current angle
815 if ( abs(RelSlope) > SlopeSmooth )
817 if ( RelSlope < 0 ) // set RelElevator to max in the correct direction
818 RelElevator = -MaxElevator;
820 RelElevator = MaxElevator;
824 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
827 fgElevMove(RelElevator);
830 #endif // THIS_CODE_IS_NOT_USED
832 // stash this runs control settings
833 // update_old_control_values();
834 old_aileron = globals->get_controls()->get_aileron();
835 old_elevator = globals->get_controls()->get_elevator();
836 old_elevator_trim = globals->get_controls()->get_elevator_trim();
837 old_rudder = globals->get_controls()->get_rudder();
839 // for cross track error
844 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
848 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
851 if ( heading_mode == FG_DG_HEADING_LOCK ) {
852 // set heading hold to current heading (as read from DG)
853 // ... no, leave target heading along ... just use the current
855 // DGTargetHeading = FGSteam::get_DG_deg();
856 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
857 // set autopilot to hold a zero turn (as reported by the TC)
858 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
859 // set heading hold to current heading
860 TargetHeading = heading_node->getDoubleValue();
861 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
862 if ( globals->get_route()->size() ) {
863 double course, distance;
865 old_lat = latitude_node->getDoubleValue();
866 old_lon = longitude_node->getDoubleValue();
868 waypoint = globals->get_route()->get_first();
869 waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
870 latitude_node->getDoubleValue(),
871 altitude_node->getDoubleValue()
873 &course, &distance );
874 TargetHeading = course;
875 TargetDistance = distance;
876 MakeTargetLatLonStr( waypoint.get_target_lat(),
877 waypoint.get_target_lon() );
878 MakeTargetWPStr( distance );
880 if ( waypoint.get_target_alt() > 0.0 ) {
881 TargetAltitude = waypoint.get_target_alt();
882 altitude_mode = FG_ALTITUDE_LOCK;
883 set_AltitudeEnabled( true );
884 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
887 SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
888 << get_TargetLatitude() << " "
889 << get_TargetLongitude() << " ) "
892 // no more way points, default to heading lock.
893 heading_mode = FG_TC_HEADING_LOCK;
897 MakeTargetHeadingStr( TargetHeading );
898 update_old_control_values();
902 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
903 altitude_mode = mode;
905 alt_error_accum = 0.0;
908 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
909 if ( TargetAltitude < altitude_agl_node->getDoubleValue()
910 * SG_FEET_TO_METER ) {
913 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
914 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
916 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
918 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
919 climb_error_accum = 0.0;
921 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
922 TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
924 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
925 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
927 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
931 update_old_control_values();
932 SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
936 void FGAutopilot::AltitudeSet( double new_altitude ) {
937 double target_alt = new_altitude;
939 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
940 target_alt = new_altitude * SG_FEET_TO_METER;
943 if( target_alt < scenery.get_cur_elev() ) {
944 target_alt = scenery.get_cur_elev();
947 TargetAltitude = target_alt;
948 altitude_mode = FG_ALTITUDE_LOCK;
950 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
951 target_alt *= SG_METER_TO_FEET;
953 // ApAltitudeDialogInput->setValue((float)target_alt);
954 MakeTargetAltitudeStr( target_alt );
956 update_old_control_values();
960 void FGAutopilot::AltitudeAdjust( double inc )
962 double target_alt, target_agl;
964 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
965 target_alt = TargetAltitude * SG_METER_TO_FEET;
966 target_agl = TargetAGL * SG_METER_TO_FEET;
968 target_alt = TargetAltitude;
969 target_agl = TargetAGL;
972 if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
975 target_alt = ( int ) ( target_alt / inc ) * inc + inc;
978 if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
981 target_agl = ( int ) ( target_agl / inc ) * inc + inc;
984 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
985 target_alt *= SG_FEET_TO_METER;
986 target_agl *= SG_FEET_TO_METER;
989 TargetAltitude = target_alt;
990 TargetAGL = target_agl;
992 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
993 target_alt *= SG_METER_TO_FEET;
994 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
995 target_agl *= SG_METER_TO_FEET;
997 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
998 MakeTargetAltitudeStr( target_alt );
999 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1000 MakeTargetAltitudeStr( target_agl );
1003 update_old_control_values();
1007 void FGAutopilot::HeadingAdjust( double inc ) {
1008 if ( heading_mode != FG_DG_HEADING_LOCK
1009 && heading_mode != FG_TRUE_HEADING_LOCK )
1011 heading_mode = FG_DG_HEADING_LOCK;
1014 if ( heading_mode == FG_DG_HEADING_LOCK ) {
1015 double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1016 DGTargetHeading = NormalizeDegrees( target );
1018 double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1019 TargetHeading = NormalizeDegrees( target );
1022 update_old_control_values();
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 );
1032 heading_mode = FG_DG_HEADING_LOCK;
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 );
1040 update_old_control_values();
1043 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1044 double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1046 TargetSpeed = target;
1050 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1051 auto_throttle = value;
1053 if ( auto_throttle == true ) {
1054 TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1055 speed_error_accum = 0.0;
1058 update_old_control_values();
1059 SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1060 << auto_throttle << ") " << TargetSpeed );
1066 ////////////////////////////////////////////////////////////////////////
1067 // Kludged methods for tying to properties.
1069 // These should change eventually; they all used to be static
1071 ////////////////////////////////////////////////////////////////////////
1074 * Get the autopilot altitude lock (true=on).
1077 FGAutopilot::getAPAltitudeLock () const
1079 return (get_AltitudeEnabled() &&
1081 == FGAutopilot::FG_ALTITUDE_LOCK);
1086 * Set the autopilot altitude lock (true=on).
1089 FGAutopilot::setAPAltitudeLock (bool lock)
1092 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_LOCK);
1093 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_LOCK)
1094 set_AltitudeEnabled(lock);
1099 * Get the autopilot target altitude in feet.
1102 FGAutopilot::getAPAltitude () const
1104 return get_TargetAltitude() * SG_METER_TO_FEET;
1109 * Set the autopilot target altitude in feet.
1112 FGAutopilot::setAPAltitude (double altitude)
1114 set_TargetAltitude( altitude * SG_FEET_TO_METER );
1118 * Get the autopilot altitude lock (true=on).
1121 FGAutopilot::getAPGSLock () const
1123 return (get_AltitudeEnabled() &&
1125 == FGAutopilot::FG_ALTITUDE_GS1));
1130 * Set the autopilot altitude lock (true=on).
1133 FGAutopilot::setAPGSLock (bool lock)
1136 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1137 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1138 set_AltitudeEnabled(lock);
1143 * Get the autopilot terrain lock (true=on).
1146 FGAutopilot::getAPTerrainLock () const
1148 return (get_AltitudeEnabled() &&
1150 == FGAutopilot::FG_ALTITUDE_TERRAIN));
1155 * Set the autopilot terrain lock (true=on).
1158 FGAutopilot::setAPTerrainLock (bool lock)
1161 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1162 set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1165 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1166 set_AltitudeEnabled(lock);
1171 * Get the autopilot target altitude in feet.
1174 FGAutopilot::getAPClimb () const
1176 return get_TargetClimbRate() * SG_METER_TO_FEET;
1181 * Set the autopilot target altitude in feet.
1184 FGAutopilot::setAPClimb (double rate)
1186 set_TargetClimbRate( rate * SG_FEET_TO_METER );
1191 * Get the autopilot heading lock (true=on).
1194 FGAutopilot::getAPHeadingLock () const
1197 (get_HeadingEnabled() &&
1198 get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1203 * Set the autopilot heading lock (true=on).
1206 FGAutopilot::setAPHeadingLock (bool lock)
1209 set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1210 if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1211 set_HeadingEnabled(lock);
1216 * Get the autopilot heading bug in degrees.
1219 FGAutopilot::getAPHeadingBug () const
1221 return get_DGTargetHeading();
1226 * Set the autopilot heading bug in degrees.
1229 FGAutopilot::setAPHeadingBug (double heading)
1231 set_DGTargetHeading( heading );
1236 * Get the autopilot wing leveler lock (true=on).
1239 FGAutopilot::getAPWingLeveler () const
1242 (get_HeadingEnabled() &&
1243 get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1248 * Set the autopilot wing leveler lock (true=on).
1251 FGAutopilot::setAPWingLeveler (bool lock)
1254 set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1255 if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1256 set_HeadingEnabled(lock);
1260 * Return true if the autopilot is locked to NAV1.
1263 FGAutopilot::getAPNAV1Lock () const
1266 (get_HeadingEnabled() &&
1267 get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1272 * Set the autopilot NAV1 lock.
1275 FGAutopilot::setAPNAV1Lock (bool lock)
1278 set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1279 if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1280 set_HeadingEnabled(lock);
1284 * Get the autopilot autothrottle lock.
1287 FGAutopilot::getAPAutoThrottleLock () const
1289 return get_AutoThrottleEnabled();
1294 * Set the autothrottle lock.
1297 FGAutopilot::setAPAutoThrottleLock (bool lock)
1299 set_AutoThrottleEnabled(lock);
1305 FGAutopilot::getAPRudderControl () const
1307 if (getAPHeadingLock())
1308 return get_TargetHeading();
1310 return globals->get_controls()->get_rudder();
1315 FGAutopilot::setAPRudderControl (double value)
1317 if (getAPHeadingLock()) {
1318 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1319 value -= get_TargetHeading();
1320 HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1322 globals->get_controls()->set_rudder(value);
1328 FGAutopilot::getAPElevatorControl () const
1330 if (getAPAltitudeLock())
1331 return get_TargetAltitude();
1333 return globals->get_controls()->get_elevator();
1338 FGAutopilot::setAPElevatorControl (double value)
1340 if (value != 0 && getAPAltitudeLock()) {
1341 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1342 value -= get_TargetAltitude();
1343 AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1345 globals->get_controls()->set_elevator(value);
1351 FGAutopilot::getAPThrottleControl () const
1353 if (getAPAutoThrottleLock())
1354 return 0.0; // always resets
1356 return globals->get_controls()->get_throttle(0);
1361 FGAutopilot::setAPThrottleControl (double value)
1363 if (getAPAutoThrottleLock())
1364 AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1366 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1369 // end of newauto.cxx