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>
38 # define finite _finite
39 #elif defined(__sun) || defined(sgi)
45 #include "AIAircraft.hxx"
46 //#include <Airports/trafficcontroller.hxx>
47 static string tempReg;
49 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
50 // cruise_speed, descent_speed, land_speed
52 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
54 {2.0, 2.0, 450.0, 1000.0, 70.0, 80.0, 100.0, 80.0, 60.0},
56 {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
58 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
60 {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
62 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
63 // ufo (extreme accel/decel)
64 {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
68 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
73 groundOffset = trafficRef->getGroundOffset();
88 groundTargetSpeed = 0;
90 // set heading and altitude locks
94 headingChangeRate = 0.0;
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"));
117 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
121 bool FGAIAircraft::init() {
122 //refuel_node = fgGetNode("systems/refuel/contact", true);
123 return FGAIBase::init(true);
127 void FGAIAircraft::bind() {
130 props->tie("controls/gear/gear-down",
131 SGRawValueMethods<FGAIAircraft,bool>(*this,
132 &FGAIAircraft::_getGearDown));
133 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
134 props->setStringValue("callsign", callsign.c_str());
135 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
136 props->setBoolValue("tanker",isTanker);
140 void FGAIAircraft::unbind() {
143 props->untie("controls/gear/gear-down");
144 props->untie("refuel/contact");
148 void FGAIAircraft::update(double dt) {
149 FGAIBase::update(dt);
155 void FGAIAircraft::setPerformance(const std::string& acclass) {
156 if (acclass == "light") {
157 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
158 } else if (acclass == "ww2_fighter") {
159 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
160 } else if (acclass == "jet_transport") {
161 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
162 } else if (acclass == "jet_fighter") {
163 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
164 } else if (acclass == "tanker") {
165 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
167 } else if (acclass == "ufo") {
168 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
170 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
175 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
181 void FGAIAircraft::Run(double dt) {
183 FGAIAircraft::dt = dt;
186 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
187 ProcessFlightPlan(dt, now);
188 if (now < fp->getStartTime()) {
189 // Do execute Ground elev for inactive aircraft, so they
190 // Are repositioned to the correct ground altitude when the user flies within visibility range.
191 // In addition, check whether we are out of user range, so this aircraft
194 Transform(); // make sure aip is initialized.
196 double userLatitude = fgGetDouble("/position/latitude-deg");
197 double userLongitude = fgGetDouble("/position/longitude-deg");
198 double course, distance;
199 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
200 SGWayPoint user (userLongitude, userLatitude, 0);
201 user.CourseAndDistance(current, &course, &distance);
202 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
206 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
207 //getGroundElev(dt); // Need to do this twice.
208 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
210 //cerr << " Actual altitude " << altitude << endl;
212 pos.setElevationFt(altitude_ft);
218 // no flight plan, update target heading, speed, and altitude
219 // from control properties. These default to the initial
220 // settings in the config file, but can be changed "on the
222 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
223 if ( lat_mode == "roll" ) {
225 = props->getDoubleValue("controls/flight/target-roll" );
229 = props->getDoubleValue("controls/flight/target-hdg" );
234 = props->getStringValue("controls/flight/longitude-mode");
235 if ( lon_mode == "alt" ) {
236 double alt = props->getDoubleValue("controls/flight/target-alt" );
240 = props->getDoubleValue("controls/flight/target-pitch" );
244 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
248 controller->update(getID(),
249 pos.getLatitudeDeg(),
250 pos.getLongitudeDeg(),
254 processATC(controller->getInstruction(getID()));
257 double turn_radius_ft;
258 double turn_circum_ft;
259 double speed_north_deg_sec;
260 double speed_east_deg_sec;
261 double dist_covered_ft;
265 double speed_diff; //= tgt_speed - speed;
267 speed_diff = tgt_speed - speed;
269 speed_diff = groundTargetSpeed - speed;
272 if (speed_diff > 0.0) {
273 speed += performance->accel * dt;
274 if (no_roll) { // apply overshoot correction
275 if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
277 if ( speed > tgt_speed ) speed = tgt_speed;
279 } else if (speed_diff < 0.0) {
281 // on ground (aircraft can't roll)
282 // deceleration performance is better due to wheel brakes.
283 speed -= performance->decel * dt * 3;
285 speed -= performance->decel * dt;
287 if (no_roll) { // apply overshoot correction
288 if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
290 if ( speed < tgt_speed ) speed = tgt_speed;
295 // convert speed to degrees per second
296 speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
297 * speed * 1.686 / ft_per_deg_lat;
298 speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
299 * speed * 1.686 / ft_per_deg_lon;
302 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
303 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
305 /* printf("%.7f %0.4f %.7f %.5f %.7f %.7f %.8f %.8f %.9f %.9f\n",
306 dt, hdg, speed, ft_per_deg_lat,
307 cos( hdg * SGD_DEGREES_TO_RADIANS ),
308 speed * 1.686 / ft_per_deg_lat,
309 speed_north_deg_sec, speed_east_deg_sec,
310 pos.getLatitudeDeg(), pos.getLongitudeDeg()); */
312 //if (!(finite(pos.lat()) && finite(pos.lon())))
314 // cerr << "Position is not finite" << endl;
315 // cerr << "speed = " << speed << endl;
316 // cerr << "dt" << dt << endl;
317 // cerr << "heading " << hdg << endl;
318 // cerr << "speed east " << speed_east_deg_sec << endl;
319 // cerr << "speed nrth " << speed_north_deg_sec << endl;
320 // cerr << "deg_lat " << ft_per_deg_lat << endl;
321 // cerr << "deg_lon " << ft_per_deg_lon << endl;
324 // adjust heading based on current bank angle
329 // double turnConstant;
331 // turnConstant = 0.0088362;
333 // turnConstant = 0.088362;
334 // If on ground, calculate heading change directly
336 double headingDiff = fabs(hdg-tgt_heading);
338 if (headingDiff > 180)
339 headingDiff = fabs(headingDiff - 360);
341 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
342 if (sign(groundTargetSpeed) != sign(tgt_speed))
343 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
345 if (headingDiff > 30.0) {
346 headingChangeRate += dt * sign(roll); // invert if pushed backward
347 // Print some debug statements to find out why aircraft may get stuck
349 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
350 // cerr << "Turning : " << trafficRef->getRegistration()
351 // cerr << " Speed = " << speed << " Heading " << hdg
352 // << " Target Heading " << tgt_heading
353 // << " Lead Distance " << fp->getLeadDistance()
354 // << " Distance to go "
355 // << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
356 // << "waypoint name " << fp->getCurrentWaypoint()->name
359 if (headingChangeRate > 30)
360 headingChangeRate = 30;
361 else if (headingChangeRate < -30)
362 headingChangeRate = -30;
365 if (fabs(headingChangeRate) > headingDiff)
366 headingChangeRate = headingDiff*sign(roll);
368 headingChangeRate += dt * sign(roll);
370 hdg += headingChangeRate * dt;
371 //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
372 // << ". Target speed: " << groundTargetSpeed << ". heading change rate"
373 // << headingChangeRate << endl;
376 if (fabs(speed) > 1.0) {
377 turn_radius_ft = 0.088362 * speed * speed
378 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
380 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
382 turn_circum_ft = SGD_2PI * turn_radius_ft;
383 dist_covered_ft = speed * 1.686 * dt;
384 alpha = dist_covered_ft / turn_circum_ft * 360.0;
385 hdg += alpha * sign(roll);
387 while ( hdg > 360.0 ) {
398 // adjust target bank angle if heading lock engaged
400 double bank_sense = 0.0;
401 double diff = fabs(hdg - tgt_heading);
403 diff = fabs(diff - 360);
405 double sum = hdg + diff;
408 if (fabs(sum - tgt_heading) < 1.0) {
409 bank_sense = 1.0; // right turn
411 bank_sense = -1.0; // left turn
414 tgt_roll = diff * bank_sense;
416 tgt_roll = 30.0 * bank_sense;
418 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
419 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
420 // The only way to resolve this is to make them slow down.
421 //if (tempReg.empty())
422 // tempReg = trafficRef->getRegistration();
423 //if (trafficRef->getRegistration() == tempReg) {
424 // cerr << trafficRef->getRegistration()
425 // << " appears to be spinning: " << spinCounter << endl
426 // << " speed " << speed << endl
427 // << " heading " << hdg << endl
428 // << " lead distance " << fp->getLeadDistance() << endl
429 // << " waypoint " << fp->getCurrentWaypoint()->name
430 // << " target heading " << tgt_heading << endl
431 // << " lead in angle " << fp->getLeadInAngle()<< endl
432 // << " roll " << roll << endl
433 // << " target_roll " << tgt_roll << endl;
438 // adjust bank angle, use 9 degrees per second
439 double bank_diff = tgt_roll - roll;
440 if (fabs(bank_diff) > 0.2) {
446 //while (roll > 180) roll -= 360;
447 //while (roll < 180) roll += 360;
450 // adjust altitude (meters) based on current vertical speed (fpm)
451 altitude_ft += vs / 60.0 * dt;
452 pos.setElevationFt(altitude_ft);
454 // adjust target Altitude, based on ground elevation when on ground
459 // find target vertical speed if altitude lock engaged
460 if (alt_lock && use_perf_vs) {
461 if (altitude_ft < tgt_altitude_ft) {
462 tgt_vs = tgt_altitude_ft - altitude_ft;
463 if (tgt_vs > performance->climb_rate)
464 tgt_vs = performance->climb_rate;
466 tgt_vs = tgt_altitude_ft - altitude_ft;
467 if (tgt_vs < (-performance->descent_rate))
468 tgt_vs = -performance->descent_rate;
472 if (alt_lock && !use_perf_vs) {
473 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
475 if (tgt_altitude_ft < altitude_ft)
477 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
478 && (fabs(max_vs) < fabs(tgt_vs)))
481 if (fabs(tgt_vs) < fabs(min_vs))
485 // adjust vertical speed
486 double vs_diff = tgt_vs - vs;
487 if (fabs(vs_diff) > 10.0) {
489 vs += (performance->climb_rate / 3.0) * dt;
494 vs -= (performance->descent_rate / 3.0) * dt;
501 // match pitch angle to vertical speed
508 //###########################//
509 // do calculations for radar //
510 //###########################//
511 double range_ft2 = UpdateRadar(manager);
513 //************************************//
515 //************************************//
518 if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
519 && (elevation > 0.0) ) {
520 //refuel_node->setBoolValue(true);
523 //refuel_node->setBoolValue(false);
532 void FGAIAircraft::AccelTo(double speed) {
537 void FGAIAircraft::PitchTo(double angle) {
543 void FGAIAircraft::RollTo(double angle) {
549 void FGAIAircraft::YawTo(double angle) {
554 void FGAIAircraft::ClimbTo(double alt_ft ) {
555 tgt_altitude_ft = alt_ft;
560 void FGAIAircraft::TurnTo(double heading) {
561 tgt_heading = heading;
566 double FGAIAircraft::sign(double x) {
574 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
575 if (!flightplan.empty()) {
576 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
577 fp->setRepeat(repeat);
583 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
589 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
592 eraseWaypoints = true;
594 eraseWaypoints = false;
597 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
598 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
599 FGAIFlightPlan::waypoint* next = 0; // the next plus 1
600 prev = fp->getPreviousWaypoint();
601 curr = fp->getCurrentWaypoint();
602 next = fp->getNextWaypoint();
605 ///////////////////////////////////////////////////////////////////////////
606 // Initialize the flightplan
607 //////////////////////////////////////////////////////////////////////////
612 fp->IncrementWaypoint(eraseWaypoints);
613 if (!(fp->getNextWaypoint()) && trafficRef)
616 prev = fp->getPreviousWaypoint(); //first waypoint
617 curr = fp->getCurrentWaypoint(); //second waypoint
618 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
620 setLatitude(prev->latitude);
621 setLongitude(prev->longitude);
622 setSpeed(prev->speed);
623 setAltitude(prev->altitude);
625 if (prev->speed > 0.0)
626 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
628 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
630 // If next doesn't exist, as in incrementally created flightplans for
631 // AI/Trafficmanager created plans,
632 // Make sure lead distance is initialized otherwise
634 fp->setLeadDistance(speed, hdg, curr, next);
636 if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
638 tgt_vs = (curr->crossat - prev->altitude)
639 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
640 / 6076.0 / prev->speed*60.0);
641 tgt_altitude_ft = curr->crossat;
644 tgt_altitude_ft = prev->altitude;
646 alt_lock = hdg_lock = true;
647 no_roll = prev->on_ground;
649 Transform(); // make sure aip is initialized.
650 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
653 // Make sure to announce the aircraft's position
654 announcePositionToController();
657 } // end of initialization
658 ///////////////////////////////////////////////////////////////////////////
659 // Check Execution time (currently once every 100 ms)
660 // Add a bit of randomization to prevent the execution of all flight plans
661 // in synchrony, which can add significant periodic framerate flutter.
662 ///////////////////////////////////////////////////////////////////////////
663 double rand_exec_time = (rand() % 100) / 100;
664 if ((dt_count < (0.1+rand_exec_time)) || (now < fp->getStartTime())) {
665 //cerr << "done fp dt" << endl;
671 // check to see if we've reached the lead point for our next turn
672 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
674 //cerr << "2" << endl;
675 double lead_dist = fp->getLeadDistance();
676 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
677 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
679 if (lead_dist < fabs(2*speed)) {
680 lead_dist = fabs(2*speed); //don't skip over the waypoint
681 //cerr << "Extending lead distance to " << lead_dist << endl;
684 //prev_dist_to_go = dist_to_go;
686 if ( dist_to_go < lead_dist ) {
687 if (curr->finished) { //end of the flight plan
696 tgt_heading = fp->getBearing(curr, next);
700 fp->IncrementWaypoint(eraseWaypoints);
701 if (!(fp->getNextWaypoint()) && trafficRef)
704 prev = fp->getPreviousWaypoint();
705 curr = fp->getCurrentWaypoint();
706 next = fp->getNextWaypoint();
708 // Now that we have incremented the waypoints, excute some traffic manager specific code
710 double userLatitude = fgGetDouble("/position/latitude-deg");
711 double userLongitude = fgGetDouble("/position/longitude-deg");
712 double course, distance;
713 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
714 SGWayPoint user (userLongitude, userLatitude, 0);
715 user.CourseAndDistance(current, &course, &distance);
716 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
721 FGAirport * dep = trafficRef->getDepartureAirport();
722 FGAirport * arr = trafficRef->getArrivalAirport();
723 if (!( dep && arr)) {
727 // This waypoint marks the fact that the aircraft has passed the initial taxi
728 // departure waypoint, so it can release the parking.
729 if (prev->name == "park2")
730 dep->getDynamics()->releaseParking(fp->getGate());
731 // This is the last taxi waypoint, and marks the the end of the flight plan
732 // so, the schedule should update and wait for the next departure time.
733 if (prev->name == "END") {
734 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
736 time_t nextDeparture = trafficRef->getDepartureTime();
737 if (nextDeparture < (now+1200)) {
738 nextDeparture = now + 1200;
740 fp->setTime(trafficRef->getDepartureTime());
742 announcePositionToController();
747 //cerr << "Current waypoint" << curr->name << endl;
748 //cerr << "Next waypoint" << next->name << endl;
749 fp->setLeadDistance(speed, tgt_heading, curr, next);
752 //cerr << "5.1" << endl;
753 if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
754 tgt_altitude_ft = prev->altitude;
755 if (curr->crossat > -1000.0) {
756 //cerr << "5.1a" << endl;
758 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
759 / 6076.0 / speed*60.0);
760 //cerr << "5.1b" << endl;
761 tgt_altitude_ft = curr->crossat;
763 //cerr << "5.1c" << endl;
765 //cerr << "5.1d" << endl;
766 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
769 //cerr << "6" << endl;
770 tgt_speed = prev->speed;
771 hdg_lock = alt_lock = true;
772 no_roll = prev->on_ground;
773 //cout << "Crossing waypoint: " << prev->name << endl;
774 //cout << " Target speed: " << tgt_speed << endl;
775 //cout << " Target altitude: " << tgt_altitude_ft << endl;
776 //cout << " Target heading: " << tgt_heading << endl << endl;
779 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
780 //cerr << "Bearing = " << calc_bearing << endl;
783 if (calc_bearing > 360)
787 if (finite(calc_bearing)) {
788 double hdg_error = calc_bearing - tgt_heading;
789 if (fabs(hdg_error) > 1.0) {
790 TurnTo( calc_bearing );
794 cerr << "calc_bearing is not a finite number : "
796 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
797 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
798 cerr << "waypoint name " << curr->name;
802 double speed_diff = speed - prevSpeed;
803 // Update the lead distance calculation if speed has changed sufficiently
804 // to prevent spinning (hopefully);
805 if (fabs(speed_diff) > 10) {
807 fp->setLeadDistance(speed, tgt_heading, curr, next);
810 //cerr << "Done Processing FlightPlan"<< endl;
814 void FGAIAircraft::initializeFlightPlan()
820 bool FGAIAircraft::_getGearDown() const {
821 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
822 && (props->getFloatValue("velocities/airspeed-kt")
823 < performance->land_speed*1.25));
827 void FGAIAircraft::loadNextLeg() {
829 //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
831 //FGAIModelEntity entity;
832 //entity.m_class = "jet_transport";
833 //entity.path = modelPath.c_str();
834 //entity.flightplan = "none";
835 //entity.latitude = _getLatitude();
836 //entity.longitude = _getLongitude();
837 //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
838 //entity.speed = 450; // HACK ALERT
839 //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
841 if ((leg = fp->getLeg()) == 10) {
845 //cerr << "Resetting leg : " << leg << endl;
849 //cerr << "Creating leg number : " << leg << endl;
850 FGAirport *dep = trafficRef->getDepartureAirport();
851 FGAirport *arr = trafficRef->getArrivalAirport();
854 //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
856 // cerr << "Departure " << dep->getId() << endl;
858 // cerr << "Arrival " << arr->getId() << endl;
861 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
862 //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
867 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
868 trafficRef->getSpeed(),
872 trafficRef->getRadius(),
873 trafficRef->getFlightType(),
876 //prev = fp->getPreviousWaypoint();
877 //curr = fp->getCurrentWaypoint();
878 //next = fp->getNextWaypoint();
879 //cerr << "25" << endl;
882 // //cerr << "Next waypoint" << next->name << endl;
883 // fp->setLeadDistance(speed, tgt_heading, curr, next);
885 //cerr << "25.1" << endl;
886 //if (curr->crossat > -1000.0) {
887 // //cerr << "25.1a" << endl;
888 // use_perf_vs = false;
890 // tgt_vs = (curr->crossat - altitude_ft)/
891 // (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
892 // //cerr << "25.1b" << endl;
893 // tgt_altitude_ft = curr->crossat;
895 // //cerr << "25.1c" << endl;
896 // use_perf_vs = true;
897 // //cerr << "25.1d" << endl;
898 // tgt_altitude_ft = prev->altitude;
899 // //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
901 //cerr << "26" << endl;
902 //tgt_speed = prev->speed;
903 //hdg_lock = alt_lock = true;
904 //no_roll = prev->on_ground;
909 //entity.fp = new FGAIFlightPlan(&entity,
911 // trafficRef->getDepartureTime(),
912 // trafficRef->getDepartureAirport(),
913 // trafficRef->getArrivalAirport(),
917 //SetFlightPlan(entity.fp);
921 // Note: This code is copied from David Luff's AILocalTraffic
922 // Warning - ground elev determination is CPU intensive
923 // Either this function or the logic of how often it is called
924 // will almost certainly change.
926 void FGAIAircraft::getGroundElev(double dt) {
929 // Update minimally every three secs, but add some randomness
930 // to prevent all IA objects doing this in synchrony
931 if (dt_elev_count < (3.0) + (rand() % 10))
936 // Only do the proper hitlist stuff if we are within visible range of the viewer.
938 double visibility_meters = fgGetDouble("/environment/visibility-m");
940 FGViewer* vw = globals->get_current_view();
941 double course, distance;
943 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
944 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
945 view.CourseAndDistance(current, &course, &distance);
946 if(distance > visibility_meters) {
947 //aip.getSGLocation()->set_cur_elev_m(aptElev);
951 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
952 double range = 500.0;
953 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
954 // Try to shedule tiles for that position.
955 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
958 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
960 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
961 tgt_altitude_ft = alt * SG_METER_TO_FEET;
963 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
964 // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
966 // tgt_altitude_ft = alt * SG_METER_TO_FEET;
967 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
972 void FGAIAircraft::setCallSign(const string& s) {
977 void FGAIAircraft::setTACANChannelID(const string& id) {
978 TACAN_channel_id = id;
982 void FGAIAircraft::doGroundAltitude() {
983 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
984 altitude_ft = (tgt_altitude_ft + groundOffset);
986 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
990 void FGAIAircraft::announcePositionToController()
993 //FGTaxiRoute *taxiRoute = fp->getTaxiRoute();
995 int leg = fp->getLeg();
997 //if (fp->getCurrentWaypoint()->routeIndex != 0) {
999 //snprintf (buffer, 10, "%d", node);
1000 // Note that leg was been incremented after creating the current leg, so we should use
1001 // leg numbers here that are one higher than the number that is used to create the leg
1004 case 3: // Taxiing to runway
1005 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
1006 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
1008 case 4: //Take off tower controller
1009 if (trafficRef->getDepartureAirport()->getDynamics())
1011 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
1012 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
1013 //cerr << trafficRef->getCallSign() << " at runway " << fp->getRunway() << "Ready for departure "
1014 // << trafficRef->getFlightType() << " to " << trafficRef->getArrivalAirport()->getId() << endl;
1015 // if (controller == 0) {
1016 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
1021 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
1024 case 9: // Taxiing for parking
1025 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
1026 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
1033 if ((controller != prevController) && (prevController != 0)) {
1034 prevController->signOff(getID());
1035 string callsign = trafficRef->getCallSign();
1036 if ( trafficRef->getHeavy())
1037 callsign += "Heavy";
1040 //cerr << callsign << " ready to taxi to runway " << fp->getRunway() << endl;
1043 //cerr << callsign << " at runway " << fp->getRunway() << "Ready for take-off. "
1044 // << trafficRef->getFlightRules() << " to " << trafficRef->getArrivalAirport()->getId()
1045 // << "(" << trafficRef->getArrivalAirport()->getName() << ")."<< endl;
1049 prevController = controller;
1051 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
1052 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
1053 trafficRef->getRadius(), leg, trafficRef->getCallSign());
1059 void FGAIAircraft::processATC(FGATCInstruction instruction)
1061 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
1062 if (instruction.getHoldPattern ()) {
1066 if (instruction.getHoldPosition ()) {
1069 //cerr << trafficRef->getCallSign() << "Holding Position " << endl;
1076 // cerr << trafficRef->getCallSign() << " Resuming Taxi " << endl;
1079 // Change speed Instruction. This can only be excecuted when there is no
1080 // Hold position instruction.
1081 if (instruction.getChangeSpeed ()) {
1083 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
1084 AccelTo(instruction.getSpeed());
1086 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
1089 if (instruction.getChangeHeading ()) {
1091 TurnTo(instruction.getHeading());
1093 if (fp) {hdg_lock = true;}
1095 if (instruction.getChangeAltitude()) {