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 static string tempReg;
48 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
49 // cruise_speed, descent_speed, land_speed
51 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
53 {2.0, 2.0, 450.0, 1000.0, 70.0, 80.0, 100.0, 80.0, 60.0},
55 {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
57 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
59 {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
61 {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
62 // ufo (extreme accel/decel)
63 {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
67 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
72 groundOffset = trafficRef->getGroundOffset();
84 // set heading and altitude locks
88 headingChangeRate = 0.0;
92 FGAIAircraft::~FGAIAircraft() {
97 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
101 FGAIBase::readFromScenario(scFileNode);
103 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
104 setFlightPlan(scFileNode->getStringValue("flightplan"),
105 scFileNode->getBoolValue("repeat", false));
106 setCallSign(scFileNode->getStringValue("callsign"));
107 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
111 bool FGAIAircraft::init() {
112 //refuel_node = fgGetNode("systems/refuel/contact", true);
113 return FGAIBase::init();
117 void FGAIAircraft::bind() {
120 props->tie("controls/gear/gear-down",
121 SGRawValueMethods<FGAIAircraft,bool>(*this,
122 &FGAIAircraft::_getGearDown));
123 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
124 props->setStringValue("callsign", callsign.c_str());
125 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
126 props->setBoolValue("tanker",isTanker);
130 void FGAIAircraft::unbind() {
133 props->untie("controls/gear/gear-down");
134 props->untie("refuel/contact");
138 void FGAIAircraft::update(double dt) {
139 FGAIBase::update(dt);
145 void FGAIAircraft::setPerformance(const std::string& acclass) {
146 if (acclass == "light") {
147 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
148 } else if (acclass == "ww2_fighter") {
149 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
150 } else if (acclass == "jet_transport") {
151 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
152 } else if (acclass == "jet_fighter") {
153 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
154 } else if (acclass == "tanker") {
155 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
157 } else if (acclass == "ufo") {
158 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
160 SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
165 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
171 void FGAIAircraft::Run(double dt) {
173 FGAIAircraft::dt = dt;
176 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
177 ProcessFlightPlan(dt, now);
178 if (now < fp->getStartTime()) {
179 // Do execute Ground elev for inactive aircraft, so they
180 // Are repositioned to the correct ground altitude when the user flies within visibility range.
182 Transform(); // make sure aip is initialized.
183 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
184 //getGroundElev(dt); // Need to do this twice.
185 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
187 //cerr << " Actual altitude " << altitude << endl;
189 pos.setElevationFt(altitude_ft);
194 // no flight plan, update target heading, speed, and altitude
195 // from control properties. These default to the initial
196 // settings in the config file, but can be changed "on the
198 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
199 if ( lat_mode == "roll" ) {
201 = props->getDoubleValue("controls/flight/target-roll" );
205 = props->getDoubleValue("controls/flight/target-hdg" );
210 = props->getStringValue("controls/flight/longitude-mode");
211 if ( lon_mode == "alt" ) {
212 double alt = props->getDoubleValue("controls/flight/target-alt" );
216 = props->getDoubleValue("controls/flight/target-pitch" );
220 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
224 controller->update(getID(),
225 pos.getLatitudeDeg(),
226 pos.getLongitudeDeg(),
230 //if (controller->hasInstruction(getID()))
232 processATC(controller->getInstruction(getID()));
236 double turn_radius_ft;
237 double turn_circum_ft;
238 double speed_north_deg_sec;
239 double speed_east_deg_sec;
240 double dist_covered_ft;
244 double speed_diff; //= tgt_speed - speed;
246 speed_diff = tgt_speed - speed;
248 speed_diff = groundTargetSpeed - speed;
251 if (speed_diff > 0.0) {
252 speed += performance->accel * dt;
253 if (no_roll) { // apply overshoot correction
254 if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
256 if ( speed > tgt_speed ) speed = tgt_speed;
258 } else if (speed_diff < 0.0) {
260 // on ground (aircraft can't roll)
261 // deceleration performance is better due to wheel brakes.
262 speed -= performance->decel * dt * 3;
264 speed -= performance->decel * dt;
266 if (no_roll) { // apply overshoot correction
267 if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
269 if ( speed < tgt_speed ) speed = tgt_speed;
274 // convert speed to degrees per second
275 speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
276 * speed * 1.686 / ft_per_deg_lat;
277 speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
278 * speed * 1.686 / ft_per_deg_lon;
281 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
282 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
284 /* printf("%.7f %0.4f %.7f %.5f %.7f %.7f %.8f %.8f %.9f %.9f\n",
285 dt, hdg, speed, ft_per_deg_lat,
286 cos( hdg * SGD_DEGREES_TO_RADIANS ),
287 speed * 1.686 / ft_per_deg_lat,
288 speed_north_deg_sec, speed_east_deg_sec,
289 pos.getLatitudeDeg(), pos.getLongitudeDeg()); */
291 //if (!(finite(pos.lat()) && finite(pos.lon())))
293 // cerr << "Position is not finite" << endl;
294 // cerr << "speed = " << speed << endl;
295 // cerr << "dt" << dt << endl;
296 // cerr << "heading " << hdg << endl;
297 // cerr << "speed east " << speed_east_deg_sec << endl;
298 // cerr << "speed nrth " << speed_north_deg_sec << endl;
299 // cerr << "deg_lat " << ft_per_deg_lat << endl;
300 // cerr << "deg_lon " << ft_per_deg_lon << endl;
303 // adjust heading based on current bank angle
308 // double turnConstant;
310 // turnConstant = 0.0088362;
312 // turnConstant = 0.088362;
313 // If on ground, calculate heading change directly
315 double headingDiff = fabs(hdg-tgt_heading);
317 if (headingDiff > 180)
318 headingDiff = fabs(headingDiff - 360);
320 groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
321 if (sign(groundTargetSpeed) != sign(tgt_speed))
322 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
324 if (headingDiff > 30.0) {
325 headingChangeRate += dt * sign(roll); // invert if pushed backward
326 // Print some debug statements to find out why aircraft may get stuck
328 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
329 // cerr << "Turning : " << trafficRef->getRegistration()
330 // cerr << " Speed = " << speed << " Heading " << hdg
331 // << " Target Heading " << tgt_heading
332 // << " Lead Distance " << fp->getLeadDistance()
333 // << " Distance to go "
334 // << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
335 // << "waypoint name " << fp->getCurrentWaypoint()->name
338 if (headingChangeRate > 30)
339 headingChangeRate = 30;
340 else if (headingChangeRate < -30)
341 headingChangeRate = -30;
344 if (fabs(headingChangeRate) > headingDiff)
345 headingChangeRate = headingDiff*sign(roll);
347 headingChangeRate += dt * sign(roll);
349 hdg += headingChangeRate * dt;
350 //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
351 // << ". Target speed: " << groundTargetSpeed << ". heading change rate"
352 // << headingChangeRate << endl;
355 if (fabs(speed) > 1.0) {
356 turn_radius_ft = 0.088362 * speed * speed
357 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
359 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
361 turn_circum_ft = SGD_2PI * turn_radius_ft;
362 dist_covered_ft = speed * 1.686 * dt;
363 alpha = dist_covered_ft / turn_circum_ft * 360.0;
364 hdg += alpha * sign(roll);
366 while ( hdg > 360.0 ) {
377 // adjust target bank angle if heading lock engaged
379 double bank_sense = 0.0;
380 double diff = fabs(hdg - tgt_heading);
382 diff = fabs(diff - 360);
384 double sum = hdg + diff;
387 if (fabs(sum - tgt_heading) < 1.0) {
388 bank_sense = 1.0; // right turn
390 bank_sense = -1.0; // left turn
393 tgt_roll = diff * bank_sense;
395 tgt_roll = 30.0 * bank_sense;
397 if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
398 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
399 // The only way to resolve this is to make them slow down.
400 //if (tempReg.empty())
401 // tempReg = trafficRef->getRegistration();
402 //if (trafficRef->getRegistration() == tempReg) {
403 // cerr << trafficRef->getRegistration()
404 // << " appears to be spinning: " << spinCounter << endl
405 // << " speed " << speed << endl
406 // << " heading " << hdg << endl
407 // << " lead distance " << fp->getLeadDistance() << endl
408 // << " waypoint " << fp->getCurrentWaypoint()->name
409 // << " target heading " << tgt_heading << endl
410 // << " lead in angle " << fp->getLeadInAngle()<< endl
411 // << " roll " << roll << endl
412 // << " target_roll " << tgt_roll << endl;
417 // adjust bank angle, use 9 degrees per second
418 double bank_diff = tgt_roll - roll;
419 if (fabs(bank_diff) > 0.2) {
425 //while (roll > 180) roll -= 360;
426 //while (roll < 180) roll += 360;
429 // adjust altitude (meters) based on current vertical speed (fpm)
430 altitude_ft += vs / 60.0 * dt;
431 pos.setElevationFt(altitude_ft);
433 // adjust target Altitude, based on ground elevation when on ground
438 // find target vertical speed if altitude lock engaged
439 if (alt_lock && use_perf_vs) {
440 if (altitude_ft < tgt_altitude_ft) {
441 tgt_vs = tgt_altitude_ft - altitude_ft;
442 if (tgt_vs > performance->climb_rate)
443 tgt_vs = performance->climb_rate;
445 tgt_vs = tgt_altitude_ft - altitude_ft;
446 if (tgt_vs < (-performance->descent_rate))
447 tgt_vs = -performance->descent_rate;
451 if (alt_lock && !use_perf_vs) {
452 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
454 if (tgt_altitude_ft < altitude_ft)
456 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
457 && (fabs(max_vs) < fabs(tgt_vs)))
460 if (fabs(tgt_vs) < fabs(min_vs))
464 // adjust vertical speed
465 double vs_diff = tgt_vs - vs;
466 if (fabs(vs_diff) > 10.0) {
468 vs += (performance->climb_rate / 3.0) * dt;
473 vs -= (performance->descent_rate / 3.0) * dt;
480 // match pitch angle to vertical speed
487 //###########################//
488 // do calculations for radar //
489 //###########################//
490 double range_ft2 = UpdateRadar(manager);
492 //************************************//
494 //************************************//
497 if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
498 && (elevation > 0.0) ) {
499 //refuel_node->setBoolValue(true);
502 //refuel_node->setBoolValue(false);
511 void FGAIAircraft::AccelTo(double speed) {
516 void FGAIAircraft::PitchTo(double angle) {
522 void FGAIAircraft::RollTo(double angle) {
528 void FGAIAircraft::YawTo(double angle) {
533 void FGAIAircraft::ClimbTo(double alt_ft ) {
534 tgt_altitude_ft = alt_ft;
539 void FGAIAircraft::TurnTo(double heading) {
540 tgt_heading = heading;
545 double FGAIAircraft::sign(double x) {
553 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
554 if (!flightplan.empty()) {
555 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
556 fp->setRepeat(repeat);
562 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
568 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
571 eraseWaypoints = true;
573 eraseWaypoints = false;
576 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
577 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
578 FGAIFlightPlan::waypoint* next = 0; // the next plus 1
579 prev = fp->getPreviousWaypoint();
580 curr = fp->getCurrentWaypoint();
581 next = fp->getNextWaypoint();
584 ///////////////////////////////////////////////////////////////////////////
585 // Initialize the flightplan
586 //////////////////////////////////////////////////////////////////////////
591 fp->IncrementWaypoint(eraseWaypoints);
592 if (!(fp->getNextWaypoint()) && trafficRef)
595 prev = fp->getPreviousWaypoint(); //first waypoint
596 curr = fp->getCurrentWaypoint(); //second waypoint
597 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
599 setLatitude(prev->latitude);
600 setLongitude(prev->longitude);
601 setSpeed(prev->speed);
602 setAltitude(prev->altitude);
604 if (prev->speed > 0.0)
605 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
607 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
609 // If next doesn't exist, as in incrementally created flightplans for
610 // AI/Trafficmanager created plans,
611 // Make sure lead distance is initialized otherwise
613 fp->setLeadDistance(speed, hdg, curr, next);
615 if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
617 tgt_vs = (curr->crossat - prev->altitude)
618 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
619 / 6076.0 / prev->speed*60.0);
620 tgt_altitude_ft = curr->crossat;
623 tgt_altitude_ft = prev->altitude;
625 alt_lock = hdg_lock = true;
626 no_roll = prev->on_ground;
628 Transform(); // make sure aip is initialized.
629 getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
632 // Make sure to announce the aircraft's position
633 announcePositionToController();
636 } // end of initialization
638 ///////////////////////////////////////////////////////////////////////////
639 // Check Execution time (currently once every 100 ms
640 ///////////////////////////////////////////////////////////////////////////
641 if ((dt_count < 0.1) || (now < fp->getStartTime())) {
642 //cerr << "done fp dt" << endl;
647 // check to see if we've reached the lead point for our next turn
648 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
650 //cerr << "2" << endl;
651 double lead_dist = fp->getLeadDistance();
652 //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
653 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
655 if (lead_dist < fabs(2*speed)) {
656 lead_dist = fabs(2*speed); //don't skip over the waypoint
657 //cerr << "Extending lead distance to " << lead_dist << endl;
660 //prev_dist_to_go = dist_to_go;
662 if ( dist_to_go < lead_dist ) {
663 if (curr->finished) { //end of the flight plan
672 tgt_heading = fp->getBearing(curr, next);
676 fp->IncrementWaypoint(eraseWaypoints);
677 if (!(fp->getNextWaypoint()) && trafficRef)
680 prev = fp->getPreviousWaypoint();
681 curr = fp->getCurrentWaypoint();
682 next = fp->getNextWaypoint();
684 // Now that we have incremented the waypoints, excute some traffic manager specific code
686 double userLatitude = fgGetDouble("/position/latitude-deg");
687 double userLongitude = fgGetDouble("/position/longitude-deg");
688 double course, distance;
689 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
690 SGWayPoint user (userLongitude, userLatitude, 0);
691 user.CourseAndDistance(current, &course, &distance);
692 if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
697 FGAirport * dep = trafficRef->getDepartureAirport();
698 FGAirport * arr = trafficRef->getArrivalAirport();
699 if (!( dep && arr)) {
703 // This waypoint marks the fact that the aircraft has passed the initial taxi
704 // departure waypoint, so it can release the parking.
705 if (prev->name == "park2")
706 dep->getDynamics()->releaseParking(fp->getGate());
707 // This is the last taxi waypoint, and marks the the end of the flight plan
708 // so, the schedule should update and wait for the next departure time.
709 if (prev->name == "END") {
710 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
712 time_t nextDeparture = trafficRef->getDepartureTime();
713 if (nextDeparture < (now+1200)) {
714 nextDeparture = now + 1200;
716 fp->setTime(trafficRef->getDepartureTime());
718 announcePositionToController();
723 //cerr << "Current waypoint" << curr->name << endl;
724 //cerr << "Next waypoint" << next->name << endl;
725 fp->setLeadDistance(speed, tgt_heading, curr, next);
728 //cerr << "5.1" << endl;
729 if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
730 tgt_altitude_ft = prev->altitude;
731 if (curr->crossat > -1000.0) {
732 //cerr << "5.1a" << endl;
734 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
735 / 6076.0 / speed*60.0);
736 //cerr << "5.1b" << endl;
737 tgt_altitude_ft = curr->crossat;
739 //cerr << "5.1c" << endl;
741 //cerr << "5.1d" << endl;
742 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
745 //cerr << "6" << endl;
746 tgt_speed = prev->speed;
747 hdg_lock = alt_lock = true;
748 no_roll = prev->on_ground;
749 //cout << "Crossing waypoint: " << prev->name << endl;
750 //cout << " Target speed: " << tgt_speed << endl;
751 //cout << " Target altitude: " << tgt_altitude_ft << endl;
752 //cout << " Target heading: " << tgt_heading << endl << endl;
755 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
756 //cerr << "Bearing = " << calc_bearing << endl;
759 if (calc_bearing > 360)
763 if (finite(calc_bearing)) {
764 double hdg_error = calc_bearing - tgt_heading;
765 if (fabs(hdg_error) > 1.0) {
766 TurnTo( calc_bearing );
770 cerr << "calc_bearing is not a finite number : "
772 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
773 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
774 cerr << "waypoint name " << curr->name;
778 double speed_diff = speed - prevSpeed;
779 // Update the lead distance calculation if speed has changed sufficiently
780 // to prevent spinning (hopefully);
781 if (fabs(speed_diff) > 10) {
783 fp->setLeadDistance(speed, tgt_heading, curr, next);
786 //cerr << "Done Processing FlightPlan"<< endl;
790 void FGAIAircraft::initializeFlightPlan()
796 bool FGAIAircraft::_getGearDown() const {
797 return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
798 && (props->getFloatValue("velocities/airspeed-kt")
799 < performance->land_speed*1.25));
803 void FGAIAircraft::loadNextLeg() {
805 //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
807 //FGAIModelEntity entity;
808 //entity.m_class = "jet_transport";
809 //entity.path = modelPath.c_str();
810 //entity.flightplan = "none";
811 //entity.latitude = _getLatitude();
812 //entity.longitude = _getLongitude();
813 //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
814 //entity.speed = 450; // HACK ALERT
815 //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
817 if ((leg = fp->getLeg()) == 10) {
821 //cerr << "Resetting leg : " << leg << endl;
825 //cerr << "Creating leg number : " << leg << endl;
826 FGAirport *dep = trafficRef->getDepartureAirport();
827 FGAirport *arr = trafficRef->getArrivalAirport();
830 //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
832 // cerr << "Departure " << dep->getId() << endl;
834 // cerr << "Arrival " << arr->getId() << endl;
837 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
838 //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
843 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
844 trafficRef->getSpeed(),
848 trafficRef->getRadius(),
849 trafficRef->getFlightType(),
852 //prev = fp->getPreviousWaypoint();
853 //curr = fp->getCurrentWaypoint();
854 //next = fp->getNextWaypoint();
855 //cerr << "25" << endl;
858 // //cerr << "Next waypoint" << next->name << endl;
859 // fp->setLeadDistance(speed, tgt_heading, curr, next);
861 //cerr << "25.1" << endl;
862 //if (curr->crossat > -1000.0) {
863 // //cerr << "25.1a" << endl;
864 // use_perf_vs = false;
866 // tgt_vs = (curr->crossat - altitude_ft)/
867 // (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
868 // //cerr << "25.1b" << endl;
869 // tgt_altitude_ft = curr->crossat;
871 // //cerr << "25.1c" << endl;
872 // use_perf_vs = true;
873 // //cerr << "25.1d" << endl;
874 // tgt_altitude_ft = prev->altitude;
875 // //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
877 //cerr << "26" << endl;
878 //tgt_speed = prev->speed;
879 //hdg_lock = alt_lock = true;
880 //no_roll = prev->on_ground;
885 //entity.fp = new FGAIFlightPlan(&entity,
887 // trafficRef->getDepartureTime(),
888 // trafficRef->getDepartureAirport(),
889 // trafficRef->getArrivalAirport(),
893 //SetFlightPlan(entity.fp);
897 // Note: This code is copied from David Luff's AILocalTraffic
898 // Warning - ground elev determination is CPU intensive
899 // Either this function or the logic of how often it is called
900 // will almost certainly change.
902 void FGAIAircraft::getGroundElev(double dt) {
905 // Update minimally every three secs, but add some randomness
906 // to prevent all IA objects doing this in synchrony
907 if (dt_elev_count < (3.0) + (rand() % 10))
912 // Only do the proper hitlist stuff if we are within visible range of the viewer.
914 double visibility_meters = fgGetDouble("/environment/visibility-m");
916 FGViewer* vw = globals->get_current_view();
917 double course, distance;
919 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
920 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
921 view.CourseAndDistance(current, &course, &distance);
922 if(distance > visibility_meters) {
923 //aip.getSGLocation()->set_cur_elev_m(aptElev);
927 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
928 double range = 500.0;
929 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
930 // Try to shedule tiles for that position.
931 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
934 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
936 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
937 tgt_altitude_ft = alt * SG_METER_TO_FEET;
939 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
940 // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
942 // tgt_altitude_ft = alt * SG_METER_TO_FEET;
943 //cerr << "Target altitude : " << tgt_altitude_ft << endl;
948 void FGAIAircraft::setCallSign(const string& s) {
953 void FGAIAircraft::setTACANChannelID(const string& id) {
954 TACAN_channel_id = id;
958 void FGAIAircraft::doGroundAltitude() {
959 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
960 altitude_ft = (tgt_altitude_ft + groundOffset);
962 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
966 void FGAIAircraft::announcePositionToController()
969 //FGTaxiRoute *taxiRoute = fp->getTaxiRoute();
971 int leg = fp->getLeg();
973 // For starters, I'll only do this for departure and arrival taxi. The mechanism
974 // could be extended to include any controller however.
975 //int node, currentTaxiSegment;
976 //if (taxiRoute->next(&node, ¤tTaxiSegment)) {
977 if (fp->getCurrentWaypoint()->routeIndex != 0) {
979 //snprintf (buffer, 10, "%d", node);
982 cerr << trafficRef->getRegistration()
983 << " taxiing to runway at segment "
984 << fp->getCurrentWaypoint()->routeIndex
986 //cerr << "Match check between taxisegment and taxiroute : " << node << " "
987 // << fp->getCurrentWaypoint()->name << endl;
988 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
989 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
992 cerr << trafficRef->getRegistration()
993 << " taxiing to parking at segment "
994 << fp->getCurrentWaypoint()->routeIndex
996 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
997 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
1004 //fp->deleteTaxiRoute();
1007 if ((controller != prevController) && (prevController != 0)) {
1008 prevController->signOff(getID());
1009 cerr << trafficRef->getRegistration()
1010 << " signing off " << endl;
1012 prevController = controller;
1014 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
1015 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
1016 trafficRef->getRadius());
1022 void FGAIAircraft::processATC(FGATCInstruction instruction)
1024 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
1025 if (instruction.getHoldPattern ()) {
1027 if (instruction.getHoldPosition ()) {
1029 if (instruction.getChangeSpeed ()) {
1030 AccelTo(instruction.getSpeed());
1032 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
1034 if (instruction.getChangeHeading ()) {
1036 TurnTo(instruction.getHeading());
1038 if (fp) {hdg_lock = true;}
1040 if (instruction.getChangeAltitude()) {