]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
Maik JUSTUS: last changes for better consistency with The FlightGear Way.
[flightgear.git] / src / AIModel / AIAircraft.cxx
1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
2 //
3 // Written by David Culp, started October 2003.
4 //
5 // Copyright (C) 2003  David P. Culp - davidculp2@comcast.net
6 //
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.
11 //
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.
16 //
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.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
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
33 #include <string>
34 #include <math.h>
35 #include <time.h>
36 #ifdef _MSC_VER
37 #  include <float.h>
38 #  define finite _finite
39 #elif defined(__sun) || defined(sgi)
40 #  include <ieeefp.h>
41 #endif
42
43 SG_USING_STD(string);
44
45 #include "AIAircraft.hxx"
46 //#include <Airports/trafficcontroller.hxx>
47    static string tempReg;
48 //
49 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
50 // cruise_speed, descent_speed, land_speed
51 //
52 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
53     // light aircraft
54     {2.0, 2.0,  450.0, 1000.0,  70.0,  80.0, 100.0,  80.0,  60.0},
55     // ww2_fighter
56     {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
57     // jet_transport
58     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
59     // jet_fighter
60     {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
61     // tanker
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}
65 };
66
67
68 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
69     FGAIBase(otAircraft)
70 {
71     trafficRef = ref;
72     if (trafficRef)
73         groundOffset = trafficRef->getGroundOffset();
74     else
75         groundOffset = 0;
76
77     fp = 0;
78     controller = 0;
79     prevController = 0;
80     dt_count = 0;
81     dt_elev_count = 0;
82     use_perf_vs = true;
83     isTanker = false;
84
85     // set heading and altitude locks
86     hdg_lock = false;
87     alt_lock = false;
88     roll = 0;
89     headingChangeRate = 0.0;
90
91     holdPos = false;
92 }
93
94
95 FGAIAircraft::~FGAIAircraft() {
96     //delete fp;
97   if (controller)
98     controller->signOff(getID());
99 }
100
101
102 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
103     if (!scFileNode)
104         return;
105
106     FGAIBase::readFromScenario(scFileNode);
107
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"));
113 }
114
115
116 bool FGAIAircraft::init() {
117     //refuel_node = fgGetNode("systems/refuel/contact", true);
118     return FGAIBase::init();
119 }
120
121
122 void FGAIAircraft::bind() {
123     FGAIBase::bind();
124
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);
132 }
133
134
135 void FGAIAircraft::unbind() {
136     FGAIBase::unbind();
137
138     props->untie("controls/gear/gear-down");
139     props->untie("refuel/contact");
140 }
141
142
143 void FGAIAircraft::update(double dt) {
144     FGAIBase::update(dt);
145     Run(dt);
146     Transform();
147 }
148
149
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]);
161         SetTanker(true);
162     } else if (acclass == "ufo") {
163         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
164     } else {
165         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
166     }
167 }
168
169
170 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
171
172    performance = ps;
173 }
174
175
176 void FGAIAircraft::Run(double dt) {
177
178     FGAIAircraft::dt = dt;
179     
180     if (fp) {
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
187             // can be deleted.
188             if (no_roll) {
189                 Transform();       // make sure aip is initialized.
190                 if (trafficRef) {
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) {
198                     setDie(true);
199                     return;
200                   }
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;
204                   doGroundAltitude();
205                   //cerr << " Actual altitude " << altitude << endl;
206                   // Transform();
207                   pos.setElevationFt(altitude_ft);
208                 }
209             }
210             return;
211         }
212     } else {
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
216         // fly".
217         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
218         if ( lat_mode == "roll" ) {
219             double angle
220                 = props->getDoubleValue("controls/flight/target-roll" );
221             RollTo( angle );
222         } else {
223              double angle
224                 = props->getDoubleValue("controls/flight/target-hdg" );
225             TurnTo( angle );
226         }
227
228         string lon_mode
229             = props->getStringValue("controls/flight/longitude-mode");
230         if ( lon_mode == "alt" ) {
231             double alt = props->getDoubleValue("controls/flight/target-alt" );
232             ClimbTo( alt );
233         } else {
234             double angle
235                 = props->getDoubleValue("controls/flight/target-pitch" );
236             PitchTo( angle );
237         }
238
239         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
240     }
241     if (controller)
242       {
243         controller->update(getID(), 
244                            pos.getLatitudeDeg(), 
245                            pos.getLongitudeDeg(),
246                            hdg,
247                            speed,
248                            altitude_ft, dt);
249         processATC(controller->getInstruction(getID()));
250       }
251       
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;
257     double alpha;
258
259     // adjust speed
260     double speed_diff; //= tgt_speed - speed;
261     if (!no_roll) {
262         speed_diff = tgt_speed - speed;
263     } else {
264         speed_diff = groundTargetSpeed - speed;
265     }
266
267     if (speed_diff > 0.0) {
268         speed += performance->accel * dt;
269         if (no_roll) { // apply overshoot correction
270           if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
271         }else {
272           if ( speed > tgt_speed ) speed = tgt_speed;
273         }
274     } else if (speed_diff < 0.0) {
275         if (no_roll) {
276             // on ground (aircraft can't roll)
277             // deceleration performance is better due to wheel brakes.
278             speed -= performance->decel * dt * 3;
279         } else {
280             speed -= performance->decel * dt;
281         }
282         if (no_roll) { // apply overshoot correction
283         if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
284         } else { 
285           if ( speed < tgt_speed ) speed = tgt_speed;
286         }
287     }
288     
289     
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;
295
296     // set new position
297     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
298     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt); 
299
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()); */
306
307     //if (!(finite(pos.lat()) && finite(pos.lon())))
308     //  {
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;
317     //  }
318
319     // adjust heading based on current bank angle
320     if (roll == 0.0)
321         roll = 0.01;
322
323     if (roll != 0.0) {
324         // double turnConstant;
325         //if (no_roll)
326         //  turnConstant = 0.0088362;
327         //else
328         //  turnConstant = 0.088362;
329         // If on ground, calculate heading change directly
330         if (no_roll) {
331             double headingDiff = fabs(hdg-tgt_heading);
332
333             if (headingDiff > 180)
334                 headingDiff = fabs(headingDiff - 360);
335
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
339
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
343                 // forever turning
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
352                 //         << endl;
353                 //}
354                 if (headingChangeRate > 30)
355                     headingChangeRate = 30;
356                 else if (headingChangeRate < -30)
357                     headingChangeRate = -30;
358
359             } else {
360                 if (fabs(headingChangeRate) > headingDiff)
361                     headingChangeRate = headingDiff*sign(roll);
362                 else
363                     headingChangeRate += dt * sign(roll);
364             }
365             hdg += headingChangeRate * dt;
366             //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
367             //     << ". Target speed: " << groundTargetSpeed << ". heading change rate"
368             //     << headingChangeRate << endl;
369
370         } else {
371             if (fabs(speed) > 1.0) {
372                 turn_radius_ft = 0.088362 * speed * speed
373                         / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
374             } else {
375                 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
376             }
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);
381         }
382         while ( hdg > 360.0 ) {
383             hdg -= 360.0;
384             spinCounter++;
385         }
386         while ( hdg < 0.0) {
387             hdg += 360.0;
388             spinCounter--;
389         }
390     }
391
392
393     // adjust target bank angle if heading lock engaged
394     if (hdg_lock) {
395         double bank_sense = 0.0;
396         double diff = fabs(hdg - tgt_heading);
397         if (diff > 180)
398             diff = fabs(diff - 360);
399
400         double sum = hdg + diff;
401         if (sum > 360.0)
402             sum -= 360.0;
403         if (fabs(sum - tgt_heading) < 1.0) {
404             bank_sense = 1.0;   // right turn
405         } else {
406             bank_sense = -1.0;  // left turn
407         }
408         if (diff < 30) {
409             tgt_roll = diff * bank_sense;
410         } else {
411             tgt_roll = 30.0 * bank_sense;
412         }
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;
429             //}
430         }
431     }
432
433     // adjust bank angle, use 9 degrees per second
434     double bank_diff = tgt_roll - roll;
435     if (fabs(bank_diff) > 0.2) {
436         if (bank_diff > 0.0)
437             roll += 9.0 * dt;
438
439         if (bank_diff < 0.0)
440             roll -= 9.0 * dt;
441         //while (roll > 180) roll -= 360;
442         //while (roll < 180) roll += 360;
443     }
444
445     // adjust altitude (meters) based on current vertical speed (fpm)
446     altitude_ft += vs / 60.0 * dt;
447     pos.setElevationFt(altitude_ft);  
448
449     // adjust target Altitude, based on ground elevation when on ground
450     if (no_roll) {
451         getGroundElev(dt);
452         doGroundAltitude();
453     } else {
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;
460             } else {
461                 tgt_vs = tgt_altitude_ft - altitude_ft;
462                 if (tgt_vs  < (-performance->descent_rate))
463                     tgt_vs = -performance->descent_rate;
464             }
465         }
466
467         if (alt_lock && !use_perf_vs) {
468             double max_vs = 4*(tgt_altitude_ft - altitude_ft);
469             double min_vs = 100;
470             if (tgt_altitude_ft < altitude_ft)
471                 min_vs = -100.0;
472             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
473                     && (fabs(max_vs) < fabs(tgt_vs)))
474                 tgt_vs = max_vs;
475
476             if (fabs(tgt_vs) < fabs(min_vs))
477                 tgt_vs = min_vs;
478         }
479     }
480     // adjust vertical speed
481     double vs_diff = tgt_vs - vs;
482     if (fabs(vs_diff) > 10.0) {
483         if (vs_diff > 0.0) {
484             vs += (performance->climb_rate / 3.0) * dt;
485
486             if (vs > tgt_vs)
487                 vs = tgt_vs;
488         } else {
489             vs -= (performance->descent_rate / 3.0) * dt;
490
491            if (vs < tgt_vs)
492                vs = tgt_vs;
493         }
494     }
495
496     // match pitch angle to vertical speed
497     if (vs > 0) {
498         pitch = vs * 0.005;
499     } else {
500         pitch = vs * 0.002;
501     }
502
503     //###########################//
504     // do calculations for radar //
505     //###########################//
506     double range_ft2 = UpdateRadar(manager);
507
508     //************************************//
509     // Tanker code                        //
510     //************************************//
511
512     if ( isTanker) {
513         if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
514                 && (elevation > 0.0) ) {
515             //refuel_node->setBoolValue(true);
516             contact = true;
517         } else {
518             //refuel_node->setBoolValue(false);
519             contact = false;
520         }
521     } else {
522         contact = false;
523     }
524 }
525
526
527 void FGAIAircraft::AccelTo(double speed) {
528     tgt_speed = speed;
529 }
530
531
532 void FGAIAircraft::PitchTo(double angle) {
533     tgt_pitch = angle;
534     alt_lock = false;
535 }
536
537
538 void FGAIAircraft::RollTo(double angle) {
539     tgt_roll = angle;
540     hdg_lock = false;
541 }
542
543
544 void FGAIAircraft::YawTo(double angle) {
545     tgt_yaw = angle;
546 }
547
548
549 void FGAIAircraft::ClimbTo(double alt_ft ) {
550     tgt_altitude_ft = alt_ft;
551     alt_lock = true;
552 }
553
554
555 void FGAIAircraft::TurnTo(double heading) {
556     tgt_heading = heading;
557     hdg_lock = true;
558 }
559
560
561 double FGAIAircraft::sign(double x) {
562     if ( x < 0.0 )
563         return -1.0;
564     else
565         return 1.0;
566 }
567
568
569 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
570     if (!flightplan.empty()) {
571         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
572         fp->setRepeat(repeat);
573         SetFlightPlan(fp);
574     }
575 }
576
577
578 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
579     delete fp;
580     fp = f;
581 }
582
583
584 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
585     bool eraseWaypoints;
586     if (trafficRef) {
587         eraseWaypoints = true;
588     } else
589         eraseWaypoints = false;
590
591  
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();
598     dt_count += dt;
599
600     ///////////////////////////////////////////////////////////////////////////
601     // Initialize the flightplan
602     //////////////////////////////////////////////////////////////////////////
603     if (!prev) {
604
605       spinCounter = 0;
606       tempReg = "";
607       fp->IncrementWaypoint(eraseWaypoints);
608       if (!(fp->getNextWaypoint()) && trafficRef)
609         loadNextLeg();
610       
611       prev = fp->getPreviousWaypoint(); //first waypoint
612       curr = fp->getCurrentWaypoint();  //second waypoint
613       next = fp->getNextWaypoint();     //third waypoint (might not exist!)
614       
615       setLatitude(prev->latitude);
616       setLongitude(prev->longitude);
617       setSpeed(prev->speed);
618       setAltitude(prev->altitude);
619       
620       if (prev->speed > 0.0)
621         setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
622       else
623         setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
624       
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
628       if (next)
629         fp->setLeadDistance(speed, hdg, curr, next);
630       
631       if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
632         use_perf_vs = false;
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;
637       } else {
638         use_perf_vs = true;
639         tgt_altitude_ft = prev->altitude;
640       }
641       alt_lock = hdg_lock = true;
642       no_roll = prev->on_ground;
643       if (no_roll) {
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
646         doGroundAltitude(); 
647       }
648       // Make sure to announce the aircraft's position 
649       announcePositionToController();
650       prevSpeed = 0;
651       return;
652     } // end of initialization
653     
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;
659       return;
660     } else {
661       dt_count = 0;
662     }
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);
665
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.
670
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;
674     }
675
676     //prev_dist_to_go = dist_to_go;
677
678     if ( dist_to_go < lead_dist ) {
679         if (curr->finished) {  //end of the flight plan
680             if (fp->getRepeat())
681                 fp->restart();
682             else
683                 setDie(true);
684             return;
685         }
686
687         if (next) {
688             tgt_heading = fp->getBearing(curr, next);
689             spinCounter = 0;
690         }
691
692         fp->IncrementWaypoint(eraseWaypoints);
693         if (!(fp->getNextWaypoint()) && trafficRef)
694             loadNextLeg();
695
696         prev = fp->getPreviousWaypoint();
697         curr = fp->getCurrentWaypoint();
698         next = fp->getNextWaypoint();
699
700         // Now that we have incremented the waypoints, excute some traffic manager specific code
701         if (trafficRef) {
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) {
709                 setDie(true);
710                 return;
711             }
712
713             FGAirport * dep = trafficRef->getDepartureAirport();
714             FGAirport * arr = trafficRef->getArrivalAirport();
715             if (!( dep && arr)) {
716                 setDie(true);
717                 return;
718             }
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
727               // delayed aircraft. 
728               time_t nextDeparture = trafficRef->getDepartureTime();
729               if (nextDeparture < (now+1200)) {
730                 nextDeparture = now + 1200; 
731               }
732               fp->setTime(trafficRef->getDepartureTime());
733             }
734             announcePositionToController();
735             
736         }
737
738         if (next) {
739             //cerr << "Current waypoint" << curr->name << endl;
740             //cerr << "Next waypoint" << next->name << endl;
741             fp->setLeadDistance(speed, tgt_heading, curr, next);
742         }
743
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;
749                 use_perf_vs = false;
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;
754             } else {
755                 //cerr << "5.1c" << endl;
756                 use_perf_vs = true;
757                 //cerr << "5.1d" << endl;
758                 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
759             }
760         }
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;
769
770     } else {
771         double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
772         //cerr << "Bearing = " << calc_bearing << endl;
773         if (speed < 0) {
774             calc_bearing +=180;
775             if (calc_bearing > 360)
776                 calc_bearing -= 360;
777         }
778
779         if (finite(calc_bearing)) {
780             double hdg_error = calc_bearing - tgt_heading;
781             if (fabs(hdg_error) > 1.0) {
782                 TurnTo( calc_bearing );
783             }
784
785         } else {
786             cerr << "calc_bearing is not a finite number : "
787                  << "Speed " << speed
788                  << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
789                  << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
790             cerr << "waypoint name " << curr->name;
791             exit(1);  // FIXME
792         }
793
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) {
798             prevSpeed = speed;
799             fp->setLeadDistance(speed, tgt_heading, curr, next);
800         }
801
802         //cerr << "Done Processing FlightPlan"<< endl;
803     }
804 }
805
806 void FGAIAircraft::initializeFlightPlan() 
807 {
808
809 }
810
811
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));
816 }
817
818
819 void FGAIAircraft::loadNextLeg() {
820     //delete fp;
821     //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
822
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);
832     int leg;
833     if ((leg = fp->getLeg())  == 10) {
834         trafficRef->next();
835         leg = 1;
836         fp->setLeg(leg);
837         //cerr << "Resetting leg : " << leg << endl;
838     }
839     //leg++;
840     //fp->setLeg(leg);
841     //cerr << "Creating leg number : " << leg << endl;
842     FGAirport *dep = trafficRef->getDepartureAirport();
843     FGAirport *arr = trafficRef->getArrivalAirport();
844     if (!(dep && arr)) {
845         setDie(true);
846         //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
847         //if (dep)
848         //  cerr << "Departure " << dep->getId() << endl;
849         //if (arr)
850         //  cerr << "Arrival   " << arr->getId() << endl;
851
852     } else {
853         double cruiseAlt = trafficRef->getCruiseAlt() * 100;
854         //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
855
856         fp->create (dep,
857                     arr,
858                     leg,
859                     cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
860                     trafficRef->getSpeed(),
861                     _getLatitude(),
862                     _getLongitude(),
863                     false,
864                     trafficRef->getRadius(),
865                     trafficRef->getFlightType(),
866                     acType,
867                     company);
868         //prev = fp->getPreviousWaypoint();
869         //curr = fp->getCurrentWaypoint();
870         //next = fp->getNextWaypoint();
871         //cerr << "25" << endl;
872         //if (next)
873         //        {
874         //  //cerr << "Next waypoint" << next->name << endl;
875         //          fp->setLeadDistance(speed, tgt_heading, curr, next);
876         //        }
877         //cerr << "25.1" << endl;
878         //if (curr->crossat > -1000.0) {
879         //        //cerr << "25.1a" << endl;
880         //        use_perf_vs = false;
881         //
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;
886         //} else {
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;
892         // }
893         //cerr << "26" << endl;
894         //tgt_speed = prev->speed;
895         //hdg_lock = alt_lock = true;
896         //no_roll = prev->on_ground;
897     }
898     //else
899     //{
900     //delete entity.fp;
901     //entity.fp = new FGAIFlightPlan(&entity,
902     //                                 999,  // A hack
903     //                                 trafficRef->getDepartureTime(),
904     //                                 trafficRef->getDepartureAirport(),
905     //                                 trafficRef->getArrivalAirport(),
906     //                                 false,
907     //                                 acType,
908     //                                 company);
909     //SetFlightPlan(entity.fp);
910 }
911
912
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.
917
918 void FGAIAircraft::getGroundElev(double dt) {
919     dt_elev_count += dt;
920
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))
924         return;
925     else
926        dt_elev_count = 0;
927
928     // Only do the proper hitlist stuff if we are within visible range of the viewer.
929     if (!invisible) {
930         double visibility_meters = fgGetDouble("/environment/visibility-m");
931
932         FGViewer* vw = globals->get_current_view();
933         double course, distance;
934
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);
940             return;
941         }
942
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 );
948         }
949
950         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
951         double alt;
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;
954
955         //cerr << "Target altitude : " << tgt_altitude_ft << endl;
956         // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
957         //                                            20000.0, alt))
958         //    tgt_altitude_ft = alt * SG_METER_TO_FEET;
959         //cerr << "Target altitude : " << tgt_altitude_ft << endl;
960     }
961 }
962
963
964 void FGAIAircraft::setCallSign(const string& s) {
965     callsign = s;
966 }
967
968
969 void FGAIAircraft::setTACANChannelID(const string& id) {
970     TACAN_channel_id = id;
971 }
972
973
974 void FGAIAircraft::doGroundAltitude() {
975    if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
976        altitude_ft = (tgt_altitude_ft + groundOffset);
977    else
978       altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
979 }
980
981
982 void FGAIAircraft::announcePositionToController() 
983 {
984   if (trafficRef) {
985     //FGTaxiRoute *taxiRoute = fp->getTaxiRoute();
986     
987     int leg = fp->getLeg();
988     
989     //if (fp->getCurrentWaypoint()->routeIndex != 0) {
990       //char buffer[10];
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
994       //
995       switch (leg) {
996       case 3: // Taxiing to runway
997         if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
998           controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
999         break;
1000       case 4: //Take off tower controller
1001         if (trafficRef->getDepartureAirport()->getDynamics())
1002           {
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;
1009                 //}
1010               
1011           } 
1012         else {
1013           cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
1014         }
1015         break;
1016       case 9: // Taxiing for parking
1017         if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
1018           controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
1019         break;
1020       default: 
1021         controller = 0;
1022         break;
1023       }
1024       
1025     if ((controller != prevController) && (prevController != 0)) {
1026       prevController->signOff(getID());
1027       string callsign =  trafficRef->getCallSign();
1028       if ( trafficRef->getHeavy())
1029         callsign += "Heavy";
1030       switch (leg) {
1031       case 3:
1032         cerr << callsign << " ready to taxi to runway " << fp->getRunway() << endl;
1033         break;
1034       case 4:
1035         cerr << callsign << " at runway " << fp->getRunway() << "Ready for take-off. "
1036              << trafficRef->getFlightRules() << " to " << trafficRef->getArrivalAirport()->getId() 
1037              << "(" << trafficRef->getArrivalAirport()->getName() << ")."<< endl;
1038       }
1039     }
1040     prevController = controller;
1041     if (controller) {
1042       controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
1043                            _getLatitude(), _getLongitude(), hdg, speed, altitude_ft, 
1044                                    trafficRef->getRadius(), leg);
1045     }
1046   }
1047 }
1048
1049
1050 void FGAIAircraft::processATC(FGATCInstruction instruction)
1051 {
1052   //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
1053   if (instruction.getHoldPattern   ()) {
1054   }
1055   
1056   // Hold Position
1057   if (instruction.getHoldPosition  ()) {
1058     if (!holdPos) {
1059       if (trafficRef)
1060         cerr << trafficRef->getCallSign() << "Holding Position " << endl;
1061       holdPos = true;
1062     }
1063     AccelTo(0.25);
1064   } else {
1065     if (holdPos) {
1066       if (trafficRef)
1067         cerr << trafficRef->getCallSign() << " Resuming Taxi " << endl;
1068       holdPos = false;
1069     }    
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());
1074     }else {
1075       if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
1076     }
1077   }
1078   if (instruction.getChangeHeading ()) { 
1079     hdg_lock = false;
1080     TurnTo(instruction.getHeading());
1081   } else {
1082     if (fp) {hdg_lock = true;}
1083   }
1084   if (instruction.getChangeAltitude()) { 
1085   }
1086
1087 }