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