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