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)
240 if (flightplan.empty()) {
241 SG_LOG(SG_AI, SG_WARN, "setFlightPlan: empty flight plan");
244 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
245 if (fp->isValidPlan()) {
246 fp->setRepeat(repeat);
249 SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan);
255 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
261 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
263 // the one behind you
264 FGAIWaypoint* prev = 0;
266 FGAIWaypoint* curr = 0;
268 FGAIWaypoint* next = 0;
270 prev = fp->getPreviousWaypoint();
271 curr = fp->getCurrentWaypoint();
272 next = fp->getNextWaypoint();
276 ///////////////////////////////////////////////////////////////////////////
277 // Initialize the flightplan
278 //////////////////////////////////////////////////////////////////////////
280 handleFirstWaypoint();
282 } // end of initialization
283 if (! fpExecutable(now))
287 double distanceToDescent;
288 if(reachedEndOfCruise(distanceToDescent)) {
289 if (!loadNextLeg(distanceToDescent)) {
293 prev = fp->getPreviousWaypoint();
294 curr = fp->getCurrentWaypoint();
295 next = fp->getNextWaypoint();
303 if (! leadPointReached(curr)) {
304 controlHeading(curr);
305 controlSpeed(curr, next);
309 cerr << getCallSign()
310 << ": verifying lead distance to waypoint : "
311 << fp->getCurrentWaypoint()->name << " "
312 << fp->getLeadDistance() << ". Distance to go "
313 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
314 << ". Target speed = "
316 << ". Current speed = "
318 << ". Minimum Bearing " << minBearing
322 if (curr->isFinished()) //end of the flight plan
332 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
333 tgt_heading = fp->getBearing(curr, next);
337 //TODO let the fp handle this (loading of next leg)
338 fp->IncrementWaypoint( trafficRef != 0 );
339 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
340 if (!loadNextLeg()) {
345 prev = fp->getPreviousWaypoint();
346 curr = fp->getCurrentWaypoint();
347 next = fp->getNextWaypoint();
349 // Now that we have incremented the waypoints, excute some traffic manager specific code
351 //TODO isn't this best executed right at the beginning?
352 if (! aiTrafficVisible()) {
357 if (! handleAirportEndPoints(prev, now)) {
362 announcePositionToController();
367 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
371 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
373 tgt_altitude_ft = prev->getAltitude();
374 if (curr->getCrossat() > -1000.0) {
376 // Distance to go in meters
377 double vert_dist_ft = curr->getCrossat() - altitude_ft;
378 double err_dist = prev->getCrossat() - altitude_ft;
379 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
380 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
383 tgt_altitude_ft = curr->getCrossat();
388 AccelTo(prev->getSpeed());
389 hdg_lock = alt_lock = true;
390 no_roll = prev->getOn_ground();
394 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
396 // err is negative when we passed too high
397 double vert_m = vert_ft * SG_FEET_TO_METER;
398 //double err_m = err * SG_FEET_TO_METER;
399 //double angle = atan2(vert_m, dist_m);
400 double speedMs = (speed * SG_NM_TO_METER) / 3600;
401 //double vs = cos(angle) * speedMs; // Now in m/s
403 //cerr << "Error term = " << err_m << endl;
405 vs = ((vert_m) / dist_m) * speedMs;
407 // Convert to feet per minute
408 vs *= (SG_METER_TO_FEET * 60);
409 //if (getCallSign() == "LUFTHANSA2002")
410 //if (fabs(vs) > 100000) {
411 // if (getCallSign() == "LUFTHANSA2057") {
412 // 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;
413 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
414 // // / 6076.0 / speed*60.0);
420 void FGAIAircraft::assertSpeed(double speed)
422 if ((speed < -50) || (speed > 1000)) {
423 cerr << getCallSign() << " "
424 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
425 << "Departure airport " << trafficRef->getDepartureAirport() << " "
426 << "Leg " << fp->getLeg() << " "
427 << "target_speed << " << tgt_speed << " "
428 << "speedFraction << " << speedFraction << " "
429 << "Currecnt speed << " << speed << " "
437 void FGAIAircraft::checkTcas(void)
439 if (props->getIntValue("tcas/threat-level",0)==3)
441 int RASense = props->getIntValue("tcas/ra-sense",0);
442 if ((RASense>0)&&(tgt_vs<4000))
448 // downward RA: descend!
449 if (altitude_ft < 1000)
451 // too low: level off
464 void FGAIAircraft::initializeFlightPlan() {
467 const char * FGAIAircraft::_getTransponderCode() const {
468 return transponderCode.c_str();
471 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
472 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
474 bool FGAIAircraft::loadNextLeg(double distance) {
477 if ((leg = fp->getLeg()) == 9) {
478 if (!trafficRef->next()) {
481 setCallSign(trafficRef->getCallSign());
486 FGAirport *dep = trafficRef->getDepartureAirport();
487 FGAirport *arr = trafficRef->getArrivalAirport();
492 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
499 trafficRef->getSpeed(),
503 trafficRef->getRadius(),
504 trafficRef->getFlightType(),
508 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
514 // Note: This code is copied from David Luff's AILocalTraffic
515 // Warning - ground elev determination is CPU intensive
516 // Either this function or the logic of how often it is called
517 // will almost certainly change.
519 void FGAIAircraft::getGroundElev(double dt) {
522 if (!needGroundElevation())
524 // Update minimally every three secs, but add some randomness
525 // to prevent all AI objects doing this in synchrony
526 if (dt_elev_count < (3.0) + (rand() % 10))
531 // Only do the proper hitlist stuff if we are within visible range of the viewer.
533 double visibility_meters = fgGetDouble("/environment/visibility-m");
534 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
538 double range = 500.0;
539 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
542 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
544 tgt_altitude_ft = alt * SG_METER_TO_FEET;
547 // aircraft is stationary and we obtained altitude for this spot - we're done.
548 _needsGroundElevation = false;
556 void FGAIAircraft::doGroundAltitude() {
557 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
560 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
562 altitude_ft = (tgt_altitude_ft + groundOffset);
564 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
570 void FGAIAircraft::announcePositionToController() {
575 int leg = fp->getLeg();
576 if (!fp->getCurrentWaypoint()) {
577 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
578 // throw an exception so this aircraft gets killed by the AIManager.
579 throw sg_exception("bad AI flight plan");
582 // Note that leg has been incremented after creating the current leg, so we should use
583 // leg numbers here that are one higher than the number that is used to create the leg
584 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
585 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
586 // the original leg numbers here!
588 case 1: // Startup and Push back
589 if (trafficRef->getDepartureAirport()->getDynamics())
590 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
592 case 2: // Taxiing to runway
593 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
594 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
596 case 3: //Take off tower controller
597 if (trafficRef->getDepartureAirport()->getDynamics()) {
598 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
601 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
605 if (trafficRef->getDepartureAirport()->getDynamics()) {
606 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
609 case 8: // Taxiing for parking
610 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
611 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
618 if ((controller != prevController) && (prevController != 0)) {
619 prevController->signOff(getID());
621 prevController = controller;
623 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
624 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
625 trafficRef->getRadius(), leg, this);
629 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
630 if (!takeOffStatus) {
631 int leg = fp->getLeg();
633 if (trafficRef->getDepartureAirport()->getDynamics()) {
634 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
636 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
638 if (towerController) {
639 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
640 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
641 trafficRef->getRadius(), leg, this);
642 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
646 takeOffStatus = state;
649 // Process ATC instructions and report back
651 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
652 if (instruction.getCheckForCircularWait()) {
653 // This is not exactly an elegant solution,
654 // but at least it gives me a chance to check
655 // if circular waits are resolved.
656 // For now, just take the offending aircraft
659 // a more proper way should be - of course - to
660 // let an offending aircraft take an evasive action
661 // for instance taxi back a little bit.
663 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
664 if (instruction.getHoldPattern ()) {}
667 if (instruction.getHoldPosition ()) {
675 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
678 // Change speed Instruction. This can only be excecuted when there is no
679 // Hold position instruction.
680 if (instruction.getChangeSpeed ()) {
682 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
683 AccelTo(instruction.getSpeed());
685 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
688 if (instruction.getChangeHeading ()) {
690 TurnTo(instruction.getHeading());
696 if (instruction.getChangeAltitude()) {}
701 void FGAIAircraft::handleFirstWaypoint() {
702 bool eraseWaypoints; //TODO YAGNI
705 eraseWaypoints = true;
707 eraseWaypoints = false;
710 FGAIWaypoint* prev = 0; // the one behind you
711 FGAIWaypoint* curr = 0; // the one ahead
712 FGAIWaypoint* next = 0;// the next plus 1
716 //TODO fp should handle this
717 fp->IncrementWaypoint(eraseWaypoints);
718 if (!(fp->getNextWaypoint()) && trafficRef)
719 if (!loadNextLeg()) {
724 prev = fp->getPreviousWaypoint(); //first waypoint
725 curr = fp->getCurrentWaypoint(); //second waypoint
726 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
728 setLatitude(prev->getLatitude());
729 setLongitude(prev->getLongitude());
730 setSpeed(prev->getSpeed());
731 setAltitude(prev->getAltitude());
733 if (prev->getSpeed() > 0.0)
734 setHeading(fp->getBearing(prev, curr));
736 setHeading(fp->getBearing(curr, prev));
738 // If next doesn't exist, as in incrementally created flightplans for
739 // AI/Trafficmanager created plans,
740 // Make sure lead distance is initialized otherwise
742 fp->setLeadDistance(speed, hdg, curr, next);
744 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
747 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
748 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
749 // / 6076.0 / prev->getSpeed()*60.0);
750 double vert_dist_ft = curr->getCrossat() - altitude_ft;
751 double err_dist = prev->getCrossat() - altitude_ft;
752 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
753 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
755 tgt_altitude_ft = curr->getCrossat();
758 tgt_altitude_ft = prev->getAltitude();
760 alt_lock = hdg_lock = true;
761 no_roll = prev->getOn_ground();
763 Transform(); // make sure aip is initialized.
764 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
766 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
768 // Make sure to announce the aircraft's position
769 announcePositionToController();
775 * Check Execution time (currently once every 100 ms)
776 * Add a bit of randomization to prevent the execution of all flight plans
777 * in synchrony, which can add significant periodic framerate flutter.
782 bool FGAIAircraft::fpExecutable(time_t now) {
783 double rand_exec_time = (rand() % 100) / 100;
784 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
789 * Check to see if we've reached the lead point for our next turn
794 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
795 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
797 //cerr << "2" << endl;
798 double lead_dist = fp->getLeadDistance();
799 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
800 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
801 tgt_speed = -(dist_to_go / 10.0);
802 if (tgt_speed > -0.5) {
805 //assertSpeed(tgt_speed);
806 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
807 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
810 if (lead_dist < fabs(2*speed)) {
811 //don't skip over the waypoint
812 lead_dist = fabs(2*speed);
813 //cerr << "Extending lead distance to " << lead_dist << endl;
816 //prev_dist_to_go = dist_to_go;
817 //if (dist_to_go < lead_dist)
818 // cerr << trafficRef->getCallSign() << " Distance : "
819 // << dist_to_go << ": Lead distance "
820 // << lead_dist << " " << curr->name
821 // << " Ground target speed " << groundTargetSpeed << endl;
823 // don't do bearing calculations for ground traffic
824 bearing = getBearing(fp->getBearing(pos, curr));
825 if (bearing < minBearing) {
826 minBearing = bearing;
827 if (minBearing < 10) {
830 if ((minBearing < 360.0) && (minBearing > 10.0)) {
831 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
837 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
838 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
839 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
840 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
843 if ((dist_to_go < lead_dist) ||
844 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
847 prev_dist_to_go = HUGE_VAL;
850 prev_dist_to_go = dist_to_go;
856 bool FGAIAircraft::aiTrafficVisible()
858 SGVec3d cartPos = SGVec3d::fromGeod(pos);
859 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
860 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
861 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
866 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
867 * in the case of an arrival.
873 //TODO the trafficRef is the right place for the method
874 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
875 // prepare routing from one airport to another
876 FGAirport * dep = trafficRef->getDepartureAirport();
877 FGAirport * arr = trafficRef->getArrivalAirport();
882 // This waypoint marks the fact that the aircraft has passed the initial taxi
883 // departure waypoint, so it can release the parking.
884 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
885 //cerr << "Passing waypoint : " << prev->getName() << endl;
886 if (prev->contains("PushBackPoint")) {
887 // clearing the parking assignment will release the gate
888 fp->setGate(ParkingAssignment());
890 //setTaxiClearanceRequest(true);
892 if (prev->contains("legend")) {
895 if (prev->contains(string("DepartureHold"))) {
896 //cerr << "Passing point DepartureHold" << endl;
897 scheduleForATCTowerDepartureControl(1);
899 if (prev->contains(string("Accel"))) {
902 //if (prev->contains(string("landing"))) {
903 // if (speed < _performance->vTaxi() * 2) {
904 // fp->shortenToFirst(2, "legend");
907 //if (prev->contains(string("final"))) {
909 // cerr << getCallSign() << " "
910 // << fp->getPreviousWaypoint()->getName()
911 // << ". Alt = " << altitude_ft
913 // << " horizontal speed " << speed
914 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
915 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
916 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
918 // This is the last taxi waypoint, and marks the the end of the flight plan
919 // so, the schedule should update and wait for the next departure time.
920 if (prev->contains("END")) {
921 time_t nextDeparture = trafficRef->getDepartureTime();
922 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
923 if (nextDeparture < (now+1200)) {
924 nextDeparture = now + 1200;
926 fp->setTime(nextDeparture);
934 * Check difference between target bearing and current heading and correct if necessary.
938 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
939 double calc_bearing = fp->getBearing(pos, curr);
940 //cerr << "Bearing = " << calc_bearing << endl;
943 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
946 if (finite(calc_bearing)) {
947 double hdg_error = calc_bearing - tgt_heading;
948 if (fabs(hdg_error) > 0.01) {
949 TurnTo( calc_bearing );
953 cerr << "calc_bearing is not a finite number : "
955 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
956 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
957 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
964 * Update the lead distance calculation if speed has changed sufficiently
965 * to prevent spinning (hopefully);
970 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
971 double speed_diff = speed - prevSpeed;
973 if (fabs(speed_diff) > 10) {
975 //assertSpeed(speed);
977 fp->setLeadDistance(speed, tgt_heading, curr, next);
984 * Update target values (heading, alt, speed) depending on flight plan or control properties
986 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
987 if (fp) // AI object has a flightplan
989 //TODO make this a function of AIBase
990 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
991 //cerr << "UpateTArgetValues() " << endl;
992 ProcessFlightPlan(dt, now);
994 // Do execute Ground elev for inactive aircraft, so they
995 // Are repositioned to the correct ground altitude when the user flies within visibility range.
996 // In addition, check whether we are out of user range, so this aircraft
999 Transform(); // make sure aip is initialized.
1003 pos.setElevationFt(altitude_ft);
1006 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
1007 aiOutOfSight = !aiTrafficVisible();
1010 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1011 aiOutOfSight = true;
1015 timeElapsed = now - fp->getStartTime();
1016 flightplanActive = fp->isActive(now);
1018 // no flight plan, update target heading, speed, and altitude
1019 // from control properties. These default to the initial
1020 // settings in the config file, but can be changed "on the
1022 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1023 if ( lat_mode == "roll" ) {
1025 = props->getDoubleValue("controls/flight/target-roll" );
1029 = props->getDoubleValue("controls/flight/target-hdg" );
1034 = props->getStringValue("controls/flight/longitude-mode");
1035 if ( lon_mode == "alt" ) {
1036 double alt = props->getDoubleValue("controls/flight/target-alt" );
1040 = props->getDoubleValue("controls/flight/target-pitch" );
1044 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1048 void FGAIAircraft::updateHeading() {
1049 // adjust heading based on current bank angle
1054 // double turnConstant;
1056 // turnConstant = 0.0088362;
1058 // turnConstant = 0.088362;
1059 // If on ground, calculate heading change directly
1061 double headingDiff = fabs(hdg-tgt_heading);
1062 // double bank_sense = 0.0;
1064 double diff = fabs(hdg - tgt_heading);
1066 diff = fabs(diff - 360);
1068 double sum = hdg + diff;
1071 if (fabs(sum - tgt_heading) < 1.0) {
1072 bank_sense = 1.0; // right turn
1074 bank_sense = -1.0; // left turn
1076 if (headingDiff > 180)
1077 headingDiff = fabs(headingDiff - 360);
1078 double sum = hdg + headingDiff;
1081 if (fabs(sum - tgt_heading) > 0.0001) {
1082 // bank_sense = -1.0;
1084 // bank_sense = 1.0;
1087 // cerr << trafficRef->getCallSign() << " Heading "
1088 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1089 //if (headingDiff > 60) {
1090 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1091 //assertSpeed(groundTargetSpeed);
1092 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1094 // groundTargetSpeed = tgt_speed;
1096 if (sign(groundTargetSpeed) != sign(tgt_speed))
1097 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1098 //assertSpeed(groundTargetSpeed);
1099 // 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.
1101 if (headingDiff > 30.0) {
1102 // invert if pushed backward
1103 headingChangeRate += 10.0 * dt * sign(roll);
1105 // Clamp the maximum steering rate to 30 degrees per second,
1106 // But only do this when the heading error is decreasing.
1107 if ((headingDiff < headingError)) {
1108 if (headingChangeRate > 30)
1109 headingChangeRate = 30;
1110 else if (headingChangeRate < -30)
1111 headingChangeRate = -30;
1115 if (fabs(headingChangeRate) > headingDiff)
1116 headingChangeRate = headingDiff*sign(roll);
1118 headingChangeRate += dt * sign(roll);
1123 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1124 headingError = headingDiff;
1125 if (fabs(headingError) < 1.0) {
1129 if (fabs(speed) > 1.0) {
1130 turn_radius_ft = 0.088362 * speed * speed
1131 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1133 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1134 turn_radius_ft = 1.0;
1136 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1137 double dist_covered_ft = speed * 1.686 * dt;
1138 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1139 hdg += alpha * sign(roll);
1141 while ( hdg > 360.0 ) {
1145 while ( hdg < 0.0) {
1153 void FGAIAircraft::updateBankAngleTarget() {
1154 // adjust target bank angle if heading lock engaged
1156 double bank_sense = 0.0;
1157 double diff = fabs(hdg - tgt_heading);
1159 diff = fabs(diff - 360);
1161 double sum = hdg + diff;
1164 if (fabs(sum - tgt_heading) < 1.0) {
1165 bank_sense = 1.0; // right turn
1167 bank_sense = -1.0; // left turn
1169 if (diff < _performance->maximumBankAngle()) {
1170 tgt_roll = diff * bank_sense;
1172 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1174 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1175 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1176 // The only way to resolve this is to make them slow down.
1182 void FGAIAircraft::updateVerticalSpeedTarget() {
1183 // adjust target Altitude, based on ground elevation when on ground
1187 } else if (alt_lock) {
1188 // find target vertical speed
1190 if (altitude_ft < tgt_altitude_ft) {
1191 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1193 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1196 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1197 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1198 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1199 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1200 //cerr << "Target vs before : " << tgt_vs;
1201 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1202 double min_vs = 100;
1203 if (tgt_altitude_ft < altitude_ft)
1205 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1206 && (fabs(max_vs) < fabs(tgt_vs)))
1209 if (fabs(tgt_vs) < fabs(min_vs))
1211 //cerr << "target vs : after " << tgt_vs << endl;
1218 void FGAIAircraft::updatePitchAngleTarget() {
1219 // if on ground and above vRotate -> initial rotation
1220 if (onGround() && (speed > _performance->vRotate()))
1221 tgt_pitch = 8.0; // some rough B737 value
1223 //TODO pitch angle on approach and landing
1225 // match pitch angle to vertical speed
1226 else if (tgt_vs > 0) {
1227 tgt_pitch = tgt_vs * 0.005;
1229 tgt_pitch = tgt_vs * 0.002;
1233 const string& FGAIAircraft::atGate()
1235 if ((fp->getLeg() < 3) && trafficRef) {
1236 if (fp->getParkingGate()) {
1237 return fp->getParkingGate()->ident();
1241 static const string empty;
1245 void FGAIAircraft::handleATCRequests() {
1246 //TODO implement NullController for having no ATC to save the conditionals
1248 controller->updateAircraftInformation(getID(),
1249 pos.getLatitudeDeg(),
1250 pos.getLongitudeDeg(),
1254 processATC(controller->getInstruction(getID()));
1256 if (towerController) {
1257 towerController->updateAircraftInformation(getID(),
1258 pos.getLatitudeDeg(),
1259 pos.getLongitudeDeg(),
1266 void FGAIAircraft::updateActualState() {
1267 //update current state
1268 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1269 double distance = speed * SG_KT_TO_MPS * dt;
1270 pos = SGGeodesy::direct(pos, hdg, distance);
1274 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1276 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1277 //assertSpeed(speed);
1279 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1281 // adjust altitude (meters) based on current vertical speed (fpm)
1282 altitude_ft += vs / 60.0 * dt;
1283 pos.setElevationFt(altitude_ft);
1285 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1286 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1289 void FGAIAircraft::updateSecondaryTargetValues() {
1290 // derived target state values
1291 updateBankAngleTarget();
1292 updateVerticalSpeedTarget();
1293 updatePitchAngleTarget();
1295 //TODO calculate wind correction angle (tgt_yaw)
1299 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1300 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1301 if (curr->getName() == string("BOD")) {
1302 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1303 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1304 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1306 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1307 double descentTimeNeeded = verticalDistance / descentRate;
1308 double distanceCovered = descentSpeed * descentTimeNeeded;
1310 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1311 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1312 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1313 cerr << "Descent rate : " << descentRate << endl;
1314 cerr << "Descent speed : " << descentSpeed << endl;
1315 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1316 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1317 cerr << "DistanceCovered : " << distanceCovered << endl;
1319 //cerr << "Distance = " << distance << endl;
1320 distance = distanceCovered;
1321 if (dist < distanceCovered) {
1322 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1334 void FGAIAircraft::resetPositionFromFlightPlan()
1336 // the one behind you
1337 FGAIWaypoint* prev = 0;
1339 FGAIWaypoint* curr = 0;
1341 FGAIWaypoint* next = 0;
1343 prev = fp->getPreviousWaypoint();
1344 curr = fp->getCurrentWaypoint();
1345 next = fp->getNextWaypoint();
1347 setLatitude(prev->getLatitude());
1348 setLongitude(prev->getLongitude());
1349 double tgt_heading = fp->getBearing(curr, next);
1350 setHeading(tgt_heading);
1351 setAltitude(prev->getAltitude());
1352 setSpeed(prev->getSpeed());
1355 double FGAIAircraft::getBearing(double crse)
1357 double hdgDiff = fabs(hdg-crse);
1359 hdgDiff = fabs(hdgDiff - 360);
1363 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1364 FGAIWaypoint* curr = 0;
1365 curr = fp->getCurrentWaypoint();
1367 // don't recalculate tracklength unless the start/stop waypoint has changed
1369 ((curr->getName() != trackCache.startWptName)||
1370 (wptName != trackCache.finalWptName)))
1372 trackCache.remainingLength = fp->checkTrackLength(wptName);
1373 trackCache.startWptName = curr->getName();
1374 trackCache.finalWptName = wptName;
1376 double tracklength = trackCache.remainingLength;
1377 if (tracklength > 0.1) {
1378 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1382 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1383 time_t arrivalTime = fp->getArrivalTime();
1385 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1386 time_t secondsToGo = arrivalTime - now;
1387 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1388 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1390 return (ete - secondsToGo); // Positive when we're too slow...
1393 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1395 double delta = target - cur;
1396 double maxDelta = maxDeltaSec * dt;
1398 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1399 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1402 // drive various properties in a semi-realistic fashion.
1403 void FGAIAircraft::updateModelProperties(double dt)
1409 SGPropertyNode* gear = props->getChild("gear", 0, true);
1410 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1411 if (!gear->hasValue("gear/position-norm")) {
1412 gear->setDoubleValue("gear/position-norm", targetGearPos);
1415 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1416 if (gearPosNorm != targetGearPos) {
1417 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1418 if (gearPosNorm < 0.001) {
1420 } else if (gearPosNorm > 0.999) {
1424 for (int i=0; i<6; ++i) {
1425 SGPropertyNode* g = gear->getChild("gear", i, true);
1426 g->setDoubleValue("position-norm", gearPosNorm);
1427 } // of gear setting loop
1428 } // of gear in-transit
1430 // double flapPosNorm = props->getDoubleValue();