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