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