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/math/point3d.hxx>
26 #include <simgear/route/waypoint.hxx>
27 #include <Main/fg_props.hxx>
28 #include <Main/globals.hxx>
29 #include <Main/viewer.hxx>
30 #include <Scenery/scenery.hxx>
31 #include <Scenery/tilemgr.hxx>
32 #include <Airports/dynamics.hxx>
39 # define finite _finite
40 #elif defined(__sun) || defined(sgi)
46 #include "AIAircraft.hxx"
47 #include "performancedata.hxx"
48 #include "performancedb.hxx"
50 //#include <Airports/trafficcontroller.hxx>
52 static string tempReg;
54 class AI_OutOfSight{};
57 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
60 groundOffset = trafficRef->getGroundOffset();
61 setCallSign(trafficRef->getCallSign());
76 groundTargetSpeed = 0;
78 // set heading and altitude locks
82 headingChangeRate = 0.0;
86 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
91 FGAIAircraft::~FGAIAircraft() {
94 controller->signOff(getID());
98 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
102 FGAIBase::readFromScenario(scFileNode);
104 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
105 setFlightPlan(scFileNode->getStringValue("flightplan"),
106 scFileNode->getBoolValue("repeat", false));
107 setCallSign(scFileNode->getStringValue("callsign"));
111 void FGAIAircraft::bind() {
114 props->tie("controls/gear/gear-down",
115 SGRawValueMethods<FGAIAircraft,bool>(*this,
116 &FGAIAircraft::_getGearDown));
120 void FGAIAircraft::unbind() {
123 props->untie("controls/gear/gear-down");
127 void FGAIAircraft::update(double dt) {
128 FGAIBase::update(dt);
133 void FGAIAircraft::setPerformance(const std::string& acclass) {
134 static PerformanceDB perfdb; //TODO make it a global service
135 setPerformance(perfdb.getDataFor(acclass));
139 void FGAIAircraft::setPerformance(PerformanceData *ps) {
144 void FGAIAircraft::Run(double dt) {
145 FGAIAircraft::dt = dt;
148 updatePrimaryTargetValues(); // target hdg, alt, speed
150 catch (AI_OutOfSight) {
153 catch (FP_Inactive) {
155 groundTargetSpeed = 0;
158 handleATCRequests(); // ATC also has a word to say
159 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
161 UpdateRadar(manager);
166 void FGAIAircraft::AccelTo(double speed) {
171 void FGAIAircraft::PitchTo(double angle) {
177 void FGAIAircraft::RollTo(double angle) {
183 void FGAIAircraft::YawTo(double angle) {
188 void FGAIAircraft::ClimbTo(double alt_ft ) {
189 tgt_altitude_ft = alt_ft;
194 void FGAIAircraft::TurnTo(double heading) {
195 tgt_heading = heading;
200 double FGAIAircraft::sign(double x) {
208 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
209 if (!flightplan.empty()) {
210 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
211 fp->setRepeat(repeat);
217 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
223 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
225 // the one behind you
226 FGAIFlightPlan::waypoint* prev = 0;
228 FGAIFlightPlan::waypoint* curr = 0;
230 FGAIFlightPlan::waypoint* next = 0;
232 prev = fp->getPreviousWaypoint();
233 curr = fp->getCurrentWaypoint();
234 next = fp->getNextWaypoint();
238 ///////////////////////////////////////////////////////////////////////////
239 // Initialize the flightplan
240 //////////////////////////////////////////////////////////////////////////
242 handleFirstWaypoint();
244 } // end of initialization
245 if (! fpExecutable(now))
249 if (! leadPointReached(curr)) {
250 controlHeading(curr);
251 controlSpeed(curr, next);
253 if (curr->finished) //end of the flight plan
263 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
264 tgt_heading = fp->getBearing(curr, next);
268 //TODO let the fp handle this (loading of next leg)
269 fp->IncrementWaypoint((bool) trafficRef);
270 if (!(fp->getNextWaypoint()) && trafficRef)
271 if (!loadNextLeg()) {
276 prev = fp->getPreviousWaypoint();
277 curr = fp->getCurrentWaypoint();
278 next = fp->getNextWaypoint();
280 // Now that we have incremented the waypoints, excute some traffic manager specific code
282 //TODO isn't this best executed right at the beginning?
283 if (! aiTrafficVisible()) {
288 if (! handleAirportEndPoints(prev, now)) {
293 announcePositionToController();
298 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
301 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
303 tgt_altitude_ft = prev->altitude;
304 if (curr->crossat > -1000.0) {
306 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
307 / 6076.0 / speed*60.0);
308 tgt_altitude_ft = curr->crossat;
313 tgt_speed = prev->speed;
314 hdg_lock = alt_lock = true;
315 no_roll = prev->on_ground;
320 void FGAIAircraft::initializeFlightPlan() {
324 bool FGAIAircraft::_getGearDown() const {
325 return _performance->gearExtensible(this);
329 bool FGAIAircraft::loadNextLeg() {
332 if ((leg = fp->getLeg()) == 10) {
333 if (!trafficRef->next()) {
336 setCallSign(trafficRef->getCallSign());
337 //props->setStringValue("callsign", callsign.c_str());
342 FGAirport *dep = trafficRef->getDepartureAirport();
343 FGAirport *arr = trafficRef->getArrivalAirport();
348 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
353 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
354 trafficRef->getSpeed(),
358 trafficRef->getRadius(),
359 trafficRef->getFlightType(),
362 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
368 // Note: This code is copied from David Luff's AILocalTraffic
369 // Warning - ground elev determination is CPU intensive
370 // Either this function or the logic of how often it is called
371 // will almost certainly change.
373 void FGAIAircraft::getGroundElev(double dt) {
376 // Update minimally every three secs, but add some randomness
377 // to prevent all AI objects doing this in synchrony
378 if (dt_elev_count < (3.0) + (rand() % 10))
383 // Only do the proper hitlist stuff if we are within visible range of the viewer.
385 double visibility_meters = fgGetDouble("/environment/visibility-m");
387 FGViewer* vw = globals->get_current_view();
388 double course, distance;
390 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
391 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
392 view.CourseAndDistance(current, &course, &distance);
393 if (distance > visibility_meters) {
394 //aip.getSGLocation()->set_cur_elev_m(aptElev);
398 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
399 double range = 500.0;
400 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
401 // Try to shedule tiles for that position.
402 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
405 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
407 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
408 tgt_altitude_ft = alt * SG_METER_TO_FEET;
413 void FGAIAircraft::doGroundAltitude() {
414 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
415 altitude_ft = (tgt_altitude_ft + groundOffset);
417 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
421 void FGAIAircraft::announcePositionToController() {
423 int leg = fp->getLeg();
425 // Note that leg has been incremented after creating the current leg, so we should use
426 // leg numbers here that are one higher than the number that is used to create the leg
429 case 2: // Startup and Push back
430 if (trafficRef->getDepartureAirport()->getDynamics())
431 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
433 case 3: // Taxiing to runway
434 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
435 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
437 case 4: //Take off tower controller
438 if (trafficRef->getDepartureAirport()->getDynamics()) {
439 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
440 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
441 //string trns = trafficRef->getCallSign() + " at runway " + fp->getRunway() +
442 // ". Ready for departure. " + trafficRef->getFlightType() + " to " +
443 // trafficRef->getArrivalAirport()->getId();
444 //fgSetString("/sim/messages/atc", trns.c_str());
445 // if (controller == 0) {
446 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
450 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
453 case 9: // Taxiing for parking
454 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
455 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
462 if ((controller != prevController) && (prevController != 0)) {
463 prevController->signOff(getID());
465 prevController = controller;
467 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
468 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
469 trafficRef->getRadius(), leg, this);
474 // Process ATC instructions and report back
476 void FGAIAircraft::processATC(FGATCInstruction instruction) {
477 if (instruction.getCheckForCircularWait()) {
478 // This is not exactly an elegant solution,
479 // but at least it gives me a chance to check
480 // if circular waits are resolved.
481 // For now, just take the offending aircraft
484 // a more proper way should be - of course - to
485 // let an offending aircraft take an evasive action
486 // for instance taxi back a little bit.
488 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
489 if (instruction.getHoldPattern ()) {}
492 if (instruction.getHoldPosition ()) {
500 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
503 // Change speed Instruction. This can only be excecuted when there is no
504 // Hold position instruction.
505 if (instruction.getChangeSpeed ()) {
507 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
508 AccelTo(instruction.getSpeed());
510 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
513 if (instruction.getChangeHeading ()) {
515 TurnTo(instruction.getHeading());
521 if (instruction.getChangeAltitude()) {}
526 void FGAIAircraft::handleFirstWaypoint() {
527 bool eraseWaypoints; //TODO YAGNI
530 eraseWaypoints = true;
532 eraseWaypoints = false;
535 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
536 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
537 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
542 //TODO fp should handle this
543 fp->IncrementWaypoint(eraseWaypoints);
544 if (!(fp->getNextWaypoint()) && trafficRef)
545 if (!loadNextLeg()) {
550 prev = fp->getPreviousWaypoint(); //first waypoint
551 curr = fp->getCurrentWaypoint(); //second waypoint
552 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
554 setLatitude(prev->latitude);
555 setLongitude(prev->longitude);
556 setSpeed(prev->speed);
557 setAltitude(prev->altitude);
559 if (prev->speed > 0.0)
560 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
562 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
564 // If next doesn't exist, as in incrementally created flightplans for
565 // AI/Trafficmanager created plans,
566 // Make sure lead distance is initialized otherwise
568 fp->setLeadDistance(speed, hdg, curr, next);
570 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
573 tgt_vs = (curr->crossat - prev->altitude)
574 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
575 / 6076.0 / prev->speed*60.0);
576 tgt_altitude_ft = curr->crossat;
579 tgt_altitude_ft = prev->altitude;
581 alt_lock = hdg_lock = true;
582 no_roll = prev->on_ground;
584 Transform(); // make sure aip is initialized.
585 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
588 // Make sure to announce the aircraft's position
589 announcePositionToController();
595 * Check Execution time (currently once every 100 ms)
596 * Add a bit of randomization to prevent the execution of all flight plans
597 * in synchrony, which can add significant periodic framerate flutter.
602 bool FGAIAircraft::fpExecutable(time_t now) {
603 double rand_exec_time = (rand() % 100) / 100;
604 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
609 * Check to see if we've reached the lead point for our next turn
614 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
615 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
617 //cerr << "2" << endl;
618 double lead_dist = fp->getLeadDistance();
619 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
621 if (lead_dist < fabs(2*speed)) {
622 //don't skip over the waypoint
623 lead_dist = fabs(2*speed);
624 //cerr << "Extending lead distance to " << lead_dist << endl;
627 //prev_dist_to_go = dist_to_go;
628 //if (dist_to_go < lead_dist)
629 // cerr << trafficRef->getCallSign() << " Distance : "
630 // << dist_to_go << ": Lead distance "
631 // << lead_dist << " " << curr->name
632 // << " Ground target speed " << groundTargetSpeed << endl;
634 return dist_to_go < lead_dist;
638 bool FGAIAircraft::aiTrafficVisible() {
639 double userLatitude = fgGetDouble("/position/latitude-deg");
640 double userLongitude = fgGetDouble("/position/longitude-deg");
641 double course, distance;
643 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
644 SGWayPoint user (userLongitude, userLatitude, 0);
646 user.CourseAndDistance(current, &course, &distance);
648 return ((distance * SG_METER_TO_NM) <= TRAFFICTOAIDISTTODIE);
653 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
654 * in the case of an arrival.
660 //TODO the trafficRef is the right place for the method
661 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
662 // prepare routing from one airport to another
663 FGAirport * dep = trafficRef->getDepartureAirport();
664 FGAirport * arr = trafficRef->getArrivalAirport();
669 // This waypoint marks the fact that the aircraft has passed the initial taxi
670 // departure waypoint, so it can release the parking.
671 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
672 if (prev->name == "PushBackPoint") {
673 dep->getDynamics()->releaseParking(fp->getGate());
674 time_t holdUntil = now + 120;
675 fp->setTime(holdUntil);
676 //cerr << _getCallsign() << "Holding at pushback point" << endl;
679 // This is the last taxi waypoint, and marks the the end of the flight plan
680 // so, the schedule should update and wait for the next departure time.
681 if (prev->name == "END") {
682 time_t nextDeparture = trafficRef->getDepartureTime();
683 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
684 if (nextDeparture < (now+1200)) {
685 nextDeparture = now + 1200;
687 fp->setTime(nextDeparture); // should be "next departure"
695 * Check difference between target bearing and current heading and correct if necessary.
699 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
700 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
701 //cerr << "Bearing = " << calc_bearing << endl;
704 if (calc_bearing > 360)
708 if (finite(calc_bearing)) {
709 double hdg_error = calc_bearing - tgt_heading;
710 if (fabs(hdg_error) > 0.01) {
711 TurnTo( calc_bearing );
715 cerr << "calc_bearing is not a finite number : "
717 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
718 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
719 cerr << "waypoint name " << curr->name;
726 * Update the lead distance calculation if speed has changed sufficiently
727 * to prevent spinning (hopefully);
732 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
733 double speed_diff = speed - prevSpeed;
735 if (fabs(speed_diff) > 10) {
738 fp->setLeadDistance(speed, tgt_heading, curr, next);
745 * Update target values (heading, alt, speed) depending on flight plan or control properties
747 void FGAIAircraft::updatePrimaryTargetValues() {
748 if (fp) // AI object has a flightplan
750 //TODO make this a function of AIBase
751 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
752 //cerr << "UpateTArgetValues() " << endl;
753 ProcessFlightPlan(dt, now);
755 // Do execute Ground elev for inactive aircraft, so they
756 // Are repositioned to the correct ground altitude when the user flies within visibility range.
757 // In addition, check whether we are out of user range, so this aircraft
760 Transform(); // make sure aip is initialized.
764 pos.setElevationFt(altitude_ft);
767 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
768 if (! aiTrafficVisible()) {
770 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
771 throw AI_OutOfSight();
774 timeElapsed = now - fp->getStartTime();
775 if (! fp->isActive(now)) {
779 // no flight plan, update target heading, speed, and altitude
780 // from control properties. These default to the initial
781 // settings in the config file, but can be changed "on the
783 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
784 if ( lat_mode == "roll" ) {
786 = props->getDoubleValue("controls/flight/target-roll" );
790 = props->getDoubleValue("controls/flight/target-hdg" );
795 = props->getStringValue("controls/flight/longitude-mode");
796 if ( lon_mode == "alt" ) {
797 double alt = props->getDoubleValue("controls/flight/target-alt" );
801 = props->getDoubleValue("controls/flight/target-pitch" );
805 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
809 void FGAIAircraft::updatePosition() {
810 // convert speed to degrees per second
811 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
812 * speed * 1.686 / ft_per_deg_lat;
813 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
814 * speed * 1.686 / ft_per_deg_lon;
817 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
818 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
822 void FGAIAircraft::updateHeading() {
823 // adjust heading based on current bank angle
828 // double turnConstant;
830 // turnConstant = 0.0088362;
832 // turnConstant = 0.088362;
833 // If on ground, calculate heading change directly
835 double headingDiff = fabs(hdg-tgt_heading);
836 double bank_sense = 0.0;
838 double diff = fabs(hdg - tgt_heading);
840 diff = fabs(diff - 360);
842 double sum = hdg + diff;
845 if (fabs(sum - tgt_heading) < 1.0) {
846 bank_sense = 1.0; // right turn
848 bank_sense = -1.0; // left turn
850 if (headingDiff > 180)
851 headingDiff = fabs(headingDiff - 360);
852 double sum = hdg + headingDiff;
855 if (fabs(sum - tgt_heading) > 0.0001) {
861 //cerr << trafficRef->getCallSign() << " Heading "
862 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
863 //if (headingDiff > 60) {
864 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
865 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
867 // groundTargetSpeed = tgt_speed;
869 if (sign(groundTargetSpeed) != sign(tgt_speed))
870 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
872 if (headingDiff > 30.0) {
873 // invert if pushed backward
874 headingChangeRate += 10.0 * dt * sign(roll);
876 // Clamp the maximum steering rate to 30 degrees per second,
877 // But only do this when the heading error is decreasing.
878 if ((headingDiff < headingError)) {
879 if (headingChangeRate > 30)
880 headingChangeRate = 30;
881 else if (headingChangeRate < -30)
882 headingChangeRate = -30;
885 if (fabs(headingChangeRate) > headingDiff)
886 headingChangeRate = headingDiff*sign(roll);
888 headingChangeRate += dt * sign(roll);
891 hdg += headingChangeRate * dt * (fabs(speed) / 15);
892 headingError = headingDiff;
894 if (fabs(speed) > 1.0) {
895 turn_radius_ft = 0.088362 * speed * speed
896 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
898 // Check if turn_radius_ft == 0; this might lead to a division by 0.
899 turn_radius_ft = 1.0;
901 double turn_circum_ft = SGD_2PI * turn_radius_ft;
902 double dist_covered_ft = speed * 1.686 * dt;
903 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
904 hdg += alpha * sign(roll);
906 while ( hdg > 360.0 ) {
918 void FGAIAircraft::updateBankAngleTarget() {
919 // adjust target bank angle if heading lock engaged
921 double bank_sense = 0.0;
922 double diff = fabs(hdg - tgt_heading);
924 diff = fabs(diff - 360);
926 double sum = hdg + diff;
929 if (fabs(sum - tgt_heading) < 1.0) {
930 bank_sense = 1.0; // right turn
932 bank_sense = -1.0; // left turn
934 if (diff < _performance->maximumBankAngle()) {
935 tgt_roll = diff * bank_sense;
937 tgt_roll = _performance->maximumBankAngle() * bank_sense;
939 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
940 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
941 // The only way to resolve this is to make them slow down.
947 void FGAIAircraft::updateVerticalSpeedTarget() {
948 // adjust target Altitude, based on ground elevation when on ground
952 } else if (alt_lock) {
953 // find target vertical speed
955 if (altitude_ft < tgt_altitude_ft) {
956 tgt_vs = tgt_altitude_ft - altitude_ft;
957 if (tgt_vs > _performance->climbRate())
958 tgt_vs = _performance->climbRate();
960 tgt_vs = tgt_altitude_ft - altitude_ft;
961 if (tgt_vs < (-_performance->descentRate()))
962 tgt_vs = -_performance->descentRate();
965 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
967 if (tgt_altitude_ft < altitude_ft)
969 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
970 && (fabs(max_vs) < fabs(tgt_vs)))
973 if (fabs(tgt_vs) < fabs(min_vs))
980 void FGAIAircraft::updatePitchAngleTarget() {
981 // if on ground and above vRotate -> initial rotation
982 if (onGround() && (speed > _performance->vRotate()))
983 tgt_pitch = 8.0; // some rough B737 value
985 //TODO pitch angle on approach and landing
987 // match pitch angle to vertical speed
988 else if (tgt_vs > 0) {
989 tgt_pitch = tgt_vs * 0.005;
991 tgt_pitch = tgt_vs * 0.002;
995 string FGAIAircraft::atGate() {
997 if (fp->getLeg() < 3) {
999 if (fp->getGate() > 0) {
1001 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1002 tmp = park->getName();
1009 void FGAIAircraft::handleATCRequests() {
1010 //TODO implement NullController for having no ATC to save the conditionals
1012 controller->update(getID(),
1013 pos.getLatitudeDeg(),
1014 pos.getLongitudeDeg(),
1018 processATC(controller->getInstruction(getID()));
1022 void FGAIAircraft::updateActualState() {
1023 //update current state
1024 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1028 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1030 speed = _performance->actualSpeed(this, tgt_speed, dt);
1033 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1035 // adjust altitude (meters) based on current vertical speed (fpm)
1036 altitude_ft += vs / 60.0 * dt;
1037 pos.setElevationFt(altitude_ft);
1039 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1040 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1043 void FGAIAircraft::updateSecondaryTargetValues() {
1044 // derived target state values
1045 updateBankAngleTarget();
1046 updateVerticalSpeedTarget();
1047 updatePitchAngleTarget();
1049 //TODO calculate wind correction angle (tgt_yaw)