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