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