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[] = {
56 {2.0, 2.0, 450.0, 1000.0, 70.0, 80.0, 100.0, 80.0, 60.0},
58 {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
60 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
62 {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
64 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
65 // ufo (extreme accel/decel)
66 {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
69 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
72 groundOffset = trafficRef->getGroundOffset();
86 groundTargetSpeed = 0;
88 // set heading and altitude locks
92 headingChangeRate = 0.0;
98 FGAIAircraft::~FGAIAircraft() {
101 controller->signOff(getID());
105 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
109 FGAIBase::readFromScenario(scFileNode);
111 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
112 setFlightPlan(scFileNode->getStringValue("flightplan"),
113 scFileNode->getBoolValue("repeat", false));
114 setCallSign(scFileNode->getStringValue("callsign"));
118 void FGAIAircraft::bind() {
121 props->tie("controls/gear/gear-down",
122 SGRawValueMethods<FGAIAircraft,bool>(*this,
123 &FGAIAircraft::_getGearDown));
124 props->setStringValue("callsign", callsign.c_str());
128 void FGAIAircraft::unbind() {
131 props->untie("controls/gear/gear-down");
135 void FGAIAircraft::update(double dt) {
136 FGAIBase::update(dt);
142 void FGAIAircraft::setPerformance(const std::string& acclass) {
143 if (acclass == "light") {
144 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
145 } else if (acclass == "ww2_fighter") {
146 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
147 } else if (acclass == "jet_transport") {
148 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
149 } else if (acclass == "jet_fighter") {
150 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
151 } else if (acclass == "tanker") {
152 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
153 } else if (acclass == "ufo") {
154 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
156 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
161 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
167 void FGAIAircraft::Run(double dt) {
169 FGAIAircraft::dt = dt;
170 if (!updateTargetValues())
174 controller->update(getID(),
175 pos.getLatitudeDeg(),
176 pos.getLongitudeDeg(),
180 processATC(controller->getInstruction(getID()));
184 adjustSpeed(groundTargetSpeed);
186 adjustSpeed(tgt_speed);
193 updateVerticalSpeed();
195 UpdateRadar(manager);
199 void FGAIAircraft::AccelTo(double speed) {
204 void FGAIAircraft::PitchTo(double angle) {
210 void FGAIAircraft::RollTo(double angle) {
216 void FGAIAircraft::YawTo(double angle) {
221 void FGAIAircraft::ClimbTo(double alt_ft ) {
222 tgt_altitude_ft = alt_ft;
227 void FGAIAircraft::TurnTo(double heading) {
228 tgt_heading = heading;
233 double FGAIAircraft::sign(double x) {
241 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
242 if (!flightplan.empty()) {
243 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
244 fp->setRepeat(repeat);
250 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
256 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
258 // the one behind you
259 FGAIFlightPlan::waypoint* prev = 0;
261 FGAIFlightPlan::waypoint* curr = 0;
263 FGAIFlightPlan::waypoint* next = 0;
265 prev = fp->getPreviousWaypoint();
266 curr = fp->getCurrentWaypoint();
267 next = fp->getNextWaypoint();
271 ///////////////////////////////////////////////////////////////////////////
272 // Initialize the flightplan
273 //////////////////////////////////////////////////////////////////////////
275 handleFirstWaypoint();
277 } // end of initialization
278 if (! fpExecutable(now))
282 if (! leadPointReached(curr)) {
283 controlHeading(curr);
284 controlSpeed(curr, next);
286 if (curr->finished) //end of the flight plan
296 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
297 tgt_heading = fp->getBearing(curr, next);
301 //TODO let the fp handle this (loading of next leg)
302 fp->IncrementWaypoint((bool) trafficRef);
303 if (!(fp->getNextWaypoint()) && trafficRef)
306 prev = fp->getPreviousWaypoint();
307 curr = fp->getCurrentWaypoint();
308 next = fp->getNextWaypoint();
310 // Now that we have incremented the waypoints, excute some traffic manager specific code
312 //TODO isn't this best executed right at the beginning?
313 if (! aiTrafficVisible()) {
318 if (! handleAirportEndPoints(prev, now)) {
323 announcePositionToController();
328 fp->setLeadDistance(speed, tgt_heading, curr, next);
331 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
333 tgt_altitude_ft = prev->altitude;
334 if (curr->crossat > -1000.0) {
336 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
337 / 6076.0 / speed*60.0);
338 tgt_altitude_ft = curr->crossat;
343 tgt_speed = prev->speed;
344 hdg_lock = alt_lock = true;
345 no_roll = prev->on_ground;
350 void FGAIAircraft::initializeFlightPlan() {
354 bool FGAIAircraft::_getGearDown() const {
355 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
356 && (props->getFloatValue("velocities/airspeed-kt")
357 < performance->land_speed*1.25));
361 void FGAIAircraft::loadNextLeg() {
364 if ((leg = fp->getLeg()) == 10) {
370 FGAirport *dep = trafficRef->getDepartureAirport();
371 FGAirport *arr = trafficRef->getArrivalAirport();
376 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
381 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
382 trafficRef->getSpeed(),
386 trafficRef->getRadius(),
387 trafficRef->getFlightType(),
394 // Note: This code is copied from David Luff's AILocalTraffic
395 // Warning - ground elev determination is CPU intensive
396 // Either this function or the logic of how often it is called
397 // will almost certainly change.
399 void FGAIAircraft::getGroundElev(double dt) {
402 // Update minimally every three secs, but add some randomness
403 // to prevent all IA objects doing this in synchrony
404 if (dt_elev_count < (3.0) + (rand() % 10))
409 // Only do the proper hitlist stuff if we are within visible range of the viewer.
411 double visibility_meters = fgGetDouble("/environment/visibility-m");
413 FGViewer* vw = globals->get_current_view();
414 double course, distance;
416 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
417 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
418 view.CourseAndDistance(current, &course, &distance);
419 if (distance > visibility_meters) {
420 //aip.getSGLocation()->set_cur_elev_m(aptElev);
424 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
425 double range = 500.0;
426 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
427 // Try to shedule tiles for that position.
428 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
431 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
433 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
434 tgt_altitude_ft = alt * SG_METER_TO_FEET;
439 void FGAIAircraft::setCallSign(const string& s) {
444 void FGAIAircraft::doGroundAltitude() {
445 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
446 altitude_ft = (tgt_altitude_ft + groundOffset);
448 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
452 void FGAIAircraft::announcePositionToController() {
454 int leg = fp->getLeg();
456 // Note that leg was been incremented after creating the current leg, so we should use
457 // leg numbers here that are one higher than the number that is used to create the leg
460 case 3: // Taxiing to runway
461 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
462 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
464 case 4: //Take off tower controller
465 if (trafficRef->getDepartureAirport()->getDynamics()) {
466 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
467 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
468 //cerr << trafficRef->getCallSign() << " at runway " << fp->getRunway() << "Ready for departure "
469 // << trafficRef->getFlightType() << " to " << trafficRef->getArrivalAirport()->getId() << endl;
470 // if (controller == 0) {
471 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
475 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
478 case 9: // Taxiing for parking
479 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
480 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
487 if ((controller != prevController) && (prevController != 0)) {
488 prevController->signOff(getID());
489 string callsign = trafficRef->getCallSign();
490 if ( trafficRef->getHeavy())
494 //cerr << callsign << " ready to taxi to runway " << fp->getRunway() << endl;
497 //cerr << callsign << " at runway " << fp->getRunway() << "Ready for take-off. "
498 // << trafficRef->getFlightRules() << " to " << trafficRef->getArrivalAirport()->getId()
499 // << "(" << trafficRef->getArrivalAirport()->getName() << ")."<< endl;
503 prevController = controller;
505 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
506 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
507 trafficRef->getRadius(), leg, trafficRef->getCallSign());
513 void FGAIAircraft::processATC(FGATCInstruction instruction) {
514 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
515 if (instruction.getHoldPattern ()) {}
518 if (instruction.getHoldPosition ()) {
526 // cerr << trafficRef->getCallSign() << " Resuming Taxi " << endl;
529 // Change speed Instruction. This can only be excecuted when there is no
530 // Hold position instruction.
531 if (instruction.getChangeSpeed ()) {
533 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
534 AccelTo(instruction.getSpeed());
536 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
539 if (instruction.getChangeHeading ()) {
541 TurnTo(instruction.getHeading());
547 if (instruction.getChangeAltitude()) {}
552 void FGAIAircraft::handleFirstWaypoint() {
553 bool eraseWaypoints; //TODO YAGNI
555 eraseWaypoints = true;
557 eraseWaypoints = false;
560 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
561 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
562 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
567 //TODO fp should handle this
568 fp->IncrementWaypoint(eraseWaypoints);
569 if (!(fp->getNextWaypoint()) && trafficRef)
572 prev = fp->getPreviousWaypoint(); //first waypoint
573 curr = fp->getCurrentWaypoint(); //second waypoint
574 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
576 setLatitude(prev->latitude);
577 setLongitude(prev->longitude);
578 setSpeed(prev->speed);
579 setAltitude(prev->altitude);
581 if (prev->speed > 0.0)
582 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
584 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
586 // If next doesn't exist, as in incrementally created flightplans for
587 // AI/Trafficmanager created plans,
588 // Make sure lead distance is initialized otherwise
590 fp->setLeadDistance(speed, hdg, curr, next);
592 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
595 tgt_vs = (curr->crossat - prev->altitude)
596 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
597 / 6076.0 / prev->speed*60.0);
598 tgt_altitude_ft = curr->crossat;
601 tgt_altitude_ft = prev->altitude;
603 alt_lock = hdg_lock = true;
604 no_roll = prev->on_ground;
606 Transform(); // make sure aip is initialized.
607 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
610 // Make sure to announce the aircraft's position
611 announcePositionToController();
617 * Check Execution time (currently once every 100 ms)
618 * Add a bit of randomization to prevent the execution of all flight plans
619 * in synchrony, which can add significant periodic framerate flutter.
624 bool FGAIAircraft::fpExecutable(time_t now) {
625 double rand_exec_time = (rand() % 100) / 100;
626 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
631 * Check to see if we've reached the lead point for our next turn
636 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
637 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
639 //cerr << "2" << endl;
640 double lead_dist = fp->getLeadDistance();
641 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
642 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
644 if (lead_dist < fabs(2*speed)) {
645 //don't skip over the waypoint
646 lead_dist = fabs(2*speed);
647 //cerr << "Extending lead distance to " << lead_dist << endl;
650 //prev_dist_to_go = dist_to_go;
651 return dist_to_go < lead_dist;
655 bool FGAIAircraft::aiTrafficVisible() {
656 double userLatitude = fgGetDouble("/position/latitude-deg");
657 double userLongitude = fgGetDouble("/position/longitude-deg");
658 double course, distance;
660 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
661 SGWayPoint user (userLongitude, userLatitude, 0);
663 user.CourseAndDistance(current, &course, &distance);
665 return ((distance * SG_METER_TO_NM) <= TRAFFICTOAIDIST);
670 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
671 * in the case of an arrival.
677 //TODO the trafficRef is the right place for the method
678 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
679 // prepare routing from one airport to another
680 FGAirport * dep = trafficRef->getDepartureAirport();
681 FGAirport * arr = trafficRef->getArrivalAirport();
686 // This waypoint marks the fact that the aircraft has passed the initial taxi
687 // departure waypoint, so it can release the parking.
688 if (prev->name == "park2") {
689 dep->getDynamics()->releaseParking(fp->getGate());
690 cerr << trafficRef->getCallSign() << "releasing parking " << fp->getGate() << endl;
693 // This is the last taxi waypoint, and marks the the end of the flight plan
694 // so, the schedule should update and wait for the next departure time.
695 if (prev->name == "END") {
696 time_t nextDeparture = trafficRef->getDepartureTime();
697 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
698 if (nextDeparture < (now+1200)) {
699 nextDeparture = now + 1200;
701 fp->setTime(nextDeparture); // should be "next departure"
709 * Check difference between target bearing and current heading and correct if necessary.
713 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
714 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
715 //cerr << "Bearing = " << calc_bearing << endl;
718 if (calc_bearing > 360)
722 if (finite(calc_bearing)) {
723 double hdg_error = calc_bearing - tgt_heading;
724 if (fabs(hdg_error) > 1.0) {
725 TurnTo( calc_bearing );
729 cerr << "calc_bearing is not a finite number : "
731 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
732 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
733 cerr << "waypoint name " << curr->name;
740 * Update the lead distance calculation if speed has changed sufficiently
741 * to prevent spinning (hopefully);
746 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
747 double speed_diff = speed - prevSpeed;
749 if (fabs(speed_diff) > 10) {
751 fp->setLeadDistance(speed, tgt_heading, curr, next);
757 * Update target values (heading, alt, speed) depending on flight plan or control properties
759 bool FGAIAircraft::updateTargetValues() {
760 if (fp) // AI object has a flightplan
762 //TODO make this a function of AIBase
763 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
764 //cerr << "UpateTArgetValues() " << endl;
765 ProcessFlightPlan(dt, now);
766 if (! fp->isActive(now)) {
767 // Do execute Ground elev for inactive aircraft, so they
768 // Are repositioned to the correct ground altitude when the user flies within visibility range.
769 // In addition, check whether we are out of user range, so this aircraft
772 Transform(); // make sure aip is initialized.
774 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
775 if (! aiTrafficVisible()) {
782 pos.setElevationFt(altitude_ft);
789 // no flight plan, update target heading, speed, and altitude
790 // from control properties. These default to the initial
791 // settings in the config file, but can be changed "on the
793 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
794 if ( lat_mode == "roll" ) {
796 = props->getDoubleValue("controls/flight/target-roll" );
800 = props->getDoubleValue("controls/flight/target-hdg" );
805 = props->getStringValue("controls/flight/longitude-mode");
806 if ( lon_mode == "alt" ) {
807 double alt = props->getDoubleValue("controls/flight/target-alt" );
811 = props->getDoubleValue("controls/flight/target-pitch" );
815 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
822 * Adjust the speed (accelerate/decelerate) to tgt_speed.
824 void FGAIAircraft::adjustSpeed(double tgt_speed) {
825 double speed_diff = tgt_speed - speed;
826 speed_diff = groundTargetSpeed - speed;
828 if (speed_diff > 0.0) // need to accelerate
830 speed += performance->accel * dt;
831 if ( speed > tgt_speed )
834 } else if (speed_diff < 0.0) {
836 // on ground (aircraft can't roll)
837 // deceleration performance is better due to wheel brakes.
838 speed -= performance->decel * dt * 3;
840 speed -= performance->decel * dt;
843 if ( speed < tgt_speed )
850 void FGAIAircraft::updatePosition() {
851 // convert speed to degrees per second
852 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
853 * speed * 1.686 / ft_per_deg_lat;
854 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
855 * speed * 1.686 / ft_per_deg_lon;
858 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
859 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
863 void FGAIAircraft::updateHeading() {
864 // adjust heading based on current bank angle
869 // double turnConstant;
871 // turnConstant = 0.0088362;
873 // turnConstant = 0.088362;
874 // If on ground, calculate heading change directly
876 double headingDiff = fabs(hdg-tgt_heading);
878 if (headingDiff > 180)
879 headingDiff = fabs(headingDiff - 360);
881 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
882 if (sign(groundTargetSpeed) != sign(tgt_speed))
883 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
885 if (headingDiff > 30.0) {
886 // invert if pushed backward
887 headingChangeRate += dt * sign(roll);
889 if (headingChangeRate > 30)
890 headingChangeRate = 30;
891 else if (headingChangeRate < -30)
892 headingChangeRate = -30;
895 if (fabs(headingChangeRate) > headingDiff)
896 headingChangeRate = headingDiff*sign(roll);
898 headingChangeRate += dt * sign(roll);
900 hdg += headingChangeRate * dt;
902 if (fabs(speed) > 1.0) {
903 turn_radius_ft = 0.088362 * speed * speed
904 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
906 // Check if turn_radius_ft == 0; this might lead to a division by 0.
907 turn_radius_ft = 1.0;
909 double turn_circum_ft = SGD_2PI * turn_radius_ft;
910 double dist_covered_ft = speed * 1.686 * dt;
911 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
912 hdg += alpha * sign(roll);
914 while ( hdg > 360.0 ) {
926 void FGAIAircraft::updateBankAngles() {
927 // adjust target bank angle if heading lock engaged
929 double bank_sense = 0.0;
930 double diff = fabs(hdg - tgt_heading);
932 diff = fabs(diff - 360);
934 double sum = hdg + diff;
937 if (fabs(sum - tgt_heading) < 1.0) {
938 bank_sense = 1.0; // right turn
940 bank_sense = -1.0; // left turn
943 tgt_roll = diff * bank_sense;
945 tgt_roll = 30.0 * bank_sense;
947 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
948 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
949 // The only way to resolve this is to make them slow down.
953 // adjust bank angle, use 9 degrees per second
954 double bank_diff = tgt_roll - roll;
955 if (fabs(bank_diff) > 0.2) {
961 //while (roll > 180) roll -= 360;
962 //while (roll < 180) roll += 360;
967 void FGAIAircraft::updateAltitudes() {
968 // adjust altitude (meters) based on current vertical speed (fpm)
969 altitude_ft += vs / 60.0 * dt;
970 pos.setElevationFt(altitude_ft);
972 // adjust target Altitude, based on ground elevation when on ground
977 // find target vertical speed if altitude lock engaged
978 if (alt_lock && use_perf_vs) {
979 if (altitude_ft < tgt_altitude_ft) {
980 tgt_vs = tgt_altitude_ft - altitude_ft;
981 if (tgt_vs > performance->climb_rate)
982 tgt_vs = performance->climb_rate;
984 tgt_vs = tgt_altitude_ft - altitude_ft;
985 if (tgt_vs < (-performance->descent_rate))
986 tgt_vs = -performance->descent_rate;
990 if (alt_lock && !use_perf_vs) {
991 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
993 if (tgt_altitude_ft < altitude_ft)
995 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
996 && (fabs(max_vs) < fabs(tgt_vs)))
999 if (fabs(tgt_vs) < fabs(min_vs))
1006 void FGAIAircraft::updateVerticalSpeed() {
1007 // adjust vertical speed
1008 double vs_diff = tgt_vs - vs;
1009 if (fabs(vs_diff) > 10.0) {
1010 if (vs_diff > 0.0) {
1011 vs += (performance->climb_rate / 3.0) * dt;
1016 vs -= (performance->descent_rate / 3.0) * dt;
1025 void FGAIAircraft::matchPitchAngle() {
1026 // match pitch angle to vertical speed