1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
3 // Written by David Culp, started October 2003.
5 // Copyright (C) 2003 David P. Culp - davidculp2@comcast.net
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include <simgear/math/point3d.hxx>
26 #include <simgear/route/waypoint.hxx>
27 #include <Main/fg_props.hxx>
28 #include <Main/globals.hxx>
29 #include <Main/viewer.hxx>
30 #include <Scenery/scenery.hxx>
31 #include <Scenery/tilemgr.hxx>
38 # define finite _finite
39 #elif defined(__sun) || defined(sgi)
45 #include "AIAircraft.hxx"
46 //#include <Airports/trafficcontroller.hxx>
48 static string tempReg;
50 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
51 // cruise_speed, descent_speed, land_speed
54 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] =
57 {2.0, 2.0, 450.0, 1000.0, 70.0, 80.0, 100.0, 80.0, 60.0},
59 {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
61 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
63 {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
65 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
66 // ufo (extreme accel/decel)
67 {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
70 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft)
74 groundOffset = trafficRef->getGroundOffset();
88 groundTargetSpeed = 0;
90 // set heading and altitude locks
94 headingChangeRate = 0.0;
100 FGAIAircraft::~FGAIAircraft()
104 controller->signOff(getID());
108 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode)
113 FGAIBase::readFromScenario(scFileNode);
115 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
116 setFlightPlan(scFileNode->getStringValue("flightplan"),
117 scFileNode->getBoolValue("repeat", false));
118 setCallSign(scFileNode->getStringValue("callsign"));
122 void FGAIAircraft::bind()
126 props->tie("controls/gear/gear-down",
127 SGRawValueMethods<FGAIAircraft,bool>(*this,
128 &FGAIAircraft::_getGearDown));
129 props->setStringValue("callsign", callsign.c_str());
133 void FGAIAircraft::unbind()
137 props->untie("controls/gear/gear-down");
141 void FGAIAircraft::update(double dt)
143 FGAIBase::update(dt);
149 void FGAIAircraft::setPerformance(const std::string& acclass)
151 if (acclass == "light")
153 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
155 else if (acclass == "ww2_fighter")
157 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
159 else if (acclass == "jet_transport")
161 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
163 else if (acclass == "jet_fighter")
165 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
167 else if (acclass == "tanker")
169 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
171 else if (acclass == "ufo")
173 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
177 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
182 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps)
189 void FGAIAircraft::Run(double dt)
192 FGAIAircraft::dt = dt;
193 if(!updateTargetValues())
198 controller->update(getID(),
199 pos.getLatitudeDeg(),
200 pos.getLongitudeDeg(),
204 processATC(controller->getInstruction(getID()));
209 adjustSpeed(groundTargetSpeed);
213 adjustSpeed(tgt_speed);
220 updateVerticalSpeed();
225 void FGAIAircraft::AccelTo(double speed)
231 void FGAIAircraft::PitchTo(double angle)
238 void FGAIAircraft::RollTo(double angle)
245 void FGAIAircraft::YawTo(double angle)
251 void FGAIAircraft::ClimbTo(double alt_ft )
253 tgt_altitude_ft = alt_ft;
258 void FGAIAircraft::TurnTo(double heading)
260 tgt_heading = heading;
265 double FGAIAircraft::sign(double x)
274 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat)
276 if (!flightplan.empty())
278 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
279 fp->setRepeat(repeat);
285 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f)
292 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now )
295 //if (! fpExecutable(now))
298 // the one behind you
299 FGAIFlightPlan::waypoint* prev = 0;
301 FGAIFlightPlan::waypoint* curr = 0;
303 FGAIFlightPlan::waypoint* next = 0;
305 prev = fp->getPreviousWaypoint();
306 curr = fp->getCurrentWaypoint();
307 next = fp->getNextWaypoint();
311 ///////////////////////////////////////////////////////////////////////////
312 // Initialize the flightplan
313 //////////////////////////////////////////////////////////////////////////
316 handleFirstWaypoint();
318 } // end of initialization
322 if (! leadPointReached(curr))
324 controlHeading(curr);
325 controlSpeed(curr, next);
329 if (curr->finished) //end of the flight plan
340 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
341 tgt_heading = fp->getBearing(curr, next);
345 //TODO let the fp handle this (loading of next leg)
346 fp->IncrementWaypoint((bool) trafficRef);
347 if (!(fp->getNextWaypoint()) && trafficRef)
350 prev = fp->getPreviousWaypoint();
351 curr = fp->getCurrentWaypoint();
352 next = fp->getNextWaypoint();
354 // Now that we have incremented the waypoints, excute some traffic manager specific code
357 //TODO isn't this best executed right at the beginning?
358 if (! aiTrafficVisible())
364 if (! handleAirportEndPoints(prev, now))
370 announcePositionToController();
376 fp->setLeadDistance(speed, tgt_heading, curr, next);
379 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
381 tgt_altitude_ft = prev->altitude;
382 if (curr->crossat > -1000.0)
385 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
386 / 6076.0 / speed*60.0);
387 tgt_altitude_ft = curr->crossat;
394 tgt_speed = prev->speed;
395 hdg_lock = alt_lock = true;
396 no_roll = prev->on_ground;
401 void FGAIAircraft::initializeFlightPlan()
407 bool FGAIAircraft::_getGearDown() const
409 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
410 && (props->getFloatValue("velocities/airspeed-kt")
411 < performance->land_speed*1.25));
415 void FGAIAircraft::loadNextLeg()
419 if ((leg = fp->getLeg()) == 10)
426 FGAirport *dep = trafficRef->getDepartureAirport();
427 FGAirport *arr = trafficRef->getArrivalAirport();
435 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
440 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
441 trafficRef->getSpeed(),
445 trafficRef->getRadius(),
446 trafficRef->getFlightType(),
453 // Note: This code is copied from David Luff's AILocalTraffic
454 // Warning - ground elev determination is CPU intensive
455 // Either this function or the logic of how often it is called
456 // will almost certainly change.
458 void FGAIAircraft::getGroundElev(double dt)
462 // Update minimally every three secs, but add some randomness
463 // to prevent all IA objects doing this in synchrony
464 if (dt_elev_count < (3.0) + (rand() % 10))
469 // Only do the proper hitlist stuff if we are within visible range of the viewer.
472 double visibility_meters = fgGetDouble("/environment/visibility-m");
474 FGViewer* vw = globals->get_current_view();
475 double course, distance;
477 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
478 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
479 view.CourseAndDistance(current, &course, &distance);
480 if(distance > visibility_meters)
482 //aip.getSGLocation()->set_cur_elev_m(aptElev);
486 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
487 double range = 500.0;
488 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range))
490 // Try to shedule tiles for that position.
491 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
494 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
496 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
497 tgt_altitude_ft = alt * SG_METER_TO_FEET;
502 void FGAIAircraft::setCallSign(const string& s)
508 void FGAIAircraft::doGroundAltitude()
510 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
511 altitude_ft = (tgt_altitude_ft + groundOffset);
513 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
517 void FGAIAircraft::announcePositionToController()
521 int leg = fp->getLeg();
523 // Note that leg was been incremented after creating the current leg, so we should use
524 // leg numbers here that are one higher than the number that is used to create the leg
528 case 3: // Taxiing to runway
529 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
530 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
532 case 4: //Take off tower controller
533 if (trafficRef->getDepartureAirport()->getDynamics())
535 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
536 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
537 //cerr << trafficRef->getCallSign() << " at runway " << fp->getRunway() << "Ready for departure "
538 // << trafficRef->getFlightType() << " to " << trafficRef->getArrivalAirport()->getId() << endl;
539 // if (controller == 0) {
540 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
546 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
549 case 9: // Taxiing for parking
550 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
551 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
558 if ((controller != prevController) && (prevController != 0))
560 prevController->signOff(getID());
561 string callsign = trafficRef->getCallSign();
562 if ( trafficRef->getHeavy())
567 //cerr << callsign << " ready to taxi to runway " << fp->getRunway() << endl;
570 //cerr << callsign << " at runway " << fp->getRunway() << "Ready for take-off. "
571 // << trafficRef->getFlightRules() << " to " << trafficRef->getArrivalAirport()->getId()
572 // << "(" << trafficRef->getArrivalAirport()->getName() << ")."<< endl;
576 prevController = controller;
579 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
580 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
581 trafficRef->getRadius(), leg, trafficRef->getCallSign());
587 void FGAIAircraft::processATC(FGATCInstruction instruction)
589 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
590 if (instruction.getHoldPattern ())
595 if (instruction.getHoldPosition ())
608 // cerr << trafficRef->getCallSign() << " Resuming Taxi " << endl;
611 // Change speed Instruction. This can only be excecuted when there is no
612 // Hold position instruction.
613 if (instruction.getChangeSpeed ())
616 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
617 AccelTo(instruction.getSpeed());
621 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
624 if (instruction.getChangeHeading ())
627 TurnTo(instruction.getHeading());
631 if (fp) {hdg_lock = true;}
633 if (instruction.getChangeAltitude())
640 void FGAIAircraft::handleFirstWaypoint()
642 bool eraseWaypoints; //TODO YAGNI
645 eraseWaypoints = true;
649 eraseWaypoints = false;
652 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
653 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
654 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
659 //TODO fp should handle this
660 fp->IncrementWaypoint(eraseWaypoints);
661 if (!(fp->getNextWaypoint()) && trafficRef)
664 prev = fp->getPreviousWaypoint(); //first waypoint
665 curr = fp->getCurrentWaypoint(); //second waypoint
666 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
668 setLatitude(prev->latitude);
669 setLongitude(prev->longitude);
670 setSpeed(prev->speed);
671 setAltitude(prev->altitude);
673 if (prev->speed > 0.0)
674 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
676 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
678 // If next doesn't exist, as in incrementally created flightplans for
679 // AI/Trafficmanager created plans,
680 // Make sure lead distance is initialized otherwise
682 fp->setLeadDistance(speed, hdg, curr, next);
684 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
687 tgt_vs = (curr->crossat - prev->altitude)
688 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
689 / 6076.0 / prev->speed*60.0);
690 tgt_altitude_ft = curr->crossat;
695 tgt_altitude_ft = prev->altitude;
697 alt_lock = hdg_lock = true;
698 no_roll = prev->on_ground;
701 Transform(); // make sure aip is initialized.
702 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
705 // Make sure to announce the aircraft's position
706 announcePositionToController();
712 * Check Execution time (currently once every 100 ms)
713 * Add a bit of randomization to prevent the execution of all flight plans
714 * in synchrony, which can add significant periodic framerate flutter.
719 bool FGAIAircraft::fpExecutable(time_t now)
721 double rand_exec_time = (rand() % 100) / 100;
722 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
727 * Check to see if we've reached the lead point for our next turn
732 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr)
734 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
736 //cerr << "2" << endl;
737 double lead_dist = fp->getLeadDistance();
738 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
739 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
741 if (lead_dist < fabs(2*speed))
743 //don't skip over the waypoint
744 lead_dist = fabs(2*speed);
745 //cerr << "Extending lead distance to " << lead_dist << endl;
748 //prev_dist_to_go = dist_to_go;
749 return dist_to_go < lead_dist;
753 bool FGAIAircraft::aiTrafficVisible()
755 double userLatitude = fgGetDouble("/position/latitude-deg");
756 double userLongitude = fgGetDouble("/position/longitude-deg");
757 double course, distance;
759 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
760 SGWayPoint user (userLongitude, userLatitude, 0);
762 user.CourseAndDistance(current, &course, &distance);
764 return ((distance * SG_METER_TO_NM) <= TRAFFICTOAIDIST);
769 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
770 * in the case of an arrival.
776 //TODO the trafficRef is the right place for the method
777 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now)
779 // prepare routing from one airport to another
780 FGAirport * dep = trafficRef->getDepartureAirport();
781 FGAirport * arr = trafficRef->getArrivalAirport();
786 // This waypoint marks the fact that the aircraft has passed the initial taxi
787 // departure waypoint, so it can release the parking.
788 if (prev->name == "park2")
789 dep->getDynamics()->releaseParking(fp->getGate());
791 // This is the last taxi waypoint, and marks the the end of the flight plan
792 // so, the schedule should update and wait for the next departure time.
793 if (prev->name == "END")
795 time_t nextDeparture = trafficRef->getDepartureTime();
796 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
797 if (nextDeparture < (now+1200))
799 nextDeparture = now + 1200;
801 fp->setTime(nextDeparture);
809 * Check difference between target bearing and current heading and correct if necessary.
813 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr)
815 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
816 //cerr << "Bearing = " << calc_bearing << endl;
820 if (calc_bearing > 360)
824 if (finite(calc_bearing))
826 double hdg_error = calc_bearing - tgt_heading;
827 if (fabs(hdg_error) > 1.0)
829 TurnTo( calc_bearing );
835 cerr << "calc_bearing is not a finite number : "
837 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
838 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
839 cerr << "waypoint name " << curr->name;
846 * Update the lead distance calculation if speed has changed sufficiently
847 * to prevent spinning (hopefully);
852 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next)
854 double speed_diff = speed - prevSpeed;
856 if (fabs(speed_diff) > 10)
859 fp->setLeadDistance(speed, tgt_heading, curr, next);
865 * Update target values (heading, alt, speed) depending on flight plan or control properties
867 bool FGAIAircraft::updateTargetValues()
869 if (fp) // AI object has a flightplan
871 //TODO make this a function of AIBase
872 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
873 //cerr << "UpateTArgetValues() " << endl;
874 ProcessFlightPlan(dt, now);
875 if (! fp->isActive(now))
877 // Do execute Ground elev for inactive aircraft, so they
878 // Are repositioned to the correct ground altitude when the user flies within visibility range.
879 // In addition, check whether we are out of user range, so this aircraft
883 Transform(); // make sure aip is initialized.
886 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
887 if (! aiTrafficVisible())
895 pos.setElevationFt(altitude_ft);
903 // no flight plan, update target heading, speed, and altitude
904 // from control properties. These default to the initial
905 // settings in the config file, but can be changed "on the
907 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
908 if ( lat_mode == "roll" )
911 = props->getDoubleValue("controls/flight/target-roll" );
917 = props->getDoubleValue("controls/flight/target-hdg" );
922 = props->getStringValue("controls/flight/longitude-mode");
923 if ( lon_mode == "alt" )
925 double alt = props->getDoubleValue("controls/flight/target-alt" );
931 = props->getDoubleValue("controls/flight/target-pitch" );
935 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
942 * Adjust the speed (accelerate/decelerate) to tgt_speed.
944 void FGAIAircraft::adjustSpeed(double tgt_speed)
946 double speed_diff = tgt_speed - speed;
947 speed_diff = groundTargetSpeed - speed;
949 if (speed_diff > 0.0) // need to accelerate
951 speed += performance->accel * dt;
952 if ( speed > tgt_speed )
956 else if (speed_diff < 0.0)
960 // on ground (aircraft can't roll)
961 // deceleration performance is better due to wheel brakes.
962 speed -= performance->decel * dt * 3;
966 speed -= performance->decel * dt;
969 if ( speed < tgt_speed )
976 void FGAIAircraft::updatePosition()
978 // convert speed to degrees per second
979 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
980 * speed * 1.686 / ft_per_deg_lat;
981 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
982 * speed * 1.686 / ft_per_deg_lon;
985 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
986 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
990 void FGAIAircraft::updateHeading()
992 // adjust heading based on current bank angle
998 // double turnConstant;
1000 // turnConstant = 0.0088362;
1002 // turnConstant = 0.088362;
1003 // If on ground, calculate heading change directly
1006 double headingDiff = fabs(hdg-tgt_heading);
1008 if (headingDiff > 180)
1009 headingDiff = fabs(headingDiff - 360);
1011 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
1012 if (sign(groundTargetSpeed) != sign(tgt_speed))
1013 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1015 if (headingDiff > 30.0)
1017 // invert if pushed backward
1018 headingChangeRate += dt * sign(roll);
1020 if (headingChangeRate > 30)
1021 headingChangeRate = 30;
1022 else if (headingChangeRate < -30)
1023 headingChangeRate = -30;
1028 if (fabs(headingChangeRate) > headingDiff)
1029 headingChangeRate = headingDiff*sign(roll);
1031 headingChangeRate += dt * sign(roll);
1033 hdg += headingChangeRate * dt;
1037 if (fabs(speed) > 1.0)
1039 turn_radius_ft = 0.088362 * speed * speed
1040 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1044 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1045 turn_radius_ft = 1.0;
1047 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1048 double dist_covered_ft = speed * 1.686 * dt;
1049 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1050 hdg += alpha * sign(roll);
1052 while ( hdg > 360.0 )
1066 void FGAIAircraft::updateBankAngles()
1068 // adjust target bank angle if heading lock engaged
1071 double bank_sense = 0.0;
1072 double diff = fabs(hdg - tgt_heading);
1074 diff = fabs(diff - 360);
1076 double sum = hdg + diff;
1079 if (fabs(sum - tgt_heading) < 1.0)
1081 bank_sense = 1.0; // right turn
1085 bank_sense = -1.0; // left turn
1089 tgt_roll = diff * bank_sense;
1093 tgt_roll = 30.0 * bank_sense;
1095 if ((fabs((double) spinCounter) > 1) && (diff > 30))
1097 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1098 // The only way to resolve this is to make them slow down.
1102 // adjust bank angle, use 9 degrees per second
1103 double bank_diff = tgt_roll - roll;
1104 if (fabs(bank_diff) > 0.2)
1106 if (bank_diff > 0.0)
1109 if (bank_diff < 0.0)
1111 //while (roll > 180) roll -= 360;
1112 //while (roll < 180) roll += 360;
1117 void FGAIAircraft::updateAltitudes()
1119 // adjust altitude (meters) based on current vertical speed (fpm)
1120 altitude_ft += vs / 60.0 * dt;
1121 pos.setElevationFt(altitude_ft);
1123 // adjust target Altitude, based on ground elevation when on ground
1131 // find target vertical speed if altitude lock engaged
1132 if (alt_lock && use_perf_vs)
1134 if (altitude_ft < tgt_altitude_ft)
1136 tgt_vs = tgt_altitude_ft - altitude_ft;
1137 if (tgt_vs > performance->climb_rate)
1138 tgt_vs = performance->climb_rate;
1142 tgt_vs = tgt_altitude_ft - altitude_ft;
1143 if (tgt_vs < (-performance->descent_rate))
1144 tgt_vs = -performance->descent_rate;
1148 if (alt_lock && !use_perf_vs)
1150 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1151 double min_vs = 100;
1152 if (tgt_altitude_ft < altitude_ft)
1154 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1155 && (fabs(max_vs) < fabs(tgt_vs)))
1158 if (fabs(tgt_vs) < fabs(min_vs))
1165 void FGAIAircraft::updateVerticalSpeed()
1167 // adjust vertical speed
1168 double vs_diff = tgt_vs - vs;
1169 if (fabs(vs_diff) > 10.0)
1173 vs += (performance->climb_rate / 3.0) * dt;
1180 vs -= (performance->descent_rate / 3.0) * dt;
1189 void FGAIAircraft::matchPitchAngle()
1191 // match pitch angle to vertical speed