]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
0b23e2c061458ce169a17973db43a13de997e59c
[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/route/waypoint.hxx>
26 #include <Main/fg_props.hxx>
27 #include <Main/globals.hxx>
28 #include <Main/viewer.hxx>
29 #include <Scenery/scenery.hxx>
30 #include <Scenery/tilemgr.hxx>
31 #include <Airports/dynamics.hxx>
32 #include <Airports/simple.hxx>
33
34 #include <string>
35 #include <math.h>
36 #include <time.h>
37
38 #ifdef _MSC_VER
39 #  include <float.h>
40 #  define finite _finite
41 #elif defined(__sun) || defined(sgi)
42 #  include <ieeefp.h>
43 #endif
44
45 using std::string;
46
47 #include "AIAircraft.hxx"
48 #include "performancedata.hxx"
49 #include "performancedb.hxx"
50 #include <signal.h>
51
52 //#include <Airports/trafficcontroller.hxx>
53
54 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
55      /* HOT must be disabled for AI Aircraft,
56       * otherwise traffic detection isn't working as expected.*/
57      FGAIBase(otAircraft, false) 
58 {
59     trafficRef = ref;
60     if (trafficRef) {
61         groundOffset = trafficRef->getGroundOffset();
62         setCallSign(trafficRef->getCallSign());
63     }
64     else
65         groundOffset = 0;
66
67     fp              = 0;
68     controller      = 0;
69     prevController  = 0;
70     towerController = 0;
71     dt_count = 0;
72     dt_elev_count = 0;
73     use_perf_vs = true;
74
75     no_roll = false;
76     tgt_speed = 0;
77     speed = 0;
78     groundTargetSpeed = 0;
79
80     // set heading and altitude locks
81     hdg_lock = false;
82     alt_lock = false;
83     roll = 0;
84     headingChangeRate = 0.0;
85     headingError = 0;
86     minBearing = 360;
87     speedFraction =1.0;
88
89     holdPos = false;
90     needsTaxiClearance = false;
91     _needsGroundElevation = true;
92
93     _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
94     dt = 0;
95     takeOffStatus = 0;
96 }
97
98
99 FGAIAircraft::~FGAIAircraft() {
100     //delete fp;
101     if (controller)
102         controller->signOff(getID());
103 }
104
105
106 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
107     if (!scFileNode)
108         return;
109
110     FGAIBase::readFromScenario(scFileNode);
111
112     setPerformance(scFileNode->getStringValue("class", "jet_transport"));
113     setFlightPlan(scFileNode->getStringValue("flightplan"),
114                   scFileNode->getBoolValue("repeat", false));
115     setCallSign(scFileNode->getStringValue("callsign"));
116 }
117
118
119 void FGAIAircraft::bind() {
120     FGAIBase::bind();
121
122     props->tie("controls/gear/gear-down",
123                SGRawValueMethods<FGAIAircraft,bool>(*this,
124                                                     &FGAIAircraft::_getGearDown));
125     props->tie("transponder-id",
126                SGRawValueMethods<FGAIAircraft,const char*>(*this,
127                                                     &FGAIAircraft::_getTransponderCode));
128 }
129
130
131 void FGAIAircraft::unbind() {
132     FGAIBase::unbind();
133
134     props->untie("controls/gear/gear-down");
135     props->untie("transponder-id");
136 }
137
138
139 void FGAIAircraft::update(double dt) {
140     FGAIBase::update(dt);
141     Run(dt);
142     Transform();
143 }
144
145 void FGAIAircraft::setPerformance(const std::string& acclass) {
146      static PerformanceDB perfdb; //TODO make it a global service
147      setPerformance(perfdb.getDataFor(acclass));
148   }
149
150
151  void FGAIAircraft::setPerformance(PerformanceData *ps) {
152      _performance = ps;
153   }
154
155
156  void FGAIAircraft::Run(double dt) {
157       FGAIAircraft::dt = dt;
158     
159      bool outOfSight = false, 
160         flightplanActive = true;
161      updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
162      if (outOfSight) {
163         return;
164      }
165
166      if (!flightplanActive) {
167         groundTargetSpeed = 0;
168      }
169
170      handleATCRequests(); // ATC also has a word to say
171      updateSecondaryTargetValues(); // target roll, vertical speed, pitch
172      updateActualState(); 
173     // We currently have one situation in which an AIAircraft object is used that is not attached to the 
174     // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
175     // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
176     // enough
177      if (manager)
178         UpdateRadar(manager);
179      checkVisibility();
180   }
181
182 void FGAIAircraft::checkVisibility() 
183 {
184   double visibility_meters = fgGetDouble("/environment/visibility-m");
185   FGViewer* vw = globals->get_current_view();
186   invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
187 }
188
189
190
191 void FGAIAircraft::AccelTo(double speed) {
192     tgt_speed = speed;
193     assertSpeed(speed);
194     if (!isStationary())
195         _needsGroundElevation = true;
196 }
197
198
199 void FGAIAircraft::PitchTo(double angle) {
200     tgt_pitch = angle;
201     alt_lock = false;
202 }
203
204
205 void FGAIAircraft::RollTo(double angle) {
206     tgt_roll = angle;
207     hdg_lock = false;
208 }
209
210
211 void FGAIAircraft::YawTo(double angle) {
212     tgt_yaw = angle;
213 }
214
215
216 void FGAIAircraft::ClimbTo(double alt_ft ) {
217     tgt_altitude_ft = alt_ft;
218     alt_lock = true;
219 }
220
221
222 void FGAIAircraft::TurnTo(double heading) {
223     tgt_heading = heading;
224     hdg_lock = true;
225 }
226
227
228 double FGAIAircraft::sign(double x) {
229     if (x == 0.0)
230         return x;
231     else
232         return x/fabs(x);
233 }
234
235
236 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
237     if (!flightplan.empty()) {
238         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
239         fp->setRepeat(repeat);
240         SetFlightPlan(fp);
241     }
242 }
243
244
245 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
246     delete fp;
247     fp = f;
248 }
249
250
251 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
252
253     // the one behind you
254     FGAIWaypoint* prev = 0;
255     // the one ahead
256     FGAIWaypoint* curr = 0;
257     // the next plus 1
258     FGAIWaypoint* next = 0;
259
260     prev = fp->getPreviousWaypoint();
261     curr = fp->getCurrentWaypoint();
262     next = fp->getNextWaypoint();
263
264     dt_count += dt;
265
266     ///////////////////////////////////////////////////////////////////////////
267     // Initialize the flightplan
268     //////////////////////////////////////////////////////////////////////////
269     if (!prev) {
270         handleFirstWaypoint();
271         return;
272     }                            // end of initialization
273     if (! fpExecutable(now))
274           return;
275     dt_count = 0;
276
277     double distanceToDescent;
278     if(reachedEndOfCruise(distanceToDescent)) {
279         if (!loadNextLeg(distanceToDescent)) {
280             setDie(true);
281             return;
282         }
283         prev = fp->getPreviousWaypoint();
284         curr = fp->getCurrentWaypoint();
285         next = fp->getNextWaypoint();
286     }
287     if (! leadPointReached(curr)) {
288         controlHeading(curr);
289         controlSpeed(curr, next);
290         
291             /*
292             if (speed < 0) { 
293                 cerr << getCallSign() 
294                      << ": verifying lead distance to waypoint : " 
295                      << fp->getCurrentWaypoint()->name << " "
296                      << fp->getLeadDistance() << ". Distance to go " 
297                      << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)) 
298                      << ". Target speed = " 
299                      << tgt_speed
300                      << ". Current speed = "
301                      << speed
302                      << ". Minimum Bearing " << minBearing
303                      << endl;
304             } */
305     } else {
306         if (curr->isFinished())      //end of the flight plan
307         {
308             if (fp->getRepeat())
309                 fp->restart();
310             else
311                 setDie(true);
312             return;
313         }
314
315         if (next) {
316             //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
317             tgt_heading = fp->getBearing(curr, next);
318             spinCounter = 0;
319         }
320
321         //TODO let the fp handle this (loading of next leg)
322         fp->IncrementWaypoint( trafficRef != 0 );
323         if  ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
324             if (!loadNextLeg()) {
325                 setDie(true);
326                 return;
327             }
328
329         prev = fp->getPreviousWaypoint();
330         curr = fp->getCurrentWaypoint();
331         next = fp->getNextWaypoint();
332
333         // Now that we have incremented the waypoints, excute some traffic manager specific code
334         if (trafficRef) {
335             //TODO isn't this best executed right at the beginning?
336             if (! aiTrafficVisible()) {
337                 setDie(true);
338                 return;
339             }
340
341             if (! handleAirportEndPoints(prev, now)) {
342                 setDie(true);
343                 return;
344             }
345
346             announcePositionToController();
347
348         }
349
350         if (next) {
351             fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
352         }
353
354
355         if (!(prev->getOn_ground()))  // only update the tgt altitude from flightplan if not on the ground
356         {
357             tgt_altitude_ft = prev->getAltitude();
358             if (curr->getCrossat() > -1000.0) {
359                 use_perf_vs = false;
360                 // Distance to go in meters
361                 double vert_dist_ft = curr->getCrossat() - altitude_ft;
362                 double err_dist     = prev->getCrossat() - altitude_ft;
363                 double dist_m       = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
364                 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
365                 
366                 checkTcas();
367                 tgt_altitude_ft = curr->getCrossat();
368             } else {
369                 use_perf_vs = true;
370             }
371         }
372         AccelTo(prev->getSpeed());
373         hdg_lock = alt_lock = true;
374         no_roll = prev->getOn_ground();
375     }
376 }
377
378 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
379 {
380     // err is negative when we passed too high
381     double vert_m = vert_ft * SG_FEET_TO_METER;
382     double err_m  = err     * SG_FEET_TO_METER;
383     //double angle = atan2(vert_m, dist_m);
384     double speedMs = (speed * SG_NM_TO_METER) / 3600;
385     //double vs = cos(angle) * speedMs; // Now in m/s
386     double vs = 0;
387     //cerr << "Error term = " << err_m << endl;
388     if (dist_m) {
389         vs = ((vert_m) / dist_m) * speedMs;
390     }
391     // Convert to feet per minute
392     vs *= (SG_METER_TO_FEET * 60);
393     //if (getCallSign() == "LUFTHANSA2002")
394     //if (fabs(vs) > 100000) {
395 //     if (getCallSign() == "LUFTHANSA2057") {
396 //         cerr << getCallSign() << " " << fp->getPreviousWaypoint()->getName() << ". Alt = " << altitude_ft <<  " vertical dist = " << vert_m << " horiz dist = " << dist_m << " << angle  = " << angle * SG_RADIANS_TO_DEGREES << " vs " << vs << " horizontal speed " << speed << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat() << endl;
397 //     //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
398 //     //                     / 6076.0 / speed*60.0);
399 //         //raise(SIGSEGV);
400 //     }
401     return vs;
402 }
403
404 void FGAIAircraft::assertSpeed(double speed)
405 {
406     if ((speed < -50) || (speed > 1000)) {
407         cerr << getCallSign() << " " 
408             << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
409             << "Departure airport " << trafficRef->getDepartureAirport() << " "
410             << "Leg " << fp->getLeg() <<  " "
411             << "target_speed << " << tgt_speed <<  " "
412             << "speedFraction << " << speedFraction << " "
413             << "Currecnt speed << " << speed << " "
414             << endl;
415        raise(SIGSEGV);
416     }
417 }
418
419
420
421 void FGAIAircraft::checkTcas(void)
422 {
423     if (props->getIntValue("tcas/threat-level",0)==3)
424     {
425         int RASense = props->getIntValue("tcas/ra-sense",0);
426         if ((RASense>0)&&(tgt_vs<4000))
427             // upward RA: climb!
428             tgt_vs = 4000;
429         else
430         if (RASense<0)
431         {
432             // downward RA: descend!
433             if (altitude_ft < 1000)
434             {
435                 // too low: level off
436                 if (tgt_vs>0)
437                     tgt_vs = 0;
438             }
439             else
440             {
441                 if (tgt_vs >- 4000)
442                     tgt_vs = -4000;
443             }
444         }
445     }
446 }
447
448 void FGAIAircraft::initializeFlightPlan() {
449 }
450
451
452 bool FGAIAircraft::_getGearDown() const {
453     return _performance->gearExtensible(this);
454 }
455
456
457 const char * FGAIAircraft::_getTransponderCode() const {
458   return transponderCode.c_str();
459 }
460
461 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
462 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint. 
463
464 bool FGAIAircraft::loadNextLeg(double distance) {
465
466     int leg;
467     if ((leg = fp->getLeg())  == 9) {
468         if (!trafficRef->next()) {
469             return false;
470         }
471         setCallSign(trafficRef->getCallSign());
472         leg = 0;
473         fp->setLeg(leg);
474     }
475
476     FGAirport *dep = trafficRef->getDepartureAirport();
477     FGAirport *arr = trafficRef->getArrivalAirport();
478     if (!(dep && arr)) {
479         setDie(true);
480
481     } else {
482         double cruiseAlt = trafficRef->getCruiseAlt() * 100;
483
484         fp->create (this,
485                     dep,
486                     arr,
487                     leg+1,
488                     cruiseAlt,
489                     trafficRef->getSpeed(),
490                     _getLatitude(),
491                     _getLongitude(),
492                     false,
493                     trafficRef->getRadius(),
494                     trafficRef->getFlightType(),
495                     acType,
496                     company,
497                     distance);
498        //cerr << "created  leg " << leg << " for " << trafficRef->getCallSign() << endl;
499     }
500     return true;
501 }
502
503
504 // Note: This code is copied from David Luff's AILocalTraffic
505 // Warning - ground elev determination is CPU intensive
506 // Either this function or the logic of how often it is called
507 // will almost certainly change.
508
509 void FGAIAircraft::getGroundElev(double dt) {
510     dt_elev_count += dt;
511
512     if (!needGroundElevation())
513         return;
514     // Update minimally every three secs, but add some randomness
515     // to prevent all AI objects doing this in synchrony
516     if (dt_elev_count < (3.0) + (rand() % 10))
517         return;
518
519     dt_elev_count = 0;
520
521     // Only do the proper hitlist stuff if we are within visible range of the viewer.
522     if (!invisible) {
523         double visibility_meters = fgGetDouble("/environment/visibility-m");
524         FGViewer* vw = globals->get_current_view();
525         
526         if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
527             return;
528         }
529
530         double range = 500.0;
531         if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
532         {
533             double alt;
534             if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
535             {
536                 tgt_altitude_ft = alt * SG_METER_TO_FEET;
537                 if (isStationary())
538                 {
539                     // aircraft is stationary and we obtained altitude for this spot - we're done.
540                     _needsGroundElevation = false;
541                 }
542             }
543         }
544     }
545 }
546
547
548 void FGAIAircraft::doGroundAltitude() {
549     if ((fp->getLeg() == 7) && ((altitude_ft -  tgt_altitude_ft) > 5)) {
550         tgt_vs = -500;
551     } else {
552         if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
553             (isStationary()))
554             altitude_ft = (tgt_altitude_ft + groundOffset);
555         else
556             altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
557         tgt_vs = 0;
558     }
559 }
560
561
562 void FGAIAircraft::announcePositionToController() {
563     if (trafficRef) {
564         int leg = fp->getLeg();
565
566         // Note that leg has been incremented after creating the current leg, so we should use
567         // leg numbers here that are one higher than the number that is used to create the leg
568         // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening. 
569         // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
570         // the original leg numbers here!
571         switch (leg) {
572           case 1:              // Startup and Push back
573             if (trafficRef->getDepartureAirport()->getDynamics())
574                 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
575             break;
576         case 2:              // Taxiing to runway
577             if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
578                 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
579             break;
580         case 3:              //Take off tower controller
581             if (trafficRef->getDepartureAirport()->getDynamics()) {
582                 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
583                 towerController = 0;
584             } else {
585                 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
586             }
587             break;
588         case 6:
589              if (trafficRef->getDepartureAirport()->getDynamics()) {
590                  controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
591               }
592               break;
593         case 8:              // Taxiing for parking
594             if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
595                 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
596             break;
597         default:
598             controller = 0;
599             break;
600         }
601
602         if ((controller != prevController) && (prevController != 0)) {
603             prevController->signOff(getID());
604         }
605         prevController = controller;
606         if (controller) {
607             controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
608                                          _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
609                                          trafficRef->getRadius(), leg, this);
610         }
611     }
612 }
613
614 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
615     if (!takeOffStatus) {
616         int leg = fp->getLeg();
617         if (trafficRef) {
618             if (trafficRef->getDepartureAirport()->getDynamics()) {
619                 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
620             } else {
621                 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
622             }
623             if (towerController) {
624                 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
625                                                    _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
626                                                     trafficRef->getRadius(), leg, this);
627                 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
628             }
629         }
630     }
631     takeOffStatus = state;
632 }
633
634 // Process ATC instructions and report back
635
636 void FGAIAircraft::processATC(FGATCInstruction instruction) {
637     if (instruction.getCheckForCircularWait()) {
638         // This is not exactly an elegant solution, 
639         // but at least it gives me a chance to check
640         // if circular waits are resolved.
641         // For now, just take the offending aircraft 
642         // out of the scene
643         setDie(true);
644         // a more proper way should be - of course - to
645         // let an offending aircraft take an evasive action
646         // for instance taxi back a little bit.
647     }
648     //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
649     if (instruction.getHoldPattern   ()) {}
650
651     // Hold Position
652     if (instruction.getHoldPosition  ()) {
653         if (!holdPos) {
654             holdPos = true;
655         }
656         AccelTo(0.0);
657     } else {
658         if (holdPos) {
659             //if (trafficRef)
660             //  cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
661             holdPos = false;
662         }
663         // Change speed Instruction. This can only be excecuted when there is no
664         // Hold position instruction.
665         if (instruction.getChangeSpeed   ()) {
666             //  if (trafficRef)
667             //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
668             AccelTo(instruction.getSpeed());
669         } else {
670             if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
671         }
672     }
673     if (instruction.getChangeHeading ()) {
674         hdg_lock = false;
675         TurnTo(instruction.getHeading());
676     } else {
677         if (fp) {
678             hdg_lock = true;
679         }
680     }
681     if (instruction.getChangeAltitude()) {}
682
683 }
684
685
686 void FGAIAircraft::handleFirstWaypoint() {
687     bool eraseWaypoints;         //TODO YAGNI
688     headingError = 0;
689     if (trafficRef) {
690         eraseWaypoints = true;
691     } else {
692         eraseWaypoints = false;
693     }
694
695     FGAIWaypoint* prev = 0; // the one behind you
696     FGAIWaypoint* curr = 0; // the one ahead
697     FGAIWaypoint* next = 0;// the next plus 1
698
699     spinCounter = 0;
700
701     //TODO fp should handle this
702     fp->IncrementWaypoint(eraseWaypoints);
703     if (!(fp->getNextWaypoint()) && trafficRef)
704         if (!loadNextLeg()) {
705             setDie(true);
706             return;
707         }
708
709     prev = fp->getPreviousWaypoint();   //first waypoint
710     curr = fp->getCurrentWaypoint();    //second waypoint
711     next = fp->getNextWaypoint();       //third waypoint (might not exist!)
712
713     setLatitude(prev->getLatitude());
714     setLongitude(prev->getLongitude());
715     setSpeed(prev->getSpeed());
716     setAltitude(prev->getAltitude());
717
718     if (prev->getSpeed() > 0.0)
719         setHeading(fp->getBearing(prev->getLatitude(), prev->getLongitude(), curr));
720     else
721         setHeading(fp->getBearing(curr->getLatitude(), curr->getLongitude(), prev));
722
723     // If next doesn't exist, as in incrementally created flightplans for
724     // AI/Trafficmanager created plans,
725     // Make sure lead distance is initialized otherwise
726     if (next)
727         fp->setLeadDistance(speed, hdg, curr, next);
728
729     if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
730     {
731         use_perf_vs = false;
732         //tgt_vs = (curr->getCrossat() - prev->getAltitude())
733         //         / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
734         //            / 6076.0 / prev->getSpeed()*60.0);
735         double vert_dist_ft = curr->getCrossat() - altitude_ft;
736         double err_dist     = prev->getCrossat() - altitude_ft;
737         double dist_m       = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
738         tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
739         checkTcas();
740         tgt_altitude_ft = curr->getCrossat();
741     } else {
742         use_perf_vs = true;
743         tgt_altitude_ft = prev->getAltitude();
744     }
745     alt_lock = hdg_lock = true;
746     no_roll = prev->getOn_ground();
747     if (no_roll) {
748         Transform();             // make sure aip is initialized.
749         getGroundElev(60.1);     // make sure it's executed first time around, so force a large dt value
750         doGroundAltitude();
751         _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
752     }
753     // Make sure to announce the aircraft's position
754     announcePositionToController();
755     prevSpeed = 0;
756 }
757
758
759 /**
760  * Check Execution time (currently once every 100 ms)
761  * Add a bit of randomization to prevent the execution of all flight plans
762  * in synchrony, which can add significant periodic framerate flutter.
763  *
764  * @param now
765  * @return
766  */
767 bool FGAIAircraft::fpExecutable(time_t now) {
768     double rand_exec_time = (rand() % 100) / 100;
769     return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
770 }
771
772
773 /**
774  * Check to see if we've reached the lead point for our next turn
775  *
776  * @param curr
777  * @return
778  */
779 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
780     double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
781
782     //cerr << "2" << endl;
783     double lead_dist = fp->getLeadDistance();
784     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
785     if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
786           tgt_speed = -(dist_to_go / 10.0);
787           if (tgt_speed > -0.5) {
788                 tgt_speed = -0.5;
789           }
790           assertSpeed(tgt_speed);
791           if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
792               fp->getPreviousWaypoint()->setSpeed(tgt_speed);
793           }
794     }
795     if (lead_dist < fabs(2*speed)) {
796       //don't skip over the waypoint
797       lead_dist = fabs(2*speed);
798       //cerr << "Extending lead distance to " << lead_dist << endl;
799     }
800
801     //prev_dist_to_go = dist_to_go;
802     //if (dist_to_go < lead_dist)
803     //     cerr << trafficRef->getCallSign() << " Distance : " 
804     //          << dist_to_go << ": Lead distance " 
805     //          << lead_dist << " " << curr->name 
806     //          << " Ground target speed " << groundTargetSpeed << endl;
807     double bearing = 0;
808      // don't do bearing calculations for ground traffic
809        bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
810        if (bearing < minBearing) {
811             minBearing = bearing;
812             if (minBearing < 10) {
813                  minBearing = 10;
814             }
815             if ((minBearing < 360.0) && (minBearing > 10.0)) {
816                 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
817             } else {
818                 speedFraction = 1.0;
819             }
820        } 
821     if (trafficRef) {
822          //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
823 /*         if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
824               cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " " 
825                    << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl; 
826          }*/
827      }
828     if ((dist_to_go < lead_dist) ||
829         ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
830         minBearing = 360;
831         speedFraction = 1.0;
832         prev_dist_to_go = HUGE_VAL;
833         return true;
834     } else {
835         prev_dist_to_go = dist_to_go;
836         return false;
837     }
838 }
839
840
841 bool FGAIAircraft::aiTrafficVisible() {
842   SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"), 
843     fgGetDouble("/position/latitude-deg")));
844   
845   return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
846 }
847
848
849 /**
850  * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
851  * in the case of an arrival.
852  *
853  * @param prev
854  * @return
855  */
856
857 //TODO the trafficRef is the right place for the method
858 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
859     // prepare routing from one airport to another
860     FGAirport * dep = trafficRef->getDepartureAirport();
861     FGAirport * arr = trafficRef->getArrivalAirport();
862
863     if (!( dep && arr))
864         return false;
865
866     // This waypoint marks the fact that the aircraft has passed the initial taxi
867     // departure waypoint, so it can release the parking.
868     //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
869     //cerr << "Passing waypoint : " << prev->getName() << endl;
870     if (prev->contains("PushBackPoint")) {
871         dep->getDynamics()->releaseParking(fp->getGate());
872         AccelTo(0.0);
873         //setTaxiClearanceRequest(true);
874     }
875     if (prev->contains("legend")) {
876         fp->incrementLeg();
877     }
878     if (prev->contains(string("DepartureHold"))) {
879         //cerr << "Passing point DepartureHold" << endl;
880         scheduleForATCTowerDepartureControl(1);
881     }
882     if (prev->contains(string("Accel"))) {
883         takeOffStatus = 3;
884     }
885     //if (prev->contains(string("landing"))) {
886     //    if (speed < _performance->vTaxi() * 2) {
887     //        fp->shortenToFirst(2, "legend");
888     //    }
889     //}
890     /*if (prev->contains(string("final"))) {
891         
892          cerr << getCallSign() << " " 
893             << fp->getPreviousWaypoint()->getName() 
894             << ". Alt = " << altitude_ft 
895             << " vs " << vs 
896             << " horizontal speed " << speed 
897             << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
898             << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation() 
899             << "Altitude difference " << (altitude_ft -  fp->getPreviousWaypoint()->getCrossat()) << endl;
900     }*/
901     // This is the last taxi waypoint, and marks the the end of the flight plan
902     // so, the schedule should update and wait for the next departure time.
903     if (prev->contains("END")) {
904         time_t nextDeparture = trafficRef->getDepartureTime();
905         // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
906         if (nextDeparture < (now+1200)) {
907             nextDeparture = now + 1200;
908         }
909         fp->setTime(nextDeparture);
910     }
911
912     return true;
913 }
914
915
916 /**
917  * Check difference between target bearing and current heading and correct if necessary.
918  *
919  * @param curr
920  */
921 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
922     double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
923     //cerr << "Bearing = " << calc_bearing << endl;
924     if (speed < 0) {
925         calc_bearing +=180;
926         if (calc_bearing > 360)
927             calc_bearing -= 360;
928     }
929
930     if (finite(calc_bearing)) {
931         double hdg_error = calc_bearing - tgt_heading;
932         if (fabs(hdg_error) > 0.01) {
933             TurnTo( calc_bearing );
934         }
935
936     } else {
937         cerr << "calc_bearing is not a finite number : "
938         << "Speed " << speed
939         << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
940         << "waypoint " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
941         cerr << "waypoint name " << curr->getName();
942         exit(1);                 // FIXME
943     }
944 }
945
946
947 /**
948  * Update the lead distance calculation if speed has changed sufficiently
949  * to prevent spinning (hopefully);
950  *
951  * @param curr
952  * @param next
953  */
954 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
955     double speed_diff = speed - prevSpeed;
956
957     if (fabs(speed_diff) > 10) {
958         prevSpeed = speed;
959         assertSpeed(speed);
960         if (next) {
961             fp->setLeadDistance(speed, tgt_heading, curr, next);
962         }
963     }
964 }
965
966
967 /**
968  * Update target values (heading, alt, speed) depending on flight plan or control properties
969  */
970 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
971     if (fp)                      // AI object has a flightplan
972     {
973         //TODO make this a function of AIBase
974         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
975         //cerr << "UpateTArgetValues() " << endl;
976         ProcessFlightPlan(dt, now);
977
978         // Do execute Ground elev for inactive aircraft, so they
979         // Are repositioned to the correct ground altitude when the user flies within visibility range.
980         // In addition, check whether we are out of user range, so this aircraft
981         // can be deleted.
982         if (onGround()) {
983                 Transform();     // make sure aip is initialized.
984                 getGroundElev(dt);
985                 doGroundAltitude();
986                 // Transform();
987                 pos.setElevationFt(altitude_ft);
988         }
989         if (trafficRef) {
990            //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
991             aiOutOfSight = !aiTrafficVisible();
992             if (aiOutOfSight) {
993                 setDie(true);
994                 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
995                 aiOutOfSight = true;
996                 return;
997             }
998         }
999         timeElapsed = now - fp->getStartTime();
1000         flightplanActive = fp->isActive(now);
1001     } else {
1002         // no flight plan, update target heading, speed, and altitude
1003         // from control properties.  These default to the initial
1004         // settings in the config file, but can be changed "on the
1005         // fly".
1006         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
1007         if ( lat_mode == "roll" ) {
1008             double angle
1009             = props->getDoubleValue("controls/flight/target-roll" );
1010             RollTo( angle );
1011         } else {
1012             double angle
1013             = props->getDoubleValue("controls/flight/target-hdg" );
1014             TurnTo( angle );
1015         }
1016
1017         string lon_mode
1018         = props->getStringValue("controls/flight/longitude-mode");
1019         if ( lon_mode == "alt" ) {
1020             double alt = props->getDoubleValue("controls/flight/target-alt" );
1021             ClimbTo( alt );
1022         } else {
1023             double angle
1024             = props->getDoubleValue("controls/flight/target-pitch" );
1025             PitchTo( angle );
1026         }
1027
1028         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1029     }
1030 }
1031
1032 void FGAIAircraft::updatePosition() {
1033     // convert speed to degrees per second
1034     double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
1035                                  * speed * 1.686 / ft_per_deg_lat;
1036     double speed_east_deg_sec  = sin( hdg * SGD_DEGREES_TO_RADIANS )
1037                                  * speed * 1.686 / ft_per_deg_lon;
1038
1039     // set new position
1040     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
1041     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
1042 }
1043
1044
1045 void FGAIAircraft::updateHeading() {
1046     // adjust heading based on current bank angle
1047     if (roll == 0.0)
1048         roll = 0.01;
1049
1050     if (roll != 0.0) {
1051         // double turnConstant;
1052         //if (no_roll)
1053         //  turnConstant = 0.0088362;
1054         //else
1055         //  turnConstant = 0.088362;
1056         // If on ground, calculate heading change directly
1057         if (onGround()) {
1058             double headingDiff = fabs(hdg-tgt_heading);
1059             double bank_sense = 0.0;
1060         /*
1061         double diff = fabs(hdg - tgt_heading);
1062         if (diff > 180)
1063             diff = fabs(diff - 360);
1064
1065         double sum = hdg + diff;
1066         if (sum > 360.0)
1067             sum -= 360.0;
1068         if (fabs(sum - tgt_heading) < 1.0) {
1069             bank_sense = 1.0;    // right turn
1070         } else {
1071             bank_sense = -1.0;   // left turn
1072         }*/
1073             if (headingDiff > 180)
1074                 headingDiff = fabs(headingDiff - 360);
1075             double sum = hdg + headingDiff;
1076             if (sum > 360.0) 
1077                 sum -= 360.0;
1078             if (fabs(sum - tgt_heading) > 0.0001) {
1079                 bank_sense = -1.0;
1080             } else {
1081                 bank_sense = 1.0;
1082             }
1083             //if (trafficRef)
1084             //  cerr << trafficRef->getCallSign() << " Heading " 
1085             //         << hdg << ". Target " << tgt_heading <<  ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1086             //if (headingDiff > 60) {
1087             groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1088             assertSpeed(groundTargetSpeed);
1089                 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1090             //} else {
1091             //    groundTargetSpeed = tgt_speed;
1092             //}
1093             if (sign(groundTargetSpeed) != sign(tgt_speed))
1094                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1095             assertSpeed(groundTargetSpeed);
1096             // Only update the target values when we're not moving because otherwise we might introduce an enormous target change rate while waiting a the gate, or holding.
1097             if (speed != 0) {
1098                 if (headingDiff > 30.0) {
1099                     // invert if pushed backward
1100                     headingChangeRate += 10.0 * dt * sign(roll);
1101
1102                     // Clamp the maximum steering rate to 30 degrees per second,
1103                     // But only do this when the heading error is decreasing.
1104                     if ((headingDiff < headingError)) {
1105                         if (headingChangeRate > 30)
1106                             headingChangeRate = 30;
1107                         else if (headingChangeRate < -30)
1108                             headingChangeRate = -30;
1109                     }
1110                 } else {
1111                     if (speed != 0) {
1112                         if (fabs(headingChangeRate) > headingDiff)
1113                             headingChangeRate = headingDiff*sign(roll);
1114                         else
1115                             headingChangeRate += dt * sign(roll);
1116                     }
1117                 }
1118             }
1119             if (trafficRef)
1120                 //cerr << trafficRef->getCallSign() << " Heading " 
1121                 //     << hdg << ". Target " << tgt_heading <<  ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1122             hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1123             headingError = headingDiff;
1124             if (fabs(headingError) < 1.0) {
1125                 hdg = tgt_heading;
1126             }
1127         } else {
1128             if (fabs(speed) > 1.0) {
1129                 turn_radius_ft = 0.088362 * speed * speed
1130                                  / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1131             } else {
1132                 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1133                 turn_radius_ft = 1.0;
1134             }
1135             double turn_circum_ft = SGD_2PI * turn_radius_ft;
1136             double dist_covered_ft = speed * 1.686 * dt;
1137             double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1138             hdg += alpha * sign(roll);
1139         }
1140         while ( hdg > 360.0 ) {
1141             hdg -= 360.0;
1142             spinCounter++;
1143         }
1144         while ( hdg < 0.0) {
1145             hdg += 360.0;
1146             spinCounter--;
1147         }
1148     }
1149 }
1150
1151
1152 void FGAIAircraft::updateBankAngleTarget() {
1153     // adjust target bank angle if heading lock engaged
1154     if (hdg_lock) {
1155         double bank_sense = 0.0;
1156         double diff = fabs(hdg - tgt_heading);
1157         if (diff > 180)
1158             diff = fabs(diff - 360);
1159
1160         double sum = hdg + diff;
1161         if (sum > 360.0)
1162             sum -= 360.0;
1163         if (fabs(sum - tgt_heading) < 1.0) {
1164             bank_sense = 1.0;    // right turn
1165         } else {
1166             bank_sense = -1.0;   // left turn
1167         }
1168         if (diff < _performance->maximumBankAngle()) {
1169             tgt_roll = diff * bank_sense;
1170         } else {
1171             tgt_roll = _performance->maximumBankAngle() * bank_sense;
1172         }
1173         if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1174             tgt_speed *= 0.999;  // Ugly hack: If aircraft get stuck, they will continually spin around.
1175             // The only way to resolve this is to make them slow down.
1176         }
1177     }
1178 }
1179
1180
1181 void FGAIAircraft::updateVerticalSpeedTarget() {
1182     // adjust target Altitude, based on ground elevation when on ground
1183     if (onGround()) {
1184         getGroundElev(dt);
1185         doGroundAltitude();
1186     } else if (alt_lock) {
1187         // find target vertical speed
1188         if (use_perf_vs) {
1189             if (altitude_ft < tgt_altitude_ft) {
1190                 tgt_vs = tgt_altitude_ft - altitude_ft;
1191                 if (tgt_vs > _performance->climbRate())
1192                     tgt_vs = _performance->climbRate();
1193             } else {
1194                 tgt_vs = tgt_altitude_ft - altitude_ft;
1195                 if (tgt_vs  < (-_performance->descentRate()))
1196                     tgt_vs = -_performance->descentRate();
1197             }
1198         } else {
1199             double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1200             double err_dist     = 0; //prev->getCrossat() - altitude_ft;
1201             double dist_m       = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1202             tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1203             //cerr << "Target vs before : " << tgt_vs;
1204 /*            double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1205             double min_vs = 100;
1206             if (tgt_altitude_ft < altitude_ft)
1207                 min_vs = -100.0;
1208             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1209                     && (fabs(max_vs) < fabs(tgt_vs)))
1210                 tgt_vs = max_vs;
1211
1212             if (fabs(tgt_vs) < fabs(min_vs))
1213                 tgt_vs = min_vs;*/
1214             //cerr << "target vs : after " << tgt_vs << endl;
1215         }
1216     } //else 
1217     //    tgt_vs = 0.0;
1218     checkTcas();
1219 }
1220
1221 void FGAIAircraft::updatePitchAngleTarget() {
1222     // if on ground and above vRotate -> initial rotation
1223     if (onGround() && (speed > _performance->vRotate()))
1224         tgt_pitch = 8.0; // some rough B737 value 
1225
1226     //TODO pitch angle on approach and landing
1227     
1228     // match pitch angle to vertical speed
1229     else if (tgt_vs > 0) {
1230         tgt_pitch = tgt_vs * 0.005;
1231     } else {
1232         tgt_pitch = tgt_vs * 0.002;
1233     }
1234 }
1235
1236 string FGAIAircraft::atGate() {
1237      string tmp("");
1238      if (fp->getLeg() < 3) {
1239          if (trafficRef) {
1240              if (fp->getGate() > 0) {
1241                  FGParking *park =
1242                      trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1243                  tmp = park->getName();
1244              }
1245          }
1246      }
1247      return tmp;
1248 }
1249
1250 void FGAIAircraft::handleATCRequests() {
1251     //TODO implement NullController for having no ATC to save the conditionals
1252     if (controller) {
1253         controller->updateAircraftInformation(getID(),
1254                                               pos.getLatitudeDeg(),
1255                                               pos.getLongitudeDeg(),
1256                                               hdg,
1257                                               speed,
1258                                               altitude_ft, dt);
1259         processATC(controller->getInstruction(getID()));
1260     }
1261     if (towerController) {
1262         towerController->updateAircraftInformation(getID(),
1263                                               pos.getLatitudeDeg(),
1264                                               pos.getLongitudeDeg(),
1265                                               hdg,
1266                                               speed,
1267                                               altitude_ft, dt);
1268     }
1269 }
1270
1271 void FGAIAircraft::updateActualState() {
1272     //update current state
1273     //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1274     updatePosition();
1275
1276     if (onGround())
1277         speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1278     else
1279         speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1280     assertSpeed(speed);
1281     updateHeading();
1282     roll = _performance->actualBankAngle(this, tgt_roll, dt);
1283
1284     // adjust altitude (meters) based on current vertical speed (fpm)
1285     altitude_ft += vs / 60.0 * dt;
1286     pos.setElevationFt(altitude_ft);
1287
1288     vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1289     pitch = _performance->actualPitch(this, tgt_pitch, dt);
1290 }
1291
1292 void FGAIAircraft::updateSecondaryTargetValues() {
1293     // derived target state values
1294     updateBankAngleTarget();
1295     updateVerticalSpeedTarget();
1296     updatePitchAngleTarget();
1297
1298     //TODO calculate wind correction angle (tgt_yaw)
1299 }
1300
1301
1302 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1303     FGAIWaypoint* curr = fp->getCurrentWaypoint();
1304     if (curr->getName() == string("BOD")) {
1305         double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1306         double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0;     // convert from kts to meter/s
1307         double descentRate  = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0;  // convert from feet/min to meter/s
1308
1309         double verticalDistance  = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1310         double descentTimeNeeded = verticalDistance / descentRate;
1311         double distanceCovered   = descentSpeed * descentTimeNeeded; 
1312
1313         //cerr << "Tracking  : " << fgGetString("/ai/track-callsign");
1314         if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1315             cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1316             cerr << "Descent rate      : " << descentRate << endl;
1317             cerr << "Descent speed     : " << descentSpeed << endl;
1318             cerr << "VerticalDistance  : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1319             cerr << "DecentTimeNeeded  : " << descentTimeNeeded << endl;
1320             cerr << "DistanceCovered   : " << distanceCovered   << endl;
1321         }
1322         //cerr << "Distance = " << distance << endl;
1323         distance = distanceCovered;
1324         if (dist < distanceCovered) {
1325               if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1326                    //exit(1);
1327               }
1328               return true;
1329         } else {
1330               return false;
1331         }
1332     } else {
1333          return false;
1334     }
1335 }
1336
1337 void FGAIAircraft::resetPositionFromFlightPlan()
1338 {
1339     // the one behind you
1340     FGAIWaypoint* prev = 0;
1341     // the one ahead
1342     FGAIWaypoint* curr = 0;
1343     // the next plus 1
1344     FGAIWaypoint* next = 0;
1345
1346     prev = fp->getPreviousWaypoint();
1347     curr = fp->getCurrentWaypoint();
1348     next = fp->getNextWaypoint();
1349
1350     setLatitude(prev->getLatitude());
1351     setLongitude(prev->getLongitude());
1352     double tgt_heading = fp->getBearing(curr, next);
1353     setHeading(tgt_heading);
1354     setAltitude(prev->getAltitude());
1355     setSpeed(prev->getSpeed());
1356 }
1357
1358 double FGAIAircraft::getBearing(double crse) 
1359 {
1360   double hdgDiff = fabs(hdg-crse);
1361   if (hdgDiff > 180)
1362       hdgDiff = fabs(hdgDiff - 360);
1363   return hdgDiff;
1364 }
1365
1366 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1367      FGAIWaypoint* curr = 0;
1368      curr = fp->getCurrentWaypoint();
1369
1370      double tracklength = fp->checkTrackLength(wptName);
1371      if (tracklength > 0.1) {
1372           tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1373      } else {
1374          return 0;
1375      }
1376      time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1377      time_t arrivalTime = fp->getArrivalTime();
1378      
1379      time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0); 
1380      time_t secondsToGo = arrivalTime - now;
1381      if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {    
1382           cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1383      }
1384      return (ete - secondsToGo); // Positive when we're too slow...
1385 }