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