1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
3 // Written by David Culp, started October 2003.
5 // Copyright (C) 2003 David P. Culp - davidculp2@comcast.net
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include <simgear/route/waypoint.hxx>
26 #include <Main/fg_props.hxx>
27 #include <Main/globals.hxx>
28 #include <Main/viewer.hxx>
29 #include <Scenery/scenery.hxx>
30 #include <Scenery/tilemgr.hxx>
31 #include <Airports/dynamics.hxx>
32 #include <Airports/simple.hxx>
40 # define finite _finite
41 #elif defined(__sun) || defined(sgi)
47 #include "AIAircraft.hxx"
48 #include "performancedata.hxx"
49 #include "performancedb.hxx"
52 //#include <Airports/trafficcontroller.hxx>
54 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
55 /* HOT must be disabled for AI Aircraft,
56 * otherwise traffic detection isn't working as expected.*/
57 FGAIBase(otAircraft, false)
61 groundOffset = trafficRef->getGroundOffset();
62 setCallSign(trafficRef->getCallSign());
78 groundTargetSpeed = 0;
80 // set heading and altitude locks
84 headingChangeRate = 0.0;
90 needsTaxiClearance = false;
91 _needsGroundElevation = true;
93 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
99 FGAIAircraft::~FGAIAircraft() {
102 controller->signOff(getID());
106 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
110 FGAIBase::readFromScenario(scFileNode);
112 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
113 setFlightPlan(scFileNode->getStringValue("flightplan"),
114 scFileNode->getBoolValue("repeat", false));
115 setCallSign(scFileNode->getStringValue("callsign"));
119 void FGAIAircraft::bind() {
122 tie("controls/gear/gear-down",
123 SGRawValueMethods<FGAIAircraft,bool>(*this,
124 &FGAIAircraft::_getGearDown));
125 tie("transponder-id",
126 SGRawValueMethods<FGAIAircraft,const char*>(*this,
127 &FGAIAircraft::_getTransponderCode));
130 void FGAIAircraft::update(double dt) {
131 FGAIBase::update(dt);
136 void FGAIAircraft::setPerformance(const std::string& acclass) {
137 static PerformanceDB perfdb; //TODO make it a global service
138 setPerformance(perfdb.getDataFor(acclass));
142 void FGAIAircraft::setPerformance(PerformanceData *ps) {
147 void FGAIAircraft::Run(double dt) {
148 FGAIAircraft::dt = dt;
150 bool outOfSight = false,
151 flightplanActive = true;
152 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
157 if (!flightplanActive) {
158 groundTargetSpeed = 0;
161 handleATCRequests(); // ATC also has a word to say
162 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
164 // We currently have one situation in which an AIAircraft object is used that is not attached to the
165 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
166 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
169 UpdateRadar(manager);
173 void FGAIAircraft::checkVisibility()
175 double visibility_meters = fgGetDouble("/environment/visibility-m");
176 FGViewer* vw = globals->get_current_view();
177 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
182 void FGAIAircraft::AccelTo(double speed) {
184 //assertSpeed(speed);
186 _needsGroundElevation = true;
190 void FGAIAircraft::PitchTo(double angle) {
196 void FGAIAircraft::RollTo(double angle) {
202 void FGAIAircraft::YawTo(double angle) {
207 void FGAIAircraft::ClimbTo(double alt_ft ) {
208 tgt_altitude_ft = alt_ft;
213 void FGAIAircraft::TurnTo(double heading) {
214 tgt_heading = heading;
219 double FGAIAircraft::sign(double x) {
227 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
228 if (!flightplan.empty()) {
229 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
230 fp->setRepeat(repeat);
236 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
242 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
244 // the one behind you
245 FGAIWaypoint* prev = 0;
247 FGAIWaypoint* curr = 0;
249 FGAIWaypoint* next = 0;
251 prev = fp->getPreviousWaypoint();
252 curr = fp->getCurrentWaypoint();
253 next = fp->getNextWaypoint();
257 ///////////////////////////////////////////////////////////////////////////
258 // Initialize the flightplan
259 //////////////////////////////////////////////////////////////////////////
261 handleFirstWaypoint();
263 } // end of initialization
264 if (! fpExecutable(now))
268 double distanceToDescent;
269 if(reachedEndOfCruise(distanceToDescent)) {
270 if (!loadNextLeg(distanceToDescent)) {
274 prev = fp->getPreviousWaypoint();
275 curr = fp->getCurrentWaypoint();
276 next = fp->getNextWaypoint();
278 if (! leadPointReached(curr)) {
279 controlHeading(curr);
280 controlSpeed(curr, next);
284 cerr << getCallSign()
285 << ": verifying lead distance to waypoint : "
286 << fp->getCurrentWaypoint()->name << " "
287 << fp->getLeadDistance() << ". Distance to go "
288 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
289 << ". Target speed = "
291 << ". Current speed = "
293 << ". Minimum Bearing " << minBearing
297 if (curr->isFinished()) //end of the flight plan
307 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
308 tgt_heading = fp->getBearing(curr, next);
312 //TODO let the fp handle this (loading of next leg)
313 fp->IncrementWaypoint( trafficRef != 0 );
314 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
315 if (!loadNextLeg()) {
320 prev = fp->getPreviousWaypoint();
321 curr = fp->getCurrentWaypoint();
322 next = fp->getNextWaypoint();
324 // Now that we have incremented the waypoints, excute some traffic manager specific code
326 //TODO isn't this best executed right at the beginning?
327 if (! aiTrafficVisible()) {
332 if (! handleAirportEndPoints(prev, now)) {
337 announcePositionToController();
342 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
346 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
348 tgt_altitude_ft = prev->getAltitude();
349 if (curr->getCrossat() > -1000.0) {
351 // Distance to go in meters
352 double vert_dist_ft = curr->getCrossat() - altitude_ft;
353 double err_dist = prev->getCrossat() - altitude_ft;
354 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
355 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
358 tgt_altitude_ft = curr->getCrossat();
363 AccelTo(prev->getSpeed());
364 hdg_lock = alt_lock = true;
365 no_roll = prev->getOn_ground();
369 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
371 // err is negative when we passed too high
372 double vert_m = vert_ft * SG_FEET_TO_METER;
373 //double err_m = err * SG_FEET_TO_METER;
374 //double angle = atan2(vert_m, dist_m);
375 double speedMs = (speed * SG_NM_TO_METER) / 3600;
376 //double vs = cos(angle) * speedMs; // Now in m/s
378 //cerr << "Error term = " << err_m << endl;
380 vs = ((vert_m) / dist_m) * speedMs;
382 // Convert to feet per minute
383 vs *= (SG_METER_TO_FEET * 60);
384 //if (getCallSign() == "LUFTHANSA2002")
385 //if (fabs(vs) > 100000) {
386 // if (getCallSign() == "LUFTHANSA2057") {
387 // 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;
388 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
389 // // / 6076.0 / speed*60.0);
395 void FGAIAircraft::assertSpeed(double speed)
397 if ((speed < -50) || (speed > 1000)) {
398 cerr << getCallSign() << " "
399 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
400 << "Departure airport " << trafficRef->getDepartureAirport() << " "
401 << "Leg " << fp->getLeg() << " "
402 << "target_speed << " << tgt_speed << " "
403 << "speedFraction << " << speedFraction << " "
404 << "Currecnt speed << " << speed << " "
412 void FGAIAircraft::checkTcas(void)
414 if (props->getIntValue("tcas/threat-level",0)==3)
416 int RASense = props->getIntValue("tcas/ra-sense",0);
417 if ((RASense>0)&&(tgt_vs<4000))
423 // downward RA: descend!
424 if (altitude_ft < 1000)
426 // too low: level off
439 void FGAIAircraft::initializeFlightPlan() {
443 bool FGAIAircraft::_getGearDown() const {
444 return _performance->gearExtensible(this);
448 const char * FGAIAircraft::_getTransponderCode() const {
449 return transponderCode.c_str();
452 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
453 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
455 bool FGAIAircraft::loadNextLeg(double distance) {
458 if ((leg = fp->getLeg()) == 9) {
459 if (!trafficRef->next()) {
462 setCallSign(trafficRef->getCallSign());
467 FGAirport *dep = trafficRef->getDepartureAirport();
468 FGAirport *arr = trafficRef->getArrivalAirport();
473 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
480 trafficRef->getSpeed(),
484 trafficRef->getRadius(),
485 trafficRef->getFlightType(),
489 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
495 // Note: This code is copied from David Luff's AILocalTraffic
496 // Warning - ground elev determination is CPU intensive
497 // Either this function or the logic of how often it is called
498 // will almost certainly change.
500 void FGAIAircraft::getGroundElev(double dt) {
503 if (!needGroundElevation())
505 // Update minimally every three secs, but add some randomness
506 // to prevent all AI objects doing this in synchrony
507 if (dt_elev_count < (3.0) + (rand() % 10))
512 // Only do the proper hitlist stuff if we are within visible range of the viewer.
514 double visibility_meters = fgGetDouble("/environment/visibility-m");
515 FGViewer* vw = globals->get_current_view();
517 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
521 double range = 500.0;
522 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
525 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
527 tgt_altitude_ft = alt * SG_METER_TO_FEET;
530 // aircraft is stationary and we obtained altitude for this spot - we're done.
531 _needsGroundElevation = false;
539 void FGAIAircraft::doGroundAltitude() {
540 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
543 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
545 altitude_ft = (tgt_altitude_ft + groundOffset);
547 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
553 void FGAIAircraft::announcePositionToController() {
555 int leg = fp->getLeg();
557 // Note that leg has been incremented after creating the current leg, so we should use
558 // leg numbers here that are one higher than the number that is used to create the leg
559 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
560 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
561 // the original leg numbers here!
563 case 1: // Startup and Push back
564 if (trafficRef->getDepartureAirport()->getDynamics())
565 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
567 case 2: // Taxiing to runway
568 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
569 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
571 case 3: //Take off tower controller
572 if (trafficRef->getDepartureAirport()->getDynamics()) {
573 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
576 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
580 if (trafficRef->getDepartureAirport()->getDynamics()) {
581 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
584 case 8: // Taxiing for parking
585 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
586 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
593 if ((controller != prevController) && (prevController != 0)) {
594 prevController->signOff(getID());
596 prevController = controller;
598 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
599 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
600 trafficRef->getRadius(), leg, this);
605 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
606 if (!takeOffStatus) {
607 int leg = fp->getLeg();
609 if (trafficRef->getDepartureAirport()->getDynamics()) {
610 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
612 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
614 if (towerController) {
615 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
616 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
617 trafficRef->getRadius(), leg, this);
618 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
622 takeOffStatus = state;
625 // Process ATC instructions and report back
627 void FGAIAircraft::processATC(FGATCInstruction instruction) {
628 if (instruction.getCheckForCircularWait()) {
629 // This is not exactly an elegant solution,
630 // but at least it gives me a chance to check
631 // if circular waits are resolved.
632 // For now, just take the offending aircraft
635 // a more proper way should be - of course - to
636 // let an offending aircraft take an evasive action
637 // for instance taxi back a little bit.
639 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
640 if (instruction.getHoldPattern ()) {}
643 if (instruction.getHoldPosition ()) {
651 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
654 // Change speed Instruction. This can only be excecuted when there is no
655 // Hold position instruction.
656 if (instruction.getChangeSpeed ()) {
658 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
659 AccelTo(instruction.getSpeed());
661 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
664 if (instruction.getChangeHeading ()) {
666 TurnTo(instruction.getHeading());
672 if (instruction.getChangeAltitude()) {}
677 void FGAIAircraft::handleFirstWaypoint() {
678 bool eraseWaypoints; //TODO YAGNI
681 eraseWaypoints = true;
683 eraseWaypoints = false;
686 FGAIWaypoint* prev = 0; // the one behind you
687 FGAIWaypoint* curr = 0; // the one ahead
688 FGAIWaypoint* next = 0;// the next plus 1
692 //TODO fp should handle this
693 fp->IncrementWaypoint(eraseWaypoints);
694 if (!(fp->getNextWaypoint()) && trafficRef)
695 if (!loadNextLeg()) {
700 prev = fp->getPreviousWaypoint(); //first waypoint
701 curr = fp->getCurrentWaypoint(); //second waypoint
702 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
704 setLatitude(prev->getLatitude());
705 setLongitude(prev->getLongitude());
706 setSpeed(prev->getSpeed());
707 setAltitude(prev->getAltitude());
709 if (prev->getSpeed() > 0.0)
710 setHeading(fp->getBearing(prev->getLatitude(), prev->getLongitude(), curr));
712 setHeading(fp->getBearing(curr->getLatitude(), curr->getLongitude(), prev));
714 // If next doesn't exist, as in incrementally created flightplans for
715 // AI/Trafficmanager created plans,
716 // Make sure lead distance is initialized otherwise
718 fp->setLeadDistance(speed, hdg, curr, next);
720 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
723 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
724 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
725 // / 6076.0 / prev->getSpeed()*60.0);
726 double vert_dist_ft = curr->getCrossat() - altitude_ft;
727 double err_dist = prev->getCrossat() - altitude_ft;
728 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
729 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
731 tgt_altitude_ft = curr->getCrossat();
734 tgt_altitude_ft = prev->getAltitude();
736 alt_lock = hdg_lock = true;
737 no_roll = prev->getOn_ground();
739 Transform(); // make sure aip is initialized.
740 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
742 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
744 // Make sure to announce the aircraft's position
745 announcePositionToController();
751 * Check Execution time (currently once every 100 ms)
752 * Add a bit of randomization to prevent the execution of all flight plans
753 * in synchrony, which can add significant periodic framerate flutter.
758 bool FGAIAircraft::fpExecutable(time_t now) {
759 double rand_exec_time = (rand() % 100) / 100;
760 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
765 * Check to see if we've reached the lead point for our next turn
770 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
771 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
773 //cerr << "2" << endl;
774 double lead_dist = fp->getLeadDistance();
775 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
776 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
777 tgt_speed = -(dist_to_go / 10.0);
778 if (tgt_speed > -0.5) {
781 //assertSpeed(tgt_speed);
782 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
783 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
786 if (lead_dist < fabs(2*speed)) {
787 //don't skip over the waypoint
788 lead_dist = fabs(2*speed);
789 //cerr << "Extending lead distance to " << lead_dist << endl;
792 //prev_dist_to_go = dist_to_go;
793 //if (dist_to_go < lead_dist)
794 // cerr << trafficRef->getCallSign() << " Distance : "
795 // << dist_to_go << ": Lead distance "
796 // << lead_dist << " " << curr->name
797 // << " Ground target speed " << groundTargetSpeed << endl;
799 // don't do bearing calculations for ground traffic
800 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
801 if (bearing < minBearing) {
802 minBearing = bearing;
803 if (minBearing < 10) {
806 if ((minBearing < 360.0) && (minBearing > 10.0)) {
807 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
813 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
814 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
815 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
816 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
819 if ((dist_to_go < lead_dist) ||
820 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
823 prev_dist_to_go = HUGE_VAL;
826 prev_dist_to_go = dist_to_go;
832 bool FGAIAircraft::aiTrafficVisible()
834 SGVec3d cartPos = SGVec3d::fromGeod(pos);
835 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
836 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
837 return (distSqr(cartPos, globals->get_aircraft_positon_cart()) < d2);
842 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
843 * in the case of an arrival.
849 //TODO the trafficRef is the right place for the method
850 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
851 // prepare routing from one airport to another
852 FGAirport * dep = trafficRef->getDepartureAirport();
853 FGAirport * arr = trafficRef->getArrivalAirport();
858 // This waypoint marks the fact that the aircraft has passed the initial taxi
859 // departure waypoint, so it can release the parking.
860 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
861 //cerr << "Passing waypoint : " << prev->getName() << endl;
862 if (prev->contains("PushBackPoint")) {
863 dep->getDynamics()->releaseParking(fp->getGate());
865 //setTaxiClearanceRequest(true);
867 if (prev->contains("legend")) {
870 if (prev->contains(string("DepartureHold"))) {
871 //cerr << "Passing point DepartureHold" << endl;
872 scheduleForATCTowerDepartureControl(1);
874 if (prev->contains(string("Accel"))) {
877 //if (prev->contains(string("landing"))) {
878 // if (speed < _performance->vTaxi() * 2) {
879 // fp->shortenToFirst(2, "legend");
882 //if (prev->contains(string("final"))) {
884 // cerr << getCallSign() << " "
885 // << fp->getPreviousWaypoint()->getName()
886 // << ". Alt = " << altitude_ft
888 // << " horizontal speed " << speed
889 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
890 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
891 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
893 // This is the last taxi waypoint, and marks the the end of the flight plan
894 // so, the schedule should update and wait for the next departure time.
895 if (prev->contains("END")) {
896 time_t nextDeparture = trafficRef->getDepartureTime();
897 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
898 if (nextDeparture < (now+1200)) {
899 nextDeparture = now + 1200;
901 fp->setTime(nextDeparture);
909 * Check difference between target bearing and current heading and correct if necessary.
913 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
914 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
915 //cerr << "Bearing = " << calc_bearing << endl;
918 if (calc_bearing > 360)
922 if (finite(calc_bearing)) {
923 double hdg_error = calc_bearing - tgt_heading;
924 if (fabs(hdg_error) > 0.01) {
925 TurnTo( calc_bearing );
929 cerr << "calc_bearing is not a finite number : "
931 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
932 << "waypoint " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
933 cerr << "waypoint name " << curr->getName();
940 * Update the lead distance calculation if speed has changed sufficiently
941 * to prevent spinning (hopefully);
946 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
947 double speed_diff = speed - prevSpeed;
949 if (fabs(speed_diff) > 10) {
951 //assertSpeed(speed);
953 fp->setLeadDistance(speed, tgt_heading, curr, next);
960 * Update target values (heading, alt, speed) depending on flight plan or control properties
962 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
963 if (fp) // AI object has a flightplan
965 //TODO make this a function of AIBase
966 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
967 //cerr << "UpateTArgetValues() " << endl;
968 ProcessFlightPlan(dt, now);
970 // Do execute Ground elev for inactive aircraft, so they
971 // Are repositioned to the correct ground altitude when the user flies within visibility range.
972 // In addition, check whether we are out of user range, so this aircraft
975 Transform(); // make sure aip is initialized.
979 pos.setElevationFt(altitude_ft);
982 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
983 aiOutOfSight = !aiTrafficVisible();
986 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
991 timeElapsed = now - fp->getStartTime();
992 flightplanActive = fp->isActive(now);
994 // no flight plan, update target heading, speed, and altitude
995 // from control properties. These default to the initial
996 // settings in the config file, but can be changed "on the
998 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
999 if ( lat_mode == "roll" ) {
1001 = props->getDoubleValue("controls/flight/target-roll" );
1005 = props->getDoubleValue("controls/flight/target-hdg" );
1010 = props->getStringValue("controls/flight/longitude-mode");
1011 if ( lon_mode == "alt" ) {
1012 double alt = props->getDoubleValue("controls/flight/target-alt" );
1016 = props->getDoubleValue("controls/flight/target-pitch" );
1020 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1024 void FGAIAircraft::updatePosition() {
1025 // convert speed to degrees per second
1026 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
1027 * speed * 1.686 / ft_per_deg_lat;
1028 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
1029 * speed * 1.686 / ft_per_deg_lon;
1032 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
1033 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
1037 void FGAIAircraft::updateHeading() {
1038 // adjust heading based on current bank angle
1043 // double turnConstant;
1045 // turnConstant = 0.0088362;
1047 // turnConstant = 0.088362;
1048 // If on ground, calculate heading change directly
1050 double headingDiff = fabs(hdg-tgt_heading);
1051 // double bank_sense = 0.0;
1053 double diff = fabs(hdg - tgt_heading);
1055 diff = fabs(diff - 360);
1057 double sum = hdg + diff;
1060 if (fabs(sum - tgt_heading) < 1.0) {
1061 bank_sense = 1.0; // right turn
1063 bank_sense = -1.0; // left turn
1065 if (headingDiff > 180)
1066 headingDiff = fabs(headingDiff - 360);
1067 double sum = hdg + headingDiff;
1070 if (fabs(sum - tgt_heading) > 0.0001) {
1071 // bank_sense = -1.0;
1073 // bank_sense = 1.0;
1076 // cerr << trafficRef->getCallSign() << " Heading "
1077 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1078 //if (headingDiff > 60) {
1079 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1080 //assertSpeed(groundTargetSpeed);
1081 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1083 // groundTargetSpeed = tgt_speed;
1085 if (sign(groundTargetSpeed) != sign(tgt_speed))
1086 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1087 //assertSpeed(groundTargetSpeed);
1088 // 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.
1090 if (headingDiff > 30.0) {
1091 // invert if pushed backward
1092 headingChangeRate += 10.0 * dt * sign(roll);
1094 // Clamp the maximum steering rate to 30 degrees per second,
1095 // But only do this when the heading error is decreasing.
1096 if ((headingDiff < headingError)) {
1097 if (headingChangeRate > 30)
1098 headingChangeRate = 30;
1099 else if (headingChangeRate < -30)
1100 headingChangeRate = -30;
1104 if (fabs(headingChangeRate) > headingDiff)
1105 headingChangeRate = headingDiff*sign(roll);
1107 headingChangeRate += dt * sign(roll);
1112 //cerr << trafficRef->getCallSign() << " Heading "
1113 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1114 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1115 headingError = headingDiff;
1116 if (fabs(headingError) < 1.0) {
1120 if (fabs(speed) > 1.0) {
1121 turn_radius_ft = 0.088362 * speed * speed
1122 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1124 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1125 turn_radius_ft = 1.0;
1127 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1128 double dist_covered_ft = speed * 1.686 * dt;
1129 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1130 hdg += alpha * sign(roll);
1132 while ( hdg > 360.0 ) {
1136 while ( hdg < 0.0) {
1144 void FGAIAircraft::updateBankAngleTarget() {
1145 // adjust target bank angle if heading lock engaged
1147 double bank_sense = 0.0;
1148 double diff = fabs(hdg - tgt_heading);
1150 diff = fabs(diff - 360);
1152 double sum = hdg + diff;
1155 if (fabs(sum - tgt_heading) < 1.0) {
1156 bank_sense = 1.0; // right turn
1158 bank_sense = -1.0; // left turn
1160 if (diff < _performance->maximumBankAngle()) {
1161 tgt_roll = diff * bank_sense;
1163 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1165 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1166 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1167 // The only way to resolve this is to make them slow down.
1173 void FGAIAircraft::updateVerticalSpeedTarget() {
1174 // adjust target Altitude, based on ground elevation when on ground
1178 } else if (alt_lock) {
1179 // find target vertical speed
1181 if (altitude_ft < tgt_altitude_ft) {
1182 tgt_vs = tgt_altitude_ft - altitude_ft;
1183 if (tgt_vs > _performance->climbRate())
1184 tgt_vs = _performance->climbRate();
1186 tgt_vs = tgt_altitude_ft - altitude_ft;
1187 if (tgt_vs < (-_performance->descentRate()))
1188 tgt_vs = -_performance->descentRate();
1191 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1192 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1193 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1194 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1195 //cerr << "Target vs before : " << tgt_vs;
1196 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1197 double min_vs = 100;
1198 if (tgt_altitude_ft < altitude_ft)
1200 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1201 && (fabs(max_vs) < fabs(tgt_vs)))
1204 if (fabs(tgt_vs) < fabs(min_vs))
1206 //cerr << "target vs : after " << tgt_vs << endl;
1213 void FGAIAircraft::updatePitchAngleTarget() {
1214 // if on ground and above vRotate -> initial rotation
1215 if (onGround() && (speed > _performance->vRotate()))
1216 tgt_pitch = 8.0; // some rough B737 value
1218 //TODO pitch angle on approach and landing
1220 // match pitch angle to vertical speed
1221 else if (tgt_vs > 0) {
1222 tgt_pitch = tgt_vs * 0.005;
1224 tgt_pitch = tgt_vs * 0.002;
1228 string FGAIAircraft::atGate() {
1230 if (fp->getLeg() < 3) {
1232 if (fp->getGate() > 0) {
1234 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1235 tmp = park->getName();
1242 void FGAIAircraft::handleATCRequests() {
1243 //TODO implement NullController for having no ATC to save the conditionals
1245 controller->updateAircraftInformation(getID(),
1246 pos.getLatitudeDeg(),
1247 pos.getLongitudeDeg(),
1251 processATC(controller->getInstruction(getID()));
1253 if (towerController) {
1254 towerController->updateAircraftInformation(getID(),
1255 pos.getLatitudeDeg(),
1256 pos.getLongitudeDeg(),
1263 void FGAIAircraft::updateActualState() {
1264 //update current state
1265 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1269 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1271 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1272 //assertSpeed(speed);
1274 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1276 // adjust altitude (meters) based on current vertical speed (fpm)
1277 altitude_ft += vs / 60.0 * dt;
1278 pos.setElevationFt(altitude_ft);
1280 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1281 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1284 void FGAIAircraft::updateSecondaryTargetValues() {
1285 // derived target state values
1286 updateBankAngleTarget();
1287 updateVerticalSpeedTarget();
1288 updatePitchAngleTarget();
1290 //TODO calculate wind correction angle (tgt_yaw)
1294 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1295 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1296 if (curr->getName() == string("BOD")) {
1297 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1298 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1299 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1301 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1302 double descentTimeNeeded = verticalDistance / descentRate;
1303 double distanceCovered = descentSpeed * descentTimeNeeded;
1305 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1306 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1307 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1308 cerr << "Descent rate : " << descentRate << endl;
1309 cerr << "Descent speed : " << descentSpeed << endl;
1310 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1311 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1312 cerr << "DistanceCovered : " << distanceCovered << endl;
1314 //cerr << "Distance = " << distance << endl;
1315 distance = distanceCovered;
1316 if (dist < distanceCovered) {
1317 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1329 void FGAIAircraft::resetPositionFromFlightPlan()
1331 // the one behind you
1332 FGAIWaypoint* prev = 0;
1334 FGAIWaypoint* curr = 0;
1336 FGAIWaypoint* next = 0;
1338 prev = fp->getPreviousWaypoint();
1339 curr = fp->getCurrentWaypoint();
1340 next = fp->getNextWaypoint();
1342 setLatitude(prev->getLatitude());
1343 setLongitude(prev->getLongitude());
1344 double tgt_heading = fp->getBearing(curr, next);
1345 setHeading(tgt_heading);
1346 setAltitude(prev->getAltitude());
1347 setSpeed(prev->getSpeed());
1350 double FGAIAircraft::getBearing(double crse)
1352 double hdgDiff = fabs(hdg-crse);
1354 hdgDiff = fabs(hdgDiff - 360);
1358 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1359 FGAIWaypoint* curr = 0;
1360 curr = fp->getCurrentWaypoint();
1362 double tracklength = fp->checkTrackLength(wptName);
1363 if (tracklength > 0.1) {
1364 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1368 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1369 time_t arrivalTime = fp->getArrivalTime();
1371 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1372 time_t secondsToGo = arrivalTime - now;
1373 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1374 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1376 return (ete - secondsToGo); // Positive when we're too slow...