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();
85 // set heading and altitude locks
89 headingChangeRate = 0.0;
95 FGAIAircraft::~FGAIAircraft() {
98 controller->signOff(getID());
102 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
106 FGAIBase::readFromScenario(scFileNode);
108 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
109 setFlightPlan(scFileNode->getStringValue("flightplan"),
110 scFileNode->getBoolValue("repeat", false));
111 setCallSign(scFileNode->getStringValue("callsign"));
112 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
116 bool FGAIAircraft::init() {
117 //refuel_node = fgGetNode("systems/refuel/contact", true);
118 return FGAIBase::init();
122 void FGAIAircraft::bind() {
125 props->tie("controls/gear/gear-down",
126 SGRawValueMethods<FGAIAircraft,bool>(*this,
127 &FGAIAircraft::_getGearDown));
128 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
129 props->setStringValue("callsign", callsign.c_str());
130 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
131 props->setBoolValue("tanker",isTanker);
135 void FGAIAircraft::unbind() {
138 props->untie("controls/gear/gear-down");
139 props->untie("refuel/contact");
143 void FGAIAircraft::update(double dt) {
144 FGAIBase::update(dt);
150 void FGAIAircraft::setPerformance(const std::string& acclass) {
151 if (acclass == "light") {
152 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
153 } else if (acclass == "ww2_fighter") {
154 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
155 } else if (acclass == "jet_transport") {
156 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
157 } else if (acclass == "jet_fighter") {
158 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
159 } else if (acclass == "tanker") {
160 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
162 } else if (acclass == "ufo") {
163 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
165 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
170 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
176 void FGAIAircraft::Run(double dt) {
178 FGAIAircraft::dt = dt;
181 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
182 ProcessFlightPlan(dt, now);
183 if (now < fp->getStartTime()) {
184 // Do execute Ground elev for inactive aircraft, so they
185 // Are repositioned to the correct ground altitude when the user flies within visibility range.
186 // In addition, check whether we are out of user range, so this aircraft
189 Transform(); // make sure aip is initialized.
191 double userLatitude = fgGetDouble("/position/latitude-deg");
192 double userLongitude = fgGetDouble("/position/longitude-deg");
193 double course, distance;
194 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
195 SGWayPoint user (userLongitude, userLatitude, 0);
196 user.CourseAndDistance(current, &course, &distance);
197 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
201 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
202 //getGroundElev(dt); // Need to do this twice.
203 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
205 //cerr << " Actual altitude " << altitude << endl;
207 pos.setElevationFt(altitude_ft);
213 // no flight plan, update target heading, speed, and altitude
214 // from control properties. These default to the initial
215 // settings in the config file, but can be changed "on the
217 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
218 if ( lat_mode == "roll" ) {
220 = props->getDoubleValue("controls/flight/target-roll" );
224 = props->getDoubleValue("controls/flight/target-hdg" );
229 = props->getStringValue("controls/flight/longitude-mode");
230 if ( lon_mode == "alt" ) {
231 double alt = props->getDoubleValue("controls/flight/target-alt" );
235 = props->getDoubleValue("controls/flight/target-pitch" );
239 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
243 controller->update(getID(),
244 pos.getLatitudeDeg(),
245 pos.getLongitudeDeg(),
249 processATC(controller->getInstruction(getID()));
252 double turn_radius_ft;
253 double turn_circum_ft;
254 double speed_north_deg_sec;
255 double speed_east_deg_sec;
256 double dist_covered_ft;
260 double speed_diff; //= tgt_speed - speed;
262 speed_diff = tgt_speed - speed;
264 speed_diff = groundTargetSpeed - speed;
267 if (speed_diff > 0.0) {
268 speed += performance->accel * dt;
269 if (no_roll) { // apply overshoot correction
270 if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
272 if ( speed > tgt_speed ) speed = tgt_speed;
274 } else if (speed_diff < 0.0) {
276 // on ground (aircraft can't roll)
277 // deceleration performance is better due to wheel brakes.
278 speed -= performance->decel * dt * 3;
280 speed -= performance->decel * dt;
282 if (no_roll) { // apply overshoot correction
283 if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
285 if ( speed < tgt_speed ) speed = tgt_speed;
290 // convert speed to degrees per second
291 speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
292 * speed * 1.686 / ft_per_deg_lat;
293 speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
294 * speed * 1.686 / ft_per_deg_lon;
297 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
298 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
300 /* printf("%.7f %0.4f %.7f %.5f %.7f %.7f %.8f %.8f %.9f %.9f\n",
301 dt, hdg, speed, ft_per_deg_lat,
302 cos( hdg * SGD_DEGREES_TO_RADIANS ),
303 speed * 1.686 / ft_per_deg_lat,
304 speed_north_deg_sec, speed_east_deg_sec,
305 pos.getLatitudeDeg(), pos.getLongitudeDeg()); */
307 //if (!(finite(pos.lat()) && finite(pos.lon())))
309 // cerr << "Position is not finite" << endl;
310 // cerr << "speed = " << speed << endl;
311 // cerr << "dt" << dt << endl;
312 // cerr << "heading " << hdg << endl;
313 // cerr << "speed east " << speed_east_deg_sec << endl;
314 // cerr << "speed nrth " << speed_north_deg_sec << endl;
315 // cerr << "deg_lat " << ft_per_deg_lat << endl;
316 // cerr << "deg_lon " << ft_per_deg_lon << endl;
319 // adjust heading based on current bank angle
324 // double turnConstant;
326 // turnConstant = 0.0088362;
328 // turnConstant = 0.088362;
329 // If on ground, calculate heading change directly
331 double headingDiff = fabs(hdg-tgt_heading);
333 if (headingDiff > 180)
334 headingDiff = fabs(headingDiff - 360);
336 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
337 if (sign(groundTargetSpeed) != sign(tgt_speed))
338 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
340 if (headingDiff > 30.0) {
341 headingChangeRate += dt * sign(roll); // invert if pushed backward
342 // Print some debug statements to find out why aircraft may get stuck
344 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
345 // cerr << "Turning : " << trafficRef->getRegistration()
346 // cerr << " Speed = " << speed << " Heading " << hdg
347 // << " Target Heading " << tgt_heading
348 // << " Lead Distance " << fp->getLeadDistance()
349 // << " Distance to go "
350 // << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
351 // << "waypoint name " << fp->getCurrentWaypoint()->name
354 if (headingChangeRate > 30)
355 headingChangeRate = 30;
356 else if (headingChangeRate < -30)
357 headingChangeRate = -30;
360 if (fabs(headingChangeRate) > headingDiff)
361 headingChangeRate = headingDiff*sign(roll);
363 headingChangeRate += dt * sign(roll);
365 hdg += headingChangeRate * dt;
366 //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
367 // << ". Target speed: " << groundTargetSpeed << ". heading change rate"
368 // << headingChangeRate << endl;
371 if (fabs(speed) > 1.0) {
372 turn_radius_ft = 0.088362 * speed * speed
373 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
375 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
377 turn_circum_ft = SGD_2PI * turn_radius_ft;
378 dist_covered_ft = speed * 1.686 * dt;
379 alpha = dist_covered_ft / turn_circum_ft * 360.0;
380 hdg += alpha * sign(roll);
382 while ( hdg > 360.0 ) {
393 // adjust target bank angle if heading lock engaged
395 double bank_sense = 0.0;
396 double diff = fabs(hdg - tgt_heading);
398 diff = fabs(diff - 360);
400 double sum = hdg + diff;
403 if (fabs(sum - tgt_heading) < 1.0) {
404 bank_sense = 1.0; // right turn
406 bank_sense = -1.0; // left turn
409 tgt_roll = diff * bank_sense;
411 tgt_roll = 30.0 * bank_sense;
413 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
414 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
415 // The only way to resolve this is to make them slow down.
416 //if (tempReg.empty())
417 // tempReg = trafficRef->getRegistration();
418 //if (trafficRef->getRegistration() == tempReg) {
419 // cerr << trafficRef->getRegistration()
420 // << " appears to be spinning: " << spinCounter << endl
421 // << " speed " << speed << endl
422 // << " heading " << hdg << endl
423 // << " lead distance " << fp->getLeadDistance() << endl
424 // << " waypoint " << fp->getCurrentWaypoint()->name
425 // << " target heading " << tgt_heading << endl
426 // << " lead in angle " << fp->getLeadInAngle()<< endl
427 // << " roll " << roll << endl
428 // << " target_roll " << tgt_roll << endl;
433 // adjust bank angle, use 9 degrees per second
434 double bank_diff = tgt_roll - roll;
435 if (fabs(bank_diff) > 0.2) {
441 //while (roll > 180) roll -= 360;
442 //while (roll < 180) roll += 360;
445 // adjust altitude (meters) based on current vertical speed (fpm)
446 altitude_ft += vs / 60.0 * dt;
447 pos.setElevationFt(altitude_ft);
449 // adjust target Altitude, based on ground elevation when on ground
454 // find target vertical speed if altitude lock engaged
455 if (alt_lock && use_perf_vs) {
456 if (altitude_ft < tgt_altitude_ft) {
457 tgt_vs = tgt_altitude_ft - altitude_ft;
458 if (tgt_vs > performance->climb_rate)
459 tgt_vs = performance->climb_rate;
461 tgt_vs = tgt_altitude_ft - altitude_ft;
462 if (tgt_vs < (-performance->descent_rate))
463 tgt_vs = -performance->descent_rate;
467 if (alt_lock && !use_perf_vs) {
468 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
470 if (tgt_altitude_ft < altitude_ft)
472 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
473 && (fabs(max_vs) < fabs(tgt_vs)))
476 if (fabs(tgt_vs) < fabs(min_vs))
480 // adjust vertical speed
481 double vs_diff = tgt_vs - vs;
482 if (fabs(vs_diff) > 10.0) {
484 vs += (performance->climb_rate / 3.0) * dt;
489 vs -= (performance->descent_rate / 3.0) * dt;
496 // match pitch angle to vertical speed
503 //###########################//
504 // do calculations for radar //
505 //###########################//
506 double range_ft2 = UpdateRadar(manager);
508 //************************************//
510 //************************************//
513 if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
514 && (elevation > 0.0) ) {
515 //refuel_node->setBoolValue(true);
518 //refuel_node->setBoolValue(false);
527 void FGAIAircraft::AccelTo(double speed) {
532 void FGAIAircraft::PitchTo(double angle) {
538 void FGAIAircraft::RollTo(double angle) {
544 void FGAIAircraft::YawTo(double angle) {
549 void FGAIAircraft::ClimbTo(double alt_ft ) {
550 tgt_altitude_ft = alt_ft;
555 void FGAIAircraft::TurnTo(double heading) {
556 tgt_heading = heading;
561 double FGAIAircraft::sign(double x) {
569 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
570 if (!flightplan.empty()) {
571 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
572 fp->setRepeat(repeat);
578 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
584 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
587 eraseWaypoints = true;
589 eraseWaypoints = false;
592 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
593 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
594 FGAIFlightPlan::waypoint* next = 0; // the next plus 1
595 prev = fp->getPreviousWaypoint();
596 curr = fp->getCurrentWaypoint();
597 next = fp->getNextWaypoint();
600 ///////////////////////////////////////////////////////////////////////////
601 // Initialize the flightplan
602 //////////////////////////////////////////////////////////////////////////
607 fp->IncrementWaypoint(eraseWaypoints);
608 if (!(fp->getNextWaypoint()) && trafficRef)
611 prev = fp->getPreviousWaypoint(); //first waypoint
612 curr = fp->getCurrentWaypoint(); //second waypoint
613 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
615 setLatitude(prev->latitude);
616 setLongitude(prev->longitude);
617 setSpeed(prev->speed);
618 setAltitude(prev->altitude);
620 if (prev->speed > 0.0)
621 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
623 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
625 // If next doesn't exist, as in incrementally created flightplans for
626 // AI/Trafficmanager created plans,
627 // Make sure lead distance is initialized otherwise
629 fp->setLeadDistance(speed, hdg, curr, next);
631 if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
633 tgt_vs = (curr->crossat - prev->altitude)
634 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
635 / 6076.0 / prev->speed*60.0);
636 tgt_altitude_ft = curr->crossat;
639 tgt_altitude_ft = prev->altitude;
641 alt_lock = hdg_lock = true;
642 no_roll = prev->on_ground;
644 Transform(); // make sure aip is initialized.
645 getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
648 // Make sure to announce the aircraft's position
649 announcePositionToController();
652 } // end of initialization
654 ///////////////////////////////////////////////////////////////////////////
655 // Check Execution time (currently once every 100 ms
656 ///////////////////////////////////////////////////////////////////////////
657 if ((dt_count < 0.1) || (now < fp->getStartTime())) {
658 //cerr << "done fp dt" << endl;
663 // check to see if we've reached the lead point for our next turn
664 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
666 //cerr << "2" << endl;
667 double lead_dist = fp->getLeadDistance();
668 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
669 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
671 if (lead_dist < fabs(2*speed)) {
672 lead_dist = fabs(2*speed); //don't skip over the waypoint
673 //cerr << "Extending lead distance to " << lead_dist << endl;
676 //prev_dist_to_go = dist_to_go;
678 if ( dist_to_go < lead_dist ) {
679 if (curr->finished) { //end of the flight plan
688 tgt_heading = fp->getBearing(curr, next);
692 fp->IncrementWaypoint(eraseWaypoints);
693 if (!(fp->getNextWaypoint()) && trafficRef)
696 prev = fp->getPreviousWaypoint();
697 curr = fp->getCurrentWaypoint();
698 next = fp->getNextWaypoint();
700 // Now that we have incremented the waypoints, excute some traffic manager specific code
702 double userLatitude = fgGetDouble("/position/latitude-deg");
703 double userLongitude = fgGetDouble("/position/longitude-deg");
704 double course, distance;
705 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
706 SGWayPoint user (userLongitude, userLatitude, 0);
707 user.CourseAndDistance(current, &course, &distance);
708 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
713 FGAirport * dep = trafficRef->getDepartureAirport();
714 FGAirport * arr = trafficRef->getArrivalAirport();
715 if (!( dep && arr)) {
719 // This waypoint marks the fact that the aircraft has passed the initial taxi
720 // departure waypoint, so it can release the parking.
721 if (prev->name == "park2")
722 dep->getDynamics()->releaseParking(fp->getGate());
723 // This is the last taxi waypoint, and marks the the end of the flight plan
724 // so, the schedule should update and wait for the next departure time.
725 if (prev->name == "END") {
726 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
728 time_t nextDeparture = trafficRef->getDepartureTime();
729 if (nextDeparture < (now+1200)) {
730 nextDeparture = now + 1200;
732 fp->setTime(trafficRef->getDepartureTime());
734 announcePositionToController();
739 //cerr << "Current waypoint" << curr->name << endl;
740 //cerr << "Next waypoint" << next->name << endl;
741 fp->setLeadDistance(speed, tgt_heading, curr, next);
744 //cerr << "5.1" << endl;
745 if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
746 tgt_altitude_ft = prev->altitude;
747 if (curr->crossat > -1000.0) {
748 //cerr << "5.1a" << endl;
750 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
751 / 6076.0 / speed*60.0);
752 //cerr << "5.1b" << endl;
753 tgt_altitude_ft = curr->crossat;
755 //cerr << "5.1c" << endl;
757 //cerr << "5.1d" << endl;
758 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
761 //cerr << "6" << endl;
762 tgt_speed = prev->speed;
763 hdg_lock = alt_lock = true;
764 no_roll = prev->on_ground;
765 //cout << "Crossing waypoint: " << prev->name << endl;
766 //cout << " Target speed: " << tgt_speed << endl;
767 //cout << " Target altitude: " << tgt_altitude_ft << endl;
768 //cout << " Target heading: " << tgt_heading << endl << endl;
771 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
772 //cerr << "Bearing = " << calc_bearing << endl;
775 if (calc_bearing > 360)
779 if (finite(calc_bearing)) {
780 double hdg_error = calc_bearing - tgt_heading;
781 if (fabs(hdg_error) > 1.0) {
782 TurnTo( calc_bearing );
786 cerr << "calc_bearing is not a finite number : "
788 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
789 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
790 cerr << "waypoint name " << curr->name;
794 double speed_diff = speed - prevSpeed;
795 // Update the lead distance calculation if speed has changed sufficiently
796 // to prevent spinning (hopefully);
797 if (fabs(speed_diff) > 10) {
799 fp->setLeadDistance(speed, tgt_heading, curr, next);
802 //cerr << "Done Processing FlightPlan"<< endl;
806 void FGAIAircraft::initializeFlightPlan()
812 bool FGAIAircraft::_getGearDown() const {
813 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
814 && (props->getFloatValue("velocities/airspeed-kt")
815 < performance->land_speed*1.25));
819 void FGAIAircraft::loadNextLeg() {
821 //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
823 //FGAIModelEntity entity;
824 //entity.m_class = "jet_transport";
825 //entity.path = modelPath.c_str();
826 //entity.flightplan = "none";
827 //entity.latitude = _getLatitude();
828 //entity.longitude = _getLongitude();
829 //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
830 //entity.speed = 450; // HACK ALERT
831 //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
833 if ((leg = fp->getLeg()) == 10) {
837 //cerr << "Resetting leg : " << leg << endl;
841 //cerr << "Creating leg number : " << leg << endl;
842 FGAirport *dep = trafficRef->getDepartureAirport();
843 FGAirport *arr = trafficRef->getArrivalAirport();
846 //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
848 // cerr << "Departure " << dep->getId() << endl;
850 // cerr << "Arrival " << arr->getId() << endl;
853 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
854 //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
859 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
860 trafficRef->getSpeed(),
864 trafficRef->getRadius(),
865 trafficRef->getFlightType(),
868 //prev = fp->getPreviousWaypoint();
869 //curr = fp->getCurrentWaypoint();
870 //next = fp->getNextWaypoint();
871 //cerr << "25" << endl;
874 // //cerr << "Next waypoint" << next->name << endl;
875 // fp->setLeadDistance(speed, tgt_heading, curr, next);
877 //cerr << "25.1" << endl;
878 //if (curr->crossat > -1000.0) {
879 // //cerr << "25.1a" << endl;
880 // use_perf_vs = false;
882 // tgt_vs = (curr->crossat - altitude_ft)/
883 // (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
884 // //cerr << "25.1b" << endl;
885 // tgt_altitude_ft = curr->crossat;
887 // //cerr << "25.1c" << endl;
888 // use_perf_vs = true;
889 // //cerr << "25.1d" << endl;
890 // tgt_altitude_ft = prev->altitude;
891 // //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
893 //cerr << "26" << endl;
894 //tgt_speed = prev->speed;
895 //hdg_lock = alt_lock = true;
896 //no_roll = prev->on_ground;
901 //entity.fp = new FGAIFlightPlan(&entity,
903 // trafficRef->getDepartureTime(),
904 // trafficRef->getDepartureAirport(),
905 // trafficRef->getArrivalAirport(),
909 //SetFlightPlan(entity.fp);
913 // Note: This code is copied from David Luff's AILocalTraffic
914 // Warning - ground elev determination is CPU intensive
915 // Either this function or the logic of how often it is called
916 // will almost certainly change.
918 void FGAIAircraft::getGroundElev(double dt) {
921 // Update minimally every three secs, but add some randomness
922 // to prevent all IA objects doing this in synchrony
923 if (dt_elev_count < (3.0) + (rand() % 10))
928 // Only do the proper hitlist stuff if we are within visible range of the viewer.
930 double visibility_meters = fgGetDouble("/environment/visibility-m");
932 FGViewer* vw = globals->get_current_view();
933 double course, distance;
935 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
936 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
937 view.CourseAndDistance(current, &course, &distance);
938 if(distance > visibility_meters) {
939 //aip.getSGLocation()->set_cur_elev_m(aptElev);
943 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
944 double range = 500.0;
945 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
946 // Try to shedule tiles for that position.
947 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
950 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
952 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
953 tgt_altitude_ft = alt * SG_METER_TO_FEET;
955 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
956 // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
958 // tgt_altitude_ft = alt * SG_METER_TO_FEET;
959 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
964 void FGAIAircraft::setCallSign(const string& s) {
969 void FGAIAircraft::setTACANChannelID(const string& id) {
970 TACAN_channel_id = id;
974 void FGAIAircraft::doGroundAltitude() {
975 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
976 altitude_ft = (tgt_altitude_ft + groundOffset);
978 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
982 void FGAIAircraft::announcePositionToController()
985 //FGTaxiRoute *taxiRoute = fp->getTaxiRoute();
987 int leg = fp->getLeg();
989 //if (fp->getCurrentWaypoint()->routeIndex != 0) {
991 //snprintf (buffer, 10, "%d", node);
992 // Note that leg was been incremented after creating the current leg, so we should use
993 // leg numbers here that are one higher than the number that is used to create the leg
996 case 3: // Taxiing to runway
997 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
998 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
1000 case 4: //Take off tower controller
1001 if (trafficRef->getDepartureAirport()->getDynamics())
1003 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
1004 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
1005 //cerr << trafficRef->getCallSign() << " at runway " << fp->getRunway() << "Ready for departure "
1006 // << trafficRef->getFlightType() << " to " << trafficRef->getArrivalAirport()->getId() << endl;
1007 // if (controller == 0) {
1008 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
1013 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
1016 case 9: // Taxiing for parking
1017 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
1018 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
1025 if ((controller != prevController) && (prevController != 0)) {
1026 prevController->signOff(getID());
1027 string callsign = trafficRef->getCallSign();
1028 if ( trafficRef->getHeavy())
1029 callsign += "Heavy";
1032 cerr << callsign << " ready to taxi to runway " << fp->getRunway() << endl;
1035 cerr << callsign << " at runway " << fp->getRunway() << "Ready for take-off. "
1036 << trafficRef->getFlightRules() << " to " << trafficRef->getArrivalAirport()->getId()
1037 << "(" << trafficRef->getArrivalAirport()->getName() << ")."<< endl;
1040 prevController = controller;
1042 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
1043 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
1044 trafficRef->getRadius(), leg);
1050 void FGAIAircraft::processATC(FGATCInstruction instruction)
1052 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
1053 if (instruction.getHoldPattern ()) {
1057 if (instruction.getHoldPosition ()) {
1060 cerr << trafficRef->getCallSign() << "Holding Position " << endl;
1067 cerr << trafficRef->getCallSign() << " Resuming Taxi " << endl;
1070 // Change speed Instruction. This can only be excecuted when there is no
1071 // Hold position instruction.
1072 if (instruction.getChangeSpeed ()) {
1073 AccelTo(instruction.getSpeed());
1075 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
1078 if (instruction.getChangeHeading ()) {
1080 TurnTo(instruction.getHeading());
1082 if (fp) {hdg_lock = true;}
1084 if (instruction.getChangeAltitude()) {