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