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