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 // this is the case for Nasal-scripted aircraft
245 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
246 if (fp->isValidPlan()) {
247 fp->setRepeat(repeat);
250 SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan);
256 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f)
263 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
265 // the one behind you
266 FGAIWaypoint* prev = 0;
268 FGAIWaypoint* curr = 0;
270 FGAIWaypoint* next = 0;
272 prev = fp->getPreviousWaypoint();
273 curr = fp->getCurrentWaypoint();
274 next = fp->getNextWaypoint();
278 ///////////////////////////////////////////////////////////////////////////
279 // Initialize the flightplan
280 //////////////////////////////////////////////////////////////////////////
282 handleFirstWaypoint();
284 } // end of initialization
285 if (! fpExecutable(now))
289 double distanceToDescent;
290 if(reachedEndOfCruise(distanceToDescent)) {
291 if (!loadNextLeg(distanceToDescent)) {
295 prev = fp->getPreviousWaypoint();
296 curr = fp->getCurrentWaypoint();
297 next = fp->getNextWaypoint();
305 if (! leadPointReached(curr)) {
306 controlHeading(curr);
307 controlSpeed(curr, next);
311 cerr << getCallSign()
312 << ": verifying lead distance to waypoint : "
313 << fp->getCurrentWaypoint()->name << " "
314 << fp->getLeadDistance() << ". Distance to go "
315 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
316 << ". Target speed = "
318 << ". Current speed = "
320 << ". Minimum Bearing " << minBearing
324 if (curr->isFinished()) //end of the flight plan
334 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
335 tgt_heading = fp->getBearing(curr, next);
339 //TODO let the fp handle this (loading of next leg)
340 fp->IncrementWaypoint( trafficRef != 0 );
341 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
342 if (!loadNextLeg()) {
347 prev = fp->getPreviousWaypoint();
348 curr = fp->getCurrentWaypoint();
349 next = fp->getNextWaypoint();
351 // Now that we have incremented the waypoints, excute some traffic manager specific code
353 //TODO isn't this best executed right at the beginning?
354 if (! aiTrafficVisible()) {
359 if (! handleAirportEndPoints(prev, now)) {
364 announcePositionToController();
369 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
373 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
375 tgt_altitude_ft = prev->getAltitude();
376 if (curr->getCrossat() > -1000.0) {
378 // Distance to go in meters
379 double vert_dist_ft = curr->getCrossat() - altitude_ft;
380 double err_dist = prev->getCrossat() - altitude_ft;
381 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
382 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
385 tgt_altitude_ft = curr->getCrossat();
390 AccelTo(prev->getSpeed());
391 hdg_lock = alt_lock = true;
392 no_roll = prev->getOn_ground();
396 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
398 // err is negative when we passed too high
399 double vert_m = vert_ft * SG_FEET_TO_METER;
400 //double err_m = err * SG_FEET_TO_METER;
401 //double angle = atan2(vert_m, dist_m);
402 double speedMs = (speed * SG_NM_TO_METER) / 3600;
403 //double vs = cos(angle) * speedMs; // Now in m/s
405 //cerr << "Error term = " << err_m << endl;
407 vs = ((vert_m) / dist_m) * speedMs;
409 // Convert to feet per minute
410 vs *= (SG_METER_TO_FEET * 60);
411 //if (getCallSign() == "LUFTHANSA2002")
412 //if (fabs(vs) > 100000) {
413 // if (getCallSign() == "LUFTHANSA2057") {
414 // 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;
415 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
416 // // / 6076.0 / speed*60.0);
422 void FGAIAircraft::assertSpeed(double speed)
424 if ((speed < -50) || (speed > 1000)) {
425 cerr << getCallSign() << " "
426 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
427 << "Departure airport " << trafficRef->getDepartureAirport() << " "
428 << "Leg " << fp->getLeg() << " "
429 << "target_speed << " << tgt_speed << " "
430 << "speedFraction << " << speedFraction << " "
431 << "Currecnt speed << " << speed << " "
439 void FGAIAircraft::checkTcas(void)
441 if (props->getIntValue("tcas/threat-level",0)==3)
443 int RASense = props->getIntValue("tcas/ra-sense",0);
444 if ((RASense>0)&&(tgt_vs<4000))
450 // downward RA: descend!
451 if (altitude_ft < 1000)
453 // too low: level off
466 void FGAIAircraft::initializeFlightPlan() {
469 const char * FGAIAircraft::_getTransponderCode() const {
470 return transponderCode.c_str();
473 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
474 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
476 bool FGAIAircraft::loadNextLeg(double distance) {
479 if ((leg = fp->getLeg()) == 9) {
480 if (!trafficRef->next()) {
483 setCallSign(trafficRef->getCallSign());
488 FGAirport *dep = trafficRef->getDepartureAirport();
489 FGAirport *arr = trafficRef->getArrivalAirport();
494 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
501 trafficRef->getSpeed(),
505 trafficRef->getRadius(),
506 trafficRef->getFlightType(),
510 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
516 // Note: This code is copied from David Luff's AILocalTraffic
517 // Warning - ground elev determination is CPU intensive
518 // Either this function or the logic of how often it is called
519 // will almost certainly change.
521 void FGAIAircraft::getGroundElev(double dt) {
524 if (!needGroundElevation())
526 // Update minimally every three secs, but add some randomness
527 // to prevent all AI objects doing this in synchrony
528 if (dt_elev_count < (3.0) + (rand() % 10))
533 // Only do the proper hitlist stuff if we are within visible range of the viewer.
535 double visibility_meters = fgGetDouble("/environment/visibility-m");
536 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
540 double range = 500.0;
541 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
544 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
546 tgt_altitude_ft = alt * SG_METER_TO_FEET;
549 // aircraft is stationary and we obtained altitude for this spot - we're done.
550 _needsGroundElevation = false;
558 void FGAIAircraft::doGroundAltitude() {
559 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
562 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
564 altitude_ft = (tgt_altitude_ft + groundOffset);
566 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
572 void FGAIAircraft::announcePositionToController() {
577 int leg = fp->getLeg();
578 if (!fp->getCurrentWaypoint()) {
579 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
580 // throw an exception so this aircraft gets killed by the AIManager.
581 throw sg_exception("bad AI flight plan");
584 // Note that leg has been incremented after creating the current leg, so we should use
585 // leg numbers here that are one higher than the number that is used to create the leg
586 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
587 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
588 // the original leg numbers here!
590 case 1: // Startup and Push back
591 if (trafficRef->getDepartureAirport()->getDynamics())
592 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
594 case 2: // Taxiing to runway
595 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
596 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
598 case 3: //Take off tower controller
599 if (trafficRef->getDepartureAirport()->getDynamics()) {
600 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
603 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
607 if (trafficRef->getDepartureAirport()->getDynamics()) {
608 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
611 case 8: // Taxiing for parking
612 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
613 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
620 if ((controller != prevController) && (prevController != 0)) {
621 prevController->signOff(getID());
623 prevController = controller;
625 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
626 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
627 trafficRef->getRadius(), leg, this);
631 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
632 if (!takeOffStatus) {
633 int leg = fp->getLeg();
635 if (trafficRef->getDepartureAirport()->getDynamics()) {
636 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
638 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
640 if (towerController) {
641 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
642 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
643 trafficRef->getRadius(), leg, this);
644 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
648 takeOffStatus = state;
651 // Process ATC instructions and report back
653 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
654 if (instruction.getCheckForCircularWait()) {
655 // This is not exactly an elegant solution,
656 // but at least it gives me a chance to check
657 // if circular waits are resolved.
658 // For now, just take the offending aircraft
661 // a more proper way should be - of course - to
662 // let an offending aircraft take an evasive action
663 // for instance taxi back a little bit.
665 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
666 if (instruction.getHoldPattern ()) {}
669 if (instruction.getHoldPosition ()) {
677 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
680 // Change speed Instruction. This can only be excecuted when there is no
681 // Hold position instruction.
682 if (instruction.getChangeSpeed ()) {
684 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
685 AccelTo(instruction.getSpeed());
687 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
690 if (instruction.getChangeHeading ()) {
692 TurnTo(instruction.getHeading());
698 if (instruction.getChangeAltitude()) {}
703 void FGAIAircraft::handleFirstWaypoint() {
704 bool eraseWaypoints; //TODO YAGNI
707 eraseWaypoints = true;
709 eraseWaypoints = false;
712 FGAIWaypoint* prev = 0; // the one behind you
713 FGAIWaypoint* curr = 0; // the one ahead
714 FGAIWaypoint* next = 0;// the next plus 1
718 //TODO fp should handle this
719 fp->IncrementWaypoint(eraseWaypoints);
720 if (!(fp->getNextWaypoint()) && trafficRef)
721 if (!loadNextLeg()) {
726 prev = fp->getPreviousWaypoint(); //first waypoint
727 curr = fp->getCurrentWaypoint(); //second waypoint
728 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
730 setLatitude(prev->getLatitude());
731 setLongitude(prev->getLongitude());
732 setSpeed(prev->getSpeed());
733 setAltitude(prev->getAltitude());
735 if (prev->getSpeed() > 0.0)
736 setHeading(fp->getBearing(prev, curr));
738 setHeading(fp->getBearing(curr, prev));
740 // If next doesn't exist, as in incrementally created flightplans for
741 // AI/Trafficmanager created plans,
742 // Make sure lead distance is initialized otherwise
744 fp->setLeadDistance(speed, hdg, curr, next);
746 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
749 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
750 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
751 // / 6076.0 / prev->getSpeed()*60.0);
752 double vert_dist_ft = curr->getCrossat() - altitude_ft;
753 double err_dist = prev->getCrossat() - altitude_ft;
754 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
755 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
757 tgt_altitude_ft = curr->getCrossat();
760 tgt_altitude_ft = prev->getAltitude();
762 alt_lock = hdg_lock = true;
763 no_roll = prev->getOn_ground();
765 Transform(); // make sure aip is initialized.
766 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
768 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
770 // Make sure to announce the aircraft's position
771 announcePositionToController();
777 * Check Execution time (currently once every 100 ms)
778 * Add a bit of randomization to prevent the execution of all flight plans
779 * in synchrony, which can add significant periodic framerate flutter.
784 bool FGAIAircraft::fpExecutable(time_t now) {
785 double rand_exec_time = (rand() % 100) / 100;
786 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
791 * Check to see if we've reached the lead point for our next turn
796 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
797 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
799 //cerr << "2" << endl;
800 double lead_dist = fp->getLeadDistance();
801 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
802 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
803 tgt_speed = -(dist_to_go / 10.0);
804 if (tgt_speed > -0.5) {
807 //assertSpeed(tgt_speed);
808 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
809 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
812 if (lead_dist < fabs(2*speed)) {
813 //don't skip over the waypoint
814 lead_dist = fabs(2*speed);
815 //cerr << "Extending lead distance to " << lead_dist << endl;
818 //prev_dist_to_go = dist_to_go;
819 //if (dist_to_go < lead_dist)
820 // cerr << trafficRef->getCallSign() << " Distance : "
821 // << dist_to_go << ": Lead distance "
822 // << lead_dist << " " << curr->name
823 // << " Ground target speed " << groundTargetSpeed << endl;
825 // don't do bearing calculations for ground traffic
826 bearing = getBearing(fp->getBearing(pos, curr));
827 if (bearing < minBearing) {
828 minBearing = bearing;
829 if (minBearing < 10) {
832 if ((minBearing < 360.0) && (minBearing > 10.0)) {
833 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
839 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
840 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
841 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
842 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
845 if ((dist_to_go < lead_dist) ||
846 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
849 prev_dist_to_go = HUGE_VAL;
852 prev_dist_to_go = dist_to_go;
858 bool FGAIAircraft::aiTrafficVisible()
860 SGVec3d cartPos = SGVec3d::fromGeod(pos);
861 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
862 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
863 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
868 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
869 * in the case of an arrival.
875 //TODO the trafficRef is the right place for the method
876 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
877 // prepare routing from one airport to another
878 FGAirport * dep = trafficRef->getDepartureAirport();
879 FGAirport * arr = trafficRef->getArrivalAirport();
884 // This waypoint marks the fact that the aircraft has passed the initial taxi
885 // departure waypoint, so it can release the parking.
886 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
887 //cerr << "Passing waypoint : " << prev->getName() << endl;
888 if (prev->contains("PushBackPoint")) {
889 // clearing the parking assignment will release the gate
890 fp->setGate(ParkingAssignment());
892 //setTaxiClearanceRequest(true);
894 if (prev->contains("legend")) {
897 if (prev->contains(string("DepartureHold"))) {
898 //cerr << "Passing point DepartureHold" << endl;
899 scheduleForATCTowerDepartureControl(1);
901 if (prev->contains(string("Accel"))) {
904 //if (prev->contains(string("landing"))) {
905 // if (speed < _performance->vTaxi() * 2) {
906 // fp->shortenToFirst(2, "legend");
909 //if (prev->contains(string("final"))) {
911 // cerr << getCallSign() << " "
912 // << fp->getPreviousWaypoint()->getName()
913 // << ". Alt = " << altitude_ft
915 // << " horizontal speed " << speed
916 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
917 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
918 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
920 // This is the last taxi waypoint, and marks the the end of the flight plan
921 // so, the schedule should update and wait for the next departure time.
922 if (prev->contains("END")) {
923 time_t nextDeparture = trafficRef->getDepartureTime();
924 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
925 if (nextDeparture < (now+1200)) {
926 nextDeparture = now + 1200;
928 fp->setTime(nextDeparture);
936 * Check difference between target bearing and current heading and correct if necessary.
940 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
941 double calc_bearing = fp->getBearing(pos, curr);
942 //cerr << "Bearing = " << calc_bearing << endl;
945 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
948 if (std::isfinite(calc_bearing)) {
949 double hdg_error = calc_bearing - tgt_heading;
950 if (fabs(hdg_error) > 0.01) {
951 TurnTo( calc_bearing );
955 cerr << "calc_bearing is not a finite number : "
957 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
958 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
959 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
966 * Update the lead distance calculation if speed has changed sufficiently
967 * to prevent spinning (hopefully);
972 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
973 double speed_diff = speed - prevSpeed;
975 if (fabs(speed_diff) > 10) {
977 //assertSpeed(speed);
979 fp->setLeadDistance(speed, tgt_heading, curr, next);
986 * Update target values (heading, alt, speed) depending on flight plan or control properties
988 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
989 if (fp) // AI object has a flightplan
991 //TODO make this a function of AIBase
992 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
993 //cerr << "UpateTArgetValues() " << endl;
994 ProcessFlightPlan(dt, now);
996 // Do execute Ground elev for inactive aircraft, so they
997 // Are repositioned to the correct ground altitude when the user flies within visibility range.
998 // In addition, check whether we are out of user range, so this aircraft
1001 Transform(); // make sure aip is initialized.
1005 pos.setElevationFt(altitude_ft);
1008 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
1009 aiOutOfSight = !aiTrafficVisible();
1012 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1013 aiOutOfSight = true;
1017 timeElapsed = now - fp->getStartTime();
1018 flightplanActive = fp->isActive(now);
1020 // no flight plan, update target heading, speed, and altitude
1021 // from control properties. These default to the initial
1022 // settings in the config file, but can be changed "on the
1024 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1025 if ( lat_mode == "roll" ) {
1027 = props->getDoubleValue("controls/flight/target-roll" );
1031 = props->getDoubleValue("controls/flight/target-hdg" );
1036 = props->getStringValue("controls/flight/longitude-mode");
1037 if ( lon_mode == "alt" ) {
1038 double alt = props->getDoubleValue("controls/flight/target-alt" );
1042 = props->getDoubleValue("controls/flight/target-pitch" );
1046 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1050 void FGAIAircraft::updateHeading() {
1051 // adjust heading based on current bank angle
1056 // double turnConstant;
1058 // turnConstant = 0.0088362;
1060 // turnConstant = 0.088362;
1061 // If on ground, calculate heading change directly
1063 double headingDiff = fabs(hdg-tgt_heading);
1064 // double bank_sense = 0.0;
1066 double diff = fabs(hdg - tgt_heading);
1068 diff = fabs(diff - 360);
1070 double sum = hdg + diff;
1073 if (fabs(sum - tgt_heading) < 1.0) {
1074 bank_sense = 1.0; // right turn
1076 bank_sense = -1.0; // left turn
1078 if (headingDiff > 180)
1079 headingDiff = fabs(headingDiff - 360);
1080 double sum = hdg + headingDiff;
1083 if (fabs(sum - tgt_heading) > 0.0001) {
1084 // bank_sense = -1.0;
1086 // bank_sense = 1.0;
1089 // cerr << trafficRef->getCallSign() << " Heading "
1090 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1091 //if (headingDiff > 60) {
1092 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1093 //assertSpeed(groundTargetSpeed);
1094 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1096 // groundTargetSpeed = tgt_speed;
1098 if (sign(groundTargetSpeed) != sign(tgt_speed))
1099 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1100 //assertSpeed(groundTargetSpeed);
1101 // 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.
1103 if (headingDiff > 30.0) {
1104 // invert if pushed backward
1105 headingChangeRate += 10.0 * dt * sign(roll);
1107 // Clamp the maximum steering rate to 30 degrees per second,
1108 // But only do this when the heading error is decreasing.
1109 if ((headingDiff < headingError)) {
1110 if (headingChangeRate > 30)
1111 headingChangeRate = 30;
1112 else if (headingChangeRate < -30)
1113 headingChangeRate = -30;
1117 if (fabs(headingChangeRate) > headingDiff)
1118 headingChangeRate = headingDiff*sign(roll);
1120 headingChangeRate += dt * sign(roll);
1125 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1126 headingError = headingDiff;
1127 if (fabs(headingError) < 1.0) {
1131 if (fabs(speed) > 1.0) {
1132 turn_radius_ft = 0.088362 * speed * speed
1133 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1135 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1136 turn_radius_ft = 1.0;
1138 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1139 double dist_covered_ft = speed * 1.686 * dt;
1140 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1141 hdg += alpha * sign(roll);
1143 while ( hdg > 360.0 ) {
1147 while ( hdg < 0.0) {
1155 void FGAIAircraft::updateBankAngleTarget() {
1156 // adjust target bank angle if heading lock engaged
1158 double bank_sense = 0.0;
1159 double diff = fabs(hdg - tgt_heading);
1161 diff = fabs(diff - 360);
1163 double sum = hdg + diff;
1166 if (fabs(sum - tgt_heading) < 1.0) {
1167 bank_sense = 1.0; // right turn
1169 bank_sense = -1.0; // left turn
1171 if (diff < _performance->maximumBankAngle()) {
1172 tgt_roll = diff * bank_sense;
1174 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1176 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1177 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1178 // The only way to resolve this is to make them slow down.
1184 void FGAIAircraft::updateVerticalSpeedTarget() {
1185 // adjust target Altitude, based on ground elevation when on ground
1189 } else if (alt_lock) {
1190 // find target vertical speed
1192 if (altitude_ft < tgt_altitude_ft) {
1193 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1195 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1198 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1199 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1200 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1201 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1202 //cerr << "Target vs before : " << tgt_vs;
1203 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1204 double min_vs = 100;
1205 if (tgt_altitude_ft < altitude_ft)
1207 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1208 && (fabs(max_vs) < fabs(tgt_vs)))
1211 if (fabs(tgt_vs) < fabs(min_vs))
1213 //cerr << "target vs : after " << tgt_vs << endl;
1220 void FGAIAircraft::updatePitchAngleTarget() {
1221 // if on ground and above vRotate -> initial rotation
1222 if (onGround() && (speed > _performance->vRotate()))
1223 tgt_pitch = 8.0; // some rough B737 value
1225 //TODO pitch angle on approach and landing
1227 // match pitch angle to vertical speed
1228 else if (tgt_vs > 0) {
1229 tgt_pitch = tgt_vs * 0.005;
1231 tgt_pitch = tgt_vs * 0.002;
1235 const string& FGAIAircraft::atGate()
1237 if ((fp->getLeg() < 3) && trafficRef) {
1238 if (fp->getParkingGate()) {
1239 return fp->getParkingGate()->ident();
1243 static const string empty;
1247 void FGAIAircraft::handleATCRequests() {
1248 //TODO implement NullController for having no ATC to save the conditionals
1250 controller->updateAircraftInformation(getID(),
1251 pos.getLatitudeDeg(),
1252 pos.getLongitudeDeg(),
1256 processATC(controller->getInstruction(getID()));
1258 if (towerController) {
1259 towerController->updateAircraftInformation(getID(),
1260 pos.getLatitudeDeg(),
1261 pos.getLongitudeDeg(),
1268 void FGAIAircraft::updateActualState() {
1269 //update current state
1270 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1271 double distance = speed * SG_KT_TO_MPS * dt;
1272 pos = SGGeodesy::direct(pos, hdg, distance);
1276 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1278 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1279 //assertSpeed(speed);
1281 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1283 // adjust altitude (meters) based on current vertical speed (fpm)
1284 altitude_ft += vs / 60.0 * dt;
1285 pos.setElevationFt(altitude_ft);
1287 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1288 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1291 void FGAIAircraft::updateSecondaryTargetValues() {
1292 // derived target state values
1293 updateBankAngleTarget();
1294 updateVerticalSpeedTarget();
1295 updatePitchAngleTarget();
1297 //TODO calculate wind correction angle (tgt_yaw)
1301 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1302 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1303 if (curr->getName() == string("BOD")) {
1304 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1305 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1306 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1308 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1309 double descentTimeNeeded = verticalDistance / descentRate;
1310 double distanceCovered = descentSpeed * descentTimeNeeded;
1312 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1313 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1314 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1315 cerr << "Descent rate : " << descentRate << endl;
1316 cerr << "Descent speed : " << descentSpeed << endl;
1317 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1318 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1319 cerr << "DistanceCovered : " << distanceCovered << endl;
1321 //cerr << "Distance = " << distance << endl;
1322 distance = distanceCovered;
1323 if (dist < distanceCovered) {
1324 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1336 void FGAIAircraft::resetPositionFromFlightPlan()
1338 // the one behind you
1339 FGAIWaypoint* prev = 0;
1341 FGAIWaypoint* curr = 0;
1343 FGAIWaypoint* next = 0;
1345 prev = fp->getPreviousWaypoint();
1346 curr = fp->getCurrentWaypoint();
1347 next = fp->getNextWaypoint();
1349 setLatitude(prev->getLatitude());
1350 setLongitude(prev->getLongitude());
1351 double tgt_heading = fp->getBearing(curr, next);
1352 setHeading(tgt_heading);
1353 setAltitude(prev->getAltitude());
1354 setSpeed(prev->getSpeed());
1357 double FGAIAircraft::getBearing(double crse)
1359 double hdgDiff = fabs(hdg-crse);
1361 hdgDiff = fabs(hdgDiff - 360);
1365 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1366 FGAIWaypoint* curr = 0;
1367 curr = fp->getCurrentWaypoint();
1369 // don't recalculate tracklength unless the start/stop waypoint has changed
1371 ((curr->getName() != trackCache.startWptName)||
1372 (wptName != trackCache.finalWptName)))
1374 trackCache.remainingLength = fp->checkTrackLength(wptName);
1375 trackCache.startWptName = curr->getName();
1376 trackCache.finalWptName = wptName;
1378 double tracklength = trackCache.remainingLength;
1379 if (tracklength > 0.1) {
1380 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1384 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1385 time_t arrivalTime = fp->getArrivalTime();
1387 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1388 time_t secondsToGo = arrivalTime - now;
1389 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1390 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1392 return (ete - secondsToGo); // Positive when we're too slow...
1395 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1397 double delta = target - cur;
1398 double maxDelta = maxDeltaSec * dt;
1400 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1401 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1404 // drive various properties in a semi-realistic fashion.
1405 void FGAIAircraft::updateModelProperties(double dt)
1411 SGPropertyNode* gear = props->getChild("gear", 0, true);
1412 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1413 if (!gear->hasValue("gear/position-norm")) {
1414 gear->setDoubleValue("gear/position-norm", targetGearPos);
1417 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1418 if (gearPosNorm != targetGearPos) {
1419 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1420 if (gearPosNorm < 0.001) {
1422 } else if (gearPosNorm > 0.999) {
1426 for (int i=0; i<6; ++i) {
1427 SGPropertyNode* g = gear->getChild("gear", i, true);
1428 g->setDoubleValue("position-norm", gearPosNorm);
1429 } // of gear setting loop
1430 } // of gear in-transit
1432 // double flapPosNorm = props->getDoubleValue();