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