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