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