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>
39 # define finite _finite
40 #elif defined(__sun) || defined(sgi)
45 #include "AIAircraft.hxx"
46 #include "performancedata.hxx"
47 #include "performancedb.hxx"
54 //#include <Airports/trafficcontroller.hxx>
56 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
57 /* HOT must be disabled for AI Aircraft,
58 * otherwise traffic detection isn't working as expected.*/
59 FGAIBase(otAircraft, false)
63 groundOffset = trafficRef->getGroundOffset();
64 setCallSign(trafficRef->getCallSign());
80 groundTargetSpeed = 0;
82 // set heading and altitude locks
86 headingChangeRate = 0.0;
92 needsTaxiClearance = false;
93 _needsGroundElevation = true;
95 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
99 trackCache.remainingLength = 0;
100 trackCache.startWptName = "-";
104 FGAIAircraft::~FGAIAircraft() {
107 controller->signOff(getID());
111 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
115 FGAIBase::readFromScenario(scFileNode);
117 setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
118 setFlightPlan(scFileNode->getStringValue("flightplan"),
119 scFileNode->getBoolValue("repeat", false));
120 setCallSign(scFileNode->getStringValue("callsign"));
124 void FGAIAircraft::bind() {
127 tie("transponder-id",
128 SGRawValueMethods<FGAIAircraft,const char*>(*this,
129 &FGAIAircraft::_getTransponderCode));
132 void FGAIAircraft::update(double dt) {
133 FGAIBase::update(dt);
138 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
140 static PerformanceDB perfdb; //TODO make it a global service
141 _performance = perfdb.getDataFor(acType, acclass);
145 void FGAIAircraft::setPerformance(PerformanceData *ps) {
150 void FGAIAircraft::Run(double dt) {
151 FGAIAircraft::dt = dt;
153 bool outOfSight = false,
154 flightplanActive = true;
155 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
160 if (!flightplanActive) {
161 groundTargetSpeed = 0;
164 handleATCRequests(); // ATC also has a word to say
165 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
168 // 25/11/12 - added but disabled, since setting properties isn't
169 // affecting the AI-model as expected.
170 updateModelProperties(dt);
173 // We currently have one situation in which an AIAircraft object is used that is not attached to the
174 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
175 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
178 UpdateRadar(manager);
182 void FGAIAircraft::checkVisibility()
184 double visibility_meters = fgGetDouble("/environment/visibility-m");
185 invisible = (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters);
190 void FGAIAircraft::AccelTo(double speed) {
192 //assertSpeed(speed);
194 _needsGroundElevation = true;
198 void FGAIAircraft::PitchTo(double angle) {
204 void FGAIAircraft::RollTo(double angle) {
210 void FGAIAircraft::YawTo(double angle) {
215 void FGAIAircraft::ClimbTo(double alt_ft ) {
216 tgt_altitude_ft = alt_ft;
221 void FGAIAircraft::TurnTo(double heading) {
222 tgt_heading = heading;
227 double FGAIAircraft::sign(double x) {
235 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
236 if (!flightplan.empty()) {
237 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
238 fp->setRepeat(repeat);
244 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
250 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
252 // the one behind you
253 FGAIWaypoint* prev = 0;
255 FGAIWaypoint* curr = 0;
257 FGAIWaypoint* next = 0;
259 prev = fp->getPreviousWaypoint();
260 curr = fp->getCurrentWaypoint();
261 next = fp->getNextWaypoint();
265 ///////////////////////////////////////////////////////////////////////////
266 // Initialize the flightplan
267 //////////////////////////////////////////////////////////////////////////
269 handleFirstWaypoint();
271 } // end of initialization
272 if (! fpExecutable(now))
276 double distanceToDescent;
277 if(reachedEndOfCruise(distanceToDescent)) {
278 if (!loadNextLeg(distanceToDescent)) {
282 prev = fp->getPreviousWaypoint();
283 curr = fp->getCurrentWaypoint();
284 next = fp->getNextWaypoint();
292 if (! leadPointReached(curr)) {
293 controlHeading(curr);
294 controlSpeed(curr, next);
298 cerr << getCallSign()
299 << ": verifying lead distance to waypoint : "
300 << fp->getCurrentWaypoint()->name << " "
301 << fp->getLeadDistance() << ". Distance to go "
302 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
303 << ". Target speed = "
305 << ". Current speed = "
307 << ". Minimum Bearing " << minBearing
311 if (curr->isFinished()) //end of the flight plan
321 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
322 tgt_heading = fp->getBearing(curr, next);
326 //TODO let the fp handle this (loading of next leg)
327 fp->IncrementWaypoint( trafficRef != 0 );
328 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
329 if (!loadNextLeg()) {
334 prev = fp->getPreviousWaypoint();
335 curr = fp->getCurrentWaypoint();
336 next = fp->getNextWaypoint();
338 // Now that we have incremented the waypoints, excute some traffic manager specific code
340 //TODO isn't this best executed right at the beginning?
341 if (! aiTrafficVisible()) {
346 if (! handleAirportEndPoints(prev, now)) {
351 announcePositionToController();
356 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
360 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
362 tgt_altitude_ft = prev->getAltitude();
363 if (curr->getCrossat() > -1000.0) {
365 // Distance to go in meters
366 double vert_dist_ft = curr->getCrossat() - altitude_ft;
367 double err_dist = prev->getCrossat() - altitude_ft;
368 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
369 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
372 tgt_altitude_ft = curr->getCrossat();
377 AccelTo(prev->getSpeed());
378 hdg_lock = alt_lock = true;
379 no_roll = prev->getOn_ground();
383 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
385 // err is negative when we passed too high
386 double vert_m = vert_ft * SG_FEET_TO_METER;
387 //double err_m = err * SG_FEET_TO_METER;
388 //double angle = atan2(vert_m, dist_m);
389 double speedMs = (speed * SG_NM_TO_METER) / 3600;
390 //double vs = cos(angle) * speedMs; // Now in m/s
392 //cerr << "Error term = " << err_m << endl;
394 vs = ((vert_m) / dist_m) * speedMs;
396 // Convert to feet per minute
397 vs *= (SG_METER_TO_FEET * 60);
398 //if (getCallSign() == "LUFTHANSA2002")
399 //if (fabs(vs) > 100000) {
400 // if (getCallSign() == "LUFTHANSA2057") {
401 // 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;
402 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
403 // // / 6076.0 / speed*60.0);
409 void FGAIAircraft::assertSpeed(double speed)
411 if ((speed < -50) || (speed > 1000)) {
412 cerr << getCallSign() << " "
413 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
414 << "Departure airport " << trafficRef->getDepartureAirport() << " "
415 << "Leg " << fp->getLeg() << " "
416 << "target_speed << " << tgt_speed << " "
417 << "speedFraction << " << speedFraction << " "
418 << "Currecnt speed << " << speed << " "
426 void FGAIAircraft::checkTcas(void)
428 if (props->getIntValue("tcas/threat-level",0)==3)
430 int RASense = props->getIntValue("tcas/ra-sense",0);
431 if ((RASense>0)&&(tgt_vs<4000))
437 // downward RA: descend!
438 if (altitude_ft < 1000)
440 // too low: level off
453 void FGAIAircraft::initializeFlightPlan() {
456 const char * FGAIAircraft::_getTransponderCode() const {
457 return transponderCode.c_str();
460 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
461 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
463 bool FGAIAircraft::loadNextLeg(double distance) {
466 if ((leg = fp->getLeg()) == 9) {
467 if (!trafficRef->next()) {
470 setCallSign(trafficRef->getCallSign());
475 FGAirport *dep = trafficRef->getDepartureAirport();
476 FGAirport *arr = trafficRef->getArrivalAirport();
481 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
488 trafficRef->getSpeed(),
492 trafficRef->getRadius(),
493 trafficRef->getFlightType(),
497 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
503 // Note: This code is copied from David Luff's AILocalTraffic
504 // Warning - ground elev determination is CPU intensive
505 // Either this function or the logic of how often it is called
506 // will almost certainly change.
508 void FGAIAircraft::getGroundElev(double dt) {
511 if (!needGroundElevation())
513 // Update minimally every three secs, but add some randomness
514 // to prevent all AI objects doing this in synchrony
515 if (dt_elev_count < (3.0) + (rand() % 10))
520 // Only do the proper hitlist stuff if we are within visible range of the viewer.
522 double visibility_meters = fgGetDouble("/environment/visibility-m");
523 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
527 double range = 500.0;
528 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
531 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
533 tgt_altitude_ft = alt * SG_METER_TO_FEET;
536 // aircraft is stationary and we obtained altitude for this spot - we're done.
537 _needsGroundElevation = false;
545 void FGAIAircraft::doGroundAltitude() {
546 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
549 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
551 altitude_ft = (tgt_altitude_ft + groundOffset);
553 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
559 void FGAIAircraft::announcePositionToController() {
561 int leg = fp->getLeg();
563 // Note that leg has been incremented after creating the current leg, so we should use
564 // leg numbers here that are one higher than the number that is used to create the leg
565 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
566 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
567 // the original leg numbers here!
569 case 1: // Startup and Push back
570 if (trafficRef->getDepartureAirport()->getDynamics())
571 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
573 case 2: // Taxiing to runway
574 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
575 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
577 case 3: //Take off tower controller
578 if (trafficRef->getDepartureAirport()->getDynamics()) {
579 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
582 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
586 if (trafficRef->getDepartureAirport()->getDynamics()) {
587 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
590 case 8: // Taxiing for parking
591 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
592 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
599 if ((controller != prevController) && (prevController != 0)) {
600 prevController->signOff(getID());
602 prevController = controller;
604 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
605 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
606 trafficRef->getRadius(), leg, this);
611 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
612 if (!takeOffStatus) {
613 int leg = fp->getLeg();
615 if (trafficRef->getDepartureAirport()->getDynamics()) {
616 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
618 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
620 if (towerController) {
621 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
622 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
623 trafficRef->getRadius(), leg, this);
624 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
628 takeOffStatus = state;
631 // Process ATC instructions and report back
633 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
634 if (instruction.getCheckForCircularWait()) {
635 // This is not exactly an elegant solution,
636 // but at least it gives me a chance to check
637 // if circular waits are resolved.
638 // For now, just take the offending aircraft
641 // a more proper way should be - of course - to
642 // let an offending aircraft take an evasive action
643 // for instance taxi back a little bit.
645 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
646 if (instruction.getHoldPattern ()) {}
649 if (instruction.getHoldPosition ()) {
657 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
660 // Change speed Instruction. This can only be excecuted when there is no
661 // Hold position instruction.
662 if (instruction.getChangeSpeed ()) {
664 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
665 AccelTo(instruction.getSpeed());
667 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
670 if (instruction.getChangeHeading ()) {
672 TurnTo(instruction.getHeading());
678 if (instruction.getChangeAltitude()) {}
683 void FGAIAircraft::handleFirstWaypoint() {
684 bool eraseWaypoints; //TODO YAGNI
687 eraseWaypoints = true;
689 eraseWaypoints = false;
692 FGAIWaypoint* prev = 0; // the one behind you
693 FGAIWaypoint* curr = 0; // the one ahead
694 FGAIWaypoint* next = 0;// the next plus 1
698 //TODO fp should handle this
699 fp->IncrementWaypoint(eraseWaypoints);
700 if (!(fp->getNextWaypoint()) && trafficRef)
701 if (!loadNextLeg()) {
706 prev = fp->getPreviousWaypoint(); //first waypoint
707 curr = fp->getCurrentWaypoint(); //second waypoint
708 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
710 setLatitude(prev->getLatitude());
711 setLongitude(prev->getLongitude());
712 setSpeed(prev->getSpeed());
713 setAltitude(prev->getAltitude());
715 if (prev->getSpeed() > 0.0)
716 setHeading(fp->getBearing(prev, curr));
718 setHeading(fp->getBearing(curr, prev));
720 // If next doesn't exist, as in incrementally created flightplans for
721 // AI/Trafficmanager created plans,
722 // Make sure lead distance is initialized otherwise
724 fp->setLeadDistance(speed, hdg, curr, next);
726 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
729 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
730 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
731 // / 6076.0 / prev->getSpeed()*60.0);
732 double vert_dist_ft = curr->getCrossat() - altitude_ft;
733 double err_dist = prev->getCrossat() - altitude_ft;
734 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
735 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
737 tgt_altitude_ft = curr->getCrossat();
740 tgt_altitude_ft = prev->getAltitude();
742 alt_lock = hdg_lock = true;
743 no_roll = prev->getOn_ground();
745 Transform(); // make sure aip is initialized.
746 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
748 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
750 // Make sure to announce the aircraft's position
751 announcePositionToController();
757 * Check Execution time (currently once every 100 ms)
758 * Add a bit of randomization to prevent the execution of all flight plans
759 * in synchrony, which can add significant periodic framerate flutter.
764 bool FGAIAircraft::fpExecutable(time_t now) {
765 double rand_exec_time = (rand() % 100) / 100;
766 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
771 * Check to see if we've reached the lead point for our next turn
776 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
777 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
779 //cerr << "2" << endl;
780 double lead_dist = fp->getLeadDistance();
781 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
782 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
783 tgt_speed = -(dist_to_go / 10.0);
784 if (tgt_speed > -0.5) {
787 //assertSpeed(tgt_speed);
788 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
789 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
792 if (lead_dist < fabs(2*speed)) {
793 //don't skip over the waypoint
794 lead_dist = fabs(2*speed);
795 //cerr << "Extending lead distance to " << lead_dist << endl;
798 //prev_dist_to_go = dist_to_go;
799 //if (dist_to_go < lead_dist)
800 // cerr << trafficRef->getCallSign() << " Distance : "
801 // << dist_to_go << ": Lead distance "
802 // << lead_dist << " " << curr->name
803 // << " Ground target speed " << groundTargetSpeed << endl;
805 // don't do bearing calculations for ground traffic
806 bearing = getBearing(fp->getBearing(pos, curr));
807 if (bearing < minBearing) {
808 minBearing = bearing;
809 if (minBearing < 10) {
812 if ((minBearing < 360.0) && (minBearing > 10.0)) {
813 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
819 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
820 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
821 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
822 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
825 if ((dist_to_go < lead_dist) ||
826 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
829 prev_dist_to_go = HUGE_VAL;
832 prev_dist_to_go = dist_to_go;
838 bool FGAIAircraft::aiTrafficVisible()
840 SGVec3d cartPos = SGVec3d::fromGeod(pos);
841 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
842 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
843 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
848 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
849 * in the case of an arrival.
855 //TODO the trafficRef is the right place for the method
856 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
857 // prepare routing from one airport to another
858 FGAirport * dep = trafficRef->getDepartureAirport();
859 FGAirport * arr = trafficRef->getArrivalAirport();
864 // This waypoint marks the fact that the aircraft has passed the initial taxi
865 // departure waypoint, so it can release the parking.
866 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
867 //cerr << "Passing waypoint : " << prev->getName() << endl;
868 if (prev->contains("PushBackPoint")) {
869 // clearing the parking assignment will release the gate
870 fp->setGate(ParkingAssignment());
872 //setTaxiClearanceRequest(true);
874 if (prev->contains("legend")) {
877 if (prev->contains(string("DepartureHold"))) {
878 //cerr << "Passing point DepartureHold" << endl;
879 scheduleForATCTowerDepartureControl(1);
881 if (prev->contains(string("Accel"))) {
884 //if (prev->contains(string("landing"))) {
885 // if (speed < _performance->vTaxi() * 2) {
886 // fp->shortenToFirst(2, "legend");
889 //if (prev->contains(string("final"))) {
891 // cerr << getCallSign() << " "
892 // << fp->getPreviousWaypoint()->getName()
893 // << ". Alt = " << altitude_ft
895 // << " horizontal speed " << speed
896 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
897 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
898 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
900 // This is the last taxi waypoint, and marks the the end of the flight plan
901 // so, the schedule should update and wait for the next departure time.
902 if (prev->contains("END")) {
903 time_t nextDeparture = trafficRef->getDepartureTime();
904 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
905 if (nextDeparture < (now+1200)) {
906 nextDeparture = now + 1200;
908 fp->setTime(nextDeparture);
916 * Check difference between target bearing and current heading and correct if necessary.
920 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
921 double calc_bearing = fp->getBearing(pos, curr);
922 //cerr << "Bearing = " << calc_bearing << endl;
925 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
928 if (finite(calc_bearing)) {
929 double hdg_error = calc_bearing - tgt_heading;
930 if (fabs(hdg_error) > 0.01) {
931 TurnTo( calc_bearing );
935 cerr << "calc_bearing is not a finite number : "
937 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
938 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
939 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
946 * Update the lead distance calculation if speed has changed sufficiently
947 * to prevent spinning (hopefully);
952 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
953 double speed_diff = speed - prevSpeed;
955 if (fabs(speed_diff) > 10) {
957 //assertSpeed(speed);
959 fp->setLeadDistance(speed, tgt_heading, curr, next);
966 * Update target values (heading, alt, speed) depending on flight plan or control properties
968 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
969 if (fp) // AI object has a flightplan
971 //TODO make this a function of AIBase
972 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
973 //cerr << "UpateTArgetValues() " << endl;
974 ProcessFlightPlan(dt, now);
976 // Do execute Ground elev for inactive aircraft, so they
977 // Are repositioned to the correct ground altitude when the user flies within visibility range.
978 // In addition, check whether we are out of user range, so this aircraft
981 Transform(); // make sure aip is initialized.
985 pos.setElevationFt(altitude_ft);
988 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
989 aiOutOfSight = !aiTrafficVisible();
992 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
997 timeElapsed = now - fp->getStartTime();
998 flightplanActive = fp->isActive(now);
1000 // no flight plan, update target heading, speed, and altitude
1001 // from control properties. These default to the initial
1002 // settings in the config file, but can be changed "on the
1004 const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1005 if ( lat_mode == "roll" ) {
1007 = props->getDoubleValue("controls/flight/target-roll" );
1011 = props->getDoubleValue("controls/flight/target-hdg" );
1016 = props->getStringValue("controls/flight/longitude-mode");
1017 if ( lon_mode == "alt" ) {
1018 double alt = props->getDoubleValue("controls/flight/target-alt" );
1022 = props->getDoubleValue("controls/flight/target-pitch" );
1026 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1030 void FGAIAircraft::updateHeading() {
1031 // adjust heading based on current bank angle
1036 // double turnConstant;
1038 // turnConstant = 0.0088362;
1040 // turnConstant = 0.088362;
1041 // If on ground, calculate heading change directly
1043 double headingDiff = fabs(hdg-tgt_heading);
1044 // double bank_sense = 0.0;
1046 double diff = fabs(hdg - tgt_heading);
1048 diff = fabs(diff - 360);
1050 double sum = hdg + diff;
1053 if (fabs(sum - tgt_heading) < 1.0) {
1054 bank_sense = 1.0; // right turn
1056 bank_sense = -1.0; // left turn
1058 if (headingDiff > 180)
1059 headingDiff = fabs(headingDiff - 360);
1060 double sum = hdg + headingDiff;
1063 if (fabs(sum - tgt_heading) > 0.0001) {
1064 // bank_sense = -1.0;
1066 // bank_sense = 1.0;
1069 // cerr << trafficRef->getCallSign() << " Heading "
1070 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1071 //if (headingDiff > 60) {
1072 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1073 //assertSpeed(groundTargetSpeed);
1074 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1076 // groundTargetSpeed = tgt_speed;
1078 if (sign(groundTargetSpeed) != sign(tgt_speed))
1079 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1080 //assertSpeed(groundTargetSpeed);
1081 // 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.
1083 if (headingDiff > 30.0) {
1084 // invert if pushed backward
1085 headingChangeRate += 10.0 * dt * sign(roll);
1087 // Clamp the maximum steering rate to 30 degrees per second,
1088 // But only do this when the heading error is decreasing.
1089 if ((headingDiff < headingError)) {
1090 if (headingChangeRate > 30)
1091 headingChangeRate = 30;
1092 else if (headingChangeRate < -30)
1093 headingChangeRate = -30;
1097 if (fabs(headingChangeRate) > headingDiff)
1098 headingChangeRate = headingDiff*sign(roll);
1100 headingChangeRate += dt * sign(roll);
1105 //cerr << trafficRef->getCallSign() << " Heading "
1106 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1107 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1108 headingError = headingDiff;
1109 if (fabs(headingError) < 1.0) {
1113 if (fabs(speed) > 1.0) {
1114 turn_radius_ft = 0.088362 * speed * speed
1115 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1117 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1118 turn_radius_ft = 1.0;
1120 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1121 double dist_covered_ft = speed * 1.686 * dt;
1122 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1123 hdg += alpha * sign(roll);
1125 while ( hdg > 360.0 ) {
1129 while ( hdg < 0.0) {
1137 void FGAIAircraft::updateBankAngleTarget() {
1138 // adjust target bank angle if heading lock engaged
1140 double bank_sense = 0.0;
1141 double diff = fabs(hdg - tgt_heading);
1143 diff = fabs(diff - 360);
1145 double sum = hdg + diff;
1148 if (fabs(sum - tgt_heading) < 1.0) {
1149 bank_sense = 1.0; // right turn
1151 bank_sense = -1.0; // left turn
1153 if (diff < _performance->maximumBankAngle()) {
1154 tgt_roll = diff * bank_sense;
1156 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1158 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1159 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1160 // The only way to resolve this is to make them slow down.
1166 void FGAIAircraft::updateVerticalSpeedTarget() {
1167 // adjust target Altitude, based on ground elevation when on ground
1171 } else if (alt_lock) {
1172 // find target vertical speed
1174 if (altitude_ft < tgt_altitude_ft) {
1175 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1177 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1180 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1181 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1182 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1183 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1184 //cerr << "Target vs before : " << tgt_vs;
1185 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1186 double min_vs = 100;
1187 if (tgt_altitude_ft < altitude_ft)
1189 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1190 && (fabs(max_vs) < fabs(tgt_vs)))
1193 if (fabs(tgt_vs) < fabs(min_vs))
1195 //cerr << "target vs : after " << tgt_vs << endl;
1202 void FGAIAircraft::updatePitchAngleTarget() {
1203 // if on ground and above vRotate -> initial rotation
1204 if (onGround() && (speed > _performance->vRotate()))
1205 tgt_pitch = 8.0; // some rough B737 value
1207 //TODO pitch angle on approach and landing
1209 // match pitch angle to vertical speed
1210 else if (tgt_vs > 0) {
1211 tgt_pitch = tgt_vs * 0.005;
1213 tgt_pitch = tgt_vs * 0.002;
1217 const string& FGAIAircraft::atGate()
1219 if ((fp->getLeg() < 3) && trafficRef) {
1220 if (fp->getParkingGate()) {
1221 return fp->getParkingGate()->ident();
1225 static const string empty;
1229 void FGAIAircraft::handleATCRequests() {
1230 //TODO implement NullController for having no ATC to save the conditionals
1232 controller->updateAircraftInformation(getID(),
1233 pos.getLatitudeDeg(),
1234 pos.getLongitudeDeg(),
1238 processATC(controller->getInstruction(getID()));
1240 if (towerController) {
1241 towerController->updateAircraftInformation(getID(),
1242 pos.getLatitudeDeg(),
1243 pos.getLongitudeDeg(),
1250 void FGAIAircraft::updateActualState() {
1251 //update current state
1252 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1253 double distance = speed * SG_KT_TO_MPS * dt;
1254 pos = SGGeodesy::direct(pos, hdg, distance);
1258 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1260 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1261 //assertSpeed(speed);
1263 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1265 // adjust altitude (meters) based on current vertical speed (fpm)
1266 altitude_ft += vs / 60.0 * dt;
1267 pos.setElevationFt(altitude_ft);
1269 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1270 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1273 void FGAIAircraft::updateSecondaryTargetValues() {
1274 // derived target state values
1275 updateBankAngleTarget();
1276 updateVerticalSpeedTarget();
1277 updatePitchAngleTarget();
1279 //TODO calculate wind correction angle (tgt_yaw)
1283 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1284 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1285 if (curr->getName() == string("BOD")) {
1286 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1287 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1288 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1290 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1291 double descentTimeNeeded = verticalDistance / descentRate;
1292 double distanceCovered = descentSpeed * descentTimeNeeded;
1294 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1295 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1296 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1297 cerr << "Descent rate : " << descentRate << endl;
1298 cerr << "Descent speed : " << descentSpeed << endl;
1299 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1300 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1301 cerr << "DistanceCovered : " << distanceCovered << endl;
1303 //cerr << "Distance = " << distance << endl;
1304 distance = distanceCovered;
1305 if (dist < distanceCovered) {
1306 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1318 void FGAIAircraft::resetPositionFromFlightPlan()
1320 // the one behind you
1321 FGAIWaypoint* prev = 0;
1323 FGAIWaypoint* curr = 0;
1325 FGAIWaypoint* next = 0;
1327 prev = fp->getPreviousWaypoint();
1328 curr = fp->getCurrentWaypoint();
1329 next = fp->getNextWaypoint();
1331 setLatitude(prev->getLatitude());
1332 setLongitude(prev->getLongitude());
1333 double tgt_heading = fp->getBearing(curr, next);
1334 setHeading(tgt_heading);
1335 setAltitude(prev->getAltitude());
1336 setSpeed(prev->getSpeed());
1339 double FGAIAircraft::getBearing(double crse)
1341 double hdgDiff = fabs(hdg-crse);
1343 hdgDiff = fabs(hdgDiff - 360);
1347 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1348 FGAIWaypoint* curr = 0;
1349 curr = fp->getCurrentWaypoint();
1351 // don't recalculate tracklength unless the start/stop waypoint has changed
1353 ((curr->getName() != trackCache.startWptName)||
1354 (wptName != trackCache.finalWptName)))
1356 trackCache.remainingLength = fp->checkTrackLength(wptName);
1357 trackCache.startWptName = curr->getName();
1358 trackCache.finalWptName = wptName;
1360 double tracklength = trackCache.remainingLength;
1361 if (tracklength > 0.1) {
1362 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1366 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1367 time_t arrivalTime = fp->getArrivalTime();
1369 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1370 time_t secondsToGo = arrivalTime - now;
1371 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1372 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1374 return (ete - secondsToGo); // Positive when we're too slow...
1377 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1379 double delta = target - cur;
1380 double maxDelta = maxDeltaSec * dt;
1382 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1383 return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1386 // drive various properties in a semi-realistic fashion.
1387 void FGAIAircraft::updateModelProperties(double dt)
1393 SGPropertyNode* gear = props->getChild("gear", 0, true);
1394 double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1395 if (!gear->hasValue("gear/position-norm")) {
1396 gear->setDoubleValue("gear/position-norm", targetGearPos);
1399 double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1400 if (gearPosNorm != targetGearPos) {
1401 gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1402 if (gearPosNorm < 0.001) {
1404 } else if (gearPosNorm > 0.999) {
1408 for (int i=0; i<6; ++i) {
1409 SGPropertyNode* g = gear->getChild("gear", i, true);
1410 g->setDoubleValue("position-norm", gearPosNorm);
1411 } // of gear setting loop
1412 } // of gear in-transit
1414 // double flapPosNorm = props->getDoubleValue();