]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
AI aircraft will need to switch frequencies before being able to request
[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                 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
451                 //string trns = trafficRef->getCallSign() + " at runway " + fp->getRunway() + 
452                 //              ". Ready for departure. " + trafficRef->getFlightType() + " to " +
453                 //              trafficRef->getArrivalAirport()->getId();
454                 //fgSetString("/sim/messages/atc", trns.c_str());
455                 //  if (controller == 0) {
456                 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
457                 //}
458                 //}
459             } else {
460                 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
461             }
462             break;
463         case 9:              // Taxiing for parking
464             if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
465                 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
466             break;
467         default:
468             controller = 0;
469             break;
470         }
471
472         if ((controller != prevController) && (prevController != 0)) {
473             prevController->signOff(getID());
474         }
475         prevController = controller;
476         if (controller) {
477             controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
478                                          _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
479                                          trafficRef->getRadius(), leg, this);
480         }
481     }
482 }
483
484 // Process ATC instructions and report back
485
486 void FGAIAircraft::processATC(FGATCInstruction instruction) {
487     if (instruction.getCheckForCircularWait()) {
488         // This is not exactly an elegant solution, 
489         // but at least it gives me a chance to check
490         // if circular waits are resolved.
491         // For now, just take the offending aircraft 
492         // out of the scene
493         setDie(true);
494         // a more proper way should be - of course - to
495         // let an offending aircraft take an evasive action
496         // for instance taxi back a little bit.
497     }
498     //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
499     if (instruction.getHoldPattern   ()) {}
500
501     // Hold Position
502     if (instruction.getHoldPosition  ()) {
503         if (!holdPos) {
504             holdPos = true;
505         }
506         AccelTo(0.0);
507     } else {
508         if (holdPos) {
509             //if (trafficRef)
510             //  cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
511             holdPos = false;
512         }
513         // Change speed Instruction. This can only be excecuted when there is no
514         // Hold position instruction.
515         if (instruction.getChangeSpeed   ()) {
516             //  if (trafficRef)
517             //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
518             AccelTo(instruction.getSpeed());
519         } else {
520             if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
521         }
522     }
523     if (instruction.getChangeHeading ()) {
524         hdg_lock = false;
525         TurnTo(instruction.getHeading());
526     } else {
527         if (fp) {
528             hdg_lock = true;
529         }
530     }
531     if (instruction.getChangeAltitude()) {}
532
533 }
534
535
536 void FGAIAircraft::handleFirstWaypoint() {
537     bool eraseWaypoints;         //TODO YAGNI
538     headingError = 0;
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         if (!loadNextLeg()) {
556             setDie(true);
557             return;
558         }
559
560     prev = fp->getPreviousWaypoint();   //first waypoint
561     curr = fp->getCurrentWaypoint();    //second waypoint
562     next = fp->getNextWaypoint();       //third waypoint (might not exist!)
563
564     setLatitude(prev->latitude);
565     setLongitude(prev->longitude);
566     setSpeed(prev->speed);
567     setAltitude(prev->altitude);
568
569     if (prev->speed > 0.0)
570         setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
571     else
572         setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
573
574     // If next doesn't exist, as in incrementally created flightplans for
575     // AI/Trafficmanager created plans,
576     // Make sure lead distance is initialized otherwise
577     if (next)
578         fp->setLeadDistance(speed, hdg, curr, next);
579
580     if (curr->crossat > -1000.0) //use a calculated descent/climb rate
581     {
582         use_perf_vs = false;
583         tgt_vs = (curr->crossat - prev->altitude)
584                  / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
585                     / 6076.0 / prev->speed*60.0);
586         tgt_altitude_ft = curr->crossat;
587     } else {
588         use_perf_vs = true;
589         tgt_altitude_ft = prev->altitude;
590     }
591     alt_lock = hdg_lock = true;
592     no_roll = prev->on_ground;
593     if (no_roll) {
594         Transform();             // make sure aip is initialized.
595         getGroundElev(60.1);     // make sure it's executed first time around, so force a large dt value
596         doGroundAltitude();
597     }
598     // Make sure to announce the aircraft's position
599     announcePositionToController();
600     prevSpeed = 0;
601 }
602
603
604 /**
605  * Check Execution time (currently once every 100 ms)
606  * Add a bit of randomization to prevent the execution of all flight plans
607  * in synchrony, which can add significant periodic framerate flutter.
608  *
609  * @param now
610  * @return
611  */
612 bool FGAIAircraft::fpExecutable(time_t now) {
613     double rand_exec_time = (rand() % 100) / 100;
614     return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
615 }
616
617
618 /**
619  * Check to see if we've reached the lead point for our next turn
620  *
621  * @param curr
622  * @return
623  */
624 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
625     double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
626
627     //cerr << "2" << endl;
628     double lead_dist = fp->getLeadDistance();
629     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
630
631     if (lead_dist < fabs(2*speed)) {
632       //don't skip over the waypoint
633       lead_dist = fabs(2*speed);
634       //cerr << "Extending lead distance to " << lead_dist << endl;
635     }
636
637     //prev_dist_to_go = dist_to_go;
638     //if (dist_to_go < lead_dist)
639     //     cerr << trafficRef->getCallSign() << " Distance : " 
640     //          << dist_to_go << ": Lead distance " 
641     //          << lead_dist << " " << curr->name 
642     //          << " Ground target speed " << groundTargetSpeed << endl;
643          
644     return dist_to_go < lead_dist;
645 }
646
647
648 bool FGAIAircraft::aiTrafficVisible() {
649   SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"), 
650     fgGetDouble("/position/latitude-deg")));
651   
652   return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
653 }
654
655
656 /**
657  * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
658  * in the case of an arrival.
659  *
660  * @param prev
661  * @return
662  */
663
664 //TODO the trafficRef is the right place for the method
665 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
666     // prepare routing from one airport to another
667     FGAirport * dep = trafficRef->getDepartureAirport();
668     FGAirport * arr = trafficRef->getArrivalAirport();
669
670     if (!( dep && arr))
671         return false;
672
673     // This waypoint marks the fact that the aircraft has passed the initial taxi
674     // departure waypoint, so it can release the parking.
675     //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
676     if (prev->name == "PushBackPoint") {
677         dep->getDynamics()->releaseParking(fp->getGate());
678         time_t holdUntil = now + 120;
679         fp->setTime(holdUntil);
680         //cerr << _getCallsign() << "Holding at pushback point" << endl;
681     }
682
683     // This is the last taxi waypoint, and marks the the end of the flight plan
684     // so, the schedule should update and wait for the next departure time.
685     if (prev->name == "END") {
686         time_t nextDeparture = trafficRef->getDepartureTime();
687         // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
688         if (nextDeparture < (now+1200)) {
689             nextDeparture = now + 1200;
690         }
691         fp->setTime(nextDeparture); // should be "next departure"
692     }
693
694     return true;
695 }
696
697
698 /**
699  * Check difference between target bearing and current heading and correct if necessary.
700  *
701  * @param curr
702  */
703 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
704     double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
705     //cerr << "Bearing = " << calc_bearing << endl;
706     if (speed < 0) {
707         calc_bearing +=180;
708         if (calc_bearing > 360)
709             calc_bearing -= 360;
710     }
711
712     if (finite(calc_bearing)) {
713         double hdg_error = calc_bearing - tgt_heading;
714         if (fabs(hdg_error) > 0.01) {
715             TurnTo( calc_bearing );
716         }
717
718     } else {
719         cerr << "calc_bearing is not a finite number : "
720         << "Speed " << speed
721         << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
722         << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
723         cerr << "waypoint name " << curr->name;
724         exit(1);                 // FIXME
725     }
726 }
727
728
729 /**
730  * Update the lead distance calculation if speed has changed sufficiently
731  * to prevent spinning (hopefully);
732  *
733  * @param curr
734  * @param next
735  */
736 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
737     double speed_diff = speed - prevSpeed;
738
739     if (fabs(speed_diff) > 10) {
740         prevSpeed = speed;
741         if (next) {
742             fp->setLeadDistance(speed, tgt_heading, curr, next);
743         }
744     }
745 }
746
747
748 /**
749  * Update target values (heading, alt, speed) depending on flight plan or control properties
750  */
751 void FGAIAircraft::updatePrimaryTargetValues() {
752     if (fp)                      // AI object has a flightplan
753     {
754         //TODO make this a function of AIBase
755         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
756         //cerr << "UpateTArgetValues() " << endl;
757         ProcessFlightPlan(dt, now);
758
759         // Do execute Ground elev for inactive aircraft, so they
760         // Are repositioned to the correct ground altitude when the user flies within visibility range.
761         // In addition, check whether we are out of user range, so this aircraft
762         // can be deleted.
763         if (onGround()) {
764                 Transform();     // make sure aip is initialized.
765                 getGroundElev(dt);
766                 doGroundAltitude();
767                 // Transform();
768                 pos.setElevationFt(altitude_ft);
769         }
770         if (trafficRef) {
771            //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
772             if (! aiTrafficVisible()) {
773                 setDie(true);
774                 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
775                 throw AI_OutOfSight();
776             }
777         }
778         timeElapsed = now - fp->getStartTime();
779         if (! fp->isActive(now)) { 
780             throw FP_Inactive();
781         }
782     } else {
783         // no flight plan, update target heading, speed, and altitude
784         // from control properties.  These default to the initial
785         // settings in the config file, but can be changed "on the
786         // fly".
787         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
788         if ( lat_mode == "roll" ) {
789             double angle
790             = props->getDoubleValue("controls/flight/target-roll" );
791             RollTo( angle );
792         } else {
793             double angle
794             = props->getDoubleValue("controls/flight/target-hdg" );
795             TurnTo( angle );
796         }
797
798         string lon_mode
799         = props->getStringValue("controls/flight/longitude-mode");
800         if ( lon_mode == "alt" ) {
801             double alt = props->getDoubleValue("controls/flight/target-alt" );
802             ClimbTo( alt );
803         } else {
804             double angle
805             = props->getDoubleValue("controls/flight/target-pitch" );
806             PitchTo( angle );
807         }
808
809         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
810     }
811 }
812
813 void FGAIAircraft::updatePosition() {
814     // convert speed to degrees per second
815     double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
816                                  * speed * 1.686 / ft_per_deg_lat;
817     double speed_east_deg_sec  = sin( hdg * SGD_DEGREES_TO_RADIANS )
818                                  * speed * 1.686 / ft_per_deg_lon;
819
820     // set new position
821     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
822     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
823 }
824
825
826 void FGAIAircraft::updateHeading() {
827     // adjust heading based on current bank angle
828     if (roll == 0.0)
829         roll = 0.01;
830
831     if (roll != 0.0) {
832         // double turnConstant;
833         //if (no_roll)
834         //  turnConstant = 0.0088362;
835         //else
836         //  turnConstant = 0.088362;
837         // If on ground, calculate heading change directly
838         if (onGround()) {
839             double headingDiff = fabs(hdg-tgt_heading);
840             double bank_sense = 0.0;
841         /*
842         double diff = fabs(hdg - tgt_heading);
843         if (diff > 180)
844             diff = fabs(diff - 360);
845
846         double sum = hdg + diff;
847         if (sum > 360.0)
848             sum -= 360.0;
849         if (fabs(sum - tgt_heading) < 1.0) {
850             bank_sense = 1.0;    // right turn
851         } else {
852             bank_sense = -1.0;   // left turn
853         }*/
854             if (headingDiff > 180)
855                 headingDiff = fabs(headingDiff - 360);
856             double sum = hdg + headingDiff;
857             if (sum > 360.0) 
858                 sum -= 360.0;
859             if (fabs(sum - tgt_heading) > 0.0001) {
860                 bank_sense = -1.0;
861             } else {
862                 bank_sense = 1.0;
863             }
864             //if (trafficRef)
865                 //cerr << trafficRef->getCallSign() << " Heading " 
866                 //     << hdg << ". Target " << tgt_heading <<  ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
867             //if (headingDiff > 60) {
868             groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
869                 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
870             //} else {
871             //    groundTargetSpeed = tgt_speed;
872             //}
873             if (sign(groundTargetSpeed) != sign(tgt_speed))
874                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
875
876             if (headingDiff > 30.0) {
877                 // invert if pushed backward
878                 headingChangeRate += 10.0 * dt * sign(roll);
879
880                 // Clamp the maximum steering rate to 30 degrees per second,
881                 // But only do this when the heading error is decreasing.
882                 if ((headingDiff < headingError)) {
883                     if (headingChangeRate > 30)
884                         headingChangeRate = 30;
885                     else if (headingChangeRate < -30)
886                         headingChangeRate = -30;
887                 }
888             } else {
889                    if (fabs(headingChangeRate) > headingDiff)
890                        headingChangeRate = headingDiff*sign(roll);
891                    else
892                        headingChangeRate += dt * sign(roll);
893             }
894
895             hdg += headingChangeRate * dt * (fabs(speed) / 15);
896             headingError = headingDiff;
897         } else {
898             if (fabs(speed) > 1.0) {
899                 turn_radius_ft = 0.088362 * speed * speed
900                                  / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
901             } else {
902                 // Check if turn_radius_ft == 0; this might lead to a division by 0.
903                 turn_radius_ft = 1.0;
904             }
905             double turn_circum_ft = SGD_2PI * turn_radius_ft;
906             double dist_covered_ft = speed * 1.686 * dt;
907             double alpha = dist_covered_ft / turn_circum_ft * 360.0;
908             hdg += alpha * sign(roll);
909         }
910         while ( hdg > 360.0 ) {
911             hdg -= 360.0;
912             spinCounter++;
913         }
914         while ( hdg < 0.0) {
915             hdg += 360.0;
916             spinCounter--;
917         }
918     }
919 }
920
921
922 void FGAIAircraft::updateBankAngleTarget() {
923     // adjust target bank angle if heading lock engaged
924     if (hdg_lock) {
925         double bank_sense = 0.0;
926         double diff = fabs(hdg - tgt_heading);
927         if (diff > 180)
928             diff = fabs(diff - 360);
929
930         double sum = hdg + diff;
931         if (sum > 360.0)
932             sum -= 360.0;
933         if (fabs(sum - tgt_heading) < 1.0) {
934             bank_sense = 1.0;    // right turn
935         } else {
936             bank_sense = -1.0;   // left turn
937         }
938         if (diff < _performance->maximumBankAngle()) {
939             tgt_roll = diff * bank_sense;
940         } else {
941             tgt_roll = _performance->maximumBankAngle() * bank_sense;
942         }
943         if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
944             tgt_speed *= 0.999;  // Ugly hack: If aircraft get stuck, they will continually spin around.
945             // The only way to resolve this is to make them slow down.
946         }
947     }
948 }
949
950
951 void FGAIAircraft::updateVerticalSpeedTarget() {
952     // adjust target Altitude, based on ground elevation when on ground
953     if (onGround()) {
954         getGroundElev(dt);
955         doGroundAltitude();
956     } else if (alt_lock) {
957         // find target vertical speed
958         if (use_perf_vs) {
959             if (altitude_ft < tgt_altitude_ft) {
960                 tgt_vs = tgt_altitude_ft - altitude_ft;
961                 if (tgt_vs > _performance->climbRate())
962                     tgt_vs = _performance->climbRate();
963             } else {
964                 tgt_vs = tgt_altitude_ft - altitude_ft;
965                 if (tgt_vs  < (-_performance->descentRate()))
966                     tgt_vs = -_performance->descentRate();
967             }
968         } else {
969             double max_vs = 4*(tgt_altitude_ft - altitude_ft);
970             double min_vs = 100;
971             if (tgt_altitude_ft < altitude_ft)
972                 min_vs = -100.0;
973             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
974                     && (fabs(max_vs) < fabs(tgt_vs)))
975                 tgt_vs = max_vs;
976
977             if (fabs(tgt_vs) < fabs(min_vs))
978                 tgt_vs = min_vs;
979         }
980     } //else 
981     //    tgt_vs = 0.0;
982 }
983
984 void FGAIAircraft::updatePitchAngleTarget() {
985     // if on ground and above vRotate -> initial rotation
986     if (onGround() && (speed > _performance->vRotate()))
987         tgt_pitch = 8.0; // some rough B737 value 
988
989     //TODO pitch angle on approach and landing
990     
991     // match pitch angle to vertical speed
992     else if (tgt_vs > 0) {
993         tgt_pitch = tgt_vs * 0.005;
994     } else {
995         tgt_pitch = tgt_vs * 0.002;
996     }
997 }
998
999 string FGAIAircraft::atGate() {
1000      string tmp("");
1001      if (fp->getLeg() < 3) {
1002          if (trafficRef) {
1003              if (fp->getGate() > 0) {
1004                  FGParking *park =
1005                      trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1006                  tmp = park->getName();
1007              }
1008          }
1009      }
1010      return tmp;
1011 }
1012
1013 void FGAIAircraft::handleATCRequests() {
1014     //TODO implement NullController for having no ATC to save the conditionals
1015     if (controller) {
1016         controller->update(getID(),
1017                            pos.getLatitudeDeg(),
1018                            pos.getLongitudeDeg(),
1019                            hdg,
1020                            speed,
1021                            altitude_ft, dt);
1022         processATC(controller->getInstruction(getID()));
1023     }
1024 }
1025
1026 void FGAIAircraft::updateActualState() {
1027     //update current state
1028     //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1029     updatePosition();
1030
1031     if (onGround())
1032         speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1033     else
1034         speed = _performance->actualSpeed(this, tgt_speed, dt);
1035
1036     updateHeading();
1037     roll = _performance->actualBankAngle(this, tgt_roll, dt);
1038
1039     // adjust altitude (meters) based on current vertical speed (fpm)
1040     altitude_ft += vs / 60.0 * dt;
1041     pos.setElevationFt(altitude_ft);
1042
1043     vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1044     pitch = _performance->actualPitch(this, tgt_pitch, dt);
1045 }
1046
1047 void FGAIAircraft::updateSecondaryTargetValues() {
1048     // derived target state values
1049     updateBankAngleTarget();
1050     updateVerticalSpeedTarget();
1051     updatePitchAngleTarget();
1052
1053     //TODO calculate wind correction angle (tgt_yaw)
1054 }