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/route/waypoint.hxx>
26 #include <Main/fg_props.hxx>
27 #include <Main/globals.hxx>
28 #include <Main/viewer.hxx>
29 #include <Scenery/scenery.hxx>
30 #include <Scenery/tilemgr.hxx>
31 #include <Airports/dynamics.hxx>
32 #include <Airports/simple.hxx>
40 # define finite _finite
41 #elif defined(__sun) || defined(sgi)
47 #include "AIAircraft.hxx"
48 #include "performancedata.hxx"
49 #include "performancedb.hxx"
51 //#include <Airports/trafficcontroller.hxx>
53 static string tempReg;
55 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
58 groundOffset = trafficRef->getGroundOffset();
59 setCallSign(trafficRef->getCallSign());
74 groundTargetSpeed = 0;
76 // set heading and altitude locks
80 headingChangeRate = 0.0;
86 needsTaxiClearance = false;
88 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
93 FGAIAircraft::~FGAIAircraft() {
96 controller->signOff(getID());
100 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
104 FGAIBase::readFromScenario(scFileNode);
106 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
107 setFlightPlan(scFileNode->getStringValue("flightplan"),
108 scFileNode->getBoolValue("repeat", false));
109 setCallSign(scFileNode->getStringValue("callsign"));
113 void FGAIAircraft::bind() {
116 props->tie("controls/gear/gear-down",
117 SGRawValueMethods<FGAIAircraft,bool>(*this,
118 &FGAIAircraft::_getGearDown));
119 props->tie("transponder-id",
120 SGRawValueMethods<FGAIAircraft,const char*>(*this,
121 &FGAIAircraft::_getTransponderCode));
125 void FGAIAircraft::unbind() {
128 props->untie("controls/gear/gear-down");
129 props->untie("transponder-id");
133 void FGAIAircraft::update(double dt) {
134 FGAIBase::update(dt);
139 void FGAIAircraft::setPerformance(const std::string& acclass) {
140 static PerformanceDB perfdb; //TODO make it a global service
141 setPerformance(perfdb.getDataFor(acclass));
145 void FGAIAircraft::setPerformance(PerformanceData *ps) {
150 void FGAIAircraft::Run(double dt) {
151 FGAIAircraft::dt = dt;
153 bool outOfSight = false,
154 flightplanActive = true;
155 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
160 if (!flightplanActive) {
161 groundTargetSpeed = 0;
164 handleATCRequests(); // ATC also has a word to say
165 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
167 UpdateRadar(manager);
171 void FGAIAircraft::checkVisibility()
173 double visibility_meters = fgGetDouble("/environment/visibility-m");
174 FGViewer* vw = globals->get_current_view();
175 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
180 void FGAIAircraft::AccelTo(double speed) {
185 void FGAIAircraft::PitchTo(double angle) {
191 void FGAIAircraft::RollTo(double angle) {
197 void FGAIAircraft::YawTo(double angle) {
202 void FGAIAircraft::ClimbTo(double alt_ft ) {
203 tgt_altitude_ft = alt_ft;
208 void FGAIAircraft::TurnTo(double heading) {
209 tgt_heading = heading;
214 double FGAIAircraft::sign(double x) {
222 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
223 if (!flightplan.empty()) {
224 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
225 fp->setRepeat(repeat);
231 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
237 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
239 // the one behind you
240 FGAIFlightPlan::waypoint* prev = 0;
242 FGAIFlightPlan::waypoint* curr = 0;
244 FGAIFlightPlan::waypoint* next = 0;
246 prev = fp->getPreviousWaypoint();
247 curr = fp->getCurrentWaypoint();
248 next = fp->getNextWaypoint();
252 ///////////////////////////////////////////////////////////////////////////
253 // Initialize the flightplan
254 //////////////////////////////////////////////////////////////////////////
256 handleFirstWaypoint();
258 } // end of initialization
259 if (! fpExecutable(now))
263 double distanceToDescent;
264 if(reachedEndOfCruise(distanceToDescent)) {
265 if (!loadNextLeg(distanceToDescent)) {
269 prev = fp->getPreviousWaypoint();
270 curr = fp->getCurrentWaypoint();
271 next = fp->getNextWaypoint();
273 if (! leadPointReached(curr)) {
274 controlHeading(curr);
275 controlSpeed(curr, next);
277 if (curr->finished) //end of the flight plan
287 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
288 tgt_heading = fp->getBearing(curr, next);
292 //TODO let the fp handle this (loading of next leg)
293 fp->IncrementWaypoint( trafficRef != 0 );
294 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
295 if (!loadNextLeg()) {
300 prev = fp->getPreviousWaypoint();
301 curr = fp->getCurrentWaypoint();
302 next = fp->getNextWaypoint();
304 // Now that we have incremented the waypoints, excute some traffic manager specific code
306 //TODO isn't this best executed right at the beginning?
307 if (! aiTrafficVisible()) {
312 if (! handleAirportEndPoints(prev, now)) {
317 announcePositionToController();
322 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
325 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
327 tgt_altitude_ft = prev->altitude;
328 if (curr->crossat > -1000.0) {
330 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
331 / 6076.0 / speed*60.0);
332 tgt_altitude_ft = curr->crossat;
337 tgt_speed = prev->speed;
338 hdg_lock = alt_lock = true;
339 no_roll = prev->on_ground;
344 void FGAIAircraft::initializeFlightPlan() {
348 bool FGAIAircraft::_getGearDown() const {
349 return _performance->gearExtensible(this);
353 const char * FGAIAircraft::_getTransponderCode() const {
354 return transponderCode.c_str();
358 bool FGAIAircraft::loadNextLeg(double distance) {
361 if ((leg = fp->getLeg()) == 10) {
362 if (!trafficRef->next()) {
365 setCallSign(trafficRef->getCallSign());
370 FGAirport *dep = trafficRef->getDepartureAirport();
371 FGAirport *arr = trafficRef->getArrivalAirport();
376 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
383 trafficRef->getSpeed(),
387 trafficRef->getRadius(),
388 trafficRef->getFlightType(),
392 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
398 // Note: This code is copied from David Luff's AILocalTraffic
399 // Warning - ground elev determination is CPU intensive
400 // Either this function or the logic of how often it is called
401 // will almost certainly change.
403 void FGAIAircraft::getGroundElev(double dt) {
406 // Update minimally every three secs, but add some randomness
407 // to prevent all AI objects doing this in synchrony
408 if (dt_elev_count < (3.0) + (rand() % 10))
413 // Only do the proper hitlist stuff if we are within visible range of the viewer.
415 double visibility_meters = fgGetDouble("/environment/visibility-m");
416 FGViewer* vw = globals->get_current_view();
418 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
422 double range = 500.0;
423 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
426 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
427 tgt_altitude_ft = alt * SG_METER_TO_FEET;
433 void FGAIAircraft::doGroundAltitude() {
434 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
435 altitude_ft = (tgt_altitude_ft + groundOffset);
437 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
442 void FGAIAircraft::announcePositionToController() {
444 int leg = fp->getLeg();
446 // Note that leg has been incremented after creating the current leg, so we should use
447 // leg numbers here that are one higher than the number that is used to create the leg
450 case 2: // Startup and Push back
451 if (trafficRef->getDepartureAirport()->getDynamics())
452 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
454 case 3: // Taxiing to runway
455 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
456 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
458 case 4: //Take off tower controller
459 if (trafficRef->getDepartureAirport()->getDynamics()) {
460 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
462 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
466 if (trafficRef->getDepartureAirport()->getDynamics()) {
467 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
470 case 9: // Taxiing for parking
471 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
472 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
479 if ((controller != prevController) && (prevController != 0)) {
480 prevController->signOff(getID());
482 prevController = controller;
484 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
485 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
486 trafficRef->getRadius(), leg, this);
491 // Process ATC instructions and report back
493 void FGAIAircraft::processATC(FGATCInstruction instruction) {
494 if (instruction.getCheckForCircularWait()) {
495 // This is not exactly an elegant solution,
496 // but at least it gives me a chance to check
497 // if circular waits are resolved.
498 // For now, just take the offending aircraft
501 // a more proper way should be - of course - to
502 // let an offending aircraft take an evasive action
503 // for instance taxi back a little bit.
505 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
506 if (instruction.getHoldPattern ()) {}
509 if (instruction.getHoldPosition ()) {
517 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
520 // Change speed Instruction. This can only be excecuted when there is no
521 // Hold position instruction.
522 if (instruction.getChangeSpeed ()) {
524 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
525 AccelTo(instruction.getSpeed());
527 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
530 if (instruction.getChangeHeading ()) {
532 TurnTo(instruction.getHeading());
538 if (instruction.getChangeAltitude()) {}
543 void FGAIAircraft::handleFirstWaypoint() {
544 bool eraseWaypoints; //TODO YAGNI
547 eraseWaypoints = true;
549 eraseWaypoints = false;
552 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
553 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
554 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
559 //TODO fp should handle this
560 fp->IncrementWaypoint(eraseWaypoints);
561 if (!(fp->getNextWaypoint()) && trafficRef)
562 if (!loadNextLeg()) {
567 prev = fp->getPreviousWaypoint(); //first waypoint
568 curr = fp->getCurrentWaypoint(); //second waypoint
569 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
571 setLatitude(prev->latitude);
572 setLongitude(prev->longitude);
573 setSpeed(prev->speed);
574 setAltitude(prev->altitude);
576 if (prev->speed > 0.0)
577 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
579 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
581 // If next doesn't exist, as in incrementally created flightplans for
582 // AI/Trafficmanager created plans,
583 // Make sure lead distance is initialized otherwise
585 fp->setLeadDistance(speed, hdg, curr, next);
587 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
590 tgt_vs = (curr->crossat - prev->altitude)
591 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
592 / 6076.0 / prev->speed*60.0);
593 tgt_altitude_ft = curr->crossat;
596 tgt_altitude_ft = prev->altitude;
598 alt_lock = hdg_lock = true;
599 no_roll = prev->on_ground;
601 Transform(); // make sure aip is initialized.
602 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
605 // Make sure to announce the aircraft's position
606 announcePositionToController();
612 * Check Execution time (currently once every 100 ms)
613 * Add a bit of randomization to prevent the execution of all flight plans
614 * in synchrony, which can add significant periodic framerate flutter.
619 bool FGAIAircraft::fpExecutable(time_t now) {
620 double rand_exec_time = (rand() % 100) / 100;
621 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
626 * Check to see if we've reached the lead point for our next turn
631 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
632 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
634 //cerr << "2" << endl;
635 double lead_dist = fp->getLeadDistance();
636 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
638 if (lead_dist < fabs(2*speed)) {
639 //don't skip over the waypoint
640 lead_dist = fabs(2*speed);
641 //cerr << "Extending lead distance to " << lead_dist << endl;
644 //prev_dist_to_go = dist_to_go;
645 //if (dist_to_go < lead_dist)
646 // cerr << trafficRef->getCallSign() << " Distance : "
647 // << dist_to_go << ": Lead distance "
648 // << lead_dist << " " << curr->name
649 // << " Ground target speed " << groundTargetSpeed << endl;
651 if (speed > 50) { // don't do bearing calculations for ground traffic
652 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
653 if (bearing < minBearing) {
654 minBearing = bearing;
655 if (minBearing < 10) {
658 if ((minBearing < 360.0) && (minBearing > 10.0)) {
659 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
666 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
667 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
668 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
669 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
672 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
681 bool FGAIAircraft::aiTrafficVisible() {
682 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
683 fgGetDouble("/position/latitude-deg")));
685 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
690 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
691 * in the case of an arrival.
697 //TODO the trafficRef is the right place for the method
698 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
699 // prepare routing from one airport to another
700 FGAirport * dep = trafficRef->getDepartureAirport();
701 FGAirport * arr = trafficRef->getArrivalAirport();
706 // This waypoint marks the fact that the aircraft has passed the initial taxi
707 // departure waypoint, so it can release the parking.
708 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
709 if (prev->name == "PushBackPoint") {
710 dep->getDynamics()->releaseParking(fp->getGate());
712 setTaxiClearanceRequest(true);
715 // This is the last taxi waypoint, and marks the the end of the flight plan
716 // so, the schedule should update and wait for the next departure time.
717 if (prev->name == "END") {
718 time_t nextDeparture = trafficRef->getDepartureTime();
719 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
720 if (nextDeparture < (now+1200)) {
721 nextDeparture = now + 1200;
723 fp->setTime(nextDeparture); // should be "next departure"
731 * Check difference between target bearing and current heading and correct if necessary.
735 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
736 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
737 //cerr << "Bearing = " << calc_bearing << endl;
740 if (calc_bearing > 360)
744 if (finite(calc_bearing)) {
745 double hdg_error = calc_bearing - tgt_heading;
746 if (fabs(hdg_error) > 0.01) {
747 TurnTo( calc_bearing );
751 cerr << "calc_bearing is not a finite number : "
753 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
754 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
755 cerr << "waypoint name " << curr->name;
762 * Update the lead distance calculation if speed has changed sufficiently
763 * to prevent spinning (hopefully);
768 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
769 double speed_diff = speed - prevSpeed;
771 if (fabs(speed_diff) > 10) {
774 fp->setLeadDistance(speed, tgt_heading, curr, next);
781 * Update target values (heading, alt, speed) depending on flight plan or control properties
783 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
784 if (fp) // AI object has a flightplan
786 //TODO make this a function of AIBase
787 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
788 //cerr << "UpateTArgetValues() " << endl;
789 ProcessFlightPlan(dt, now);
791 // Do execute Ground elev for inactive aircraft, so they
792 // Are repositioned to the correct ground altitude when the user flies within visibility range.
793 // In addition, check whether we are out of user range, so this aircraft
796 Transform(); // make sure aip is initialized.
800 pos.setElevationFt(altitude_ft);
803 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
804 aiOutOfSight = !aiTrafficVisible();
807 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
812 timeElapsed = now - fp->getStartTime();
813 flightplanActive = fp->isActive(now);
815 // no flight plan, update target heading, speed, and altitude
816 // from control properties. These default to the initial
817 // settings in the config file, but can be changed "on the
819 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
820 if ( lat_mode == "roll" ) {
822 = props->getDoubleValue("controls/flight/target-roll" );
826 = props->getDoubleValue("controls/flight/target-hdg" );
831 = props->getStringValue("controls/flight/longitude-mode");
832 if ( lon_mode == "alt" ) {
833 double alt = props->getDoubleValue("controls/flight/target-alt" );
837 = props->getDoubleValue("controls/flight/target-pitch" );
841 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
845 void FGAIAircraft::updatePosition() {
846 // convert speed to degrees per second
847 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
848 * speed * 1.686 / ft_per_deg_lat;
849 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
850 * speed * 1.686 / ft_per_deg_lon;
853 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
854 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
858 void FGAIAircraft::updateHeading() {
859 // adjust heading based on current bank angle
864 // double turnConstant;
866 // turnConstant = 0.0088362;
868 // turnConstant = 0.088362;
869 // If on ground, calculate heading change directly
871 double headingDiff = fabs(hdg-tgt_heading);
872 double bank_sense = 0.0;
874 double diff = fabs(hdg - tgt_heading);
876 diff = fabs(diff - 360);
878 double sum = hdg + diff;
881 if (fabs(sum - tgt_heading) < 1.0) {
882 bank_sense = 1.0; // right turn
884 bank_sense = -1.0; // left turn
886 if (headingDiff > 180)
887 headingDiff = fabs(headingDiff - 360);
888 double sum = hdg + headingDiff;
891 if (fabs(sum - tgt_heading) > 0.0001) {
897 //cerr << trafficRef->getCallSign() << " Heading "
898 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
899 //if (headingDiff > 60) {
900 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
901 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
903 // groundTargetSpeed = tgt_speed;
905 if (sign(groundTargetSpeed) != sign(tgt_speed))
906 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
908 if (headingDiff > 30.0) {
909 // invert if pushed backward
910 headingChangeRate += 10.0 * dt * sign(roll);
912 // Clamp the maximum steering rate to 30 degrees per second,
913 // But only do this when the heading error is decreasing.
914 if ((headingDiff < headingError)) {
915 if (headingChangeRate > 30)
916 headingChangeRate = 30;
917 else if (headingChangeRate < -30)
918 headingChangeRate = -30;
921 if (fabs(headingChangeRate) > headingDiff)
922 headingChangeRate = headingDiff*sign(roll);
924 headingChangeRate += dt * sign(roll);
927 hdg += headingChangeRate * dt * (fabs(speed) / 15);
928 headingError = headingDiff;
930 if (fabs(speed) > 1.0) {
931 turn_radius_ft = 0.088362 * speed * speed
932 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
934 // Check if turn_radius_ft == 0; this might lead to a division by 0.
935 turn_radius_ft = 1.0;
937 double turn_circum_ft = SGD_2PI * turn_radius_ft;
938 double dist_covered_ft = speed * 1.686 * dt;
939 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
940 hdg += alpha * sign(roll);
942 while ( hdg > 360.0 ) {
954 void FGAIAircraft::updateBankAngleTarget() {
955 // adjust target bank angle if heading lock engaged
957 double bank_sense = 0.0;
958 double diff = fabs(hdg - tgt_heading);
960 diff = fabs(diff - 360);
962 double sum = hdg + diff;
965 if (fabs(sum - tgt_heading) < 1.0) {
966 bank_sense = 1.0; // right turn
968 bank_sense = -1.0; // left turn
970 if (diff < _performance->maximumBankAngle()) {
971 tgt_roll = diff * bank_sense;
973 tgt_roll = _performance->maximumBankAngle() * bank_sense;
975 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
976 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
977 // The only way to resolve this is to make them slow down.
983 void FGAIAircraft::updateVerticalSpeedTarget() {
984 // adjust target Altitude, based on ground elevation when on ground
988 } else if (alt_lock) {
989 // find target vertical speed
991 if (altitude_ft < tgt_altitude_ft) {
992 tgt_vs = tgt_altitude_ft - altitude_ft;
993 if (tgt_vs > _performance->climbRate())
994 tgt_vs = _performance->climbRate();
996 tgt_vs = tgt_altitude_ft - altitude_ft;
997 if (tgt_vs < (-_performance->descentRate()))
998 tgt_vs = -_performance->descentRate();
1001 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1002 double min_vs = 100;
1003 if (tgt_altitude_ft < altitude_ft)
1005 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1006 && (fabs(max_vs) < fabs(tgt_vs)))
1009 if (fabs(tgt_vs) < fabs(min_vs))
1016 void FGAIAircraft::updatePitchAngleTarget() {
1017 // if on ground and above vRotate -> initial rotation
1018 if (onGround() && (speed > _performance->vRotate()))
1019 tgt_pitch = 8.0; // some rough B737 value
1021 //TODO pitch angle on approach and landing
1023 // match pitch angle to vertical speed
1024 else if (tgt_vs > 0) {
1025 tgt_pitch = tgt_vs * 0.005;
1027 tgt_pitch = tgt_vs * 0.002;
1031 string FGAIAircraft::atGate() {
1033 if (fp->getLeg() < 3) {
1035 if (fp->getGate() > 0) {
1037 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1038 tmp = park->getName();
1045 void FGAIAircraft::handleATCRequests() {
1046 //TODO implement NullController for having no ATC to save the conditionals
1048 controller->update(getID(),
1049 pos.getLatitudeDeg(),
1050 pos.getLongitudeDeg(),
1054 processATC(controller->getInstruction(getID()));
1058 void FGAIAircraft::updateActualState() {
1059 //update current state
1060 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1064 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1066 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1069 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1071 // adjust altitude (meters) based on current vertical speed (fpm)
1072 altitude_ft += vs / 60.0 * dt;
1073 pos.setElevationFt(altitude_ft);
1075 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1076 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1079 void FGAIAircraft::updateSecondaryTargetValues() {
1080 // derived target state values
1081 updateBankAngleTarget();
1082 updateVerticalSpeedTarget();
1083 updatePitchAngleTarget();
1085 //TODO calculate wind correction angle (tgt_yaw)
1089 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1090 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1091 if (curr->name == "BOD") {
1092 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1093 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1094 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1096 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1097 double descentTimeNeeded = verticalDistance / descentRate;
1098 double distanceCovered = descentSpeed * descentTimeNeeded;
1100 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1101 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1102 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1103 cerr << "Descent rate : " << descentRate << endl;
1104 cerr << "Descent speed : " << descentSpeed << endl;
1105 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1106 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1107 cerr << "DistanceCovered : " << distanceCovered << endl;
1109 //cerr << "Distance = " << distance << endl;
1110 distance = distanceCovered;
1111 if (dist < distanceCovered) {
1112 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1124 void FGAIAircraft::resetPositionFromFlightPlan()
1126 // the one behind you
1127 FGAIFlightPlan::waypoint* prev = 0;
1129 FGAIFlightPlan::waypoint* curr = 0;
1131 FGAIFlightPlan::waypoint* next = 0;
1133 prev = fp->getPreviousWaypoint();
1134 curr = fp->getCurrentWaypoint();
1135 next = fp->getNextWaypoint();
1137 setLatitude(prev->latitude);
1138 setLongitude(prev->longitude);
1139 double tgt_heading = fp->getBearing(curr, next);
1140 setHeading(tgt_heading);
1141 setAltitude(prev->altitude);
1142 setSpeed(prev->speed);
1145 double FGAIAircraft::getBearing(double crse)
1147 double hdgDiff = fabs(hdg-crse);
1149 hdgDiff = fabs(hdgDiff - 360);
1153 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1154 FGAIFlightPlan::waypoint* curr = 0;
1155 curr = fp->getCurrentWaypoint();
1157 double tracklength = fp->checkTrackLength(wptName);
1158 if (tracklength > 0.1) {
1159 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1163 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1164 time_t arrivalTime = fp->getArrivalTime();
1166 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1167 time_t secondsToGo = arrivalTime - now;
1168 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1169 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1171 return (ete - secondsToGo); // Positive when we're too slow...