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"
51 //#include <Airports/trafficcontroller.hxx>
53 static string tempReg;
55 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
56 /* HOT must be disabled for AI Aircraft,
57 * otherwise traffic detection isn't working as expected.*/
58 FGAIBase(otAircraft, false)
62 groundOffset = trafficRef->getGroundOffset();
63 setCallSign(trafficRef->getCallSign());
79 groundTargetSpeed = 0;
81 // set heading and altitude locks
85 headingChangeRate = 0.0;
91 needsTaxiClearance = false;
92 _needsGroundElevation = true;
94 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
96 scheduledForTakeoff = false;
100 FGAIAircraft::~FGAIAircraft() {
103 controller->signOff(getID());
107 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
111 FGAIBase::readFromScenario(scFileNode);
113 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
114 setFlightPlan(scFileNode->getStringValue("flightplan"),
115 scFileNode->getBoolValue("repeat", false));
116 setCallSign(scFileNode->getStringValue("callsign"));
120 void FGAIAircraft::bind() {
123 props->tie("controls/gear/gear-down",
124 SGRawValueMethods<FGAIAircraft,bool>(*this,
125 &FGAIAircraft::_getGearDown));
126 props->tie("transponder-id",
127 SGRawValueMethods<FGAIAircraft,const char*>(*this,
128 &FGAIAircraft::_getTransponderCode));
132 void FGAIAircraft::unbind() {
135 props->untie("controls/gear/gear-down");
136 props->untie("transponder-id");
140 void FGAIAircraft::update(double dt) {
141 FGAIBase::update(dt);
146 void FGAIAircraft::setPerformance(const std::string& acclass) {
147 static PerformanceDB perfdb; //TODO make it a global service
148 setPerformance(perfdb.getDataFor(acclass));
152 void FGAIAircraft::setPerformance(PerformanceData *ps) {
157 void FGAIAircraft::Run(double dt) {
158 FGAIAircraft::dt = dt;
160 bool outOfSight = false,
161 flightplanActive = true;
162 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
167 if (!flightplanActive) {
168 groundTargetSpeed = 0;
171 handleATCRequests(); // ATC also has a word to say
172 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
174 // We currently have one situation in which an AIAircraft object is used that is not attached to the
175 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
176 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
179 UpdateRadar(manager);
183 void FGAIAircraft::checkVisibility()
185 double visibility_meters = fgGetDouble("/environment/visibility-m");
186 FGViewer* vw = globals->get_current_view();
187 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
192 void FGAIAircraft::AccelTo(double speed) {
195 _needsGroundElevation = true;
199 void FGAIAircraft::PitchTo(double angle) {
205 void FGAIAircraft::RollTo(double angle) {
211 void FGAIAircraft::YawTo(double angle) {
216 void FGAIAircraft::ClimbTo(double alt_ft ) {
217 tgt_altitude_ft = alt_ft;
222 void FGAIAircraft::TurnTo(double heading) {
223 tgt_heading = heading;
228 double FGAIAircraft::sign(double x) {
236 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
237 if (!flightplan.empty()) {
238 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
239 fp->setRepeat(repeat);
245 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
251 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
253 // the one behind you
254 FGAIWaypoint* prev = 0;
256 FGAIWaypoint* curr = 0;
258 FGAIWaypoint* next = 0;
260 prev = fp->getPreviousWaypoint();
261 curr = fp->getCurrentWaypoint();
262 next = fp->getNextWaypoint();
266 ///////////////////////////////////////////////////////////////////////////
267 // Initialize the flightplan
268 //////////////////////////////////////////////////////////////////////////
270 handleFirstWaypoint();
272 } // end of initialization
273 if (! fpExecutable(now))
277 double distanceToDescent;
278 if(reachedEndOfCruise(distanceToDescent)) {
279 if (!loadNextLeg(distanceToDescent)) {
283 prev = fp->getPreviousWaypoint();
284 curr = fp->getCurrentWaypoint();
285 next = fp->getNextWaypoint();
287 if (! leadPointReached(curr)) {
288 controlHeading(curr);
289 controlSpeed(curr, next);
292 cerr << getCallSign()
293 << ": verifying lead distance to waypoint : "
294 << fp->getCurrentWaypoint()->name << " "
295 << fp->getLeadDistance() << ". Distance to go "
296 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
297 << ". Target speed = "
299 << ". Current speed = "
301 << ". Minimum Bearing " << minBearing
305 if (curr->isFinished()) //end of the flight plan
315 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
316 tgt_heading = fp->getBearing(curr, next);
320 //TODO let the fp handle this (loading of next leg)
321 fp->IncrementWaypoint( trafficRef != 0 );
322 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
323 if (!loadNextLeg()) {
328 prev = fp->getPreviousWaypoint();
329 curr = fp->getCurrentWaypoint();
330 next = fp->getNextWaypoint();
332 // Now that we have incremented the waypoints, excute some traffic manager specific code
334 //TODO isn't this best executed right at the beginning?
335 if (! aiTrafficVisible()) {
340 if (! handleAirportEndPoints(prev, now)) {
345 announcePositionToController();
350 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
353 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
355 tgt_altitude_ft = prev->getAltitude();
356 if (curr->getCrossat() > -1000.0) {
358 tgt_vs = (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
359 / 6076.0 / speed*60.0);
361 tgt_altitude_ft = curr->getCrossat();
366 AccelTo(prev->getSpeed());
367 hdg_lock = alt_lock = true;
368 no_roll = prev->getOn_ground();
372 void FGAIAircraft::checkTcas(void)
374 if (props->getIntValue("tcas/threat-level",0)==3)
376 int RASense = props->getIntValue("tcas/ra-sense",0);
377 if ((RASense>0)&&(tgt_vs<4000))
383 // downward RA: descend!
384 if (altitude_ft < 1000)
386 // too low: level off
399 void FGAIAircraft::initializeFlightPlan() {
403 bool FGAIAircraft::_getGearDown() const {
404 return _performance->gearExtensible(this);
408 const char * FGAIAircraft::_getTransponderCode() const {
409 return transponderCode.c_str();
412 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
413 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
415 bool FGAIAircraft::loadNextLeg(double distance) {
418 if ((leg = fp->getLeg()) == 9) {
419 if (!trafficRef->next()) {
422 setCallSign(trafficRef->getCallSign());
427 FGAirport *dep = trafficRef->getDepartureAirport();
428 FGAirport *arr = trafficRef->getArrivalAirport();
433 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
440 trafficRef->getSpeed(),
444 trafficRef->getRadius(),
445 trafficRef->getFlightType(),
449 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
455 // Note: This code is copied from David Luff's AILocalTraffic
456 // Warning - ground elev determination is CPU intensive
457 // Either this function or the logic of how often it is called
458 // will almost certainly change.
460 void FGAIAircraft::getGroundElev(double dt) {
463 if (!needGroundElevation())
465 // Update minimally every three secs, but add some randomness
466 // to prevent all AI objects doing this in synchrony
467 if (dt_elev_count < (3.0) + (rand() % 10))
472 // Only do the proper hitlist stuff if we are within visible range of the viewer.
474 double visibility_meters = fgGetDouble("/environment/visibility-m");
475 FGViewer* vw = globals->get_current_view();
477 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
481 double range = 500.0;
482 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
485 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
487 tgt_altitude_ft = alt * SG_METER_TO_FEET;
490 // aircraft is stationary and we obtained altitude for this spot - we're done.
491 _needsGroundElevation = false;
499 void FGAIAircraft::doGroundAltitude() {
500 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
502 altitude_ft = (tgt_altitude_ft + groundOffset);
504 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
509 void FGAIAircraft::announcePositionToController() {
511 int leg = fp->getLeg();
513 // Note that leg has been incremented after creating the current leg, so we should use
514 // leg numbers here that are one higher than the number that is used to create the leg
515 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
516 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
517 // the original leg numbers here!
519 case 1: // Startup and Push back
520 if (trafficRef->getDepartureAirport()->getDynamics())
521 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
523 case 2: // Taxiing to runway
524 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
525 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
527 case 3: //Take off tower controller
528 if (trafficRef->getDepartureAirport()->getDynamics()) {
529 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
531 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
535 if (trafficRef->getDepartureAirport()->getDynamics()) {
536 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
539 case 8: // Taxiing for parking
540 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
541 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
548 if ((controller != prevController) && (prevController != 0)) {
549 prevController->signOff(getID());
551 prevController = controller;
553 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
554 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
555 trafficRef->getRadius(), leg, this);
560 void FGAIAircraft::scheduleForATCTowerDepartureControl() {
561 if (!scheduledForTakeoff) {
562 int leg = fp->getLeg();
564 if (trafficRef->getDepartureAirport()->getDynamics()) {
565 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
567 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
569 if (towerController) {
570 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
571 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
572 trafficRef->getRadius(), leg, this);
576 scheduledForTakeoff = true;
579 // Process ATC instructions and report back
581 void FGAIAircraft::processATC(FGATCInstruction instruction) {
582 if (instruction.getCheckForCircularWait()) {
583 // This is not exactly an elegant solution,
584 // but at least it gives me a chance to check
585 // if circular waits are resolved.
586 // For now, just take the offending aircraft
589 // a more proper way should be - of course - to
590 // let an offending aircraft take an evasive action
591 // for instance taxi back a little bit.
593 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
594 if (instruction.getHoldPattern ()) {}
597 if (instruction.getHoldPosition ()) {
605 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
608 // Change speed Instruction. This can only be excecuted when there is no
609 // Hold position instruction.
610 if (instruction.getChangeSpeed ()) {
612 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
613 AccelTo(instruction.getSpeed());
615 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
618 if (instruction.getChangeHeading ()) {
620 TurnTo(instruction.getHeading());
626 if (instruction.getChangeAltitude()) {}
631 void FGAIAircraft::handleFirstWaypoint() {
632 bool eraseWaypoints; //TODO YAGNI
635 eraseWaypoints = true;
637 eraseWaypoints = false;
640 FGAIWaypoint* prev = 0; // the one behind you
641 FGAIWaypoint* curr = 0; // the one ahead
642 FGAIWaypoint* next = 0;// the next plus 1
647 //TODO fp should handle this
648 fp->IncrementWaypoint(eraseWaypoints);
649 if (!(fp->getNextWaypoint()) && trafficRef)
650 if (!loadNextLeg()) {
655 prev = fp->getPreviousWaypoint(); //first waypoint
656 curr = fp->getCurrentWaypoint(); //second waypoint
657 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
659 setLatitude(prev->getLatitude());
660 setLongitude(prev->getLongitude());
661 setSpeed(prev->getSpeed());
662 setAltitude(prev->getAltitude());
664 if (prev->getSpeed() > 0.0)
665 setHeading(fp->getBearing(prev->getLatitude(), prev->getLongitude(), curr));
667 setHeading(fp->getBearing(curr->getLatitude(), curr->getLongitude(), prev));
669 // If next doesn't exist, as in incrementally created flightplans for
670 // AI/Trafficmanager created plans,
671 // Make sure lead distance is initialized otherwise
673 fp->setLeadDistance(speed, hdg, curr, next);
675 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
678 tgt_vs = (curr->getCrossat() - prev->getAltitude())
679 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
680 / 6076.0 / prev->getSpeed()*60.0);
682 tgt_altitude_ft = curr->getCrossat();
685 tgt_altitude_ft = prev->getAltitude();
687 alt_lock = hdg_lock = true;
688 no_roll = prev->getOn_ground();
690 Transform(); // make sure aip is initialized.
691 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
693 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
695 // Make sure to announce the aircraft's position
696 announcePositionToController();
702 * Check Execution time (currently once every 100 ms)
703 * Add a bit of randomization to prevent the execution of all flight plans
704 * in synchrony, which can add significant periodic framerate flutter.
709 bool FGAIAircraft::fpExecutable(time_t now) {
710 double rand_exec_time = (rand() % 100) / 100;
711 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
716 * Check to see if we've reached the lead point for our next turn
721 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
722 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
724 //cerr << "2" << endl;
725 double lead_dist = fp->getLeadDistance();
726 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
727 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
728 tgt_speed = -(dist_to_go / 10.0);
729 if (tgt_speed > -0.5) {
732 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
733 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
736 if (lead_dist < fabs(2*speed)) {
737 //don't skip over the waypoint
738 lead_dist = fabs(2*speed);
739 //cerr << "Extending lead distance to " << lead_dist << endl;
742 //prev_dist_to_go = dist_to_go;
743 //if (dist_to_go < lead_dist)
744 // cerr << trafficRef->getCallSign() << " Distance : "
745 // << dist_to_go << ": Lead distance "
746 // << lead_dist << " " << curr->name
747 // << " Ground target speed " << groundTargetSpeed << endl;
749 if (speed > 50) { // don't do bearing calculations for ground traffic
750 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
751 if (bearing < minBearing) {
752 minBearing = bearing;
753 if (minBearing < 10) {
756 if ((minBearing < 360.0) && (minBearing > 10.0)) {
757 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
764 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
765 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
766 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
767 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
770 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
779 bool FGAIAircraft::aiTrafficVisible() {
780 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
781 fgGetDouble("/position/latitude-deg")));
783 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
788 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
789 * in the case of an arrival.
795 //TODO the trafficRef is the right place for the method
796 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
797 // prepare routing from one airport to another
798 FGAirport * dep = trafficRef->getDepartureAirport();
799 FGAirport * arr = trafficRef->getArrivalAirport();
804 // This waypoint marks the fact that the aircraft has passed the initial taxi
805 // departure waypoint, so it can release the parking.
806 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
807 if (prev->contains("PushBackPoint")) {
808 dep->getDynamics()->releaseParking(fp->getGate());
810 setTaxiClearanceRequest(true);
812 if (prev->contains("legend")) {
815 if (prev->contains(string("DepartureHold"))) {
816 scheduleForATCTowerDepartureControl();
819 // This is the last taxi waypoint, and marks the the end of the flight plan
820 // so, the schedule should update and wait for the next departure time.
821 if (prev->contains("END")) {
822 time_t nextDeparture = trafficRef->getDepartureTime();
823 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
824 if (nextDeparture < (now+1200)) {
825 nextDeparture = now + 1200;
827 fp->setTime(nextDeparture); // should be "next departure"
835 * Check difference between target bearing and current heading and correct if necessary.
839 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
840 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
841 //cerr << "Bearing = " << calc_bearing << endl;
844 if (calc_bearing > 360)
848 if (finite(calc_bearing)) {
849 double hdg_error = calc_bearing - tgt_heading;
850 if (fabs(hdg_error) > 0.01) {
851 TurnTo( calc_bearing );
855 cerr << "calc_bearing is not a finite number : "
857 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
858 << "waypoint " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
859 cerr << "waypoint name " << curr->getName();
866 * Update the lead distance calculation if speed has changed sufficiently
867 * to prevent spinning (hopefully);
872 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
873 double speed_diff = speed - prevSpeed;
875 if (fabs(speed_diff) > 10) {
878 fp->setLeadDistance(speed, tgt_heading, curr, next);
885 * Update target values (heading, alt, speed) depending on flight plan or control properties
887 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
888 if (fp) // AI object has a flightplan
890 //TODO make this a function of AIBase
891 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
892 //cerr << "UpateTArgetValues() " << endl;
893 ProcessFlightPlan(dt, now);
895 // Do execute Ground elev for inactive aircraft, so they
896 // Are repositioned to the correct ground altitude when the user flies within visibility range.
897 // In addition, check whether we are out of user range, so this aircraft
900 Transform(); // make sure aip is initialized.
904 pos.setElevationFt(altitude_ft);
907 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
908 aiOutOfSight = !aiTrafficVisible();
911 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
916 timeElapsed = now - fp->getStartTime();
917 flightplanActive = fp->isActive(now);
919 // no flight plan, update target heading, speed, and altitude
920 // from control properties. These default to the initial
921 // settings in the config file, but can be changed "on the
923 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
924 if ( lat_mode == "roll" ) {
926 = props->getDoubleValue("controls/flight/target-roll" );
930 = props->getDoubleValue("controls/flight/target-hdg" );
935 = props->getStringValue("controls/flight/longitude-mode");
936 if ( lon_mode == "alt" ) {
937 double alt = props->getDoubleValue("controls/flight/target-alt" );
941 = props->getDoubleValue("controls/flight/target-pitch" );
945 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
949 void FGAIAircraft::updatePosition() {
950 // convert speed to degrees per second
951 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
952 * speed * 1.686 / ft_per_deg_lat;
953 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
954 * speed * 1.686 / ft_per_deg_lon;
957 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
958 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
962 void FGAIAircraft::updateHeading() {
963 // adjust heading based on current bank angle
968 // double turnConstant;
970 // turnConstant = 0.0088362;
972 // turnConstant = 0.088362;
973 // If on ground, calculate heading change directly
975 double headingDiff = fabs(hdg-tgt_heading);
976 double bank_sense = 0.0;
978 double diff = fabs(hdg - tgt_heading);
980 diff = fabs(diff - 360);
982 double sum = hdg + diff;
985 if (fabs(sum - tgt_heading) < 1.0) {
986 bank_sense = 1.0; // right turn
988 bank_sense = -1.0; // left turn
990 if (headingDiff > 180)
991 headingDiff = fabs(headingDiff - 360);
992 double sum = hdg + headingDiff;
995 if (fabs(sum - tgt_heading) > 0.0001) {
1001 // cerr << trafficRef->getCallSign() << " Heading "
1002 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1003 //if (headingDiff > 60) {
1004 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1005 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1007 // groundTargetSpeed = tgt_speed;
1009 if (sign(groundTargetSpeed) != sign(tgt_speed))
1010 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1012 // 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.
1014 if (headingDiff > 30.0) {
1015 // invert if pushed backward
1016 headingChangeRate += 10.0 * dt * sign(roll);
1018 // Clamp the maximum steering rate to 30 degrees per second,
1019 // But only do this when the heading error is decreasing.
1020 if ((headingDiff < headingError)) {
1021 if (headingChangeRate > 30)
1022 headingChangeRate = 30;
1023 else if (headingChangeRate < -30)
1024 headingChangeRate = -30;
1028 if (fabs(headingChangeRate) > headingDiff)
1029 headingChangeRate = headingDiff*sign(roll);
1031 headingChangeRate += dt * sign(roll);
1036 //cerr << trafficRef->getCallSign() << " Heading "
1037 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1038 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1039 headingError = headingDiff;
1041 if (fabs(speed) > 1.0) {
1042 turn_radius_ft = 0.088362 * speed * speed
1043 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1045 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1046 turn_radius_ft = 1.0;
1048 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1049 double dist_covered_ft = speed * 1.686 * dt;
1050 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1051 hdg += alpha * sign(roll);
1053 while ( hdg > 360.0 ) {
1057 while ( hdg < 0.0) {
1065 void FGAIAircraft::updateBankAngleTarget() {
1066 // adjust target bank angle if heading lock engaged
1068 double bank_sense = 0.0;
1069 double diff = fabs(hdg - tgt_heading);
1071 diff = fabs(diff - 360);
1073 double sum = hdg + diff;
1076 if (fabs(sum - tgt_heading) < 1.0) {
1077 bank_sense = 1.0; // right turn
1079 bank_sense = -1.0; // left turn
1081 if (diff < _performance->maximumBankAngle()) {
1082 tgt_roll = diff * bank_sense;
1084 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1086 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1087 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1088 // The only way to resolve this is to make them slow down.
1094 void FGAIAircraft::updateVerticalSpeedTarget() {
1095 // adjust target Altitude, based on ground elevation when on ground
1099 } else if (alt_lock) {
1100 // find target vertical speed
1102 if (altitude_ft < tgt_altitude_ft) {
1103 tgt_vs = tgt_altitude_ft - altitude_ft;
1104 if (tgt_vs > _performance->climbRate())
1105 tgt_vs = _performance->climbRate();
1107 tgt_vs = tgt_altitude_ft - altitude_ft;
1108 if (tgt_vs < (-_performance->descentRate()))
1109 tgt_vs = -_performance->descentRate();
1112 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1113 double min_vs = 100;
1114 if (tgt_altitude_ft < altitude_ft)
1116 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1117 && (fabs(max_vs) < fabs(tgt_vs)))
1120 if (fabs(tgt_vs) < fabs(min_vs))
1128 void FGAIAircraft::updatePitchAngleTarget() {
1129 // if on ground and above vRotate -> initial rotation
1130 if (onGround() && (speed > _performance->vRotate()))
1131 tgt_pitch = 8.0; // some rough B737 value
1133 //TODO pitch angle on approach and landing
1135 // match pitch angle to vertical speed
1136 else if (tgt_vs > 0) {
1137 tgt_pitch = tgt_vs * 0.005;
1139 tgt_pitch = tgt_vs * 0.002;
1143 string FGAIAircraft::atGate() {
1145 if (fp->getLeg() < 3) {
1147 if (fp->getGate() > 0) {
1149 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1150 tmp = park->getName();
1157 void FGAIAircraft::handleATCRequests() {
1158 //TODO implement NullController for having no ATC to save the conditionals
1160 controller->updateAircraftInformation(getID(),
1161 pos.getLatitudeDeg(),
1162 pos.getLongitudeDeg(),
1166 processATC(controller->getInstruction(getID()));
1170 void FGAIAircraft::updateActualState() {
1171 //update current state
1172 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1176 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1178 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1181 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1183 // adjust altitude (meters) based on current vertical speed (fpm)
1184 altitude_ft += vs / 60.0 * dt;
1185 pos.setElevationFt(altitude_ft);
1187 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1188 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1191 void FGAIAircraft::updateSecondaryTargetValues() {
1192 // derived target state values
1193 updateBankAngleTarget();
1194 updateVerticalSpeedTarget();
1195 updatePitchAngleTarget();
1197 //TODO calculate wind correction angle (tgt_yaw)
1201 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1202 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1203 if (curr->getName() == string("BOD")) {
1204 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1205 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1206 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1208 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1209 double descentTimeNeeded = verticalDistance / descentRate;
1210 double distanceCovered = descentSpeed * descentTimeNeeded;
1212 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1213 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1214 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1215 cerr << "Descent rate : " << descentRate << endl;
1216 cerr << "Descent speed : " << descentSpeed << endl;
1217 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1218 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1219 cerr << "DistanceCovered : " << distanceCovered << endl;
1221 //cerr << "Distance = " << distance << endl;
1222 distance = distanceCovered;
1223 if (dist < distanceCovered) {
1224 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1236 void FGAIAircraft::resetPositionFromFlightPlan()
1238 // the one behind you
1239 FGAIWaypoint* prev = 0;
1241 FGAIWaypoint* curr = 0;
1243 FGAIWaypoint* next = 0;
1245 prev = fp->getPreviousWaypoint();
1246 curr = fp->getCurrentWaypoint();
1247 next = fp->getNextWaypoint();
1249 setLatitude(prev->getLatitude());
1250 setLongitude(prev->getLongitude());
1251 double tgt_heading = fp->getBearing(curr, next);
1252 setHeading(tgt_heading);
1253 setAltitude(prev->getAltitude());
1254 setSpeed(prev->getSpeed());
1257 double FGAIAircraft::getBearing(double crse)
1259 double hdgDiff = fabs(hdg-crse);
1261 hdgDiff = fabs(hdgDiff - 360);
1265 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1266 FGAIWaypoint* curr = 0;
1267 curr = fp->getCurrentWaypoint();
1269 double tracklength = fp->checkTrackLength(wptName);
1270 if (tracklength > 0.1) {
1271 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1275 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1276 time_t arrivalTime = fp->getArrivalTime();
1278 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1279 time_t secondsToGo = arrivalTime - now;
1280 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1281 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1283 return (ete - secondsToGo); // Positive when we're too slow...