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