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);
290 cerr << getCallSign()
291 << ": verifying lead distance to waypoint : "
292 << fp->getCurrentWaypoint()->name << " "
293 << fp->getLeadDistance() << ". Distance to go "
294 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
295 << ". Target speed = "
297 << ". Current speed = "
299 << ". Minimum Bearing " << minBearing
303 if (curr->finished) //end of the flight plan
313 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
314 tgt_heading = fp->getBearing(curr, next);
318 //TODO let the fp handle this (loading of next leg)
319 fp->IncrementWaypoint( trafficRef != 0 );
320 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
321 if (!loadNextLeg()) {
326 prev = fp->getPreviousWaypoint();
327 curr = fp->getCurrentWaypoint();
328 next = fp->getNextWaypoint();
330 // Now that we have incremented the waypoints, excute some traffic manager specific code
332 //TODO isn't this best executed right at the beginning?
333 if (! aiTrafficVisible()) {
338 if (! handleAirportEndPoints(prev, now)) {
343 announcePositionToController();
348 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
351 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
353 tgt_altitude_ft = prev->altitude;
354 if (curr->crossat > -1000.0) {
356 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
357 / 6076.0 / speed*60.0);
359 tgt_altitude_ft = curr->crossat;
364 AccelTo(prev->speed);
365 hdg_lock = alt_lock = true;
366 no_roll = prev->on_ground;
370 void FGAIAircraft::checkTcas(void)
372 if (props->getIntValue("tcas/threat-level",0)==3)
374 int RASense = props->getIntValue("tcas/ra-sense",0);
375 if ((RASense>0)&&(tgt_vs<4000))
381 // downward RA: descend!
382 if (altitude_ft < 1000)
384 // too low: level off
397 void FGAIAircraft::initializeFlightPlan() {
401 bool FGAIAircraft::_getGearDown() const {
402 return _performance->gearExtensible(this);
406 const char * FGAIAircraft::_getTransponderCode() const {
407 return transponderCode.c_str();
411 bool FGAIAircraft::loadNextLeg(double distance) {
414 if ((leg = fp->getLeg()) == 10) {
415 if (!trafficRef->next()) {
418 setCallSign(trafficRef->getCallSign());
423 FGAirport *dep = trafficRef->getDepartureAirport();
424 FGAirport *arr = trafficRef->getArrivalAirport();
429 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
436 trafficRef->getSpeed(),
440 trafficRef->getRadius(),
441 trafficRef->getFlightType(),
445 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
451 // Note: This code is copied from David Luff's AILocalTraffic
452 // Warning - ground elev determination is CPU intensive
453 // Either this function or the logic of how often it is called
454 // will almost certainly change.
456 void FGAIAircraft::getGroundElev(double dt) {
459 if (!needGroundElevation())
461 // Update minimally every three secs, but add some randomness
462 // to prevent all AI objects doing this in synchrony
463 if (dt_elev_count < (3.0) + (rand() % 10))
468 // Only do the proper hitlist stuff if we are within visible range of the viewer.
470 double visibility_meters = fgGetDouble("/environment/visibility-m");
471 FGViewer* vw = globals->get_current_view();
473 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
477 double range = 500.0;
478 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
481 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
483 tgt_altitude_ft = alt * SG_METER_TO_FEET;
486 // aircraft is stationary and we obtained altitude for this spot - we're done.
487 _needsGroundElevation = false;
495 void FGAIAircraft::doGroundAltitude() {
496 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
498 altitude_ft = (tgt_altitude_ft + groundOffset);
500 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
505 void FGAIAircraft::announcePositionToController() {
507 int leg = fp->getLeg();
509 // Note that leg has been incremented after creating the current leg, so we should use
510 // leg numbers here that are one higher than the number that is used to create the leg
513 case 2: // Startup and Push back
514 if (trafficRef->getDepartureAirport()->getDynamics())
515 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
517 case 3: // Taxiing to runway
518 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
519 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
521 case 4: //Take off tower controller
522 if (trafficRef->getDepartureAirport()->getDynamics()) {
523 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
525 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
529 if (trafficRef->getDepartureAirport()->getDynamics()) {
530 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
533 case 9: // Taxiing for parking
534 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
535 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
542 if ((controller != prevController) && (prevController != 0)) {
543 prevController->signOff(getID());
545 prevController = controller;
547 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
548 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
549 trafficRef->getRadius(), leg, this);
554 // Process ATC instructions and report back
556 void FGAIAircraft::processATC(FGATCInstruction instruction) {
557 if (instruction.getCheckForCircularWait()) {
558 // This is not exactly an elegant solution,
559 // but at least it gives me a chance to check
560 // if circular waits are resolved.
561 // For now, just take the offending aircraft
564 // a more proper way should be - of course - to
565 // let an offending aircraft take an evasive action
566 // for instance taxi back a little bit.
568 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
569 if (instruction.getHoldPattern ()) {}
572 if (instruction.getHoldPosition ()) {
580 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
583 // Change speed Instruction. This can only be excecuted when there is no
584 // Hold position instruction.
585 if (instruction.getChangeSpeed ()) {
587 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
588 AccelTo(instruction.getSpeed());
590 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
593 if (instruction.getChangeHeading ()) {
595 TurnTo(instruction.getHeading());
601 if (instruction.getChangeAltitude()) {}
606 void FGAIAircraft::handleFirstWaypoint() {
607 bool eraseWaypoints; //TODO YAGNI
610 eraseWaypoints = true;
612 eraseWaypoints = false;
615 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
616 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
617 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
622 //TODO fp should handle this
623 fp->IncrementWaypoint(eraseWaypoints);
624 if (!(fp->getNextWaypoint()) && trafficRef)
625 if (!loadNextLeg()) {
630 prev = fp->getPreviousWaypoint(); //first waypoint
631 curr = fp->getCurrentWaypoint(); //second waypoint
632 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
634 setLatitude(prev->latitude);
635 setLongitude(prev->longitude);
636 setSpeed(prev->speed);
637 setAltitude(prev->altitude);
639 if (prev->speed > 0.0)
640 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
642 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
644 // If next doesn't exist, as in incrementally created flightplans for
645 // AI/Trafficmanager created plans,
646 // Make sure lead distance is initialized otherwise
648 fp->setLeadDistance(speed, hdg, curr, next);
650 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
653 tgt_vs = (curr->crossat - prev->altitude)
654 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
655 / 6076.0 / prev->speed*60.0);
657 tgt_altitude_ft = curr->crossat;
660 tgt_altitude_ft = prev->altitude;
662 alt_lock = hdg_lock = true;
663 no_roll = prev->on_ground;
665 Transform(); // make sure aip is initialized.
666 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
668 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
670 // Make sure to announce the aircraft's position
671 announcePositionToController();
677 * Check Execution time (currently once every 100 ms)
678 * Add a bit of randomization to prevent the execution of all flight plans
679 * in synchrony, which can add significant periodic framerate flutter.
684 bool FGAIAircraft::fpExecutable(time_t now) {
685 double rand_exec_time = (rand() % 100) / 100;
686 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
691 * Check to see if we've reached the lead point for our next turn
696 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
697 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
699 //cerr << "2" << endl;
700 double lead_dist = fp->getLeadDistance();
701 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
702 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->name == string("PushBackPoint")) {
703 tgt_speed = -(dist_to_go / 10.0);
704 if (tgt_speed > -0.5) {
707 if (fp->getPreviousWaypoint()->speed < tgt_speed) {
708 fp->getPreviousWaypoint()->speed = tgt_speed;
711 if (lead_dist < fabs(2*speed)) {
712 //don't skip over the waypoint
713 lead_dist = fabs(2*speed);
714 //cerr << "Extending lead distance to " << lead_dist << endl;
717 //prev_dist_to_go = dist_to_go;
718 //if (dist_to_go < lead_dist)
719 // cerr << trafficRef->getCallSign() << " Distance : "
720 // << dist_to_go << ": Lead distance "
721 // << lead_dist << " " << curr->name
722 // << " Ground target speed " << groundTargetSpeed << endl;
724 if (speed > 50) { // don't do bearing calculations for ground traffic
725 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
726 if (bearing < minBearing) {
727 minBearing = bearing;
728 if (minBearing < 10) {
731 if ((minBearing < 360.0) && (minBearing > 10.0)) {
732 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
739 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
740 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
741 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
742 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
745 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
754 bool FGAIAircraft::aiTrafficVisible() {
755 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
756 fgGetDouble("/position/latitude-deg")));
758 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
763 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
764 * in the case of an arrival.
770 //TODO the trafficRef is the right place for the method
771 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
772 // prepare routing from one airport to another
773 FGAirport * dep = trafficRef->getDepartureAirport();
774 FGAirport * arr = trafficRef->getArrivalAirport();
779 // This waypoint marks the fact that the aircraft has passed the initial taxi
780 // departure waypoint, so it can release the parking.
781 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
782 if (prev->name == "PushBackPoint") {
783 dep->getDynamics()->releaseParking(fp->getGate());
785 setTaxiClearanceRequest(true);
788 // This is the last taxi waypoint, and marks the the end of the flight plan
789 // so, the schedule should update and wait for the next departure time.
790 if (prev->name == "END") {
791 time_t nextDeparture = trafficRef->getDepartureTime();
792 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
793 if (nextDeparture < (now+1200)) {
794 nextDeparture = now + 1200;
796 fp->setTime(nextDeparture); // should be "next departure"
804 * Check difference between target bearing and current heading and correct if necessary.
808 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
809 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
810 //cerr << "Bearing = " << calc_bearing << endl;
813 if (calc_bearing > 360)
817 if (finite(calc_bearing)) {
818 double hdg_error = calc_bearing - tgt_heading;
819 if (fabs(hdg_error) > 0.01) {
820 TurnTo( calc_bearing );
824 cerr << "calc_bearing is not a finite number : "
826 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
827 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
828 cerr << "waypoint name " << curr->name;
835 * Update the lead distance calculation if speed has changed sufficiently
836 * to prevent spinning (hopefully);
841 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
842 double speed_diff = speed - prevSpeed;
844 if (fabs(speed_diff) > 10) {
847 fp->setLeadDistance(speed, tgt_heading, curr, next);
854 * Update target values (heading, alt, speed) depending on flight plan or control properties
856 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
857 if (fp) // AI object has a flightplan
859 //TODO make this a function of AIBase
860 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
861 //cerr << "UpateTArgetValues() " << endl;
862 ProcessFlightPlan(dt, now);
864 // Do execute Ground elev for inactive aircraft, so they
865 // Are repositioned to the correct ground altitude when the user flies within visibility range.
866 // In addition, check whether we are out of user range, so this aircraft
869 Transform(); // make sure aip is initialized.
873 pos.setElevationFt(altitude_ft);
876 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
877 aiOutOfSight = !aiTrafficVisible();
880 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
885 timeElapsed = now - fp->getStartTime();
886 flightplanActive = fp->isActive(now);
888 // no flight plan, update target heading, speed, and altitude
889 // from control properties. These default to the initial
890 // settings in the config file, but can be changed "on the
892 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
893 if ( lat_mode == "roll" ) {
895 = props->getDoubleValue("controls/flight/target-roll" );
899 = props->getDoubleValue("controls/flight/target-hdg" );
904 = props->getStringValue("controls/flight/longitude-mode");
905 if ( lon_mode == "alt" ) {
906 double alt = props->getDoubleValue("controls/flight/target-alt" );
910 = props->getDoubleValue("controls/flight/target-pitch" );
914 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
918 void FGAIAircraft::updatePosition() {
919 // convert speed to degrees per second
920 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
921 * speed * 1.686 / ft_per_deg_lat;
922 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
923 * speed * 1.686 / ft_per_deg_lon;
926 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
927 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
931 void FGAIAircraft::updateHeading() {
932 // adjust heading based on current bank angle
937 // double turnConstant;
939 // turnConstant = 0.0088362;
941 // turnConstant = 0.088362;
942 // If on ground, calculate heading change directly
944 double headingDiff = fabs(hdg-tgt_heading);
945 double bank_sense = 0.0;
947 double diff = fabs(hdg - tgt_heading);
949 diff = fabs(diff - 360);
951 double sum = hdg + diff;
954 if (fabs(sum - tgt_heading) < 1.0) {
955 bank_sense = 1.0; // right turn
957 bank_sense = -1.0; // left turn
959 if (headingDiff > 180)
960 headingDiff = fabs(headingDiff - 360);
961 double sum = hdg + headingDiff;
964 if (fabs(sum - tgt_heading) > 0.0001) {
970 // cerr << trafficRef->getCallSign() << " Heading "
971 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
972 //if (headingDiff > 60) {
973 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
974 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
976 // groundTargetSpeed = tgt_speed;
978 if (sign(groundTargetSpeed) != sign(tgt_speed))
979 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
981 // 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.
983 if (headingDiff > 30.0) {
984 // invert if pushed backward
985 headingChangeRate += 10.0 * dt * sign(roll);
987 // Clamp the maximum steering rate to 30 degrees per second,
988 // But only do this when the heading error is decreasing.
989 if ((headingDiff < headingError)) {
990 if (headingChangeRate > 30)
991 headingChangeRate = 30;
992 else if (headingChangeRate < -30)
993 headingChangeRate = -30;
997 if (fabs(headingChangeRate) > headingDiff)
998 headingChangeRate = headingDiff*sign(roll);
1000 headingChangeRate += dt * sign(roll);
1005 //cerr << trafficRef->getCallSign() << " Heading "
1006 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1007 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1008 headingError = headingDiff;
1010 if (fabs(speed) > 1.0) {
1011 turn_radius_ft = 0.088362 * speed * speed
1012 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1014 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1015 turn_radius_ft = 1.0;
1017 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1018 double dist_covered_ft = speed * 1.686 * dt;
1019 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1020 hdg += alpha * sign(roll);
1022 while ( hdg > 360.0 ) {
1026 while ( hdg < 0.0) {
1034 void FGAIAircraft::updateBankAngleTarget() {
1035 // adjust target bank angle if heading lock engaged
1037 double bank_sense = 0.0;
1038 double diff = fabs(hdg - tgt_heading);
1040 diff = fabs(diff - 360);
1042 double sum = hdg + diff;
1045 if (fabs(sum - tgt_heading) < 1.0) {
1046 bank_sense = 1.0; // right turn
1048 bank_sense = -1.0; // left turn
1050 if (diff < _performance->maximumBankAngle()) {
1051 tgt_roll = diff * bank_sense;
1053 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1055 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1056 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1057 // The only way to resolve this is to make them slow down.
1063 void FGAIAircraft::updateVerticalSpeedTarget() {
1064 // adjust target Altitude, based on ground elevation when on ground
1068 } else if (alt_lock) {
1069 // find target vertical speed
1071 if (altitude_ft < tgt_altitude_ft) {
1072 tgt_vs = tgt_altitude_ft - altitude_ft;
1073 if (tgt_vs > _performance->climbRate())
1074 tgt_vs = _performance->climbRate();
1076 tgt_vs = tgt_altitude_ft - altitude_ft;
1077 if (tgt_vs < (-_performance->descentRate()))
1078 tgt_vs = -_performance->descentRate();
1081 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1082 double min_vs = 100;
1083 if (tgt_altitude_ft < altitude_ft)
1085 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1086 && (fabs(max_vs) < fabs(tgt_vs)))
1089 if (fabs(tgt_vs) < fabs(min_vs))
1097 void FGAIAircraft::updatePitchAngleTarget() {
1098 // if on ground and above vRotate -> initial rotation
1099 if (onGround() && (speed > _performance->vRotate()))
1100 tgt_pitch = 8.0; // some rough B737 value
1102 //TODO pitch angle on approach and landing
1104 // match pitch angle to vertical speed
1105 else if (tgt_vs > 0) {
1106 tgt_pitch = tgt_vs * 0.005;
1108 tgt_pitch = tgt_vs * 0.002;
1112 string FGAIAircraft::atGate() {
1114 if (fp->getLeg() < 3) {
1116 if (fp->getGate() > 0) {
1118 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1119 tmp = park->getName();
1126 void FGAIAircraft::handleATCRequests() {
1127 //TODO implement NullController for having no ATC to save the conditionals
1129 controller->updateAircraftInformation(getID(),
1130 pos.getLatitudeDeg(),
1131 pos.getLongitudeDeg(),
1135 processATC(controller->getInstruction(getID()));
1139 void FGAIAircraft::updateActualState() {
1140 //update current state
1141 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1145 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1147 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1150 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1152 // adjust altitude (meters) based on current vertical speed (fpm)
1153 altitude_ft += vs / 60.0 * dt;
1154 pos.setElevationFt(altitude_ft);
1156 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1157 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1160 void FGAIAircraft::updateSecondaryTargetValues() {
1161 // derived target state values
1162 updateBankAngleTarget();
1163 updateVerticalSpeedTarget();
1164 updatePitchAngleTarget();
1166 //TODO calculate wind correction angle (tgt_yaw)
1170 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1171 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1172 if (curr->name == "BOD") {
1173 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1174 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1175 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1177 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1178 double descentTimeNeeded = verticalDistance / descentRate;
1179 double distanceCovered = descentSpeed * descentTimeNeeded;
1181 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1182 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1183 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1184 cerr << "Descent rate : " << descentRate << endl;
1185 cerr << "Descent speed : " << descentSpeed << endl;
1186 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1187 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1188 cerr << "DistanceCovered : " << distanceCovered << endl;
1190 //cerr << "Distance = " << distance << endl;
1191 distance = distanceCovered;
1192 if (dist < distanceCovered) {
1193 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1205 void FGAIAircraft::resetPositionFromFlightPlan()
1207 // the one behind you
1208 FGAIFlightPlan::waypoint* prev = 0;
1210 FGAIFlightPlan::waypoint* curr = 0;
1212 FGAIFlightPlan::waypoint* next = 0;
1214 prev = fp->getPreviousWaypoint();
1215 curr = fp->getCurrentWaypoint();
1216 next = fp->getNextWaypoint();
1218 setLatitude(prev->latitude);
1219 setLongitude(prev->longitude);
1220 double tgt_heading = fp->getBearing(curr, next);
1221 setHeading(tgt_heading);
1222 setAltitude(prev->altitude);
1223 setSpeed(prev->speed);
1226 double FGAIAircraft::getBearing(double crse)
1228 double hdgDiff = fabs(hdg-crse);
1230 hdgDiff = fabs(hdgDiff - 360);
1234 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1235 FGAIFlightPlan::waypoint* curr = 0;
1236 curr = fp->getCurrentWaypoint();
1238 double tracklength = fp->checkTrackLength(wptName);
1239 if (tracklength > 0.1) {
1240 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1244 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1245 time_t arrivalTime = fp->getArrivalTime();
1247 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1248 time_t secondsToGo = arrivalTime - now;
1249 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1250 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1252 return (ete - secondsToGo); // Positive when we're too slow...