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 <Main/fg_props.hxx>
26 #include <Main/globals.hxx>
27 #include <Scenery/scenery.hxx>
28 #include <Scenery/tilemgr.hxx>
29 #include <Airports/dynamics.hxx>
30 #include <Airports/airport.hxx>
31 #include <Main/util.hxx>
33 #include <simgear/structure/exception.hxx>
41 # define finite _finite
42 #elif defined(__sun) || defined(sgi)
47 #include "AIAircraft.hxx"
48 #include "performancedata.hxx"
49 #include "performancedb.hxx"
56 //#include <Airports/trafficcontroller.hxx>
58 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
59 /* HOT must be disabled for AI Aircraft,
60 * otherwise traffic detection isn't working as expected.*/
61 FGAIBase(otAircraft, false)
65 groundOffset = trafficRef->getGroundOffset();
66 setCallSign(trafficRef->getCallSign());
82 groundTargetSpeed = 0;
84 // set heading and altitude locks
88 headingChangeRate = 0.0;
92 prev_dist_to_go = 0.0;
95 needsTaxiClearance = false;
96 _needsGroundElevation = true;
98 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
102 trackCache.remainingLength = 0;
103 trackCache.startWptName = "-";
107 FGAIAircraft::~FGAIAircraft() {
110 controller->signOff(getID());
114 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
118 FGAIBase::readFromScenario(scFileNode);
120 setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
121 setFlightPlan(scFileNode->getStringValue("flightplan"),
122 scFileNode->getBoolValue("repeat", false));
123 setCallSign(scFileNode->getStringValue("callsign"));
127 void FGAIAircraft::bind() {
130 tie("transponder-id",
131 SGRawValueMethods<FGAIAircraft,const char*>(*this,
132 &FGAIAircraft::_getTransponderCode));
135 void FGAIAircraft::update(double dt) {
136 FGAIBase::update(dt);
141 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
143 static PerformanceDB perfdb; //TODO make it a global service
144 _performance = perfdb.getDataFor(acType, acclass);
148 void FGAIAircraft::setPerformance(PerformanceData *ps) {
153 void FGAIAircraft::Run(double dt) {
154 FGAIAircraft::dt = dt;
156 bool outOfSight = false,
157 flightplanActive = true;
158 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
163 if (!flightplanActive) {
164 groundTargetSpeed = 0;
167 handleATCRequests(); // ATC also has a word to say
168 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
171 // 25/11/12 - added but disabled, since setting properties isn't
172 // affecting the AI-model as expected.
173 updateModelProperties(dt);
176 // We currently have one situation in which an AIAircraft object is used that is not attached to the
177 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
178 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
181 UpdateRadar(manager);
185 void FGAIAircraft::checkVisibility()
187 double visibility_meters = fgGetDouble("/environment/visibility-m");
188 invisible = (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters);
193 void FGAIAircraft::AccelTo(double speed) {
195 //assertSpeed(speed);
197 _needsGroundElevation = true;
201 void FGAIAircraft::PitchTo(double angle) {
207 void FGAIAircraft::RollTo(double angle) {
213 void FGAIAircraft::YawTo(double angle) {
218 void FGAIAircraft::ClimbTo(double alt_ft ) {
219 tgt_altitude_ft = alt_ft;
224 void FGAIAircraft::TurnTo(double heading) {
225 tgt_heading = heading;
230 double FGAIAircraft::sign(double x) {
238 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
239 if (!flightplan.empty()) {
240 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
241 fp->setRepeat(repeat);
247 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
253 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
255 // the one behind you
256 FGAIWaypoint* prev = 0;
258 FGAIWaypoint* curr = 0;
260 FGAIWaypoint* next = 0;
262 prev = fp->getPreviousWaypoint();
263 curr = fp->getCurrentWaypoint();
264 next = fp->getNextWaypoint();
268 ///////////////////////////////////////////////////////////////////////////
269 // Initialize the flightplan
270 //////////////////////////////////////////////////////////////////////////
272 handleFirstWaypoint();
274 } // end of initialization
275 if (! fpExecutable(now))
279 double distanceToDescent;
280 if(reachedEndOfCruise(distanceToDescent)) {
281 if (!loadNextLeg(distanceToDescent)) {
285 prev = fp->getPreviousWaypoint();
286 curr = fp->getCurrentWaypoint();
287 next = fp->getNextWaypoint();
295 if (! leadPointReached(curr)) {
296 controlHeading(curr);
297 controlSpeed(curr, next);
301 cerr << getCallSign()
302 << ": verifying lead distance to waypoint : "
303 << fp->getCurrentWaypoint()->name << " "
304 << fp->getLeadDistance() << ". Distance to go "
305 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
306 << ". Target speed = "
308 << ". Current speed = "
310 << ". Minimum Bearing " << minBearing
314 if (curr->isFinished()) //end of the flight plan
324 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
325 tgt_heading = fp->getBearing(curr, next);
329 //TODO let the fp handle this (loading of next leg)
330 fp->IncrementWaypoint( trafficRef != 0 );
331 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
332 if (!loadNextLeg()) {
337 prev = fp->getPreviousWaypoint();
338 curr = fp->getCurrentWaypoint();
339 next = fp->getNextWaypoint();
341 // Now that we have incremented the waypoints, excute some traffic manager specific code
343 //TODO isn't this best executed right at the beginning?
344 if (! aiTrafficVisible()) {
349 if (! handleAirportEndPoints(prev, now)) {
354 announcePositionToController();
359 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
363 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
365 tgt_altitude_ft = prev->getAltitude();
366 if (curr->getCrossat() > -1000.0) {
368 // Distance to go in meters
369 double vert_dist_ft = curr->getCrossat() - altitude_ft;
370 double err_dist = prev->getCrossat() - altitude_ft;
371 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
372 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
375 tgt_altitude_ft = curr->getCrossat();
380 AccelTo(prev->getSpeed());
381 hdg_lock = alt_lock = true;
382 no_roll = prev->getOn_ground();
386 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
388 // err is negative when we passed too high
389 double vert_m = vert_ft * SG_FEET_TO_METER;
390 //double err_m = err * SG_FEET_TO_METER;
391 //double angle = atan2(vert_m, dist_m);
392 double speedMs = (speed * SG_NM_TO_METER) / 3600;
393 //double vs = cos(angle) * speedMs; // Now in m/s
395 //cerr << "Error term = " << err_m << endl;
397 vs = ((vert_m) / dist_m) * speedMs;
399 // Convert to feet per minute
400 vs *= (SG_METER_TO_FEET * 60);
401 //if (getCallSign() == "LUFTHANSA2002")
402 //if (fabs(vs) > 100000) {
403 // if (getCallSign() == "LUFTHANSA2057") {
404 // cerr << getCallSign() << " " << fp->getPreviousWaypoint()->getName() << ". Alt = " << altitude_ft << " vertical dist = " << vert_m << " horiz dist = " << dist_m << " << angle = " << angle * SG_RADIANS_TO_DEGREES << " vs " << vs << " horizontal speed " << speed << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat() << endl;
405 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
406 // // / 6076.0 / speed*60.0);
412 void FGAIAircraft::assertSpeed(double speed)
414 if ((speed < -50) || (speed > 1000)) {
415 cerr << getCallSign() << " "
416 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
417 << "Departure airport " << trafficRef->getDepartureAirport() << " "
418 << "Leg " << fp->getLeg() << " "
419 << "target_speed << " << tgt_speed << " "
420 << "speedFraction << " << speedFraction << " "
421 << "Currecnt speed << " << speed << " "
429 void FGAIAircraft::checkTcas(void)
431 if (props->getIntValue("tcas/threat-level",0)==3)
433 int RASense = props->getIntValue("tcas/ra-sense",0);
434 if ((RASense>0)&&(tgt_vs<4000))
440 // downward RA: descend!
441 if (altitude_ft < 1000)
443 // too low: level off
456 void FGAIAircraft::initializeFlightPlan() {
459 const char * FGAIAircraft::_getTransponderCode() const {
460 return transponderCode.c_str();
463 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
464 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
466 bool FGAIAircraft::loadNextLeg(double distance) {
469 if ((leg = fp->getLeg()) == 9) {
470 if (!trafficRef->next()) {
473 setCallSign(trafficRef->getCallSign());
478 FGAirport *dep = trafficRef->getDepartureAirport();
479 FGAirport *arr = trafficRef->getArrivalAirport();
484 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
491 trafficRef->getSpeed(),
495 trafficRef->getRadius(),
496 trafficRef->getFlightType(),
500 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
506 // Note: This code is copied from David Luff's AILocalTraffic
507 // Warning - ground elev determination is CPU intensive
508 // Either this function or the logic of how often it is called
509 // will almost certainly change.
511 void FGAIAircraft::getGroundElev(double dt) {
514 if (!needGroundElevation())
516 // Update minimally every three secs, but add some randomness
517 // to prevent all AI objects doing this in synchrony
518 if (dt_elev_count < (3.0) + (rand() % 10))
523 // Only do the proper hitlist stuff if we are within visible range of the viewer.
525 double visibility_meters = fgGetDouble("/environment/visibility-m");
526 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
530 double range = 500.0;
531 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
534 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
536 tgt_altitude_ft = alt * SG_METER_TO_FEET;
539 // aircraft is stationary and we obtained altitude for this spot - we're done.
540 _needsGroundElevation = false;
548 void FGAIAircraft::doGroundAltitude() {
549 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
552 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
554 altitude_ft = (tgt_altitude_ft + groundOffset);
556 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
562 void FGAIAircraft::announcePositionToController() {
567 int leg = fp->getLeg();
568 if (!fp->getCurrentWaypoint()) {
569 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
570 // throw an exception so this aircraft gets killed by the AIManager.
571 throw sg_exception("bad AI flight plan");
574 // Note that leg has been incremented after creating the current leg, so we should use
575 // leg numbers here that are one higher than the number that is used to create the leg
576 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
577 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
578 // the original leg numbers here!
580 case 1: // Startup and Push back
581 if (trafficRef->getDepartureAirport()->getDynamics())
582 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
584 case 2: // Taxiing to runway
585 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
586 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
588 case 3: //Take off tower controller
589 if (trafficRef->getDepartureAirport()->getDynamics()) {
590 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
593 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
597 if (trafficRef->getDepartureAirport()->getDynamics()) {
598 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
601 case 8: // Taxiing for parking
602 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
603 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
610 if ((controller != prevController) && (prevController != 0)) {
611 prevController->signOff(getID());
613 prevController = controller;
615 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
616 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
617 trafficRef->getRadius(), leg, this);
621 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
622 if (!takeOffStatus) {
623 int leg = fp->getLeg();
625 if (trafficRef->getDepartureAirport()->getDynamics()) {
626 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
628 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
630 if (towerController) {
631 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
632 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
633 trafficRef->getRadius(), leg, this);
634 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
638 takeOffStatus = state;
641 // Process ATC instructions and report back
643 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
644 if (instruction.getCheckForCircularWait()) {
645 // This is not exactly an elegant solution,
646 // but at least it gives me a chance to check
647 // if circular waits are resolved.
648 // For now, just take the offending aircraft
651 // a more proper way should be - of course - to
652 // let an offending aircraft take an evasive action
653 // for instance taxi back a little bit.
655 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
656 if (instruction.getHoldPattern ()) {}
659 if (instruction.getHoldPosition ()) {
667 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
670 // Change speed Instruction. This can only be excecuted when there is no
671 // Hold position instruction.
672 if (instruction.getChangeSpeed ()) {
674 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
675 AccelTo(instruction.getSpeed());
677 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
680 if (instruction.getChangeHeading ()) {
682 TurnTo(instruction.getHeading());
688 if (instruction.getChangeAltitude()) {}
693 void FGAIAircraft::handleFirstWaypoint() {
694 bool eraseWaypoints; //TODO YAGNI
697 eraseWaypoints = true;
699 eraseWaypoints = false;
702 FGAIWaypoint* prev = 0; // the one behind you
703 FGAIWaypoint* curr = 0; // the one ahead
704 FGAIWaypoint* next = 0;// the next plus 1
708 //TODO fp should handle this
709 fp->IncrementWaypoint(eraseWaypoints);
710 if (!(fp->getNextWaypoint()) && trafficRef)
711 if (!loadNextLeg()) {
716 prev = fp->getPreviousWaypoint(); //first waypoint
717 curr = fp->getCurrentWaypoint(); //second waypoint
718 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
720 setLatitude(prev->getLatitude());
721 setLongitude(prev->getLongitude());
722 setSpeed(prev->getSpeed());
723 setAltitude(prev->getAltitude());
725 if (prev->getSpeed() > 0.0)
726 setHeading(fp->getBearing(prev, curr));
728 setHeading(fp->getBearing(curr, prev));
730 // If next doesn't exist, as in incrementally created flightplans for
731 // AI/Trafficmanager created plans,
732 // Make sure lead distance is initialized otherwise
734 fp->setLeadDistance(speed, hdg, curr, next);
736 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
739 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
740 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
741 // / 6076.0 / prev->getSpeed()*60.0);
742 double vert_dist_ft = curr->getCrossat() - altitude_ft;
743 double err_dist = prev->getCrossat() - altitude_ft;
744 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
745 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
747 tgt_altitude_ft = curr->getCrossat();
750 tgt_altitude_ft = prev->getAltitude();
752 alt_lock = hdg_lock = true;
753 no_roll = prev->getOn_ground();
755 Transform(); // make sure aip is initialized.
756 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
758 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
760 // Make sure to announce the aircraft's position
761 announcePositionToController();
767 * Check Execution time (currently once every 100 ms)
768 * Add a bit of randomization to prevent the execution of all flight plans
769 * in synchrony, which can add significant periodic framerate flutter.
774 bool FGAIAircraft::fpExecutable(time_t now) {
775 double rand_exec_time = (rand() % 100) / 100;
776 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
781 * Check to see if we've reached the lead point for our next turn
786 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
787 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
789 //cerr << "2" << endl;
790 double lead_dist = fp->getLeadDistance();
791 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
792 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
793 tgt_speed = -(dist_to_go / 10.0);
794 if (tgt_speed > -0.5) {
797 //assertSpeed(tgt_speed);
798 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
799 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
802 if (lead_dist < fabs(2*speed)) {
803 //don't skip over the waypoint
804 lead_dist = fabs(2*speed);
805 //cerr << "Extending lead distance to " << lead_dist << endl;
808 //prev_dist_to_go = dist_to_go;
809 //if (dist_to_go < lead_dist)
810 // cerr << trafficRef->getCallSign() << " Distance : "
811 // << dist_to_go << ": Lead distance "
812 // << lead_dist << " " << curr->name
813 // << " Ground target speed " << groundTargetSpeed << endl;
815 // don't do bearing calculations for ground traffic
816 bearing = getBearing(fp->getBearing(pos, curr));
817 if (bearing < minBearing) {
818 minBearing = bearing;
819 if (minBearing < 10) {
822 if ((minBearing < 360.0) && (minBearing > 10.0)) {
823 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
829 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
830 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
831 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
832 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
835 if ((dist_to_go < lead_dist) ||
836 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
839 prev_dist_to_go = HUGE_VAL;
842 prev_dist_to_go = dist_to_go;
848 bool FGAIAircraft::aiTrafficVisible()
850 SGVec3d cartPos = SGVec3d::fromGeod(pos);
851 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
852 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
853 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
858 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
859 * in the case of an arrival.
865 //TODO the trafficRef is the right place for the method
866 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
867 // prepare routing from one airport to another
868 FGAirport * dep = trafficRef->getDepartureAirport();
869 FGAirport * arr = trafficRef->getArrivalAirport();
874 // This waypoint marks the fact that the aircraft has passed the initial taxi
875 // departure waypoint, so it can release the parking.
876 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
877 //cerr << "Passing waypoint : " << prev->getName() << endl;
878 if (prev->contains("PushBackPoint")) {
879 // clearing the parking assignment will release the gate
880 fp->setGate(ParkingAssignment());
882 //setTaxiClearanceRequest(true);
884 if (prev->contains("legend")) {
887 if (prev->contains(string("DepartureHold"))) {
888 //cerr << "Passing point DepartureHold" << endl;
889 scheduleForATCTowerDepartureControl(1);
891 if (prev->contains(string("Accel"))) {
894 //if (prev->contains(string("landing"))) {
895 // if (speed < _performance->vTaxi() * 2) {
896 // fp->shortenToFirst(2, "legend");
899 //if (prev->contains(string("final"))) {
901 // cerr << getCallSign() << " "
902 // << fp->getPreviousWaypoint()->getName()
903 // << ". Alt = " << altitude_ft
905 // << " horizontal speed " << speed
906 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
907 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
908 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
910 // This is the last taxi waypoint, and marks the the end of the flight plan
911 // so, the schedule should update and wait for the next departure time.
912 if (prev->contains("END")) {
913 time_t nextDeparture = trafficRef->getDepartureTime();
914 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
915 if (nextDeparture < (now+1200)) {
916 nextDeparture = now + 1200;
918 fp->setTime(nextDeparture);
926 * Check difference between target bearing and current heading and correct if necessary.
930 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
931 double calc_bearing = fp->getBearing(pos, curr);
932 //cerr << "Bearing = " << calc_bearing << endl;
935 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
938 if (finite(calc_bearing)) {
939 double hdg_error = calc_bearing - tgt_heading;
940 if (fabs(hdg_error) > 0.01) {
941 TurnTo( calc_bearing );
945 cerr << "calc_bearing is not a finite number : "
947 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
948 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
949 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
956 * Update the lead distance calculation if speed has changed sufficiently
957 * to prevent spinning (hopefully);
962 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
963 double speed_diff = speed - prevSpeed;
965 if (fabs(speed_diff) > 10) {
967 //assertSpeed(speed);
969 fp->setLeadDistance(speed, tgt_heading, curr, next);
976 * Update target values (heading, alt, speed) depending on flight plan or control properties
978 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
979 if (fp) // AI object has a flightplan
981 //TODO make this a function of AIBase
982 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
983 //cerr << "UpateTArgetValues() " << endl;
984 ProcessFlightPlan(dt, now);
986 // Do execute Ground elev for inactive aircraft, so they
987 // Are repositioned to the correct ground altitude when the user flies within visibility range.
988 // In addition, check whether we are out of user range, so this aircraft
991 Transform(); // make sure aip is initialized.
995 pos.setElevationFt(altitude_ft);
998 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
999 aiOutOfSight = !aiTrafficVisible();
1002 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1003 aiOutOfSight = true;
1007 timeElapsed = now - fp->getStartTime();
1008 flightplanActive = fp->isActive(now);
1010 // no flight plan, update target heading, speed, and altitude
1011 // from control properties. These default to the initial
1012 // settings in the config file, but can be changed "on the
1014 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1015 if ( lat_mode == "roll" ) {
1017 = props->getDoubleValue("controls/flight/target-roll" );
1021 = props->getDoubleValue("controls/flight/target-hdg" );
1026 = props->getStringValue("controls/flight/longitude-mode");
1027 if ( lon_mode == "alt" ) {
1028 double alt = props->getDoubleValue("controls/flight/target-alt" );
1032 = props->getDoubleValue("controls/flight/target-pitch" );
1036 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1040 void FGAIAircraft::updateHeading() {
1041 // adjust heading based on current bank angle
1046 // double turnConstant;
1048 // turnConstant = 0.0088362;
1050 // turnConstant = 0.088362;
1051 // If on ground, calculate heading change directly
1053 double headingDiff = fabs(hdg-tgt_heading);
1054 // double bank_sense = 0.0;
1056 double diff = fabs(hdg - tgt_heading);
1058 diff = fabs(diff - 360);
1060 double sum = hdg + diff;
1063 if (fabs(sum - tgt_heading) < 1.0) {
1064 bank_sense = 1.0; // right turn
1066 bank_sense = -1.0; // left turn
1068 if (headingDiff > 180)
1069 headingDiff = fabs(headingDiff - 360);
1070 double sum = hdg + headingDiff;
1073 if (fabs(sum - tgt_heading) > 0.0001) {
1074 // bank_sense = -1.0;
1076 // bank_sense = 1.0;
1079 // cerr << trafficRef->getCallSign() << " Heading "
1080 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1081 //if (headingDiff > 60) {
1082 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1083 //assertSpeed(groundTargetSpeed);
1084 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1086 // groundTargetSpeed = tgt_speed;
1088 if (sign(groundTargetSpeed) != sign(tgt_speed))
1089 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1090 //assertSpeed(groundTargetSpeed);
1091 // 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.
1093 if (headingDiff > 30.0) {
1094 // invert if pushed backward
1095 headingChangeRate += 10.0 * dt * sign(roll);
1097 // Clamp the maximum steering rate to 30 degrees per second,
1098 // But only do this when the heading error is decreasing.
1099 if ((headingDiff < headingError)) {
1100 if (headingChangeRate > 30)
1101 headingChangeRate = 30;
1102 else if (headingChangeRate < -30)
1103 headingChangeRate = -30;
1107 if (fabs(headingChangeRate) > headingDiff)
1108 headingChangeRate = headingDiff*sign(roll);
1110 headingChangeRate += dt * sign(roll);
1115 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1116 headingError = headingDiff;
1117 if (fabs(headingError) < 1.0) {
1121 if (fabs(speed) > 1.0) {
1122 turn_radius_ft = 0.088362 * speed * speed
1123 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1125 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1126 turn_radius_ft = 1.0;
1128 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1129 double dist_covered_ft = speed * 1.686 * dt;
1130 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1131 hdg += alpha * sign(roll);
1133 while ( hdg > 360.0 ) {
1137 while ( hdg < 0.0) {
1145 void FGAIAircraft::updateBankAngleTarget() {
1146 // adjust target bank angle if heading lock engaged
1148 double bank_sense = 0.0;
1149 double diff = fabs(hdg - tgt_heading);
1151 diff = fabs(diff - 360);
1153 double sum = hdg + diff;
1156 if (fabs(sum - tgt_heading) < 1.0) {
1157 bank_sense = 1.0; // right turn
1159 bank_sense = -1.0; // left turn
1161 if (diff < _performance->maximumBankAngle()) {
1162 tgt_roll = diff * bank_sense;
1164 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1166 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1167 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1168 // The only way to resolve this is to make them slow down.
1174 void FGAIAircraft::updateVerticalSpeedTarget() {
1175 // adjust target Altitude, based on ground elevation when on ground
1179 } else if (alt_lock) {
1180 // find target vertical speed
1182 if (altitude_ft < tgt_altitude_ft) {
1183 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1185 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1188 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1189 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1190 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1191 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1192 //cerr << "Target vs before : " << tgt_vs;
1193 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1194 double min_vs = 100;
1195 if (tgt_altitude_ft < altitude_ft)
1197 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1198 && (fabs(max_vs) < fabs(tgt_vs)))
1201 if (fabs(tgt_vs) < fabs(min_vs))
1203 //cerr << "target vs : after " << tgt_vs << endl;
1210 void FGAIAircraft::updatePitchAngleTarget() {
1211 // if on ground and above vRotate -> initial rotation
1212 if (onGround() && (speed > _performance->vRotate()))
1213 tgt_pitch = 8.0; // some rough B737 value
1215 //TODO pitch angle on approach and landing
1217 // match pitch angle to vertical speed
1218 else if (tgt_vs > 0) {
1219 tgt_pitch = tgt_vs * 0.005;
1221 tgt_pitch = tgt_vs * 0.002;
1225 const string& FGAIAircraft::atGate()
1227 if ((fp->getLeg() < 3) && trafficRef) {
1228 if (fp->getParkingGate()) {
1229 return fp->getParkingGate()->ident();
1233 static const string empty;
1237 void FGAIAircraft::handleATCRequests() {
1238 //TODO implement NullController for having no ATC to save the conditionals
1240 controller->updateAircraftInformation(getID(),
1241 pos.getLatitudeDeg(),
1242 pos.getLongitudeDeg(),
1246 processATC(controller->getInstruction(getID()));
1248 if (towerController) {
1249 towerController->updateAircraftInformation(getID(),
1250 pos.getLatitudeDeg(),
1251 pos.getLongitudeDeg(),
1258 void FGAIAircraft::updateActualState() {
1259 //update current state
1260 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1261 double distance = speed * SG_KT_TO_MPS * dt;
1262 pos = SGGeodesy::direct(pos, hdg, distance);
1266 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1268 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1269 //assertSpeed(speed);
1271 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1273 // adjust altitude (meters) based on current vertical speed (fpm)
1274 altitude_ft += vs / 60.0 * dt;
1275 pos.setElevationFt(altitude_ft);
1277 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1278 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1281 void FGAIAircraft::updateSecondaryTargetValues() {
1282 // derived target state values
1283 updateBankAngleTarget();
1284 updateVerticalSpeedTarget();
1285 updatePitchAngleTarget();
1287 //TODO calculate wind correction angle (tgt_yaw)
1291 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1292 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1293 if (curr->getName() == string("BOD")) {
1294 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1295 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1296 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1298 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1299 double descentTimeNeeded = verticalDistance / descentRate;
1300 double distanceCovered = descentSpeed * descentTimeNeeded;
1302 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1303 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1304 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1305 cerr << "Descent rate : " << descentRate << endl;
1306 cerr << "Descent speed : " << descentSpeed << endl;
1307 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1308 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1309 cerr << "DistanceCovered : " << distanceCovered << endl;
1311 //cerr << "Distance = " << distance << endl;
1312 distance = distanceCovered;
1313 if (dist < distanceCovered) {
1314 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1326 void FGAIAircraft::resetPositionFromFlightPlan()
1328 // the one behind you
1329 FGAIWaypoint* prev = 0;
1331 FGAIWaypoint* curr = 0;
1333 FGAIWaypoint* next = 0;
1335 prev = fp->getPreviousWaypoint();
1336 curr = fp->getCurrentWaypoint();
1337 next = fp->getNextWaypoint();
1339 setLatitude(prev->getLatitude());
1340 setLongitude(prev->getLongitude());
1341 double tgt_heading = fp->getBearing(curr, next);
1342 setHeading(tgt_heading);
1343 setAltitude(prev->getAltitude());
1344 setSpeed(prev->getSpeed());
1347 double FGAIAircraft::getBearing(double crse)
1349 double hdgDiff = fabs(hdg-crse);
1351 hdgDiff = fabs(hdgDiff - 360);
1355 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1356 FGAIWaypoint* curr = 0;
1357 curr = fp->getCurrentWaypoint();
1359 // don't recalculate tracklength unless the start/stop waypoint has changed
1361 ((curr->getName() != trackCache.startWptName)||
1362 (wptName != trackCache.finalWptName)))
1364 trackCache.remainingLength = fp->checkTrackLength(wptName);
1365 trackCache.startWptName = curr->getName();
1366 trackCache.finalWptName = wptName;
1368 double tracklength = trackCache.remainingLength;
1369 if (tracklength > 0.1) {
1370 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1374 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1375 time_t arrivalTime = fp->getArrivalTime();
1377 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1378 time_t secondsToGo = arrivalTime - now;
1379 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1380 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1382 return (ete - secondsToGo); // Positive when we're too slow...
1385 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1387 double delta = target - cur;
1388 double maxDelta = maxDeltaSec * dt;
1390 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1391 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1394 // drive various properties in a semi-realistic fashion.
1395 void FGAIAircraft::updateModelProperties(double dt)
1401 SGPropertyNode* gear = props->getChild("gear", 0, true);
1402 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1403 if (!gear->hasValue("gear/position-norm")) {
1404 gear->setDoubleValue("gear/position-norm", targetGearPos);
1407 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1408 if (gearPosNorm != targetGearPos) {
1409 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1410 if (gearPosNorm < 0.001) {
1412 } else if (gearPosNorm > 0.999) {
1416 for (int i=0; i<6; ++i) {
1417 SGPropertyNode* g = gear->getChild("gear", i, true);
1418 g->setDoubleValue("position-norm", gearPosNorm);
1419 } // of gear setting loop
1420 } // of gear in-transit
1422 // double flapPosNorm = props->getDoubleValue();