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