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) :
56 /* HOT must be disabled for AI Aircraft,
57 * otherwise traffic detection isn't working as expected.*/
58 FGAIBase(otAircraft, false)
62 groundOffset = trafficRef->getGroundOffset();
63 setCallSign(trafficRef->getCallSign());
78 groundTargetSpeed = 0;
80 // set heading and altitude locks
84 headingChangeRate = 0.0;
90 needsTaxiClearance = false;
91 _needsGroundElevation = true;
93 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
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->tie("transponder-id",
125 SGRawValueMethods<FGAIAircraft,const char*>(*this,
126 &FGAIAircraft::_getTransponderCode));
130 void FGAIAircraft::unbind() {
133 props->untie("controls/gear/gear-down");
134 props->untie("transponder-id");
138 void FGAIAircraft::update(double dt) {
139 FGAIBase::update(dt);
144 void FGAIAircraft::setPerformance(const std::string& acclass) {
145 static PerformanceDB perfdb; //TODO make it a global service
146 setPerformance(perfdb.getDataFor(acclass));
150 void FGAIAircraft::setPerformance(PerformanceData *ps) {
155 void FGAIAircraft::Run(double dt) {
156 FGAIAircraft::dt = dt;
158 bool outOfSight = false,
159 flightplanActive = true;
160 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
165 if (!flightplanActive) {
166 groundTargetSpeed = 0;
169 handleATCRequests(); // ATC also has a word to say
170 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
172 // We currently have one situation in which an AIAircraft object is used that is not attached to the
173 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
174 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
177 UpdateRadar(manager);
181 void FGAIAircraft::checkVisibility()
183 double visibility_meters = fgGetDouble("/environment/visibility-m");
184 FGViewer* vw = globals->get_current_view();
185 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
190 void FGAIAircraft::AccelTo(double speed) {
193 _needsGroundElevation = true;
197 void FGAIAircraft::PitchTo(double angle) {
203 void FGAIAircraft::RollTo(double angle) {
209 void FGAIAircraft::YawTo(double angle) {
214 void FGAIAircraft::ClimbTo(double alt_ft ) {
215 tgt_altitude_ft = alt_ft;
220 void FGAIAircraft::TurnTo(double heading) {
221 tgt_heading = heading;
226 double FGAIAircraft::sign(double x) {
234 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
235 if (!flightplan.empty()) {
236 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
237 fp->setRepeat(repeat);
243 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
249 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
251 // the one behind you
252 FGAIFlightPlan::waypoint* prev = 0;
254 FGAIFlightPlan::waypoint* curr = 0;
256 FGAIFlightPlan::waypoint* next = 0;
258 prev = fp->getPreviousWaypoint();
259 curr = fp->getCurrentWaypoint();
260 next = fp->getNextWaypoint();
264 ///////////////////////////////////////////////////////////////////////////
265 // Initialize the flightplan
266 //////////////////////////////////////////////////////////////////////////
268 handleFirstWaypoint();
270 } // end of initialization
271 if (! fpExecutable(now))
275 double distanceToDescent;
276 if(reachedEndOfCruise(distanceToDescent)) {
277 if (!loadNextLeg(distanceToDescent)) {
281 prev = fp->getPreviousWaypoint();
282 curr = fp->getCurrentWaypoint();
283 next = fp->getNextWaypoint();
285 if (! leadPointReached(curr)) {
286 controlHeading(curr);
287 controlSpeed(curr, next);
289 cerr << getCallSign()
290 << ": verifying lead distance to waypoint : "
291 << fp->getCurrentWaypoint()->name << " "
292 << fp->getLeadDistance() << ". Distance to go "
293 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
294 << ". Target speed = "
296 << ". Current speed = "
298 << ". Minimum Bearing " << minBearing
302 if (curr->finished) //end of the flight plan
312 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
313 tgt_heading = fp->getBearing(curr, next);
317 //TODO let the fp handle this (loading of next leg)
318 fp->IncrementWaypoint( trafficRef != 0 );
319 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
320 if (!loadNextLeg()) {
325 prev = fp->getPreviousWaypoint();
326 curr = fp->getCurrentWaypoint();
327 next = fp->getNextWaypoint();
329 // Now that we have incremented the waypoints, excute some traffic manager specific code
331 //TODO isn't this best executed right at the beginning?
332 if (! aiTrafficVisible()) {
337 if (! handleAirportEndPoints(prev, now)) {
342 announcePositionToController();
347 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
350 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
352 tgt_altitude_ft = prev->altitude;
353 if (curr->crossat > -1000.0) {
355 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
356 / 6076.0 / speed*60.0);
358 tgt_altitude_ft = curr->crossat;
363 AccelTo(prev->speed);
364 hdg_lock = alt_lock = true;
365 no_roll = prev->on_ground;
369 void FGAIAircraft::checkTcas(void)
371 if (props->getIntValue("tcas/threat-level",0)==3)
373 int RASense = props->getIntValue("tcas/ra-sense",0);
374 if ((RASense>0)&&(tgt_vs<4000))
380 // downward RA: descend!
381 if (altitude_ft < 1000)
383 // too low: level off
396 void FGAIAircraft::initializeFlightPlan() {
400 bool FGAIAircraft::_getGearDown() const {
401 return _performance->gearExtensible(this);
405 const char * FGAIAircraft::_getTransponderCode() const {
406 return transponderCode.c_str();
410 bool FGAIAircraft::loadNextLeg(double distance) {
413 if ((leg = fp->getLeg()) == 10) {
414 if (!trafficRef->next()) {
417 setCallSign(trafficRef->getCallSign());
422 FGAirport *dep = trafficRef->getDepartureAirport();
423 FGAirport *arr = trafficRef->getArrivalAirport();
428 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
435 trafficRef->getSpeed(),
439 trafficRef->getRadius(),
440 trafficRef->getFlightType(),
444 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
450 // Note: This code is copied from David Luff's AILocalTraffic
451 // Warning - ground elev determination is CPU intensive
452 // Either this function or the logic of how often it is called
453 // will almost certainly change.
455 void FGAIAircraft::getGroundElev(double dt) {
458 if (!needGroundElevation())
460 // Update minimally every three secs, but add some randomness
461 // to prevent all AI objects doing this in synchrony
462 if (dt_elev_count < (3.0) + (rand() % 10))
467 // Only do the proper hitlist stuff if we are within visible range of the viewer.
469 double visibility_meters = fgGetDouble("/environment/visibility-m");
470 FGViewer* vw = globals->get_current_view();
472 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
476 double range = 500.0;
477 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
480 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
482 tgt_altitude_ft = alt * SG_METER_TO_FEET;
485 // aircraft is stationary and we obtained altitude for this spot - we're done.
486 _needsGroundElevation = false;
494 void FGAIAircraft::doGroundAltitude() {
495 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
497 altitude_ft = (tgt_altitude_ft + groundOffset);
499 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
504 void FGAIAircraft::announcePositionToController() {
506 int leg = fp->getLeg();
508 // Note that leg has been incremented after creating the current leg, so we should use
509 // leg numbers here that are one higher than the number that is used to create the leg
512 case 2: // Startup and Push back
513 if (trafficRef->getDepartureAirport()->getDynamics())
514 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
516 case 3: // Taxiing to runway
517 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
518 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
520 case 4: //Take off tower controller
521 if (trafficRef->getDepartureAirport()->getDynamics()) {
522 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
524 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
528 if (trafficRef->getDepartureAirport()->getDynamics()) {
529 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
532 case 9: // Taxiing for parking
533 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
534 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
541 if ((controller != prevController) && (prevController != 0)) {
542 prevController->signOff(getID());
544 prevController = controller;
546 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
547 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
548 trafficRef->getRadius(), leg, this);
553 // Process ATC instructions and report back
555 void FGAIAircraft::processATC(FGATCInstruction instruction) {
556 if (instruction.getCheckForCircularWait()) {
557 // This is not exactly an elegant solution,
558 // but at least it gives me a chance to check
559 // if circular waits are resolved.
560 // For now, just take the offending aircraft
563 // a more proper way should be - of course - to
564 // let an offending aircraft take an evasive action
565 // for instance taxi back a little bit.
567 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
568 if (instruction.getHoldPattern ()) {}
571 if (instruction.getHoldPosition ()) {
579 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
582 // Change speed Instruction. This can only be excecuted when there is no
583 // Hold position instruction.
584 if (instruction.getChangeSpeed ()) {
586 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
587 AccelTo(instruction.getSpeed());
589 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
592 if (instruction.getChangeHeading ()) {
594 TurnTo(instruction.getHeading());
600 if (instruction.getChangeAltitude()) {}
605 void FGAIAircraft::handleFirstWaypoint() {
606 bool eraseWaypoints; //TODO YAGNI
609 eraseWaypoints = true;
611 eraseWaypoints = false;
614 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
615 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
616 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
621 //TODO fp should handle this
622 fp->IncrementWaypoint(eraseWaypoints);
623 if (!(fp->getNextWaypoint()) && trafficRef)
624 if (!loadNextLeg()) {
629 prev = fp->getPreviousWaypoint(); //first waypoint
630 curr = fp->getCurrentWaypoint(); //second waypoint
631 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
633 setLatitude(prev->latitude);
634 setLongitude(prev->longitude);
635 setSpeed(prev->speed);
636 setAltitude(prev->altitude);
638 if (prev->speed > 0.0)
639 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
641 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
643 // If next doesn't exist, as in incrementally created flightplans for
644 // AI/Trafficmanager created plans,
645 // Make sure lead distance is initialized otherwise
647 fp->setLeadDistance(speed, hdg, curr, next);
649 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
652 tgt_vs = (curr->crossat - prev->altitude)
653 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
654 / 6076.0 / prev->speed*60.0);
656 tgt_altitude_ft = curr->crossat;
659 tgt_altitude_ft = prev->altitude;
661 alt_lock = hdg_lock = true;
662 no_roll = prev->on_ground;
664 Transform(); // make sure aip is initialized.
665 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
667 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
669 // Make sure to announce the aircraft's position
670 announcePositionToController();
676 * Check Execution time (currently once every 100 ms)
677 * Add a bit of randomization to prevent the execution of all flight plans
678 * in synchrony, which can add significant periodic framerate flutter.
683 bool FGAIAircraft::fpExecutable(time_t now) {
684 double rand_exec_time = (rand() % 100) / 100;
685 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
690 * Check to see if we've reached the lead point for our next turn
695 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
696 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
698 //cerr << "2" << endl;
699 double lead_dist = fp->getLeadDistance();
700 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
701 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->name == string("PushBackPoint")) {
702 tgt_speed = -(dist_to_go / 10.0);
703 if (tgt_speed > -0.5) {
706 if (fp->getPreviousWaypoint()->speed < tgt_speed) {
707 fp->getPreviousWaypoint()->speed = tgt_speed;
710 if (lead_dist < fabs(2*speed)) {
711 //don't skip over the waypoint
712 lead_dist = fabs(2*speed);
713 //cerr << "Extending lead distance to " << lead_dist << endl;
716 //prev_dist_to_go = dist_to_go;
717 //if (dist_to_go < lead_dist)
718 // cerr << trafficRef->getCallSign() << " Distance : "
719 // << dist_to_go << ": Lead distance "
720 // << lead_dist << " " << curr->name
721 // << " Ground target speed " << groundTargetSpeed << endl;
723 if (speed > 50) { // don't do bearing calculations for ground traffic
724 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
725 if (bearing < minBearing) {
726 minBearing = bearing;
727 if (minBearing < 10) {
730 if ((minBearing < 360.0) && (minBearing > 10.0)) {
731 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
738 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
739 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
740 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
741 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
744 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
753 bool FGAIAircraft::aiTrafficVisible() {
754 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
755 fgGetDouble("/position/latitude-deg")));
757 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
762 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
763 * in the case of an arrival.
769 //TODO the trafficRef is the right place for the method
770 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
771 // prepare routing from one airport to another
772 FGAirport * dep = trafficRef->getDepartureAirport();
773 FGAirport * arr = trafficRef->getArrivalAirport();
778 // This waypoint marks the fact that the aircraft has passed the initial taxi
779 // departure waypoint, so it can release the parking.
780 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
781 if (prev->name == "PushBackPoint") {
782 dep->getDynamics()->releaseParking(fp->getGate());
784 setTaxiClearanceRequest(true);
787 // This is the last taxi waypoint, and marks the the end of the flight plan
788 // so, the schedule should update and wait for the next departure time.
789 if (prev->name == "END") {
790 time_t nextDeparture = trafficRef->getDepartureTime();
791 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
792 if (nextDeparture < (now+1200)) {
793 nextDeparture = now + 1200;
795 fp->setTime(nextDeparture); // should be "next departure"
803 * Check difference between target bearing and current heading and correct if necessary.
807 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
808 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
809 //cerr << "Bearing = " << calc_bearing << endl;
812 if (calc_bearing > 360)
816 if (finite(calc_bearing)) {
817 double hdg_error = calc_bearing - tgt_heading;
818 if (fabs(hdg_error) > 0.01) {
819 TurnTo( calc_bearing );
823 cerr << "calc_bearing is not a finite number : "
825 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
826 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
827 cerr << "waypoint name " << curr->name;
834 * Update the lead distance calculation if speed has changed sufficiently
835 * to prevent spinning (hopefully);
840 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
841 double speed_diff = speed - prevSpeed;
843 if (fabs(speed_diff) > 10) {
846 fp->setLeadDistance(speed, tgt_heading, curr, next);
853 * Update target values (heading, alt, speed) depending on flight plan or control properties
855 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
856 if (fp) // AI object has a flightplan
858 //TODO make this a function of AIBase
859 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
860 //cerr << "UpateTArgetValues() " << endl;
861 ProcessFlightPlan(dt, now);
863 // Do execute Ground elev for inactive aircraft, so they
864 // Are repositioned to the correct ground altitude when the user flies within visibility range.
865 // In addition, check whether we are out of user range, so this aircraft
868 Transform(); // make sure aip is initialized.
872 pos.setElevationFt(altitude_ft);
875 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
876 aiOutOfSight = !aiTrafficVisible();
879 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
884 timeElapsed = now - fp->getStartTime();
885 flightplanActive = fp->isActive(now);
887 // no flight plan, update target heading, speed, and altitude
888 // from control properties. These default to the initial
889 // settings in the config file, but can be changed "on the
891 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
892 if ( lat_mode == "roll" ) {
894 = props->getDoubleValue("controls/flight/target-roll" );
898 = props->getDoubleValue("controls/flight/target-hdg" );
903 = props->getStringValue("controls/flight/longitude-mode");
904 if ( lon_mode == "alt" ) {
905 double alt = props->getDoubleValue("controls/flight/target-alt" );
909 = props->getDoubleValue("controls/flight/target-pitch" );
913 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
917 void FGAIAircraft::updatePosition() {
918 // convert speed to degrees per second
919 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
920 * speed * 1.686 / ft_per_deg_lat;
921 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
922 * speed * 1.686 / ft_per_deg_lon;
925 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
926 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
930 void FGAIAircraft::updateHeading() {
931 // adjust heading based on current bank angle
936 // double turnConstant;
938 // turnConstant = 0.0088362;
940 // turnConstant = 0.088362;
941 // If on ground, calculate heading change directly
943 double headingDiff = fabs(hdg-tgt_heading);
944 double bank_sense = 0.0;
946 double diff = fabs(hdg - tgt_heading);
948 diff = fabs(diff - 360);
950 double sum = hdg + diff;
953 if (fabs(sum - tgt_heading) < 1.0) {
954 bank_sense = 1.0; // right turn
956 bank_sense = -1.0; // left turn
958 if (headingDiff > 180)
959 headingDiff = fabs(headingDiff - 360);
960 double sum = hdg + headingDiff;
963 if (fabs(sum - tgt_heading) > 0.0001) {
969 // cerr << trafficRef->getCallSign() << " Heading "
970 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
971 //if (headingDiff > 60) {
972 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
973 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
975 // groundTargetSpeed = tgt_speed;
977 if (sign(groundTargetSpeed) != sign(tgt_speed))
978 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
980 // Only update the target values when we're not moving because otherwise we might introduce an enormous target change rate while waiting a the gate, or holding.
982 if (headingDiff > 30.0) {
983 // invert if pushed backward
984 headingChangeRate += 10.0 * dt * sign(roll);
986 // Clamp the maximum steering rate to 30 degrees per second,
987 // But only do this when the heading error is decreasing.
988 if ((headingDiff < headingError)) {
989 if (headingChangeRate > 30)
990 headingChangeRate = 30;
991 else if (headingChangeRate < -30)
992 headingChangeRate = -30;
996 if (fabs(headingChangeRate) > headingDiff)
997 headingChangeRate = headingDiff*sign(roll);
999 headingChangeRate += dt * sign(roll);
1004 //cerr << trafficRef->getCallSign() << " Heading "
1005 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1006 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1007 headingError = headingDiff;
1009 if (fabs(speed) > 1.0) {
1010 turn_radius_ft = 0.088362 * speed * speed
1011 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1013 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1014 turn_radius_ft = 1.0;
1016 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1017 double dist_covered_ft = speed * 1.686 * dt;
1018 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1019 hdg += alpha * sign(roll);
1021 while ( hdg > 360.0 ) {
1025 while ( hdg < 0.0) {
1033 void FGAIAircraft::updateBankAngleTarget() {
1034 // adjust target bank angle if heading lock engaged
1036 double bank_sense = 0.0;
1037 double diff = fabs(hdg - tgt_heading);
1039 diff = fabs(diff - 360);
1041 double sum = hdg + diff;
1044 if (fabs(sum - tgt_heading) < 1.0) {
1045 bank_sense = 1.0; // right turn
1047 bank_sense = -1.0; // left turn
1049 if (diff < _performance->maximumBankAngle()) {
1050 tgt_roll = diff * bank_sense;
1052 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1054 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1055 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1056 // The only way to resolve this is to make them slow down.
1062 void FGAIAircraft::updateVerticalSpeedTarget() {
1063 // adjust target Altitude, based on ground elevation when on ground
1067 } else if (alt_lock) {
1068 // find target vertical speed
1070 if (altitude_ft < tgt_altitude_ft) {
1071 tgt_vs = tgt_altitude_ft - altitude_ft;
1072 if (tgt_vs > _performance->climbRate())
1073 tgt_vs = _performance->climbRate();
1075 tgt_vs = tgt_altitude_ft - altitude_ft;
1076 if (tgt_vs < (-_performance->descentRate()))
1077 tgt_vs = -_performance->descentRate();
1080 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1081 double min_vs = 100;
1082 if (tgt_altitude_ft < altitude_ft)
1084 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1085 && (fabs(max_vs) < fabs(tgt_vs)))
1088 if (fabs(tgt_vs) < fabs(min_vs))
1096 void FGAIAircraft::updatePitchAngleTarget() {
1097 // if on ground and above vRotate -> initial rotation
1098 if (onGround() && (speed > _performance->vRotate()))
1099 tgt_pitch = 8.0; // some rough B737 value
1101 //TODO pitch angle on approach and landing
1103 // match pitch angle to vertical speed
1104 else if (tgt_vs > 0) {
1105 tgt_pitch = tgt_vs * 0.005;
1107 tgt_pitch = tgt_vs * 0.002;
1111 string FGAIAircraft::atGate() {
1113 if (fp->getLeg() < 3) {
1115 if (fp->getGate() > 0) {
1117 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1118 tmp = park->getName();
1125 void FGAIAircraft::handleATCRequests() {
1126 //TODO implement NullController for having no ATC to save the conditionals
1128 controller->updateAircraftInformation(getID(),
1129 pos.getLatitudeDeg(),
1130 pos.getLongitudeDeg(),
1134 processATC(controller->getInstruction(getID()));
1138 void FGAIAircraft::updateActualState() {
1139 //update current state
1140 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1144 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1146 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1149 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1151 // adjust altitude (meters) based on current vertical speed (fpm)
1152 altitude_ft += vs / 60.0 * dt;
1153 pos.setElevationFt(altitude_ft);
1155 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1156 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1159 void FGAIAircraft::updateSecondaryTargetValues() {
1160 // derived target state values
1161 updateBankAngleTarget();
1162 updateVerticalSpeedTarget();
1163 updatePitchAngleTarget();
1165 //TODO calculate wind correction angle (tgt_yaw)
1169 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1170 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1171 if (curr->name == "BOD") {
1172 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1173 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1174 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1176 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1177 double descentTimeNeeded = verticalDistance / descentRate;
1178 double distanceCovered = descentSpeed * descentTimeNeeded;
1180 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1181 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1182 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1183 cerr << "Descent rate : " << descentRate << endl;
1184 cerr << "Descent speed : " << descentSpeed << endl;
1185 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1186 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1187 cerr << "DistanceCovered : " << distanceCovered << endl;
1189 //cerr << "Distance = " << distance << endl;
1190 distance = distanceCovered;
1191 if (dist < distanceCovered) {
1192 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1204 void FGAIAircraft::resetPositionFromFlightPlan()
1206 // the one behind you
1207 FGAIFlightPlan::waypoint* prev = 0;
1209 FGAIFlightPlan::waypoint* curr = 0;
1211 FGAIFlightPlan::waypoint* next = 0;
1213 prev = fp->getPreviousWaypoint();
1214 curr = fp->getCurrentWaypoint();
1215 next = fp->getNextWaypoint();
1217 setLatitude(prev->latitude);
1218 setLongitude(prev->longitude);
1219 double tgt_heading = fp->getBearing(curr, next);
1220 setHeading(tgt_heading);
1221 setAltitude(prev->altitude);
1222 setSpeed(prev->speed);
1225 double FGAIAircraft::getBearing(double crse)
1227 double hdgDiff = fabs(hdg-crse);
1229 hdgDiff = fabs(hdgDiff - 360);
1233 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1234 FGAIFlightPlan::waypoint* curr = 0;
1235 curr = fp->getCurrentWaypoint();
1237 double tracklength = fp->checkTrackLength(wptName);
1238 if (tracklength > 0.1) {
1239 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1243 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1244 time_t arrivalTime = fp->getArrivalTime();
1246 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1247 time_t secondsToGo = arrivalTime - now;
1248 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1249 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1251 return (ete - secondsToGo); // Positive when we're too slow...