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