]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
19f57f5c28fd18f109b4ad289a7f4738afd0beee
[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/math/point3d.hxx>
26 #include <simgear/route/waypoint.hxx>
27 #include <Main/fg_props.hxx>
28 #include <Main/globals.hxx>
29 #include <Main/viewer.hxx>
30 #include <Scenery/scenery.hxx>
31 #include <Scenery/tilemgr.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 SG_USING_STD(string);
44
45 #include "AIAircraft.hxx"
46 //#include <Airports/trafficcontroller.hxx>
47
48 static string tempReg;
49 //
50 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
51 // cruise_speed, descent_speed, land_speed
52 //
53
54 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
55             // light aircraft
56             {2.0, 2.0,  450.0, 1000.0,  70.0,  80.0, 100.0,  80.0,  60.0},
57             // ww2_fighter
58             {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
59             // jet_transport
60             {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
61             // jet_fighter
62             {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
63             // tanker
64             {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
65             // ufo (extreme accel/decel)
66             {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
67         };
68
69 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
70     trafficRef = ref;
71     if (trafficRef)
72         groundOffset = trafficRef->getGroundOffset();
73     else
74         groundOffset = 0;
75
76     fp = 0;
77     controller = 0;
78     prevController = 0;
79     dt_count = 0;
80     dt_elev_count = 0;
81     use_perf_vs = true;
82
83     no_roll = false;
84     tgt_speed = 0;
85     speed = 0;
86     groundTargetSpeed = 0;
87
88     // set heading and altitude locks
89     hdg_lock = false;
90     alt_lock = false;
91     roll = 0;
92     headingChangeRate = 0.0;
93
94     holdPos = false;
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->setStringValue("callsign", callsign.c_str());
125 }
126
127
128 void FGAIAircraft::unbind() {
129     FGAIBase::unbind();
130
131     props->untie("controls/gear/gear-down");
132 }
133
134
135 void FGAIAircraft::update(double dt) {
136     FGAIBase::update(dt);
137     Run(dt);
138     Transform();
139 }
140
141
142 void FGAIAircraft::setPerformance(const std::string& acclass) {
143     if (acclass == "light") {
144         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
145     } else if (acclass == "ww2_fighter") {
146         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
147     } else if (acclass == "jet_transport") {
148         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
149     } else if (acclass == "jet_fighter") {
150         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
151     } else if (acclass == "tanker") {
152         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
153     } else if (acclass == "ufo") {
154         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
155     } else {
156         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
157     }
158 }
159
160
161 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
162
163     performance = ps;
164 }
165
166
167 void FGAIAircraft::Run(double dt) {
168
169     FGAIAircraft::dt = dt;
170     if (!updateTargetValues())
171         return;
172
173     if (controller) {
174         controller->update(getID(),
175                            pos.getLatitudeDeg(),
176                            pos.getLongitudeDeg(),
177                            hdg,
178                            speed,
179                            altitude_ft, dt);
180         processATC(controller->getInstruction(getID()));
181     }
182
183     if (no_roll) {
184         adjustSpeed(groundTargetSpeed);
185     } else {
186         adjustSpeed(tgt_speed);
187     }
188
189     updatePosition();
190     updateHeading();
191     updateBankAngles();
192     updateAltitudes();
193     updateVerticalSpeed();
194     matchPitchAngle();
195     UpdateRadar(manager);
196 }
197
198
199 void FGAIAircraft::AccelTo(double speed) {
200     tgt_speed = speed;
201 }
202
203
204 void FGAIAircraft::PitchTo(double angle) {
205     tgt_pitch = angle;
206     alt_lock = false;
207 }
208
209
210 void FGAIAircraft::RollTo(double angle) {
211     tgt_roll = angle;
212     hdg_lock = false;
213 }
214
215
216 void FGAIAircraft::YawTo(double angle) {
217     tgt_yaw = angle;
218 }
219
220
221 void FGAIAircraft::ClimbTo(double alt_ft ) {
222     tgt_altitude_ft = alt_ft;
223     alt_lock = true;
224 }
225
226
227 void FGAIAircraft::TurnTo(double heading) {
228     tgt_heading = heading;
229     hdg_lock = true;
230 }
231
232
233 double FGAIAircraft::sign(double x) {
234     if (x == 0.0)
235         return x;
236     else
237         return x/fabs(x);
238 }
239
240
241 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
242     if (!flightplan.empty()) {
243         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
244         fp->setRepeat(repeat);
245         SetFlightPlan(fp);
246     }
247 }
248
249
250 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
251     delete fp;
252     fp = f;
253 }
254
255
256 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
257
258     // the one behind you
259     FGAIFlightPlan::waypoint* prev = 0;
260     // the one ahead
261     FGAIFlightPlan::waypoint* curr = 0;
262     // the next plus 1
263     FGAIFlightPlan::waypoint* next = 0;
264
265     prev = fp->getPreviousWaypoint();
266     curr = fp->getCurrentWaypoint();
267     next = fp->getNextWaypoint();
268
269     dt_count += dt;
270
271     ///////////////////////////////////////////////////////////////////////////
272     // Initialize the flightplan
273     //////////////////////////////////////////////////////////////////////////
274     if (!prev) {
275         handleFirstWaypoint();
276         return;
277     }                            // end of initialization
278     if (! fpExecutable(now))
279           return;
280     dt_count = 0;
281
282     if (! leadPointReached(curr)) {
283         controlHeading(curr);
284         controlSpeed(curr, next);
285     } else {
286         if (curr->finished)      //end of the flight plan
287         {
288             if (fp->getRepeat())
289                 fp->restart();
290             else
291                 setDie(true);
292             return;
293         }
294
295         if (next) {
296             //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
297             tgt_heading = fp->getBearing(curr, next);
298             spinCounter = 0;
299         }
300
301         //TODO let the fp handle this (loading of next leg)
302         fp->IncrementWaypoint((bool) trafficRef);
303         if (!(fp->getNextWaypoint()) && trafficRef)
304             loadNextLeg();
305
306         prev = fp->getPreviousWaypoint();
307         curr = fp->getCurrentWaypoint();
308         next = fp->getNextWaypoint();
309
310         // Now that we have incremented the waypoints, excute some traffic manager specific code
311         if (trafficRef) {
312             //TODO isn't this best executed right at the beginning?
313             if (! aiTrafficVisible()) {
314                 setDie(true);
315                 return;
316             }
317
318             if (! handleAirportEndPoints(prev, now)) {
319                 setDie(true);
320                 return;
321             }
322
323             announcePositionToController();
324
325         }
326
327         if (next) {
328             fp->setLeadDistance(speed, tgt_heading, curr, next);
329         }
330
331         if (!(prev->on_ground))  // only update the tgt altitude from flightplan if not on the ground
332         {
333             tgt_altitude_ft = prev->altitude;
334             if (curr->crossat > -1000.0) {
335                 use_perf_vs = false;
336                 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
337                          / 6076.0 / speed*60.0);
338                 tgt_altitude_ft = curr->crossat;
339             } else {
340                 use_perf_vs = true;
341             }
342         }
343         tgt_speed = prev->speed;
344         hdg_lock = alt_lock = true;
345         no_roll = prev->on_ground;
346     }
347 }
348
349
350 void FGAIAircraft::initializeFlightPlan() {
351 }
352
353
354 bool FGAIAircraft::_getGearDown() const {
355     return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
356             && (props->getFloatValue("velocities/airspeed-kt")
357                 < performance->land_speed*1.25));
358 }
359
360
361 void FGAIAircraft::loadNextLeg() {
362
363     int leg;
364     if ((leg = fp->getLeg())  == 10) {
365         trafficRef->next();
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 (dep,
379                     arr,
380                     leg,
381                     cruiseAlt,           //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
382                     trafficRef->getSpeed(),
383                     _getLatitude(),
384                     _getLongitude(),
385                     false,
386                     trafficRef->getRadius(),
387                     trafficRef->getFlightType(),
388                     acType,
389                     company);
390     }
391 }
392
393
394 // Note: This code is copied from David Luff's AILocalTraffic
395 // Warning - ground elev determination is CPU intensive
396 // Either this function or the logic of how often it is called
397 // will almost certainly change.
398
399 void FGAIAircraft::getGroundElev(double dt) {
400     dt_elev_count += dt;
401
402     // Update minimally every three secs, but add some randomness
403     // to prevent all IA objects doing this in synchrony
404     if (dt_elev_count < (3.0) + (rand() % 10))
405         return;
406     else
407         dt_elev_count = 0;
408
409     // Only do the proper hitlist stuff if we are within visible range of the viewer.
410     if (!invisible) {
411         double visibility_meters = fgGetDouble("/environment/visibility-m");
412
413         FGViewer* vw = globals->get_current_view();
414         double course, distance;
415
416         SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
417         SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
418         view.CourseAndDistance(current, &course, &distance);
419         if (distance > visibility_meters) {
420             //aip.getSGLocation()->set_cur_elev_m(aptElev);
421             return;
422         }
423
424         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
425         double range = 500.0;
426         if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
427             // Try to shedule tiles for that position.
428             globals->get_tile_mgr()->update( aip.getSGLocation(), range );
429         }
430
431         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
432         double alt;
433         if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
434             tgt_altitude_ft = alt * SG_METER_TO_FEET;
435     }
436 }
437
438
439 void FGAIAircraft::setCallSign(const string& s) {
440     callsign = s;
441 }
442
443
444 void FGAIAircraft::doGroundAltitude() {
445     if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
446         altitude_ft = (tgt_altitude_ft + groundOffset);
447     else
448         altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
449 }
450
451
452 void FGAIAircraft::announcePositionToController() {
453     if (trafficRef) {
454         int leg = fp->getLeg();
455
456         // Note that leg was been incremented after creating the current leg, so we should use
457         // leg numbers here that are one higher than the number that is used to create the leg
458         //
459         switch (leg) {
460         case 3:              // Taxiing to runway
461             if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
462                 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
463             break;
464         case 4:              //Take off tower controller
465             if (trafficRef->getDepartureAirport()->getDynamics()) {
466                 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
467                 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
468                 //cerr << trafficRef->getCallSign() << " at runway " << fp->getRunway() << "Ready for departure "
469                 //   << trafficRef->getFlightType() << " to " << trafficRef->getArrivalAirport()->getId() << endl;
470                 //  if (controller == 0) {
471                 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
472                 //}
473
474             } else {
475                 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
476             }
477             break;
478         case 9:              // Taxiing for parking
479             if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
480                 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
481             break;
482         default:
483             controller = 0;
484             break;
485         }
486
487         if ((controller != prevController) && (prevController != 0)) {
488             prevController->signOff(getID());
489             string callsign =  trafficRef->getCallSign();
490             if ( trafficRef->getHeavy())
491                 callsign += "Heavy";
492             switch (leg) {
493             case 3:
494                 //cerr << callsign << " ready to taxi to runway " << fp->getRunway() << endl;
495                 break;
496             case 4:
497                 //cerr << callsign << " at runway " << fp->getRunway() << "Ready for take-off. "
498                 //     << trafficRef->getFlightRules() << " to " << trafficRef->getArrivalAirport()->getId()
499                 //     << "(" << trafficRef->getArrivalAirport()->getName() << ")."<< endl;
500                 break;
501             }
502         }
503         prevController = controller;
504         if (controller) {
505             controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
506                                          _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
507                                          trafficRef->getRadius(), leg, trafficRef->getCallSign());
508         }
509     }
510 }
511
512
513 void FGAIAircraft::processATC(FGATCInstruction instruction) {
514     //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
515     if (instruction.getHoldPattern   ()) {}
516
517     // Hold Position
518     if (instruction.getHoldPosition  ()) {
519         if (!holdPos) {
520             holdPos = true;
521         }
522         AccelTo(0.0);
523     } else {
524         if (holdPos) {
525             //if (trafficRef)
526             //  cerr << trafficRef->getCallSign() << " Resuming Taxi " << endl;
527             holdPos = false;
528         }
529         // Change speed Instruction. This can only be excecuted when there is no
530         // Hold position instruction.
531         if (instruction.getChangeSpeed   ()) {
532             //  if (trafficRef)
533             //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
534             AccelTo(instruction.getSpeed());
535         } else {
536             if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
537         }
538     }
539     if (instruction.getChangeHeading ()) {
540         hdg_lock = false;
541         TurnTo(instruction.getHeading());
542     } else {
543         if (fp) {
544             hdg_lock = true;
545         }
546     }
547     if (instruction.getChangeAltitude()) {}
548
549 }
550
551
552 void FGAIAircraft::handleFirstWaypoint() {
553     bool eraseWaypoints;         //TODO YAGNI
554     if (trafficRef) {
555         eraseWaypoints = true;
556     } else {
557         eraseWaypoints = false;
558     }
559
560     FGAIFlightPlan::waypoint* prev = 0; // the one behind you
561     FGAIFlightPlan::waypoint* curr = 0; // the one ahead
562     FGAIFlightPlan::waypoint* next = 0;// the next plus 1
563
564     spinCounter = 0;
565     tempReg = "";
566
567     //TODO fp should handle this
568     fp->IncrementWaypoint(eraseWaypoints);
569     if (!(fp->getNextWaypoint()) && trafficRef)
570         loadNextLeg();
571
572     prev = fp->getPreviousWaypoint();   //first waypoint
573     curr = fp->getCurrentWaypoint();    //second waypoint
574     next = fp->getNextWaypoint();       //third waypoint (might not exist!)
575
576     setLatitude(prev->latitude);
577     setLongitude(prev->longitude);
578     setSpeed(prev->speed);
579     setAltitude(prev->altitude);
580
581     if (prev->speed > 0.0)
582         setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
583     else
584         setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
585
586     // If next doesn't exist, as in incrementally created flightplans for
587     // AI/Trafficmanager created plans,
588     // Make sure lead distance is initialized otherwise
589     if (next)
590         fp->setLeadDistance(speed, hdg, curr, next);
591
592     if (curr->crossat > -1000.0) //use a calculated descent/climb rate
593     {
594         use_perf_vs = false;
595         tgt_vs = (curr->crossat - prev->altitude)
596                  / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
597                     / 6076.0 / prev->speed*60.0);
598         tgt_altitude_ft = curr->crossat;
599     } else {
600         use_perf_vs = true;
601         tgt_altitude_ft = prev->altitude;
602     }
603     alt_lock = hdg_lock = true;
604     no_roll = prev->on_ground;
605     if (no_roll) {
606         Transform();             // make sure aip is initialized.
607         getGroundElev(60.1);     // make sure it's executed first time around, so force a large dt value
608         doGroundAltitude();
609     }
610     // Make sure to announce the aircraft's position
611     announcePositionToController();
612     prevSpeed = 0;
613 }
614
615
616 /**
617  * Check Execution time (currently once every 100 ms)
618  * Add a bit of randomization to prevent the execution of all flight plans
619  * in synchrony, which can add significant periodic framerate flutter.
620  *
621  * @param now
622  * @return
623  */
624 bool FGAIAircraft::fpExecutable(time_t now) {
625     double rand_exec_time = (rand() % 100) / 100;
626     return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
627 }
628
629
630 /**
631  * Check to see if we've reached the lead point for our next turn
632  *
633  * @param curr
634  * @return
635  */
636 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
637     double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
638
639     //cerr << "2" << endl;
640     double lead_dist = fp->getLeadDistance();
641     //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
642     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
643
644     if (lead_dist < fabs(2*speed)) {
645       //don't skip over the waypoint
646       lead_dist = fabs(2*speed);
647       //cerr << "Extending lead distance to " << lead_dist << endl;
648     }
649
650     //prev_dist_to_go = dist_to_go;
651     return dist_to_go < lead_dist;
652 }
653
654
655 bool FGAIAircraft::aiTrafficVisible() {
656     double userLatitude  = fgGetDouble("/position/latitude-deg");
657     double userLongitude = fgGetDouble("/position/longitude-deg");
658     double course, distance;
659
660     SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
661     SGWayPoint user (userLongitude, userLatitude, 0);
662
663     user.CourseAndDistance(current, &course, &distance);
664
665     return ((distance * SG_METER_TO_NM) <= TRAFFICTOAIDIST);
666 }
667
668
669 /**
670  * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
671  * in the case of an arrival.
672  *
673  * @param prev
674  * @return
675  */
676
677 //TODO the trafficRef is the right place for the method
678 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
679     // prepare routing from one airport to another
680     FGAirport * dep = trafficRef->getDepartureAirport();
681     FGAirport * arr = trafficRef->getArrivalAirport();
682
683     if (!( dep && arr))
684         return false;
685
686     // This waypoint marks the fact that the aircraft has passed the initial taxi
687     // departure waypoint, so it can release the parking.
688     if (prev->name == "park2") {
689         dep->getDynamics()->releaseParking(fp->getGate());
690     }
691
692     // This is the last taxi waypoint, and marks the the end of the flight plan
693     // so, the schedule should update and wait for the next departure time.
694     if (prev->name == "END") {
695         time_t nextDeparture = trafficRef->getDepartureTime();
696         // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
697         if (nextDeparture < (now+1200)) {
698             nextDeparture = now + 1200;
699         }
700         fp->setTime(nextDeparture); // should be "next departure"
701     }
702
703     return true;
704 }
705
706
707 /**
708  * Check difference between target bearing and current heading and correct if necessary.
709  *
710  * @param curr
711  */
712 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
713     double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
714     //cerr << "Bearing = " << calc_bearing << endl;
715     if (speed < 0) {
716         calc_bearing +=180;
717         if (calc_bearing > 360)
718             calc_bearing -= 360;
719     }
720
721     if (finite(calc_bearing)) {
722         double hdg_error = calc_bearing - tgt_heading;
723         if (fabs(hdg_error) > 1.0) {
724             TurnTo( calc_bearing );
725         }
726
727     } else {
728         cerr << "calc_bearing is not a finite number : "
729         << "Speed " << speed
730         << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
731         << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
732         cerr << "waypoint name " << curr->name;
733         exit(1);                 // FIXME
734     }
735 }
736
737
738 /**
739  * Update the lead distance calculation if speed has changed sufficiently
740  * to prevent spinning (hopefully);
741  *
742  * @param curr
743  * @param next
744  */
745 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
746     double speed_diff = speed - prevSpeed;
747
748     if (fabs(speed_diff) > 10) {
749         prevSpeed = speed;
750         fp->setLeadDistance(speed, tgt_heading, curr, next);
751     }
752 }
753
754
755 /**
756  * Update target values (heading, alt, speed) depending on flight plan or control properties
757  */
758 bool FGAIAircraft::updateTargetValues() {
759     if (fp)                      // AI object has a flightplan
760     {
761         //TODO make this a function of AIBase
762         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
763         //cerr << "UpateTArgetValues() " << endl;
764         ProcessFlightPlan(dt, now);
765         if (! fp->isActive(now)) {
766             // Do execute Ground elev for inactive aircraft, so they
767             // Are repositioned to the correct ground altitude when the user flies within visibility range.
768             // In addition, check whether we are out of user range, so this aircraft
769             // can be deleted.
770             if (no_roll) {
771                 Transform();     // make sure aip is initialized.
772                 if (trafficRef) {
773                     //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
774                     if (! aiTrafficVisible()) {
775                         setDie(true);
776                         return false;
777                     }
778                     getGroundElev(dt);
779                     doGroundAltitude();
780                     // Transform();
781                     pos.setElevationFt(altitude_ft);
782                 }
783             }
784             return false;
785         }
786     }
787     else {
788         // no flight plan, update target heading, speed, and altitude
789         // from control properties.  These default to the initial
790         // settings in the config file, but can be changed "on the
791         // fly".
792         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
793         if ( lat_mode == "roll" ) {
794             double angle
795             = props->getDoubleValue("controls/flight/target-roll" );
796             RollTo( angle );
797         } else {
798             double angle
799             = props->getDoubleValue("controls/flight/target-hdg" );
800             TurnTo( angle );
801         }
802
803         string lon_mode
804         = props->getStringValue("controls/flight/longitude-mode");
805         if ( lon_mode == "alt" ) {
806             double alt = props->getDoubleValue("controls/flight/target-alt" );
807             ClimbTo( alt );
808         } else {
809             double angle
810             = props->getDoubleValue("controls/flight/target-pitch" );
811             PitchTo( angle );
812         }
813
814         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
815     }
816     return true;
817 }
818
819
820 /**
821  * Adjust the speed (accelerate/decelerate) to tgt_speed.
822  */
823 void FGAIAircraft::adjustSpeed(double tgt_speed) {
824     double speed_diff = tgt_speed - speed;
825     speed_diff = groundTargetSpeed - speed;
826
827     if (speed_diff > 0.0)        // need to accelerate
828     {
829         speed += performance->accel * dt;
830         if ( speed > tgt_speed )
831             speed = tgt_speed;
832
833     } else if (speed_diff < 0.0) {
834         if (no_roll) {
835             // on ground (aircraft can't roll)
836             // deceleration performance is better due to wheel brakes.
837             speed -= performance->decel * dt * 3;
838         } else {
839             speed -= performance->decel * dt;
840         }
841
842         if ( speed < tgt_speed )
843             speed = tgt_speed;
844
845     }
846 }
847
848
849 void FGAIAircraft::updatePosition() {
850     // convert speed to degrees per second
851     double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
852                                  * speed * 1.686 / ft_per_deg_lat;
853     double speed_east_deg_sec  = sin( hdg * SGD_DEGREES_TO_RADIANS )
854                                  * speed * 1.686 / ft_per_deg_lon;
855
856     // set new position
857     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
858     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
859 }
860
861
862 void FGAIAircraft::updateHeading() {
863     // adjust heading based on current bank angle
864     if (roll == 0.0)
865         roll = 0.01;
866
867     if (roll != 0.0) {
868         // double turnConstant;
869         //if (no_roll)
870         //  turnConstant = 0.0088362;
871         //else
872         //  turnConstant = 0.088362;
873         // If on ground, calculate heading change directly
874         if (no_roll) {
875             double headingDiff = fabs(hdg-tgt_heading);
876
877             if (headingDiff > 180)
878                 headingDiff = fabs(headingDiff - 360);
879
880             groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
881             if (sign(groundTargetSpeed) != sign(tgt_speed))
882                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
883
884             if (headingDiff > 30.0) {
885                 // invert if pushed backward
886                 headingChangeRate += dt * sign(roll);
887
888                 if (headingChangeRate > 30)
889                     headingChangeRate = 30;
890                 else if (headingChangeRate < -30)
891                     headingChangeRate = -30;
892
893             } else {
894                 if (fabs(headingChangeRate) > headingDiff)
895                     headingChangeRate = headingDiff*sign(roll);
896                 else
897                     headingChangeRate += dt * sign(roll);
898             }
899             hdg += headingChangeRate * dt;
900         } else {
901             if (fabs(speed) > 1.0) {
902                 turn_radius_ft = 0.088362 * speed * speed
903                                  / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
904             } else {
905                 // Check if turn_radius_ft == 0; this might lead to a division by 0.
906                 turn_radius_ft = 1.0;
907             }
908             double turn_circum_ft = SGD_2PI * turn_radius_ft;
909             double dist_covered_ft = speed * 1.686 * dt;
910             double alpha = dist_covered_ft / turn_circum_ft * 360.0;
911             hdg += alpha * sign(roll);
912         }
913         while ( hdg > 360.0 ) {
914             hdg -= 360.0;
915             spinCounter++;
916         }
917         while ( hdg < 0.0) {
918             hdg += 360.0;
919             spinCounter--;
920         }
921     }
922 }
923
924
925 void FGAIAircraft::updateBankAngles() {
926     // adjust target bank angle if heading lock engaged
927     if (hdg_lock) {
928         double bank_sense = 0.0;
929         double diff = fabs(hdg - tgt_heading);
930         if (diff > 180)
931             diff = fabs(diff - 360);
932
933         double sum = hdg + diff;
934         if (sum > 360.0)
935             sum -= 360.0;
936         if (fabs(sum - tgt_heading) < 1.0) {
937             bank_sense = 1.0;    // right turn
938         } else {
939             bank_sense = -1.0;   // left turn
940         }
941         if (diff < 30) {
942             tgt_roll = diff * bank_sense;
943         } else {
944             tgt_roll = 30.0 * bank_sense;
945         }
946         if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
947             tgt_speed *= 0.999;  // Ugly hack: If aircraft get stuck, they will continually spin around.
948             // The only way to resolve this is to make them slow down.
949         }
950     }
951
952     // adjust bank angle, use 9 degrees per second
953     double bank_diff = tgt_roll - roll;
954     if (fabs(bank_diff) > 0.2) {
955         if (bank_diff > 0.0)
956             roll += 9.0 * dt;
957
958         if (bank_diff < 0.0)
959             roll -= 9.0 * dt;
960         //while (roll > 180) roll -= 360;
961         //while (roll < 180) roll += 360;
962     }
963 }
964
965
966 void FGAIAircraft::updateAltitudes() {
967     // adjust altitude (meters) based on current vertical speed (fpm)
968     altitude_ft += vs / 60.0 * dt;
969     pos.setElevationFt(altitude_ft);
970
971     // adjust target Altitude, based on ground elevation when on ground
972     if (no_roll) {
973         getGroundElev(dt);
974         doGroundAltitude();
975     } else {
976         // find target vertical speed if altitude lock engaged
977         if (alt_lock && use_perf_vs) {
978             if (altitude_ft < tgt_altitude_ft) {
979                 tgt_vs = tgt_altitude_ft - altitude_ft;
980                 if (tgt_vs > performance->climb_rate)
981                     tgt_vs = performance->climb_rate;
982             } else {
983                 tgt_vs = tgt_altitude_ft - altitude_ft;
984                 if (tgt_vs  < (-performance->descent_rate))
985                     tgt_vs = -performance->descent_rate;
986             }
987         }
988
989         if (alt_lock && !use_perf_vs) {
990             double max_vs = 4*(tgt_altitude_ft - altitude_ft);
991             double min_vs = 100;
992             if (tgt_altitude_ft < altitude_ft)
993                 min_vs = -100.0;
994             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
995                     && (fabs(max_vs) < fabs(tgt_vs)))
996                 tgt_vs = max_vs;
997
998             if (fabs(tgt_vs) < fabs(min_vs))
999                 tgt_vs = min_vs;
1000         }
1001     }
1002 }
1003
1004
1005 void FGAIAircraft::updateVerticalSpeed() {
1006     // adjust vertical speed
1007     double vs_diff = tgt_vs - vs;
1008     if (fabs(vs_diff) > 10.0) {
1009         if (vs_diff > 0.0) {
1010             vs += (performance->climb_rate / 3.0) * dt;
1011
1012             if (vs > tgt_vs)
1013                 vs = tgt_vs;
1014         } else {
1015             vs -= (performance->descent_rate / 3.0) * dt;
1016
1017             if (vs < tgt_vs)
1018                 vs = tgt_vs;
1019         }
1020     }
1021 }
1022
1023
1024 void FGAIAircraft::matchPitchAngle() {
1025     // match pitch angle to vertical speed
1026     if (vs > 0) {
1027         pitch = vs * 0.005;
1028     } else {
1029         pitch = vs * 0.002;
1030     }
1031 }