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) : FGAIBase(otAircraft) {
58 groundOffset = trafficRef->getGroundOffset();
59 setCallSign(trafficRef->getCallSign());
74 groundTargetSpeed = 0;
76 // set heading and altitude locks
80 headingChangeRate = 0.0;
86 needsTaxiClearance = false;
87 _needsGroundElevation = true;
89 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
94 FGAIAircraft::~FGAIAircraft() {
97 controller->signOff(getID());
101 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
105 FGAIBase::readFromScenario(scFileNode);
107 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
108 setFlightPlan(scFileNode->getStringValue("flightplan"),
109 scFileNode->getBoolValue("repeat", false));
110 setCallSign(scFileNode->getStringValue("callsign"));
114 void FGAIAircraft::bind() {
117 props->tie("controls/gear/gear-down",
118 SGRawValueMethods<FGAIAircraft,bool>(*this,
119 &FGAIAircraft::_getGearDown));
120 props->tie("transponder-id",
121 SGRawValueMethods<FGAIAircraft,const char*>(*this,
122 &FGAIAircraft::_getTransponderCode));
126 void FGAIAircraft::unbind() {
129 props->untie("controls/gear/gear-down");
130 props->untie("transponder-id");
134 void FGAIAircraft::update(double dt) {
135 FGAIBase::update(dt);
140 void FGAIAircraft::setPerformance(const std::string& acclass) {
141 static PerformanceDB perfdb; //TODO make it a global service
142 setPerformance(perfdb.getDataFor(acclass));
146 void FGAIAircraft::setPerformance(PerformanceData *ps) {
151 void FGAIAircraft::Run(double dt) {
152 FGAIAircraft::dt = dt;
154 bool outOfSight = false,
155 flightplanActive = true;
156 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
161 if (!flightplanActive) {
162 groundTargetSpeed = 0;
165 handleATCRequests(); // ATC also has a word to say
166 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
168 // We currently have one situation in which an AIAircraft object is used that is not attached to the
169 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
170 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
173 UpdateRadar(manager);
177 void FGAIAircraft::checkVisibility()
179 double visibility_meters = fgGetDouble("/environment/visibility-m");
180 FGViewer* vw = globals->get_current_view();
181 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
186 void FGAIAircraft::AccelTo(double speed) {
189 _needsGroundElevation = true;
193 void FGAIAircraft::PitchTo(double angle) {
199 void FGAIAircraft::RollTo(double angle) {
205 void FGAIAircraft::YawTo(double angle) {
210 void FGAIAircraft::ClimbTo(double alt_ft ) {
211 tgt_altitude_ft = alt_ft;
216 void FGAIAircraft::TurnTo(double heading) {
217 tgt_heading = heading;
222 double FGAIAircraft::sign(double x) {
230 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
231 if (!flightplan.empty()) {
232 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
233 fp->setRepeat(repeat);
239 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
245 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
247 // the one behind you
248 FGAIFlightPlan::waypoint* prev = 0;
250 FGAIFlightPlan::waypoint* curr = 0;
252 FGAIFlightPlan::waypoint* next = 0;
254 prev = fp->getPreviousWaypoint();
255 curr = fp->getCurrentWaypoint();
256 next = fp->getNextWaypoint();
260 ///////////////////////////////////////////////////////////////////////////
261 // Initialize the flightplan
262 //////////////////////////////////////////////////////////////////////////
264 handleFirstWaypoint();
266 } // end of initialization
267 if (! fpExecutable(now))
271 double distanceToDescent;
272 if(reachedEndOfCruise(distanceToDescent)) {
273 if (!loadNextLeg(distanceToDescent)) {
277 prev = fp->getPreviousWaypoint();
278 curr = fp->getCurrentWaypoint();
279 next = fp->getNextWaypoint();
281 if (! leadPointReached(curr)) {
282 controlHeading(curr);
283 controlSpeed(curr, next);
285 cerr << getCallSign()
286 << ": verifying lead distance to waypoint : "
287 << fp->getCurrentWaypoint()->name << " "
288 << fp->getLeadDistance() << ". Distance to go "
289 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
290 << ". Target speed = "
292 << ". Current speed = "
294 << ". Minimum Bearing " << minBearing
298 if (curr->finished) //end of the flight plan
308 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
309 tgt_heading = fp->getBearing(curr, next);
313 //TODO let the fp handle this (loading of next leg)
314 fp->IncrementWaypoint( trafficRef != 0 );
315 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
316 if (!loadNextLeg()) {
321 prev = fp->getPreviousWaypoint();
322 curr = fp->getCurrentWaypoint();
323 next = fp->getNextWaypoint();
325 // Now that we have incremented the waypoints, excute some traffic manager specific code
327 //TODO isn't this best executed right at the beginning?
328 if (! aiTrafficVisible()) {
333 if (! handleAirportEndPoints(prev, now)) {
338 announcePositionToController();
343 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
346 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
348 tgt_altitude_ft = prev->altitude;
349 if (curr->crossat > -1000.0) {
351 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
352 / 6076.0 / speed*60.0);
354 tgt_altitude_ft = curr->crossat;
359 AccelTo(prev->speed);
360 hdg_lock = alt_lock = true;
361 no_roll = prev->on_ground;
365 void FGAIAircraft::checkTcas(void)
367 if (props->getIntValue("tcas/threat-level",0)==3)
369 int RASense = props->getIntValue("tcas/ra-sense",0);
370 if ((RASense>0)&&(tgt_vs<4000))
376 // downward RA: descend!
377 if (altitude_ft < 1000)
379 // too low: level off
392 void FGAIAircraft::initializeFlightPlan() {
396 bool FGAIAircraft::_getGearDown() const {
397 return _performance->gearExtensible(this);
401 const char * FGAIAircraft::_getTransponderCode() const {
402 return transponderCode.c_str();
406 bool FGAIAircraft::loadNextLeg(double distance) {
409 if ((leg = fp->getLeg()) == 10) {
410 if (!trafficRef->next()) {
413 setCallSign(trafficRef->getCallSign());
418 FGAirport *dep = trafficRef->getDepartureAirport();
419 FGAirport *arr = trafficRef->getArrivalAirport();
424 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
431 trafficRef->getSpeed(),
435 trafficRef->getRadius(),
436 trafficRef->getFlightType(),
440 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
446 // Note: This code is copied from David Luff's AILocalTraffic
447 // Warning - ground elev determination is CPU intensive
448 // Either this function or the logic of how often it is called
449 // will almost certainly change.
451 void FGAIAircraft::getGroundElev(double dt) {
454 if (!needGroundElevation())
456 // Update minimally every three secs, but add some randomness
457 // to prevent all AI objects doing this in synchrony
458 if (dt_elev_count < (3.0) + (rand() % 10))
463 // Only do the proper hitlist stuff if we are within visible range of the viewer.
465 double visibility_meters = fgGetDouble("/environment/visibility-m");
466 FGViewer* vw = globals->get_current_view();
468 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
472 double range = 500.0;
473 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
476 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
478 tgt_altitude_ft = alt * SG_METER_TO_FEET;
481 // aircraft is stationary and we obtained altitude for this spot - we're done.
482 _needsGroundElevation = false;
490 void FGAIAircraft::doGroundAltitude() {
491 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
493 altitude_ft = (tgt_altitude_ft + groundOffset);
495 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
500 void FGAIAircraft::announcePositionToController() {
502 int leg = fp->getLeg();
504 // Note that leg has been incremented after creating the current leg, so we should use
505 // leg numbers here that are one higher than the number that is used to create the leg
508 case 2: // Startup and Push back
509 if (trafficRef->getDepartureAirport()->getDynamics())
510 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
512 case 3: // Taxiing to runway
513 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
514 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
516 case 4: //Take off tower controller
517 if (trafficRef->getDepartureAirport()->getDynamics()) {
518 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
520 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
524 if (trafficRef->getDepartureAirport()->getDynamics()) {
525 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
528 case 9: // Taxiing for parking
529 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
530 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
537 if ((controller != prevController) && (prevController != 0)) {
538 prevController->signOff(getID());
540 prevController = controller;
542 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
543 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
544 trafficRef->getRadius(), leg, this);
549 // Process ATC instructions and report back
551 void FGAIAircraft::processATC(FGATCInstruction instruction) {
552 if (instruction.getCheckForCircularWait()) {
553 // This is not exactly an elegant solution,
554 // but at least it gives me a chance to check
555 // if circular waits are resolved.
556 // For now, just take the offending aircraft
559 // a more proper way should be - of course - to
560 // let an offending aircraft take an evasive action
561 // for instance taxi back a little bit.
563 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
564 if (instruction.getHoldPattern ()) {}
567 if (instruction.getHoldPosition ()) {
575 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
578 // Change speed Instruction. This can only be excecuted when there is no
579 // Hold position instruction.
580 if (instruction.getChangeSpeed ()) {
582 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
583 AccelTo(instruction.getSpeed());
585 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
588 if (instruction.getChangeHeading ()) {
590 TurnTo(instruction.getHeading());
596 if (instruction.getChangeAltitude()) {}
601 void FGAIAircraft::handleFirstWaypoint() {
602 bool eraseWaypoints; //TODO YAGNI
605 eraseWaypoints = true;
607 eraseWaypoints = false;
610 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
611 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
612 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
617 //TODO fp should handle this
618 fp->IncrementWaypoint(eraseWaypoints);
619 if (!(fp->getNextWaypoint()) && trafficRef)
620 if (!loadNextLeg()) {
625 prev = fp->getPreviousWaypoint(); //first waypoint
626 curr = fp->getCurrentWaypoint(); //second waypoint
627 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
629 setLatitude(prev->latitude);
630 setLongitude(prev->longitude);
631 setSpeed(prev->speed);
632 setAltitude(prev->altitude);
634 if (prev->speed > 0.0)
635 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
637 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
639 // If next doesn't exist, as in incrementally created flightplans for
640 // AI/Trafficmanager created plans,
641 // Make sure lead distance is initialized otherwise
643 fp->setLeadDistance(speed, hdg, curr, next);
645 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
648 tgt_vs = (curr->crossat - prev->altitude)
649 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
650 / 6076.0 / prev->speed*60.0);
652 tgt_altitude_ft = curr->crossat;
655 tgt_altitude_ft = prev->altitude;
657 alt_lock = hdg_lock = true;
658 no_roll = prev->on_ground;
660 Transform(); // make sure aip is initialized.
661 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
663 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
665 // Make sure to announce the aircraft's position
666 announcePositionToController();
672 * Check Execution time (currently once every 100 ms)
673 * Add a bit of randomization to prevent the execution of all flight plans
674 * in synchrony, which can add significant periodic framerate flutter.
679 bool FGAIAircraft::fpExecutable(time_t now) {
680 double rand_exec_time = (rand() % 100) / 100;
681 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
686 * Check to see if we've reached the lead point for our next turn
691 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
692 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
694 //cerr << "2" << endl;
695 double lead_dist = fp->getLeadDistance();
696 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
697 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->name == string("PushBackPoint")) {
698 tgt_speed = -(dist_to_go / 10.0);
699 if (tgt_speed > -0.5) {
702 if (fp->getPreviousWaypoint()->speed < tgt_speed) {
703 fp->getPreviousWaypoint()->speed = tgt_speed;
706 if (lead_dist < fabs(2*speed)) {
707 //don't skip over the waypoint
708 lead_dist = fabs(2*speed);
709 //cerr << "Extending lead distance to " << lead_dist << endl;
712 //prev_dist_to_go = dist_to_go;
713 //if (dist_to_go < lead_dist)
714 // cerr << trafficRef->getCallSign() << " Distance : "
715 // << dist_to_go << ": Lead distance "
716 // << lead_dist << " " << curr->name
717 // << " Ground target speed " << groundTargetSpeed << endl;
719 if (speed > 50) { // don't do bearing calculations for ground traffic
720 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
721 if (bearing < minBearing) {
722 minBearing = bearing;
723 if (minBearing < 10) {
726 if ((minBearing < 360.0) && (minBearing > 10.0)) {
727 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
734 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
735 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
736 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
737 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
740 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
749 bool FGAIAircraft::aiTrafficVisible() {
750 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
751 fgGetDouble("/position/latitude-deg")));
753 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
758 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
759 * in the case of an arrival.
765 //TODO the trafficRef is the right place for the method
766 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
767 // prepare routing from one airport to another
768 FGAirport * dep = trafficRef->getDepartureAirport();
769 FGAirport * arr = trafficRef->getArrivalAirport();
774 // This waypoint marks the fact that the aircraft has passed the initial taxi
775 // departure waypoint, so it can release the parking.
776 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
777 if (prev->name == "PushBackPoint") {
778 dep->getDynamics()->releaseParking(fp->getGate());
780 setTaxiClearanceRequest(true);
783 // This is the last taxi waypoint, and marks the the end of the flight plan
784 // so, the schedule should update and wait for the next departure time.
785 if (prev->name == "END") {
786 time_t nextDeparture = trafficRef->getDepartureTime();
787 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
788 if (nextDeparture < (now+1200)) {
789 nextDeparture = now + 1200;
791 fp->setTime(nextDeparture); // should be "next departure"
799 * Check difference between target bearing and current heading and correct if necessary.
803 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
804 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
805 //cerr << "Bearing = " << calc_bearing << endl;
808 if (calc_bearing > 360)
812 if (finite(calc_bearing)) {
813 double hdg_error = calc_bearing - tgt_heading;
814 if (fabs(hdg_error) > 0.01) {
815 TurnTo( calc_bearing );
819 cerr << "calc_bearing is not a finite number : "
821 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
822 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
823 cerr << "waypoint name " << curr->name;
830 * Update the lead distance calculation if speed has changed sufficiently
831 * to prevent spinning (hopefully);
836 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
837 double speed_diff = speed - prevSpeed;
839 if (fabs(speed_diff) > 10) {
842 fp->setLeadDistance(speed, tgt_heading, curr, next);
849 * Update target values (heading, alt, speed) depending on flight plan or control properties
851 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
852 if (fp) // AI object has a flightplan
854 //TODO make this a function of AIBase
855 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
856 //cerr << "UpateTArgetValues() " << endl;
857 ProcessFlightPlan(dt, now);
859 // Do execute Ground elev for inactive aircraft, so they
860 // Are repositioned to the correct ground altitude when the user flies within visibility range.
861 // In addition, check whether we are out of user range, so this aircraft
864 Transform(); // make sure aip is initialized.
868 pos.setElevationFt(altitude_ft);
871 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
872 aiOutOfSight = !aiTrafficVisible();
875 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
880 timeElapsed = now - fp->getStartTime();
881 flightplanActive = fp->isActive(now);
883 // no flight plan, update target heading, speed, and altitude
884 // from control properties. These default to the initial
885 // settings in the config file, but can be changed "on the
887 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
888 if ( lat_mode == "roll" ) {
890 = props->getDoubleValue("controls/flight/target-roll" );
894 = props->getDoubleValue("controls/flight/target-hdg" );
899 = props->getStringValue("controls/flight/longitude-mode");
900 if ( lon_mode == "alt" ) {
901 double alt = props->getDoubleValue("controls/flight/target-alt" );
905 = props->getDoubleValue("controls/flight/target-pitch" );
909 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
913 void FGAIAircraft::updatePosition() {
914 // convert speed to degrees per second
915 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
916 * speed * 1.686 / ft_per_deg_lat;
917 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
918 * speed * 1.686 / ft_per_deg_lon;
921 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
922 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
926 void FGAIAircraft::updateHeading() {
927 // adjust heading based on current bank angle
932 // double turnConstant;
934 // turnConstant = 0.0088362;
936 // turnConstant = 0.088362;
937 // If on ground, calculate heading change directly
939 double headingDiff = fabs(hdg-tgt_heading);
940 double bank_sense = 0.0;
942 double diff = fabs(hdg - tgt_heading);
944 diff = fabs(diff - 360);
946 double sum = hdg + diff;
949 if (fabs(sum - tgt_heading) < 1.0) {
950 bank_sense = 1.0; // right turn
952 bank_sense = -1.0; // left turn
954 if (headingDiff > 180)
955 headingDiff = fabs(headingDiff - 360);
956 double sum = hdg + headingDiff;
959 if (fabs(sum - tgt_heading) > 0.0001) {
965 // cerr << trafficRef->getCallSign() << " Heading "
966 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
967 //if (headingDiff > 60) {
968 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
969 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
971 // groundTargetSpeed = tgt_speed;
973 if (sign(groundTargetSpeed) != sign(tgt_speed))
974 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
976 // 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.
978 if (headingDiff > 30.0) {
979 // invert if pushed backward
980 headingChangeRate += 10.0 * dt * sign(roll);
982 // Clamp the maximum steering rate to 30 degrees per second,
983 // But only do this when the heading error is decreasing.
984 if ((headingDiff < headingError)) {
985 if (headingChangeRate > 30)
986 headingChangeRate = 30;
987 else if (headingChangeRate < -30)
988 headingChangeRate = -30;
992 if (fabs(headingChangeRate) > headingDiff)
993 headingChangeRate = headingDiff*sign(roll);
995 headingChangeRate += dt * sign(roll);
1000 //cerr << trafficRef->getCallSign() << " Heading "
1001 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1002 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1003 headingError = headingDiff;
1005 if (fabs(speed) > 1.0) {
1006 turn_radius_ft = 0.088362 * speed * speed
1007 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1009 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1010 turn_radius_ft = 1.0;
1012 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1013 double dist_covered_ft = speed * 1.686 * dt;
1014 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1015 hdg += alpha * sign(roll);
1017 while ( hdg > 360.0 ) {
1021 while ( hdg < 0.0) {
1029 void FGAIAircraft::updateBankAngleTarget() {
1030 // adjust target bank angle if heading lock engaged
1032 double bank_sense = 0.0;
1033 double diff = fabs(hdg - tgt_heading);
1035 diff = fabs(diff - 360);
1037 double sum = hdg + diff;
1040 if (fabs(sum - tgt_heading) < 1.0) {
1041 bank_sense = 1.0; // right turn
1043 bank_sense = -1.0; // left turn
1045 if (diff < _performance->maximumBankAngle()) {
1046 tgt_roll = diff * bank_sense;
1048 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1050 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1051 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1052 // The only way to resolve this is to make them slow down.
1058 void FGAIAircraft::updateVerticalSpeedTarget() {
1059 // adjust target Altitude, based on ground elevation when on ground
1063 } else if (alt_lock) {
1064 // find target vertical speed
1066 if (altitude_ft < tgt_altitude_ft) {
1067 tgt_vs = tgt_altitude_ft - altitude_ft;
1068 if (tgt_vs > _performance->climbRate())
1069 tgt_vs = _performance->climbRate();
1071 tgt_vs = tgt_altitude_ft - altitude_ft;
1072 if (tgt_vs < (-_performance->descentRate()))
1073 tgt_vs = -_performance->descentRate();
1076 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1077 double min_vs = 100;
1078 if (tgt_altitude_ft < altitude_ft)
1080 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1081 && (fabs(max_vs) < fabs(tgt_vs)))
1084 if (fabs(tgt_vs) < fabs(min_vs))
1092 void FGAIAircraft::updatePitchAngleTarget() {
1093 // if on ground and above vRotate -> initial rotation
1094 if (onGround() && (speed > _performance->vRotate()))
1095 tgt_pitch = 8.0; // some rough B737 value
1097 //TODO pitch angle on approach and landing
1099 // match pitch angle to vertical speed
1100 else if (tgt_vs > 0) {
1101 tgt_pitch = tgt_vs * 0.005;
1103 tgt_pitch = tgt_vs * 0.002;
1107 string FGAIAircraft::atGate() {
1109 if (fp->getLeg() < 3) {
1111 if (fp->getGate() > 0) {
1113 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1114 tmp = park->getName();
1121 void FGAIAircraft::handleATCRequests() {
1122 //TODO implement NullController for having no ATC to save the conditionals
1124 controller->updateAircraftInformation(getID(),
1125 pos.getLatitudeDeg(),
1126 pos.getLongitudeDeg(),
1130 processATC(controller->getInstruction(getID()));
1134 void FGAIAircraft::updateActualState() {
1135 //update current state
1136 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1140 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1142 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1145 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1147 // adjust altitude (meters) based on current vertical speed (fpm)
1148 altitude_ft += vs / 60.0 * dt;
1149 pos.setElevationFt(altitude_ft);
1151 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1152 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1155 void FGAIAircraft::updateSecondaryTargetValues() {
1156 // derived target state values
1157 updateBankAngleTarget();
1158 updateVerticalSpeedTarget();
1159 updatePitchAngleTarget();
1161 //TODO calculate wind correction angle (tgt_yaw)
1165 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1166 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1167 if (curr->name == "BOD") {
1168 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1169 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1170 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1172 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1173 double descentTimeNeeded = verticalDistance / descentRate;
1174 double distanceCovered = descentSpeed * descentTimeNeeded;
1176 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1177 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1178 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1179 cerr << "Descent rate : " << descentRate << endl;
1180 cerr << "Descent speed : " << descentSpeed << endl;
1181 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1182 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1183 cerr << "DistanceCovered : " << distanceCovered << endl;
1185 //cerr << "Distance = " << distance << endl;
1186 distance = distanceCovered;
1187 if (dist < distanceCovered) {
1188 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1200 void FGAIAircraft::resetPositionFromFlightPlan()
1202 // the one behind you
1203 FGAIFlightPlan::waypoint* prev = 0;
1205 FGAIFlightPlan::waypoint* curr = 0;
1207 FGAIFlightPlan::waypoint* next = 0;
1209 prev = fp->getPreviousWaypoint();
1210 curr = fp->getCurrentWaypoint();
1211 next = fp->getNextWaypoint();
1213 setLatitude(prev->latitude);
1214 setLongitude(prev->longitude);
1215 double tgt_heading = fp->getBearing(curr, next);
1216 setHeading(tgt_heading);
1217 setAltitude(prev->altitude);
1218 setSpeed(prev->speed);
1221 double FGAIAircraft::getBearing(double crse)
1223 double hdgDiff = fabs(hdg-crse);
1225 hdgDiff = fabs(hdgDiff - 360);
1229 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1230 FGAIFlightPlan::waypoint* curr = 0;
1231 curr = fp->getCurrentWaypoint();
1233 double tracklength = fp->checkTrackLength(wptName);
1234 if (tracklength > 0.1) {
1235 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1239 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1240 time_t arrivalTime = fp->getArrivalTime();
1242 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1243 time_t secondsToGo = arrivalTime - now;
1244 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1245 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1247 return (ete - secondsToGo); // Positive when we're too slow...