]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
remove obsolete constants
[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    static string tempReg;
47 //
48 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
49 // cruise_speed, descent_speed, land_speed
50 //
51 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
52     // light aircraft
53     {2.0, 2.0,  450.0, 1000.0,  70.0,  80.0, 100.0,  80.0,  60.0},
54     // ww2_fighter
55     {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
56     // jet_transport
57     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
58     // jet_fighter
59     {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
60     // tanker
61     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0}
62 };
63
64
65 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
66     FGAIBase(otAircraft)
67 {
68     trafficRef = ref;
69     if (trafficRef)
70         groundOffset = trafficRef->getGroundOffset();
71     else
72         groundOffset = 0;
73
74     fp = 0;
75     dt_count = 0;
76     dt_elev_count = 0;
77     use_perf_vs = true;
78     isTanker = false;
79
80     // set heading and altitude locks
81     hdg_lock = false;
82     alt_lock = false;
83     roll = 0;
84     headingChangeRate = 0.0;
85 }
86
87
88 FGAIAircraft::~FGAIAircraft() {
89     //delete fp;
90 }
91
92
93 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
94     if (!scFileNode)
95         return;
96
97     FGAIBase::readFromScenario(scFileNode);
98
99     setPerformance(scFileNode->getStringValue("class", "jet_transport"));
100     setFlightPlan(scFileNode->getStringValue("flightplan"),
101                   scFileNode->getBoolValue("repeat", false));
102     setCallSign(scFileNode->getStringValue("callsign"));
103     setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
104 }
105
106
107 bool FGAIAircraft::init() {
108     //refuel_node = fgGetNode("systems/refuel/contact", true);
109     return FGAIBase::init();
110 }
111
112
113 void FGAIAircraft::bind() {
114     FGAIBase::bind();
115
116     props->tie("controls/gear/gear-down",
117                SGRawValueMethods<FGAIAircraft,bool>(*this,
118                                               &FGAIAircraft::_getGearDown));
119     props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
120     props->setStringValue("callsign", callsign.c_str());
121     props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
122     props->setBoolValue("tanker",isTanker);
123 }
124
125
126 void FGAIAircraft::unbind() {
127     FGAIBase::unbind();
128
129     props->untie("controls/gear/gear-down");
130     props->untie("refuel/contact");
131 }
132
133
134 void FGAIAircraft::update(double dt) {
135     FGAIBase::update(dt);
136     Run(dt);
137     Transform();
138 }
139
140
141 void FGAIAircraft::setPerformance(const std::string& acclass) {
142     if (acclass == "light") {
143         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
144     } else if (acclass == "ww2_fighter") {
145         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
146     } else if (acclass == "jet_transport") {
147         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
148     } else if (acclass == "jet_fighter") {
149         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
150     } else if (acclass == "tanker") {
151         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
152         SetTanker(true);
153     } else {
154         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
155     }
156 }
157
158
159 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
160
161    performance = ps;
162 }
163
164
165 void FGAIAircraft::Run(double dt) {
166
167     FGAIAircraft::dt = dt;
168
169     if (fp) {
170         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
171         ProcessFlightPlan(dt, now);
172         if (now < fp->getStartTime()) {
173             // Do execute Ground elev for inactive aircraft, so they
174             // Are repositioned to the correct ground altitude when the user flies within visibility range.
175             if (no_roll) {
176                 Transform();       // make sure aip is initialized.
177                 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
178                 //getGroundElev(dt); // Need to do this twice.
179                 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
180                 doGroundAltitude();
181                 //cerr << " Actual altitude " << altitude << endl;
182                 // Transform();
183                 pos.setelev(altitude * SG_FEET_TO_METER);
184             }
185             return;
186         }
187     }
188
189     double turn_radius_ft;
190     double turn_circum_ft;
191     double speed_north_deg_sec;
192     double speed_east_deg_sec;
193     double dist_covered_ft;
194     double alpha;
195
196     // adjust speed
197     double speed_diff; //= tgt_speed - speed;
198     if (!no_roll) {
199         speed_diff = tgt_speed - speed;
200     } else {
201         speed_diff = groundTargetSpeed - speed;
202     }
203     if (fabs(speed_diff) > 0.2) {
204         if (speed_diff > 0.0)
205             speed += performance->accel * dt;
206         if (speed_diff < 0.0) {
207             if (no_roll) { // was (!no_roll) but seems more logical this way (ground brakes).
208                 speed -= performance->decel * dt * 3;
209             } else {
210                 speed -= performance->decel * dt;
211             }
212         }
213     }
214
215     // convert speed to degrees per second
216     speed_north_deg_sec = cos( hdg / SG_RADIANS_TO_DEGREES )
217                           * speed * 1.686 / ft_per_deg_lat;
218     speed_east_deg_sec  = sin( hdg / SG_RADIANS_TO_DEGREES )
219                           * speed * 1.686 / ft_per_deg_lon;
220
221     // set new position
222     pos.setlat( pos.lat() + speed_north_deg_sec * dt);
223     pos.setlon( pos.lon() + speed_east_deg_sec * dt);
224     //if (!(finite(pos.lat()) && finite(pos.lon())))
225     //  {
226     //    cerr << "Position is not finite" << endl;
227     //    cerr << "speed = " << speed << endl;
228     //    cerr << "dt" << dt << endl;
229     //    cerr << "heading " << hdg << endl;
230     //    cerr << "speed east " << speed_east_deg_sec << endl;
231     //    cerr << "speed nrth " << speed_north_deg_sec << endl;
232     //    cerr << "deg_lat    " << ft_per_deg_lat << endl;
233     //    cerr << "deg_lon    " << ft_per_deg_lon << endl;
234     //  }
235
236     // adjust heading based on current bank angle
237     if (roll == 0.0)
238         roll = 0.01;
239
240     if (roll != 0.0) {
241         // double turnConstant;
242         //if (no_roll)
243         //  turnConstant = 0.0088362;
244         //else
245         //  turnConstant = 0.088362;
246         // If on ground, calculate heading change directly
247         if (no_roll) {
248             double headingDiff = fabs(hdg-tgt_heading);
249
250             if (headingDiff > 180)
251                 headingDiff = fabs(headingDiff - 360);
252
253             groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
254             if (sign(groundTargetSpeed) != sign(tgt_speed))
255                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
256
257             if (headingDiff > 30.0) {
258                 headingChangeRate += dt * sign(roll); // invert if pushed backward
259                 // Print some debug statements to find out why aircraft may get stuck
260                 // forever turning
261                 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
262                 //    cerr << "Turning : " << trafficRef->getRegistration()
263                 //    cerr <<  " Speed = " << speed << " Heading " << hdg
264                 //         << " Target Heading " << tgt_heading
265                 //         << " Lead Distance " <<  fp->getLeadDistance()
266                 //         << " Distance to go "
267                 //         << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
268                 //         << "waypoint name " << fp->getCurrentWaypoint()->name
269                 //         << endl;
270                 //}
271                 if (headingChangeRate > 30)
272                     headingChangeRate = 30;
273                 else if (headingChangeRate < -30)
274                     headingChangeRate = -30;
275
276             } else {
277                 if (fabs(headingChangeRate) > headingDiff)
278                     headingChangeRate = headingDiff*sign(roll);
279                 else
280                     headingChangeRate += dt * sign(roll);
281             }
282             hdg += headingChangeRate * dt;
283             //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
284             //     << ". Target speed: " << groundTargetSpeed << ". heading change rate"
285             //     << headingChangeRate << endl;
286
287         } else {
288             if (fabs(speed) > 1.0) {
289                 turn_radius_ft = 0.088362 * speed * speed
290                         / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
291             } else {
292                 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
293             }
294             turn_circum_ft = SGD_2PI * turn_radius_ft;
295             dist_covered_ft = speed * 1.686 * dt;
296             alpha = dist_covered_ft / turn_circum_ft * 360.0;
297             hdg += alpha * sign(roll);
298         }
299         while ( hdg > 360.0 ) {
300             hdg -= 360.0;
301             spinCounter++;
302         }
303         while ( hdg < 0.0) {
304             hdg += 360.0;
305             spinCounter--;
306         }
307     }
308
309
310     // adjust target bank angle if heading lock engaged
311     if (hdg_lock) {
312         double bank_sense = 0.0;
313         double diff = fabs(hdg - tgt_heading);
314         if (diff > 180)
315             diff = fabs(diff - 360);
316
317         double sum = hdg + diff;
318         if (sum > 360.0)
319             sum -= 360.0;
320         if (fabs(sum - tgt_heading) < 1.0) {
321             bank_sense = 1.0;   // right turn
322         } else {
323             bank_sense = -1.0;  // left turn
324         }
325         if (diff < 30) {
326             tgt_roll = diff * bank_sense;
327         } else {
328             tgt_roll = 30.0 * bank_sense;
329         }
330         if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
331             tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
332             // The only way to resolve this is to make them slow down.
333             //if (tempReg.empty())
334             //  tempReg = trafficRef->getRegistration();
335             //if (trafficRef->getRegistration() == tempReg) {
336             //    cerr << trafficRef->getRegistration()
337             //         << " appears to be spinning: " << spinCounter << endl
338             //         << " speed          " << speed << endl
339             //         << " heading        " << hdg << endl
340             //         << " lead distance  " << fp->getLeadDistance() << endl
341             //         << " waypoint       " << fp->getCurrentWaypoint()->name
342             //         << " target heading " << tgt_heading << endl
343             //         << " lead in angle  " << fp->getLeadInAngle()<< endl
344             //         << " roll           " << roll << endl
345             //         << " target_roll    " << tgt_roll << endl;
346             //}
347         }
348     }
349
350     // adjust bank angle, use 9 degrees per second
351     double bank_diff = tgt_roll - roll;
352     if (fabs(bank_diff) > 0.2) {
353         if (bank_diff > 0.0)
354             roll += 9.0 * dt;
355
356         if (bank_diff < 0.0)
357             roll -= 9.0 * dt;
358         //while (roll > 180) roll -= 360;
359         //while (roll < 180) roll += 360;
360     }
361
362     // adjust altitude (meters) based on current vertical speed (fpm)
363     altitude += vs / 60.0 * dt;
364     pos.setelev(altitude * SG_FEET_TO_METER);
365     double altitude_ft = altitude;
366
367     // adjust target Altitude, based on ground elevation when on ground
368     if (no_roll) {
369         getGroundElev(dt);
370         doGroundAltitude();
371     } else {
372         // find target vertical speed if altitude lock engaged
373         if (alt_lock && use_perf_vs) {
374             if (altitude_ft < tgt_altitude) {
375                 tgt_vs = tgt_altitude - altitude_ft;
376                 if (tgt_vs > performance->climb_rate)
377                     tgt_vs = performance->climb_rate;
378             } else {
379                 tgt_vs = tgt_altitude - altitude_ft;
380                 if (tgt_vs  < (-performance->descent_rate))
381                     tgt_vs = -performance->descent_rate;
382             }
383         }
384
385         if (alt_lock && !use_perf_vs) {
386             double max_vs = 4*(tgt_altitude - altitude);
387             double min_vs = 100;
388             if (tgt_altitude < altitude)
389                 min_vs = -100.0;
390             if ((fabs(tgt_altitude - altitude) < 1500.0)
391                     && (fabs(max_vs) < fabs(tgt_vs)))
392                 tgt_vs = max_vs;
393
394             if (fabs(tgt_vs) < fabs(min_vs))
395                 tgt_vs = min_vs;
396         }
397     }
398     // adjust vertical speed
399     double vs_diff = tgt_vs - vs;
400     if (fabs(vs_diff) > 10.0) {
401         if (vs_diff > 0.0) {
402             vs += 900.0 * dt;
403
404             if (vs > tgt_vs)
405                 vs = tgt_vs;
406         } else {
407             vs -= 400.0 * dt;
408
409            if (vs < tgt_vs)
410                vs = tgt_vs;
411         }
412     }
413
414     // match pitch angle to vertical speed
415     if (vs > 0) {
416         pitch = vs * 0.005;
417     } else {
418         pitch = vs * 0.002;
419     }
420
421     //###########################//
422     // do calculations for radar //
423     //###########################//
424     double range_ft2 = UpdateRadar(manager);
425
426     //************************************//
427     // Tanker code                        //
428     //************************************//
429
430     if ( isTanker) {
431         if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
432                 && (elevation > 0.0) ) {
433             //refuel_node->setBoolValue(true);
434             contact = true;
435         } else {
436             //refuel_node->setBoolValue(false);
437             contact = false;
438         }
439     } else {
440         contact = false;
441     }
442 }
443
444
445 void FGAIAircraft::AccelTo(double speed) {
446     tgt_speed = speed;
447 }
448
449
450 void FGAIAircraft::PitchTo(double angle) {
451     tgt_pitch = angle;
452     alt_lock = false;
453 }
454
455
456 void FGAIAircraft::RollTo(double angle) {
457     tgt_roll = angle;
458     hdg_lock = false;
459 }
460
461
462 void FGAIAircraft::YawTo(double angle) {
463     tgt_yaw = angle;
464 }
465
466
467 void FGAIAircraft::ClimbTo(double altitude) {
468     tgt_altitude = altitude;
469     alt_lock = true;
470 }
471
472
473 void FGAIAircraft::TurnTo(double heading) {
474     tgt_heading = heading;
475     hdg_lock = true;
476 }
477
478
479 double FGAIAircraft::sign(double x) {
480     if ( x < 0.0 )
481         return -1.0;
482     else
483         return 1.0;
484 }
485
486
487 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
488     if (!flightplan.empty()) {
489         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
490         fp->setRepeat(repeat);
491         SetFlightPlan(fp);
492     }
493 }
494
495
496 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
497     delete fp;
498     fp = f;
499 }
500
501
502 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
503     bool eraseWaypoints;
504     if (trafficRef) {
505 //      FGAirport *arr;
506 //      FGAirport *dep;
507         eraseWaypoints = true;
508 //      cerr << trafficRef->getRegistration();
509 //      cerr << "Departure airport " << endl;
510 //      dep = trafficRef->getDepartureAirport();
511 //      if (dep)
512 //          cerr << dep->getId() << endl;
513 //      cerr << "Arrival   airport " << endl;
514 //      arr = trafficRef->getArrivalAirport();
515 //      if (arr)
516 //          cerr << arr->getId() <<endl << endl;;
517     } else
518         eraseWaypoints = false;
519
520     //cerr << "Processing Flightplan" << endl;
521     FGAIFlightPlan::waypoint* prev = 0; // the one behind you
522     FGAIFlightPlan::waypoint* curr = 0; // the one ahead
523     FGAIFlightPlan::waypoint* next = 0; // the next plus 1
524     prev = fp->getPreviousWaypoint();
525     curr = fp->getCurrentWaypoint();
526     next = fp->getNextWaypoint();
527     dt_count += dt;
528
529     if (!prev) {  //beginning of flightplan, do this initialization once
530         //setBank(0.0);
531         spinCounter = 0;
532         tempReg = "";
533         //prev_dist_to_go = HUGE;
534         //cerr << "Before increment " << curr-> name << endl;
535         fp->IncrementWaypoint(eraseWaypoints);
536         //prev = fp->getPreviousWaypoint(); //first waypoint
537         //curr = fp->getCurrentWaypoint();  //second waypoint
538         //next = fp->getNextWaypoint();     //third waypoint (might not exist!)
539         //cerr << "After increment " << prev-> name << endl;
540         if (!(fp->getNextWaypoint()) && trafficRef)
541             loadNextLeg();
542
543         //cerr << "After load " << prev-> name << endl;
544         prev = fp->getPreviousWaypoint(); //first waypoint
545         curr = fp->getCurrentWaypoint();  //second waypoint
546         next = fp->getNextWaypoint();     //third waypoint (might not exist!)
547         //cerr << "After load " << prev-> name << endl;
548         setLatitude(prev->latitude);
549         setLongitude(prev->longitude);
550         setSpeed(prev->speed);
551         setAltitude(prev->altitude);
552
553         if (prev->speed > 0.0)
554             setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
555         else
556             setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
557
558         // If next doesn't exist, as in incrementally created flightplans for
559         // AI/Trafficmanager created plans,
560         // Make sure lead distance is initialized otherwise
561         if (next)
562             fp->setLeadDistance(speed, hdg, curr, next);
563
564         if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
565             use_perf_vs = false;
566             tgt_vs = (curr->crossat - prev->altitude)
567                     / (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)
568                     / 6076.0 / prev->speed*60.0);
569             tgt_altitude = curr->crossat;
570         } else {
571             use_perf_vs = true;
572             tgt_altitude = prev->altitude;
573         }
574         alt_lock = hdg_lock = true;
575         no_roll = prev->on_ground;
576         if (no_roll) {
577             Transform();         // make sure aip is initialized.
578             getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
579             //getGroundElev(60.1); // Need to do this twice.
580             //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude << endl;
581             doGroundAltitude(); //(tgt_altitude);
582         }
583         prevSpeed = 0;
584         //cout << "First waypoint:  " << prev->name << endl;
585         //cout << "  Target speed:    " << tgt_speed << endl;
586         //cout << "  Target altitude: " << tgt_altitude << endl;
587         //cout << "  Target heading:  " << tgt_heading << endl << endl;
588         //cerr << "Done Flightplan init" << endl;
589         return;
590     } // end of initialization
591
592     // let's only process the flight plan every 100 ms.
593     if ((dt_count < 0.1) || (now < fp->getStartTime())) {
594         //cerr  << "done fp dt" << endl;
595         return;
596     } else {
597         dt_count = 0;
598     }
599     // check to see if we've reached the lead point for our next turn
600     double dist_to_go = fp->getDistanceToGo(pos.lat(), pos.lon(), curr);
601
602     //cerr << "2" << endl;
603     double lead_dist = fp->getLeadDistance();
604     //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
605     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
606
607     if (lead_dist < fabs(2*speed)) {
608         lead_dist = fabs(2*speed);  //don't skip over the waypoint
609         //cerr << "Extending lead distance to " << lead_dist << endl;
610     }
611 //  FGAirport * apt = trafficRef->getDepartureAirport();
612 //  if ((dist_to_go > prev_dist_to_go) && trafficRef && apt) {
613 //      if (apt->getId() == string("EHAM"))
614 //          cerr << "Alert: " << trafficRef->getRegistration() << " is moving away from waypoint " << curr->name  << endl
615 //               << "Target heading : " << tgt_heading << "act heading " << hdg << " Tgt speed : " << tgt_speed << endl
616 //               << "Lead distance : " << lead_dist  << endl
617 //               << "Distance to go: " << dist_to_go << endl;
618 //  }
619
620     prev_dist_to_go = dist_to_go;
621     //cerr << "2" << endl;
622     //if (no_roll)
623     //  lead_dist = 10.0;
624     //cout << "Leg : " << (fp->getLeg()-1) << ". dist_to_go: " << dist_to_go << ",  lead_dist: "
625     //     << lead_dist << ", tgt_speed " << tgt_speed << ", tgt_heading " << tgt_heading
626     //     << " speed " << speed << " hdg " << hdg << ". Altitude "  << altitude << " TAget alt :"
627     //     << tgt_altitude << endl;
628
629     if ( dist_to_go < lead_dist ) {
630         //prev_dist_to_go = HUGE;
631         // For traffic manager generated aircraft:
632         // check if the aircraft flies of of user range. And adjust the
633         // Current waypoint's elevation according to Terrain Elevation
634         if (curr->finished) {  //end of the flight plan
635             if (fp->getRepeat())
636                 fp->restart();
637             else
638                 setDie(true);
639
640             //cerr << "Done die end of fp" << endl;
641             return;
642         }
643
644         // we've reached the lead-point for the waypoint ahead
645         //cerr << "4" << endl;
646         //cerr << "Situation after lead point" << endl;
647         //cerr << "Prviious: " << prev->name << endl;
648         //cerr << "Current : " << curr->name << endl;
649         //cerr << "Next    : " << next->name << endl;
650         if (next) {
651             tgt_heading = fp->getBearing(curr, next);
652             spinCounter = 0;
653         }
654
655         fp->IncrementWaypoint(eraseWaypoints);
656         if (!(fp->getNextWaypoint()) && trafficRef)
657             loadNextLeg();
658
659         prev = fp->getPreviousWaypoint();
660         curr = fp->getCurrentWaypoint();
661         next = fp->getNextWaypoint();
662
663         // Now that we have incremented the waypoints, excute some traffic manager specific code
664         // based on the name of the waypoint we just passed.
665         if (trafficRef) {
666             double userLatitude  = fgGetDouble("/position/latitude-deg");
667             double userLongitude = fgGetDouble("/position/longitude-deg");
668             double course, distance;
669             SGWayPoint current (pos.lon(), pos.lat(), 0);
670             SGWayPoint user (userLongitude, userLatitude, 0);
671             user.CourseAndDistance(current, &course, &distance);
672             if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
673                 setDie(true);
674                 //cerr << "done fp die out of range" << endl;
675                 return;
676             }
677
678             FGAirport * dep = trafficRef->getDepartureAirport();
679             FGAirport * arr = trafficRef->getArrivalAirport();
680             // At parking the beginning of the airport
681             if (!( dep && arr)) {
682                 setDie(true);
683                 return;
684             }
685
686             //if ((dep->getId() == string("EHAM") || (arr->getId() == string("EHAM")))) {
687             //    cerr << trafficRef->getRegistration()
688             //         << " Enroute from " << dep->getId()
689             //         << " to "           << arr->getId()
690             //         << " just crossed " << prev->name
691             //         << " Assigned rwy     " << fp->getRunwayId()
692             //         << " " << fp->getRunway() << endl;
693             // }
694             //if ((dep->getId() == string("EHAM")) && (prev->name == "park2")) {
695             //    cerr << "Schiphol ground "
696             //         << trafficRef->getCallSign();
697             //    if (trafficRef->getHeavy())
698             //        cerr << "Heavy";
699             //    cerr << ", is type "
700             //         << trafficRef->getAircraft()
701             //         << " ready to go. IFR to "
702             //         << arr->getId() <<endl;
703             // }
704
705             if (prev->name == "park2")
706                 dep->getDynamics()->releaseParking(fp->getGate());
707
708             // Some debug messages, specific to testing the Logical networks.
709             // if ((arr->getId() == string("EHAM")) && (prev->name  == "Center")) {
710             //     cerr << "Schiphol ground "
711             //          << trafficRef->getRegistration() << " "
712             //          << trafficRef->getCallSign();
713             //     if (trafficRef->getHeavy())
714             //         cerr << "Heavy";
715             //     cerr << ", arriving from " << dep->getName() ;
716             //     cerr << " landed runway "
717             //          << fp->getRunway()
718             //          << " request taxi to gate "
719             //          << arr->getDynamics()->getParkingName(fp->getGate())
720             //          << endl;
721             // }
722             if (prev->name == "END")
723                 fp->setTime(trafficRef->getDepartureTime());
724             //cerr << "5" << endl;
725         }
726
727         if (next) {
728             //cerr << "Current waypoint" << curr->name << endl;
729             //cerr << "Next waypoint" << next->name << endl;
730             fp->setLeadDistance(speed, tgt_heading, curr, next);
731         }
732
733         //cerr << "5.1" << endl;
734         if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
735             tgt_altitude = prev->altitude;
736             if (curr->crossat > -1000.0) {
737                 //cerr << "5.1a" << endl;
738                 use_perf_vs = false;
739                 tgt_vs = (curr->crossat - altitude) / (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)
740                         / 6076.0 / speed*60.0);
741                 //cerr << "5.1b" << endl;
742                 tgt_altitude = curr->crossat;
743             } else {
744                 //cerr << "5.1c" << endl;
745                 use_perf_vs = true;
746                 //cerr << "5.1d" << endl;
747                 //cerr << "Setting target altitude : " <<tgt_altitude << endl;
748             }
749         }
750         //cerr << "6" << endl;
751         tgt_speed = prev->speed;
752         hdg_lock = alt_lock = true;
753         no_roll = prev->on_ground;
754         //cout << "Crossing waypoint: " << prev->name << endl;
755         //cout << "  Target speed:    " << tgt_speed << endl;
756         //cout << "  Target altitude: " << tgt_altitude << endl;
757         //cout << "  Target heading:  " << tgt_heading << endl << endl;
758
759     } else {
760         double calc_bearing = fp->getBearing(pos.lat(), pos.lon(), curr);
761         //cerr << "Bearing = " << calc_bearing << endl;
762         if (speed < 0) {
763             calc_bearing +=180;
764             if (calc_bearing > 360)
765                 calc_bearing -= 360;
766         }
767
768         if (finite(calc_bearing)) {
769             double hdg_error = calc_bearing - tgt_heading;
770             if (fabs(hdg_error) > 1.0) {
771                 TurnTo( calc_bearing );
772             }
773
774         } else {
775             cerr << "calc_bearing is not a finite number : "
776                  << "Speed " << speed
777                  << "pos : " << pos.lat() << ", " << pos.lon()
778                  << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
779             cerr << "waypoint name " << curr->name;
780             exit(1);  // FIXME
781         }
782
783         double speed_diff = speed - prevSpeed;
784         // Update the lead distance calculation if speed has changed sufficiently
785         // to prevent spinning (hopefully);
786         if (fabs(speed_diff) > 10) {
787             prevSpeed = speed;
788             fp->setLeadDistance(speed, tgt_heading, curr, next);
789         }
790
791         //cerr << "Done Processing FlightPlan"<< endl;
792     }
793 }
794
795
796 bool FGAIAircraft::_getGearDown() const {
797     return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
798             && (props->getFloatValue("velocities/airspeed-kt")
799             < performance->land_speed*1.25));
800 }
801
802
803 void FGAIAircraft::loadNextLeg() {
804     //delete fp;
805     //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
806
807     //FGAIModelEntity entity;
808     //entity.m_class = "jet_transport";
809     //entity.path = modelPath.c_str();
810     //entity.flightplan = "none";
811     //entity.latitude = _getLatitude();
812     //entity.longitude = _getLongitude();
813     //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
814     //entity.speed = 450; // HACK ALERT
815     //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
816     int leg;
817     if ((leg = fp->getLeg())  == 10) {
818         trafficRef->next();
819         leg = 1;
820         fp->setLeg(leg);
821         //cerr << "Resetting leg : " << leg << endl;
822     }
823     //leg++;
824     //fp->setLeg(leg);
825     //cerr << "Creating leg number : " << leg << endl;
826     FGAirport *dep = trafficRef->getDepartureAirport();
827     FGAirport *arr = trafficRef->getArrivalAirport();
828     if (!(dep && arr)) {
829         setDie(true);
830         //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
831         //if (dep)
832         //  cerr << "Departure " << dep->getId() << endl;
833         //if (arr)
834         //  cerr << "Arrival   " << arr->getId() << endl;
835
836     } else {
837         double cruiseAlt = trafficRef->getCruiseAlt() * 100;
838         //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
839
840         fp->create (dep,
841                     arr,
842                     leg,
843                     cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
844                     trafficRef->getSpeed(),
845                     _getLatitude(),
846                     _getLongitude(),
847                     false,
848                     trafficRef->getRadius(),
849                     trafficRef->getFlightType(),
850                     acType,
851                     company);
852         //prev = fp->getPreviousWaypoint();
853         //curr = fp->getCurrentWaypoint();
854         //next = fp->getNextWaypoint();
855         //cerr << "25" << endl;
856         //if (next)
857         //        {
858         //  //cerr << "Next waypoint" << next->name << endl;
859         //          fp->setLeadDistance(speed, tgt_heading, curr, next);
860         //        }
861         //cerr << "25.1" << endl;
862         //if (curr->crossat > -1000.0) {
863         //        //cerr << "25.1a" << endl;
864         //        use_perf_vs = false;
865         //
866         //        tgt_vs = (curr->crossat - altitude)/
867         //          (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
868         //        //cerr << "25.1b" << endl;
869         //        tgt_altitude = curr->crossat;
870         //} else {
871         //        //cerr << "25.1c" << endl;
872         //        use_perf_vs = true;
873         //        //cerr << "25.1d" << endl;
874         //        tgt_altitude = prev->altitude;
875         //        //cerr << "Setting target altitude : " <<tgt_altitude << endl;
876         // }
877         //cerr << "26" << endl;
878         //tgt_speed = prev->speed;
879         //hdg_lock = alt_lock = true;
880         //no_roll = prev->on_ground;
881     }
882     //else
883     //{
884     //delete entity.fp;
885     //entity.fp = new FGAIFlightPlan(&entity,
886     //                                 999,  // A hack
887     //                                 trafficRef->getDepartureTime(),
888     //                                 trafficRef->getDepartureAirport(),
889     //                                 trafficRef->getArrivalAirport(),
890     //                                 false,
891     //                                 acType,
892     //                                 company);
893     //SetFlightPlan(entity.fp);
894 }
895
896
897 // Note: This code is copied from David Luff's AILocalTraffic
898 // Warning - ground elev determination is CPU intensive
899 // Either this function or the logic of how often it is called
900 // will almost certainly change.
901
902 void FGAIAircraft::getGroundElev(double dt) {
903     dt_elev_count += dt;
904
905     // Update minimally every three secs, but add some randomness
906     // to prevent all IA objects doing this in synchrony
907     if (dt_elev_count < (3.0) + (rand() % 10))
908         return;
909     else
910        dt_elev_count = 0;
911
912     // It would be nice if we could set the correct tile center here in order to get a correct
913     // answer with one call to the function, but what I tried in the two commented-out lines
914     // below only intermittently worked, and I haven't quite groked why yet.
915     //SGBucket buck(pos.lon(), pos.lat());
916     //aip.getSGLocation()->set_tile_center(Point3D(buck.get_center_lon(), buck.get_center_lat(), 0.0));
917
918     // Only do the proper hitlist stuff if we are within visible range of the viewer.
919     if (!invisible) {
920         double visibility_meters = fgGetDouble("/environment/visibility-m");
921
922         FGViewer* vw = globals->get_current_view();
923         double course, distance;
924
925         //Point3D currView(vw->getLongitude_deg(),
926         //                 vw->getLatitude_deg(), 0.0);
927         SGWayPoint current (pos.lon(), pos.lat(), 0);
928         SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
929         view.CourseAndDistance(current, &course, &distance);
930         if(distance > visibility_meters) {
931             //aip.getSGLocation()->set_cur_elev_m(aptElev);
932             return;
933         }
934
935         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
936         double range = 500.0;
937         if (!globals->get_tile_mgr()->scenery_available(pos.lat(), pos.lon(), range)) {
938             // Try to shedule tiles for that position.
939             globals->get_tile_mgr()->update( aip.getSGLocation(), range );
940         }
941
942         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
943         double alt;
944         if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(), 20000.0, alt))
945             tgt_altitude = alt * SG_METER_TO_FEET;
946
947         //cerr << "Target altitude : " << tgt_altitude << endl;
948         // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
949         //                                            20000.0, alt))
950         //    tgt_altitude = alt * SG_METER_TO_FEET;
951         //cerr << "Target altitude : " << tgt_altitude << endl;
952     }
953 }
954
955
956 void FGAIAircraft::setCallSign(const string& s) {
957     callsign = s;
958 }
959
960
961 void FGAIAircraft::setTACANChannelID(const string& id) {
962     TACAN_channel_id = id;
963 }
964
965
966 void FGAIAircraft::doGroundAltitude() {
967    if (fabs(altitude - (tgt_altitude+groundOffset)) > 1000.0)
968        altitude = (tgt_altitude + groundOffset);
969    else
970       altitude += 0.1 * ((tgt_altitude+groundOffset) - altitude);
971 }
972