]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
Fix for refueling and radar calculations.
[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         cerr << trafficRef->getCallSign() << "releasing parking " << fp->getGate() << 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) > 1.0) {
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         fp->setLeadDistance(speed, tgt_heading, curr, next);
752     }
753 }
754
755
756 /**
757  * Update target values (heading, alt, speed) depending on flight plan or control properties
758  */
759 bool FGAIAircraft::updateTargetValues() {
760     if (fp)                      // AI object has a flightplan
761     {
762         //TODO make this a function of AIBase
763         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
764         //cerr << "UpateTArgetValues() " << endl;
765         ProcessFlightPlan(dt, now);
766         if (! fp->isActive(now)) {
767             // Do execute Ground elev for inactive aircraft, so they
768             // Are repositioned to the correct ground altitude when the user flies within visibility range.
769             // In addition, check whether we are out of user range, so this aircraft
770             // can be deleted.
771             if (no_roll) {
772                 Transform();     // make sure aip is initialized.
773                 if (trafficRef) {
774                     //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
775                     if (! aiTrafficVisible()) {
776                         setDie(true);
777                         return false;
778                     }
779                     getGroundElev(dt);
780                     doGroundAltitude();
781                     // Transform();
782                     pos.setElevationFt(altitude_ft);
783                 }
784             }
785             return false;
786         }
787     }
788     else {
789         // no flight plan, update target heading, speed, and altitude
790         // from control properties.  These default to the initial
791         // settings in the config file, but can be changed "on the
792         // fly".
793         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
794         if ( lat_mode == "roll" ) {
795             double angle
796             = props->getDoubleValue("controls/flight/target-roll" );
797             RollTo( angle );
798         } else {
799             double angle
800             = props->getDoubleValue("controls/flight/target-hdg" );
801             TurnTo( angle );
802         }
803
804         string lon_mode
805         = props->getStringValue("controls/flight/longitude-mode");
806         if ( lon_mode == "alt" ) {
807             double alt = props->getDoubleValue("controls/flight/target-alt" );
808             ClimbTo( alt );
809         } else {
810             double angle
811             = props->getDoubleValue("controls/flight/target-pitch" );
812             PitchTo( angle );
813         }
814
815         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
816     }
817     return true;
818 }
819
820
821 /**
822  * Adjust the speed (accelerate/decelerate) to tgt_speed.
823  */
824 void FGAIAircraft::adjustSpeed(double tgt_speed) {
825     double speed_diff = tgt_speed - speed;
826     speed_diff = groundTargetSpeed - speed;
827
828     if (speed_diff > 0.0)        // need to accelerate
829     {
830         speed += performance->accel * dt;
831         if ( speed > tgt_speed )
832             speed = tgt_speed;
833
834     } else if (speed_diff < 0.0) {
835         if (no_roll) {
836             // on ground (aircraft can't roll)
837             // deceleration performance is better due to wheel brakes.
838             speed -= performance->decel * dt * 3;
839         } else {
840             speed -= performance->decel * dt;
841         }
842
843         if ( speed < tgt_speed )
844             speed = tgt_speed;
845
846     }
847 }
848
849
850 void FGAIAircraft::updatePosition() {
851     // convert speed to degrees per second
852     double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
853                                  * speed * 1.686 / ft_per_deg_lat;
854     double speed_east_deg_sec  = sin( hdg * SGD_DEGREES_TO_RADIANS )
855                                  * speed * 1.686 / ft_per_deg_lon;
856
857     // set new position
858     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
859     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
860 }
861
862
863 void FGAIAircraft::updateHeading() {
864     // adjust heading based on current bank angle
865     if (roll == 0.0)
866         roll = 0.01;
867
868     if (roll != 0.0) {
869         // double turnConstant;
870         //if (no_roll)
871         //  turnConstant = 0.0088362;
872         //else
873         //  turnConstant = 0.088362;
874         // If on ground, calculate heading change directly
875         if (no_roll) {
876             double headingDiff = fabs(hdg-tgt_heading);
877
878             if (headingDiff > 180)
879                 headingDiff = fabs(headingDiff - 360);
880
881             groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
882             if (sign(groundTargetSpeed) != sign(tgt_speed))
883                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
884
885             if (headingDiff > 30.0) {
886                 // invert if pushed backward
887                 headingChangeRate += dt * sign(roll);
888
889                 if (headingChangeRate > 30)
890                     headingChangeRate = 30;
891                 else if (headingChangeRate < -30)
892                     headingChangeRate = -30;
893
894             } else {
895                 if (fabs(headingChangeRate) > headingDiff)
896                     headingChangeRate = headingDiff*sign(roll);
897                 else
898                     headingChangeRate += dt * sign(roll);
899             }
900             hdg += headingChangeRate * dt;
901         } else {
902             if (fabs(speed) > 1.0) {
903                 turn_radius_ft = 0.088362 * speed * speed
904                                  / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
905             } else {
906                 // Check if turn_radius_ft == 0; this might lead to a division by 0.
907                 turn_radius_ft = 1.0;
908             }
909             double turn_circum_ft = SGD_2PI * turn_radius_ft;
910             double dist_covered_ft = speed * 1.686 * dt;
911             double alpha = dist_covered_ft / turn_circum_ft * 360.0;
912             hdg += alpha * sign(roll);
913         }
914         while ( hdg > 360.0 ) {
915             hdg -= 360.0;
916             spinCounter++;
917         }
918         while ( hdg < 0.0) {
919             hdg += 360.0;
920             spinCounter--;
921         }
922     }
923 }
924
925
926 void FGAIAircraft::updateBankAngles() {
927     // adjust target bank angle if heading lock engaged
928     if (hdg_lock) {
929         double bank_sense = 0.0;
930         double diff = fabs(hdg - tgt_heading);
931         if (diff > 180)
932             diff = fabs(diff - 360);
933
934         double sum = hdg + diff;
935         if (sum > 360.0)
936             sum -= 360.0;
937         if (fabs(sum - tgt_heading) < 1.0) {
938             bank_sense = 1.0;    // right turn
939         } else {
940             bank_sense = -1.0;   // left turn
941         }
942         if (diff < 30) {
943             tgt_roll = diff * bank_sense;
944         } else {
945             tgt_roll = 30.0 * bank_sense;
946         }
947         if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
948             tgt_speed *= 0.999;  // Ugly hack: If aircraft get stuck, they will continually spin around.
949             // The only way to resolve this is to make them slow down.
950         }
951     }
952
953     // adjust bank angle, use 9 degrees per second
954     double bank_diff = tgt_roll - roll;
955     if (fabs(bank_diff) > 0.2) {
956         if (bank_diff > 0.0)
957             roll += 9.0 * dt;
958
959         if (bank_diff < 0.0)
960             roll -= 9.0 * dt;
961         //while (roll > 180) roll -= 360;
962         //while (roll < 180) roll += 360;
963     }
964 }
965
966
967 void FGAIAircraft::updateAltitudes() {
968     // adjust altitude (meters) based on current vertical speed (fpm)
969     altitude_ft += vs / 60.0 * dt;
970     pos.setElevationFt(altitude_ft);
971
972     // adjust target Altitude, based on ground elevation when on ground
973     if (no_roll) {
974         getGroundElev(dt);
975         doGroundAltitude();
976     } else {
977         // find target vertical speed if altitude lock engaged
978         if (alt_lock && use_perf_vs) {
979             if (altitude_ft < tgt_altitude_ft) {
980                 tgt_vs = tgt_altitude_ft - altitude_ft;
981                 if (tgt_vs > performance->climb_rate)
982                     tgt_vs = performance->climb_rate;
983             } else {
984                 tgt_vs = tgt_altitude_ft - altitude_ft;
985                 if (tgt_vs  < (-performance->descent_rate))
986                     tgt_vs = -performance->descent_rate;
987             }
988         }
989
990         if (alt_lock && !use_perf_vs) {
991             double max_vs = 4*(tgt_altitude_ft - altitude_ft);
992             double min_vs = 100;
993             if (tgt_altitude_ft < altitude_ft)
994                 min_vs = -100.0;
995             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
996                     && (fabs(max_vs) < fabs(tgt_vs)))
997                 tgt_vs = max_vs;
998
999             if (fabs(tgt_vs) < fabs(min_vs))
1000                 tgt_vs = min_vs;
1001         }
1002     }
1003 }
1004
1005
1006 void FGAIAircraft::updateVerticalSpeed() {
1007     // adjust vertical speed
1008     double vs_diff = tgt_vs - vs;
1009     if (fabs(vs_diff) > 10.0) {
1010         if (vs_diff > 0.0) {
1011             vs += (performance->climb_rate / 3.0) * dt;
1012
1013             if (vs > tgt_vs)
1014                 vs = tgt_vs;
1015         } else {
1016             vs -= (performance->descent_rate / 3.0) * dt;
1017
1018             if (vs < tgt_vs)
1019                 vs = tgt_vs;
1020         }
1021     }
1022 }
1023
1024
1025 void FGAIAircraft::matchPitchAngle() {
1026     // match pitch angle to vertical speed
1027     if (vs > 0) {
1028         pitch = vs * 0.005;
1029     } else {
1030         pitch = vs * 0.002;
1031     }
1032 }