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