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