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;
87 _needsGroundElevation = true;
89 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
94 FGAIAircraft::~FGAIAircraft() {
97 controller->signOff(getID());
101 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
105 FGAIBase::readFromScenario(scFileNode);
107 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
108 setFlightPlan(scFileNode->getStringValue("flightplan"),
109 scFileNode->getBoolValue("repeat", false));
110 setCallSign(scFileNode->getStringValue("callsign"));
114 void FGAIAircraft::bind() {
117 props->tie("controls/gear/gear-down",
118 SGRawValueMethods<FGAIAircraft,bool>(*this,
119 &FGAIAircraft::_getGearDown));
120 props->tie("transponder-id",
121 SGRawValueMethods<FGAIAircraft,const char*>(*this,
122 &FGAIAircraft::_getTransponderCode));
126 void FGAIAircraft::unbind() {
129 props->untie("controls/gear/gear-down");
130 props->untie("transponder-id");
134 void FGAIAircraft::update(double dt) {
135 FGAIBase::update(dt);
140 void FGAIAircraft::setPerformance(const std::string& acclass) {
141 static PerformanceDB perfdb; //TODO make it a global service
142 setPerformance(perfdb.getDataFor(acclass));
146 void FGAIAircraft::setPerformance(PerformanceData *ps) {
151 void FGAIAircraft::Run(double dt) {
152 FGAIAircraft::dt = dt;
154 bool outOfSight = false,
155 flightplanActive = true;
156 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
161 if (!flightplanActive) {
162 groundTargetSpeed = 0;
165 handleATCRequests(); // ATC also has a word to say
166 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
168 UpdateRadar(manager);
172 void FGAIAircraft::checkVisibility()
174 double visibility_meters = fgGetDouble("/environment/visibility-m");
175 FGViewer* vw = globals->get_current_view();
176 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
181 void FGAIAircraft::AccelTo(double speed) {
184 _needsGroundElevation = true;
188 void FGAIAircraft::PitchTo(double angle) {
194 void FGAIAircraft::RollTo(double angle) {
200 void FGAIAircraft::YawTo(double angle) {
205 void FGAIAircraft::ClimbTo(double alt_ft ) {
206 tgt_altitude_ft = alt_ft;
211 void FGAIAircraft::TurnTo(double heading) {
212 tgt_heading = heading;
217 double FGAIAircraft::sign(double x) {
225 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
226 if (!flightplan.empty()) {
227 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
228 fp->setRepeat(repeat);
234 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
240 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
242 // the one behind you
243 FGAIFlightPlan::waypoint* prev = 0;
245 FGAIFlightPlan::waypoint* curr = 0;
247 FGAIFlightPlan::waypoint* next = 0;
249 prev = fp->getPreviousWaypoint();
250 curr = fp->getCurrentWaypoint();
251 next = fp->getNextWaypoint();
255 ///////////////////////////////////////////////////////////////////////////
256 // Initialize the flightplan
257 //////////////////////////////////////////////////////////////////////////
259 handleFirstWaypoint();
261 } // end of initialization
262 if (! fpExecutable(now))
266 double distanceToDescent;
267 if(reachedEndOfCruise(distanceToDescent)) {
268 if (!loadNextLeg(distanceToDescent)) {
272 prev = fp->getPreviousWaypoint();
273 curr = fp->getCurrentWaypoint();
274 next = fp->getNextWaypoint();
276 if (! leadPointReached(curr)) {
277 controlHeading(curr);
278 controlSpeed(curr, next);
280 if (curr->finished) //end of the flight plan
290 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
291 tgt_heading = fp->getBearing(curr, next);
295 //TODO let the fp handle this (loading of next leg)
296 fp->IncrementWaypoint( trafficRef != 0 );
297 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
298 if (!loadNextLeg()) {
303 prev = fp->getPreviousWaypoint();
304 curr = fp->getCurrentWaypoint();
305 next = fp->getNextWaypoint();
307 // Now that we have incremented the waypoints, excute some traffic manager specific code
309 //TODO isn't this best executed right at the beginning?
310 if (! aiTrafficVisible()) {
315 if (! handleAirportEndPoints(prev, now)) {
320 announcePositionToController();
325 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
328 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
330 tgt_altitude_ft = prev->altitude;
331 if (curr->crossat > -1000.0) {
333 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
334 / 6076.0 / speed*60.0);
336 tgt_altitude_ft = curr->crossat;
341 AccelTo(prev->speed);
342 hdg_lock = alt_lock = true;
343 no_roll = prev->on_ground;
347 void FGAIAircraft::checkTcas(void)
349 if (props->getIntValue("tcas/threat-level",0)==3)
351 int RASense = props->getIntValue("tcas/ra-sense",0);
352 if ((RASense>0)&&(tgt_vs<4000))
358 // downward RA: descend!
359 if (altitude_ft < 1000)
361 // too low: level off
374 void FGAIAircraft::initializeFlightPlan() {
378 bool FGAIAircraft::_getGearDown() const {
379 return _performance->gearExtensible(this);
383 const char * FGAIAircraft::_getTransponderCode() const {
384 return transponderCode.c_str();
388 bool FGAIAircraft::loadNextLeg(double distance) {
391 if ((leg = fp->getLeg()) == 10) {
392 if (!trafficRef->next()) {
395 setCallSign(trafficRef->getCallSign());
400 FGAirport *dep = trafficRef->getDepartureAirport();
401 FGAirport *arr = trafficRef->getArrivalAirport();
406 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
413 trafficRef->getSpeed(),
417 trafficRef->getRadius(),
418 trafficRef->getFlightType(),
422 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
428 // Note: This code is copied from David Luff's AILocalTraffic
429 // Warning - ground elev determination is CPU intensive
430 // Either this function or the logic of how often it is called
431 // will almost certainly change.
433 void FGAIAircraft::getGroundElev(double dt) {
436 if (!needGroundElevation())
438 // Update minimally every three secs, but add some randomness
439 // to prevent all AI objects doing this in synchrony
440 if (dt_elev_count < (3.0) + (rand() % 10))
445 // Only do the proper hitlist stuff if we are within visible range of the viewer.
447 double visibility_meters = fgGetDouble("/environment/visibility-m");
448 FGViewer* vw = globals->get_current_view();
450 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
454 double range = 500.0;
455 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
458 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
460 tgt_altitude_ft = alt * SG_METER_TO_FEET;
463 // aircraft is stationary and we obtained altitude for this spot - we're done.
464 _needsGroundElevation = false;
472 void FGAIAircraft::doGroundAltitude() {
473 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
475 altitude_ft = (tgt_altitude_ft + groundOffset);
477 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
482 void FGAIAircraft::announcePositionToController() {
484 int leg = fp->getLeg();
486 // Note that leg has been incremented after creating the current leg, so we should use
487 // leg numbers here that are one higher than the number that is used to create the leg
490 case 2: // Startup and Push back
491 if (trafficRef->getDepartureAirport()->getDynamics())
492 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
494 case 3: // Taxiing to runway
495 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
496 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
498 case 4: //Take off tower controller
499 if (trafficRef->getDepartureAirport()->getDynamics()) {
500 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
502 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
506 if (trafficRef->getDepartureAirport()->getDynamics()) {
507 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
510 case 9: // Taxiing for parking
511 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
512 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
519 if ((controller != prevController) && (prevController != 0)) {
520 prevController->signOff(getID());
522 prevController = controller;
524 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
525 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
526 trafficRef->getRadius(), leg, this);
531 // Process ATC instructions and report back
533 void FGAIAircraft::processATC(FGATCInstruction instruction) {
534 if (instruction.getCheckForCircularWait()) {
535 // This is not exactly an elegant solution,
536 // but at least it gives me a chance to check
537 // if circular waits are resolved.
538 // For now, just take the offending aircraft
541 // a more proper way should be - of course - to
542 // let an offending aircraft take an evasive action
543 // for instance taxi back a little bit.
545 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
546 if (instruction.getHoldPattern ()) {}
549 if (instruction.getHoldPosition ()) {
557 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
560 // Change speed Instruction. This can only be excecuted when there is no
561 // Hold position instruction.
562 if (instruction.getChangeSpeed ()) {
564 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
565 AccelTo(instruction.getSpeed());
567 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
570 if (instruction.getChangeHeading ()) {
572 TurnTo(instruction.getHeading());
578 if (instruction.getChangeAltitude()) {}
583 void FGAIAircraft::handleFirstWaypoint() {
584 bool eraseWaypoints; //TODO YAGNI
587 eraseWaypoints = true;
589 eraseWaypoints = false;
592 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
593 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
594 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
599 //TODO fp should handle this
600 fp->IncrementWaypoint(eraseWaypoints);
601 if (!(fp->getNextWaypoint()) && trafficRef)
602 if (!loadNextLeg()) {
607 prev = fp->getPreviousWaypoint(); //first waypoint
608 curr = fp->getCurrentWaypoint(); //second waypoint
609 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
611 setLatitude(prev->latitude);
612 setLongitude(prev->longitude);
613 setSpeed(prev->speed);
614 setAltitude(prev->altitude);
616 if (prev->speed > 0.0)
617 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
619 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
621 // If next doesn't exist, as in incrementally created flightplans for
622 // AI/Trafficmanager created plans,
623 // Make sure lead distance is initialized otherwise
625 fp->setLeadDistance(speed, hdg, curr, next);
627 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
630 tgt_vs = (curr->crossat - prev->altitude)
631 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
632 / 6076.0 / prev->speed*60.0);
634 tgt_altitude_ft = curr->crossat;
637 tgt_altitude_ft = prev->altitude;
639 alt_lock = hdg_lock = true;
640 no_roll = prev->on_ground;
642 Transform(); // make sure aip is initialized.
643 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
645 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
647 // Make sure to announce the aircraft's position
648 announcePositionToController();
654 * Check Execution time (currently once every 100 ms)
655 * Add a bit of randomization to prevent the execution of all flight plans
656 * in synchrony, which can add significant periodic framerate flutter.
661 bool FGAIAircraft::fpExecutable(time_t now) {
662 double rand_exec_time = (rand() % 100) / 100;
663 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
668 * Check to see if we've reached the lead point for our next turn
673 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
674 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
676 //cerr << "2" << endl;
677 double lead_dist = fp->getLeadDistance();
678 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
680 if (lead_dist < fabs(2*speed)) {
681 //don't skip over the waypoint
682 lead_dist = fabs(2*speed);
683 //cerr << "Extending lead distance to " << lead_dist << endl;
686 //prev_dist_to_go = dist_to_go;
687 //if (dist_to_go < lead_dist)
688 // cerr << trafficRef->getCallSign() << " Distance : "
689 // << dist_to_go << ": Lead distance "
690 // << lead_dist << " " << curr->name
691 // << " Ground target speed " << groundTargetSpeed << endl;
693 if (speed > 50) { // don't do bearing calculations for ground traffic
694 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
695 if (bearing < minBearing) {
696 minBearing = bearing;
697 if (minBearing < 10) {
700 if ((minBearing < 360.0) && (minBearing > 10.0)) {
701 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
708 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
709 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
710 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
711 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
714 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
723 bool FGAIAircraft::aiTrafficVisible() {
724 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
725 fgGetDouble("/position/latitude-deg")));
727 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
732 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
733 * in the case of an arrival.
739 //TODO the trafficRef is the right place for the method
740 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
741 // prepare routing from one airport to another
742 FGAirport * dep = trafficRef->getDepartureAirport();
743 FGAirport * arr = trafficRef->getArrivalAirport();
748 // This waypoint marks the fact that the aircraft has passed the initial taxi
749 // departure waypoint, so it can release the parking.
750 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
751 if (prev->name == "PushBackPoint") {
752 dep->getDynamics()->releaseParking(fp->getGate());
754 setTaxiClearanceRequest(true);
757 // This is the last taxi waypoint, and marks the the end of the flight plan
758 // so, the schedule should update and wait for the next departure time.
759 if (prev->name == "END") {
760 time_t nextDeparture = trafficRef->getDepartureTime();
761 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
762 if (nextDeparture < (now+1200)) {
763 nextDeparture = now + 1200;
765 fp->setTime(nextDeparture); // should be "next departure"
773 * Check difference between target bearing and current heading and correct if necessary.
777 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
778 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
779 //cerr << "Bearing = " << calc_bearing << endl;
782 if (calc_bearing > 360)
786 if (finite(calc_bearing)) {
787 double hdg_error = calc_bearing - tgt_heading;
788 if (fabs(hdg_error) > 0.01) {
789 TurnTo( calc_bearing );
793 cerr << "calc_bearing is not a finite number : "
795 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
796 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
797 cerr << "waypoint name " << curr->name;
804 * Update the lead distance calculation if speed has changed sufficiently
805 * to prevent spinning (hopefully);
810 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
811 double speed_diff = speed - prevSpeed;
813 if (fabs(speed_diff) > 10) {
816 fp->setLeadDistance(speed, tgt_heading, curr, next);
823 * Update target values (heading, alt, speed) depending on flight plan or control properties
825 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
826 if (fp) // AI object has a flightplan
828 //TODO make this a function of AIBase
829 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
830 //cerr << "UpateTArgetValues() " << endl;
831 ProcessFlightPlan(dt, now);
833 // Do execute Ground elev for inactive aircraft, so they
834 // Are repositioned to the correct ground altitude when the user flies within visibility range.
835 // In addition, check whether we are out of user range, so this aircraft
838 Transform(); // make sure aip is initialized.
842 pos.setElevationFt(altitude_ft);
845 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
846 aiOutOfSight = !aiTrafficVisible();
849 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
854 timeElapsed = now - fp->getStartTime();
855 flightplanActive = fp->isActive(now);
857 // no flight plan, update target heading, speed, and altitude
858 // from control properties. These default to the initial
859 // settings in the config file, but can be changed "on the
861 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
862 if ( lat_mode == "roll" ) {
864 = props->getDoubleValue("controls/flight/target-roll" );
868 = props->getDoubleValue("controls/flight/target-hdg" );
873 = props->getStringValue("controls/flight/longitude-mode");
874 if ( lon_mode == "alt" ) {
875 double alt = props->getDoubleValue("controls/flight/target-alt" );
879 = props->getDoubleValue("controls/flight/target-pitch" );
883 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
887 void FGAIAircraft::updatePosition() {
888 // convert speed to degrees per second
889 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
890 * speed * 1.686 / ft_per_deg_lat;
891 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
892 * speed * 1.686 / ft_per_deg_lon;
895 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
896 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
900 void FGAIAircraft::updateHeading() {
901 // adjust heading based on current bank angle
906 // double turnConstant;
908 // turnConstant = 0.0088362;
910 // turnConstant = 0.088362;
911 // If on ground, calculate heading change directly
913 double headingDiff = fabs(hdg-tgt_heading);
914 double bank_sense = 0.0;
916 double diff = fabs(hdg - tgt_heading);
918 diff = fabs(diff - 360);
920 double sum = hdg + diff;
923 if (fabs(sum - tgt_heading) < 1.0) {
924 bank_sense = 1.0; // right turn
926 bank_sense = -1.0; // left turn
928 if (headingDiff > 180)
929 headingDiff = fabs(headingDiff - 360);
930 double sum = hdg + headingDiff;
933 if (fabs(sum - tgt_heading) > 0.0001) {
939 //cerr << trafficRef->getCallSign() << " Heading "
940 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
941 //if (headingDiff > 60) {
942 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
943 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
945 // groundTargetSpeed = tgt_speed;
947 if (sign(groundTargetSpeed) != sign(tgt_speed))
948 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
950 if (headingDiff > 30.0) {
951 // invert if pushed backward
952 headingChangeRate += 10.0 * dt * sign(roll);
954 // Clamp the maximum steering rate to 30 degrees per second,
955 // But only do this when the heading error is decreasing.
956 if ((headingDiff < headingError)) {
957 if (headingChangeRate > 30)
958 headingChangeRate = 30;
959 else if (headingChangeRate < -30)
960 headingChangeRate = -30;
963 if (fabs(headingChangeRate) > headingDiff)
964 headingChangeRate = headingDiff*sign(roll);
966 headingChangeRate += dt * sign(roll);
969 hdg += headingChangeRate * dt * (fabs(speed) / 15);
970 headingError = headingDiff;
972 if (fabs(speed) > 1.0) {
973 turn_radius_ft = 0.088362 * speed * speed
974 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
976 // Check if turn_radius_ft == 0; this might lead to a division by 0.
977 turn_radius_ft = 1.0;
979 double turn_circum_ft = SGD_2PI * turn_radius_ft;
980 double dist_covered_ft = speed * 1.686 * dt;
981 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
982 hdg += alpha * sign(roll);
984 while ( hdg > 360.0 ) {
996 void FGAIAircraft::updateBankAngleTarget() {
997 // adjust target bank angle if heading lock engaged
999 double bank_sense = 0.0;
1000 double diff = fabs(hdg - tgt_heading);
1002 diff = fabs(diff - 360);
1004 double sum = hdg + diff;
1007 if (fabs(sum - tgt_heading) < 1.0) {
1008 bank_sense = 1.0; // right turn
1010 bank_sense = -1.0; // left turn
1012 if (diff < _performance->maximumBankAngle()) {
1013 tgt_roll = diff * bank_sense;
1015 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1017 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1018 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1019 // The only way to resolve this is to make them slow down.
1025 void FGAIAircraft::updateVerticalSpeedTarget() {
1026 // adjust target Altitude, based on ground elevation when on ground
1030 } else if (alt_lock) {
1031 // find target vertical speed
1033 if (altitude_ft < tgt_altitude_ft) {
1034 tgt_vs = tgt_altitude_ft - altitude_ft;
1035 if (tgt_vs > _performance->climbRate())
1036 tgt_vs = _performance->climbRate();
1038 tgt_vs = tgt_altitude_ft - altitude_ft;
1039 if (tgt_vs < (-_performance->descentRate()))
1040 tgt_vs = -_performance->descentRate();
1043 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1044 double min_vs = 100;
1045 if (tgt_altitude_ft < altitude_ft)
1047 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1048 && (fabs(max_vs) < fabs(tgt_vs)))
1051 if (fabs(tgt_vs) < fabs(min_vs))
1059 void FGAIAircraft::updatePitchAngleTarget() {
1060 // if on ground and above vRotate -> initial rotation
1061 if (onGround() && (speed > _performance->vRotate()))
1062 tgt_pitch = 8.0; // some rough B737 value
1064 //TODO pitch angle on approach and landing
1066 // match pitch angle to vertical speed
1067 else if (tgt_vs > 0) {
1068 tgt_pitch = tgt_vs * 0.005;
1070 tgt_pitch = tgt_vs * 0.002;
1074 string FGAIAircraft::atGate() {
1076 if (fp->getLeg() < 3) {
1078 if (fp->getGate() > 0) {
1080 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1081 tmp = park->getName();
1088 void FGAIAircraft::handleATCRequests() {
1089 //TODO implement NullController for having no ATC to save the conditionals
1091 controller->update(getID(),
1092 pos.getLatitudeDeg(),
1093 pos.getLongitudeDeg(),
1097 processATC(controller->getInstruction(getID()));
1101 void FGAIAircraft::updateActualState() {
1102 //update current state
1103 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1107 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1109 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1112 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1114 // adjust altitude (meters) based on current vertical speed (fpm)
1115 altitude_ft += vs / 60.0 * dt;
1116 pos.setElevationFt(altitude_ft);
1118 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1119 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1122 void FGAIAircraft::updateSecondaryTargetValues() {
1123 // derived target state values
1124 updateBankAngleTarget();
1125 updateVerticalSpeedTarget();
1126 updatePitchAngleTarget();
1128 //TODO calculate wind correction angle (tgt_yaw)
1132 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1133 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1134 if (curr->name == "BOD") {
1135 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1136 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1137 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1139 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1140 double descentTimeNeeded = verticalDistance / descentRate;
1141 double distanceCovered = descentSpeed * descentTimeNeeded;
1143 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1144 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1145 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1146 cerr << "Descent rate : " << descentRate << endl;
1147 cerr << "Descent speed : " << descentSpeed << endl;
1148 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1149 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1150 cerr << "DistanceCovered : " << distanceCovered << endl;
1152 //cerr << "Distance = " << distance << endl;
1153 distance = distanceCovered;
1154 if (dist < distanceCovered) {
1155 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1167 void FGAIAircraft::resetPositionFromFlightPlan()
1169 // the one behind you
1170 FGAIFlightPlan::waypoint* prev = 0;
1172 FGAIFlightPlan::waypoint* curr = 0;
1174 FGAIFlightPlan::waypoint* next = 0;
1176 prev = fp->getPreviousWaypoint();
1177 curr = fp->getCurrentWaypoint();
1178 next = fp->getNextWaypoint();
1180 setLatitude(prev->latitude);
1181 setLongitude(prev->longitude);
1182 double tgt_heading = fp->getBearing(curr, next);
1183 setHeading(tgt_heading);
1184 setAltitude(prev->altitude);
1185 setSpeed(prev->speed);
1188 double FGAIAircraft::getBearing(double crse)
1190 double hdgDiff = fabs(hdg-crse);
1192 hdgDiff = fabs(hdgDiff - 360);
1196 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1197 FGAIFlightPlan::waypoint* curr = 0;
1198 curr = fp->getCurrentWaypoint();
1200 double tracklength = fp->checkTrackLength(wptName);
1201 if (tracklength > 0.1) {
1202 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1206 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1207 time_t arrivalTime = fp->getArrivalTime();
1209 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1210 time_t secondsToGo = arrivalTime - now;
1211 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1212 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1214 return (ete - secondsToGo); // Positive when we're too slow...