]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
Ground network distance tracking code. AIAircraft taxiing at airports
[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     // ufo (extreme accel/decel)
63     {30.0, 30.0, 6000.0, 6000.0, 150.0, 300.0, 430.0, 300.0, 130.0}
64 };
65
66
67 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
68     FGAIBase(otAircraft)
69 {
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     isTanker = false;
83
84     // set heading and altitude locks
85     hdg_lock = false;
86     alt_lock = false;
87     roll = 0;
88     headingChangeRate = 0.0;
89 }
90
91
92 FGAIAircraft::~FGAIAircraft() {
93     //delete fp;
94 }
95
96
97 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
98     if (!scFileNode)
99         return;
100
101     FGAIBase::readFromScenario(scFileNode);
102
103     setPerformance(scFileNode->getStringValue("class", "jet_transport"));
104     setFlightPlan(scFileNode->getStringValue("flightplan"),
105                   scFileNode->getBoolValue("repeat", false));
106     setCallSign(scFileNode->getStringValue("callsign"));
107     setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID"));
108 }
109
110
111 bool FGAIAircraft::init() {
112     //refuel_node = fgGetNode("systems/refuel/contact", true);
113     return FGAIBase::init();
114 }
115
116
117 void FGAIAircraft::bind() {
118     FGAIBase::bind();
119
120     props->tie("controls/gear/gear-down",
121                SGRawValueMethods<FGAIAircraft,bool>(*this,
122                                               &FGAIAircraft::_getGearDown));
123     props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
124     props->setStringValue("callsign", callsign.c_str());
125     props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
126     props->setBoolValue("tanker",isTanker);
127 }
128
129
130 void FGAIAircraft::unbind() {
131     FGAIBase::unbind();
132
133     props->untie("controls/gear/gear-down");
134     props->untie("refuel/contact");
135 }
136
137
138 void FGAIAircraft::update(double dt) {
139     FGAIBase::update(dt);
140     Run(dt);
141     Transform();
142 }
143
144
145 void FGAIAircraft::setPerformance(const std::string& acclass) {
146     if (acclass == "light") {
147         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
148     } else if (acclass == "ww2_fighter") {
149         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
150     } else if (acclass == "jet_transport") {
151         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
152     } else if (acclass == "jet_fighter") {
153         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
154     } else if (acclass == "tanker") {
155         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
156         SetTanker(true);
157     } else if (acclass == "ufo") {
158         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::UFO]);
159     } else {
160         SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
161     }
162 }
163
164
165 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
166
167    performance = ps;
168 }
169
170
171 void FGAIAircraft::Run(double dt) {
172
173     FGAIAircraft::dt = dt;
174     
175     if (fp) {
176         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
177         ProcessFlightPlan(dt, now);
178         if (now < fp->getStartTime()) {
179             // Do execute Ground elev for inactive aircraft, so they
180             // Are repositioned to the correct ground altitude when the user flies within visibility range.
181             if (no_roll) {
182                 Transform();       // make sure aip is initialized.
183                 getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
184                 //getGroundElev(dt); // Need to do this twice.
185                 //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
186                 doGroundAltitude();
187                 //cerr << " Actual altitude " << altitude << endl;
188                 // Transform();
189                 pos.setElevationFt(altitude_ft);
190             }
191             return;
192         }
193     } else {
194         // no flight plan, update target heading, speed, and altitude
195         // from control properties.  These default to the initial
196         // settings in the config file, but can be changed "on the
197         // fly".
198         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
199         if ( lat_mode == "roll" ) {
200             double angle
201                 = props->getDoubleValue("controls/flight/target-roll" );
202             RollTo( angle );
203         } else {
204              double angle
205                 = props->getDoubleValue("controls/flight/target-hdg" );
206             TurnTo( angle );
207         }
208
209         string lon_mode
210             = props->getStringValue("controls/flight/longitude-mode");
211         if ( lon_mode == "alt" ) {
212             double alt = props->getDoubleValue("controls/flight/target-alt" );
213             ClimbTo( alt );
214         } else {
215             double angle
216                 = props->getDoubleValue("controls/flight/target-pitch" );
217             PitchTo( angle );
218         }
219
220         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
221     }
222     if (controller)
223       {
224         controller->update(getID(), 
225                            pos.getLatitudeDeg(), 
226                            pos.getLongitudeDeg(),
227                            hdg,
228                            speed,
229                            altitude_ft);
230         //if (controller->hasInstruction(getID()))
231         //  {
232             processATC(controller->getInstruction(getID()));
233             //  }
234       }
235       
236     double turn_radius_ft;
237     double turn_circum_ft;
238     double speed_north_deg_sec;
239     double speed_east_deg_sec;
240     double dist_covered_ft;
241     double alpha;
242
243     // adjust speed
244     double speed_diff; //= tgt_speed - speed;
245     if (!no_roll) {
246         speed_diff = tgt_speed - speed;
247     } else {
248         speed_diff = groundTargetSpeed - speed;
249     }
250
251     if (speed_diff > 0.0) {
252         speed += performance->accel * dt;
253         if (no_roll) { // apply overshoot correction
254           if ( speed > groundTargetSpeed ) speed = groundTargetSpeed;
255         }else {
256           if ( speed > tgt_speed ) speed = tgt_speed;
257         }
258     } else if (speed_diff < 0.0) {
259         if (no_roll) {
260             // on ground (aircraft can't roll)
261             // deceleration performance is better due to wheel brakes.
262             speed -= performance->decel * dt * 3;
263         } else {
264             speed -= performance->decel * dt;
265         }
266         if (no_roll) { // apply overshoot correction
267         if (speed < groundTargetSpeed ) speed = groundTargetSpeed;
268         } else { 
269           if ( speed < tgt_speed ) speed = tgt_speed;
270         }
271     }
272     
273     
274     // convert speed to degrees per second
275     speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
276                           * speed * 1.686 / ft_per_deg_lat;
277     speed_east_deg_sec  = sin( hdg * SGD_DEGREES_TO_RADIANS )
278                           * speed * 1.686 / ft_per_deg_lon;
279
280     // set new position
281     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
282     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt); 
283
284     /* printf("%.7f %0.4f %.7f %.5f %.7f %.7f %.8f %.8f %.9f %.9f\n",
285            dt, hdg, speed, ft_per_deg_lat,
286            cos( hdg * SGD_DEGREES_TO_RADIANS ),
287            speed * 1.686 / ft_per_deg_lat,
288            speed_north_deg_sec, speed_east_deg_sec,
289            pos.getLatitudeDeg(), pos.getLongitudeDeg()); */
290
291     //if (!(finite(pos.lat()) && finite(pos.lon())))
292     //  {
293     //    cerr << "Position is not finite" << endl;
294     //    cerr << "speed = " << speed << endl;
295     //    cerr << "dt" << dt << endl;
296     //    cerr << "heading " << hdg << endl;
297     //    cerr << "speed east " << speed_east_deg_sec << endl;
298     //    cerr << "speed nrth " << speed_north_deg_sec << endl;
299     //    cerr << "deg_lat    " << ft_per_deg_lat << endl;
300     //    cerr << "deg_lon    " << ft_per_deg_lon << endl;
301     //  }
302
303     // adjust heading based on current bank angle
304     if (roll == 0.0)
305         roll = 0.01;
306
307     if (roll != 0.0) {
308         // double turnConstant;
309         //if (no_roll)
310         //  turnConstant = 0.0088362;
311         //else
312         //  turnConstant = 0.088362;
313         // If on ground, calculate heading change directly
314         if (no_roll) {
315             double headingDiff = fabs(hdg-tgt_heading);
316
317             if (headingDiff > 180)
318                 headingDiff = fabs(headingDiff - 360);
319
320             groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
321             if (sign(groundTargetSpeed) != sign(tgt_speed))
322                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
323
324             if (headingDiff > 30.0) {
325                 headingChangeRate += dt * sign(roll); // invert if pushed backward
326                 // Print some debug statements to find out why aircraft may get stuck
327                 // forever turning
328                 //if (trafficRef->getDepartureAirport()->getId() == string("EHAM")) {
329                 //    cerr << "Turning : " << trafficRef->getRegistration()
330                 //    cerr <<  " Speed = " << speed << " Heading " << hdg
331                 //         << " Target Heading " << tgt_heading
332                 //         << " Lead Distance " <<  fp->getLeadDistance()
333                 //         << " Distance to go "
334                 //         << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
335                 //         << "waypoint name " << fp->getCurrentWaypoint()->name
336                 //         << endl;
337                 //}
338                 if (headingChangeRate > 30)
339                     headingChangeRate = 30;
340                 else if (headingChangeRate < -30)
341                     headingChangeRate = -30;
342
343             } else {
344                 if (fabs(headingChangeRate) > headingDiff)
345                     headingChangeRate = headingDiff*sign(roll);
346                 else
347                     headingChangeRate += dt * sign(roll);
348             }
349             hdg += headingChangeRate * dt;
350             //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading
351             //     << ". Target speed: " << groundTargetSpeed << ". heading change rate"
352             //     << headingChangeRate << endl;
353
354         } else {
355             if (fabs(speed) > 1.0) {
356                 turn_radius_ft = 0.088362 * speed * speed
357                         / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
358             } else {
359                 turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
360             }
361             turn_circum_ft = SGD_2PI * turn_radius_ft;
362             dist_covered_ft = speed * 1.686 * dt;
363             alpha = dist_covered_ft / turn_circum_ft * 360.0;
364             hdg += alpha * sign(roll);
365         }
366         while ( hdg > 360.0 ) {
367             hdg -= 360.0;
368             spinCounter++;
369         }
370         while ( hdg < 0.0) {
371             hdg += 360.0;
372             spinCounter--;
373         }
374     }
375
376
377     // adjust target bank angle if heading lock engaged
378     if (hdg_lock) {
379         double bank_sense = 0.0;
380         double diff = fabs(hdg - tgt_heading);
381         if (diff > 180)
382             diff = fabs(diff - 360);
383
384         double sum = hdg + diff;
385         if (sum > 360.0)
386             sum -= 360.0;
387         if (fabs(sum - tgt_heading) < 1.0) {
388             bank_sense = 1.0;   // right turn
389         } else {
390             bank_sense = -1.0;  // left turn
391         }
392         if (diff < 30) {
393             tgt_roll = diff * bank_sense;
394         } else {
395             tgt_roll = 30.0 * bank_sense;
396         }
397         if ((fabs((double) spinCounter) > 1) && (diff > 30)) {
398             tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
399             // The only way to resolve this is to make them slow down.
400             //if (tempReg.empty())
401             //  tempReg = trafficRef->getRegistration();
402             //if (trafficRef->getRegistration() == tempReg) {
403             //    cerr << trafficRef->getRegistration()
404             //         << " appears to be spinning: " << spinCounter << endl
405             //         << " speed          " << speed << endl
406             //         << " heading        " << hdg << endl
407             //         << " lead distance  " << fp->getLeadDistance() << endl
408             //         << " waypoint       " << fp->getCurrentWaypoint()->name
409             //         << " target heading " << tgt_heading << endl
410             //         << " lead in angle  " << fp->getLeadInAngle()<< endl
411             //         << " roll           " << roll << endl
412             //         << " target_roll    " << tgt_roll << endl;
413             //}
414         }
415     }
416
417     // adjust bank angle, use 9 degrees per second
418     double bank_diff = tgt_roll - roll;
419     if (fabs(bank_diff) > 0.2) {
420         if (bank_diff > 0.0)
421             roll += 9.0 * dt;
422
423         if (bank_diff < 0.0)
424             roll -= 9.0 * dt;
425         //while (roll > 180) roll -= 360;
426         //while (roll < 180) roll += 360;
427     }
428
429     // adjust altitude (meters) based on current vertical speed (fpm)
430     altitude_ft += vs / 60.0 * dt;
431     pos.setElevationFt(altitude_ft);  
432
433     // adjust target Altitude, based on ground elevation when on ground
434     if (no_roll) {
435         getGroundElev(dt);
436         doGroundAltitude();
437     } else {
438         // find target vertical speed if altitude lock engaged
439         if (alt_lock && use_perf_vs) {
440             if (altitude_ft < tgt_altitude_ft) {
441                 tgt_vs = tgt_altitude_ft - altitude_ft;
442                 if (tgt_vs > performance->climb_rate)
443                     tgt_vs = performance->climb_rate;
444             } else {
445                 tgt_vs = tgt_altitude_ft - altitude_ft;
446                 if (tgt_vs  < (-performance->descent_rate))
447                     tgt_vs = -performance->descent_rate;
448             }
449         }
450
451         if (alt_lock && !use_perf_vs) {
452             double max_vs = 4*(tgt_altitude_ft - altitude_ft);
453             double min_vs = 100;
454             if (tgt_altitude_ft < altitude_ft)
455                 min_vs = -100.0;
456             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
457                     && (fabs(max_vs) < fabs(tgt_vs)))
458                 tgt_vs = max_vs;
459
460             if (fabs(tgt_vs) < fabs(min_vs))
461                 tgt_vs = min_vs;
462         }
463     }
464     // adjust vertical speed
465     double vs_diff = tgt_vs - vs;
466     if (fabs(vs_diff) > 10.0) {
467         if (vs_diff > 0.0) {
468             vs += (performance->climb_rate / 3.0) * dt;
469
470             if (vs > tgt_vs)
471                 vs = tgt_vs;
472         } else {
473             vs -= (performance->descent_rate / 3.0) * dt;
474
475            if (vs < tgt_vs)
476                vs = tgt_vs;
477         }
478     }
479
480     // match pitch angle to vertical speed
481     if (vs > 0) {
482         pitch = vs * 0.005;
483     } else {
484         pitch = vs * 0.002;
485     }
486
487     //###########################//
488     // do calculations for radar //
489     //###########################//
490     double range_ft2 = UpdateRadar(manager);
491
492     //************************************//
493     // Tanker code                        //
494     //************************************//
495
496     if ( isTanker) {
497         if ( (range_ft2 < 250.0 * 250.0) && (y_shift > 0.0)
498                 && (elevation > 0.0) ) {
499             //refuel_node->setBoolValue(true);
500             contact = true;
501         } else {
502             //refuel_node->setBoolValue(false);
503             contact = false;
504         }
505     } else {
506         contact = false;
507     }
508 }
509
510
511 void FGAIAircraft::AccelTo(double speed) {
512     tgt_speed = speed;
513 }
514
515
516 void FGAIAircraft::PitchTo(double angle) {
517     tgt_pitch = angle;
518     alt_lock = false;
519 }
520
521
522 void FGAIAircraft::RollTo(double angle) {
523     tgt_roll = angle;
524     hdg_lock = false;
525 }
526
527
528 void FGAIAircraft::YawTo(double angle) {
529     tgt_yaw = angle;
530 }
531
532
533 void FGAIAircraft::ClimbTo(double alt_ft ) {
534     tgt_altitude_ft = alt_ft;
535     alt_lock = true;
536 }
537
538
539 void FGAIAircraft::TurnTo(double heading) {
540     tgt_heading = heading;
541     hdg_lock = true;
542 }
543
544
545 double FGAIAircraft::sign(double x) {
546     if ( x < 0.0 )
547         return -1.0;
548     else
549         return 1.0;
550 }
551
552
553 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
554     if (!flightplan.empty()) {
555         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
556         fp->setRepeat(repeat);
557         SetFlightPlan(fp);
558     }
559 }
560
561
562 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
563     delete fp;
564     fp = f;
565 }
566
567
568 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
569     bool eraseWaypoints;
570     if (trafficRef) {
571         eraseWaypoints = true;
572     } else
573         eraseWaypoints = false;
574
575  
576     FGAIFlightPlan::waypoint* prev = 0; // the one behind you
577     FGAIFlightPlan::waypoint* curr = 0; // the one ahead
578     FGAIFlightPlan::waypoint* next = 0; // the next plus 1
579     prev = fp->getPreviousWaypoint();
580     curr = fp->getCurrentWaypoint();
581     next = fp->getNextWaypoint();
582     dt_count += dt;
583
584     ///////////////////////////////////////////////////////////////////////////
585     // Initialize the flightplan
586     //////////////////////////////////////////////////////////////////////////
587     if (!prev) {
588
589       spinCounter = 0;
590       tempReg = "";
591       fp->IncrementWaypoint(eraseWaypoints);
592       if (!(fp->getNextWaypoint()) && trafficRef)
593         loadNextLeg();
594       
595       prev = fp->getPreviousWaypoint(); //first waypoint
596       curr = fp->getCurrentWaypoint();  //second waypoint
597       next = fp->getNextWaypoint();     //third waypoint (might not exist!)
598       
599       setLatitude(prev->latitude);
600       setLongitude(prev->longitude);
601       setSpeed(prev->speed);
602       setAltitude(prev->altitude);
603       
604       if (prev->speed > 0.0)
605         setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
606       else
607         setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
608       
609       // If next doesn't exist, as in incrementally created flightplans for
610       // AI/Trafficmanager created plans,
611       // Make sure lead distance is initialized otherwise
612       if (next)
613         fp->setLeadDistance(speed, hdg, curr, next);
614       
615       if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
616         use_perf_vs = false;
617         tgt_vs = (curr->crossat - prev->altitude)
618           / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
619              / 6076.0 / prev->speed*60.0);
620         tgt_altitude_ft = curr->crossat;
621       } else {
622         use_perf_vs = true;
623         tgt_altitude_ft = prev->altitude;
624       }
625       alt_lock = hdg_lock = true;
626       no_roll = prev->on_ground;
627       if (no_roll) {
628         Transform();         // make sure aip is initialized.
629         getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
630         doGroundAltitude(); 
631       }
632       // Make sure to announce the aircraft's position 
633       announcePositionToController();
634       prevSpeed = 0;
635       return;
636     } // end of initialization
637     
638     ///////////////////////////////////////////////////////////////////////////
639     // Check Execution time (currently once every 100 ms
640     ///////////////////////////////////////////////////////////////////////////
641     if ((dt_count < 0.1) || (now < fp->getStartTime())) {
642       //cerr  << "done fp dt" << endl;
643       return;
644     } else {
645       dt_count = 0;
646     }
647     // check to see if we've reached the lead point for our next turn
648     double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
649
650     //cerr << "2" << endl;
651     double lead_dist = fp->getLeadDistance();
652     //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
653     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
654
655     if (lead_dist < fabs(2*speed)) {
656         lead_dist = fabs(2*speed);  //don't skip over the waypoint
657         //cerr << "Extending lead distance to " << lead_dist << endl;
658     }
659
660     //prev_dist_to_go = dist_to_go;
661
662     if ( dist_to_go < lead_dist ) {
663         if (curr->finished) {  //end of the flight plan
664             if (fp->getRepeat())
665                 fp->restart();
666             else
667                 setDie(true);
668             return;
669         }
670
671         if (next) {
672             tgt_heading = fp->getBearing(curr, next);
673             spinCounter = 0;
674         }
675
676         fp->IncrementWaypoint(eraseWaypoints);
677         if (!(fp->getNextWaypoint()) && trafficRef)
678             loadNextLeg();
679
680         prev = fp->getPreviousWaypoint();
681         curr = fp->getCurrentWaypoint();
682         next = fp->getNextWaypoint();
683
684         // Now that we have incremented the waypoints, excute some traffic manager specific code
685         if (trafficRef) {
686             double userLatitude  = fgGetDouble("/position/latitude-deg");
687             double userLongitude = fgGetDouble("/position/longitude-deg");
688             double course, distance;
689             SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
690             SGWayPoint user (userLongitude, userLatitude, 0);
691             user.CourseAndDistance(current, &course, &distance);
692             if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST) {
693                 setDie(true);
694                 return;
695             }
696
697             FGAirport * dep = trafficRef->getDepartureAirport();
698             FGAirport * arr = trafficRef->getArrivalAirport();
699             if (!( dep && arr)) {
700                 setDie(true);
701                 return;
702             }
703             // This waypoint marks the fact that the aircraft has passed the initial taxi
704             // departure waypoint, so it can release the parking.
705             if (prev->name == "park2")
706                 dep->getDynamics()->releaseParking(fp->getGate());
707             // This is the last taxi waypoint, and marks the the end of the flight plan
708             // so, the schedule should update and wait for the next departure time. 
709             if (prev->name == "END") {
710               // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
711               // delayed aircraft. 
712               time_t nextDeparture = trafficRef->getDepartureTime();
713               if (nextDeparture < (now+1200)) {
714                 nextDeparture = now + 1200; 
715               }
716               fp->setTime(trafficRef->getDepartureTime());
717             }
718             announcePositionToController();
719             
720         }
721
722         if (next) {
723             //cerr << "Current waypoint" << curr->name << endl;
724             //cerr << "Next waypoint" << next->name << endl;
725             fp->setLeadDistance(speed, tgt_heading, curr, next);
726         }
727
728         //cerr << "5.1" << endl;
729         if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
730             tgt_altitude_ft = prev->altitude;
731             if (curr->crossat > -1000.0) {
732                 //cerr << "5.1a" << endl;
733                 use_perf_vs = false;
734                 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
735                         / 6076.0 / speed*60.0);
736                 //cerr << "5.1b" << endl;
737                 tgt_altitude_ft = curr->crossat;
738             } else {
739                 //cerr << "5.1c" << endl;
740                 use_perf_vs = true;
741                 //cerr << "5.1d" << endl;
742                 //cerr << "Setting target altitude : " <<tgt_altitude_ft << endl;
743             }
744         }
745         //cerr << "6" << endl;
746         tgt_speed = prev->speed;
747         hdg_lock = alt_lock = true;
748         no_roll = prev->on_ground;
749         //cout << "Crossing waypoint: " << prev->name << endl;
750         //cout << "  Target speed:    " << tgt_speed << endl;
751         //cout << "  Target altitude: " << tgt_altitude_ft << endl;
752         //cout << "  Target heading:  " << tgt_heading << endl << endl;
753
754     } else {
755         double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
756         //cerr << "Bearing = " << calc_bearing << endl;
757         if (speed < 0) {
758             calc_bearing +=180;
759             if (calc_bearing > 360)
760                 calc_bearing -= 360;
761         }
762
763         if (finite(calc_bearing)) {
764             double hdg_error = calc_bearing - tgt_heading;
765             if (fabs(hdg_error) > 1.0) {
766                 TurnTo( calc_bearing );
767             }
768
769         } else {
770             cerr << "calc_bearing is not a finite number : "
771                  << "Speed " << speed
772                  << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
773                  << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
774             cerr << "waypoint name " << curr->name;
775             exit(1);  // FIXME
776         }
777
778         double speed_diff = speed - prevSpeed;
779         // Update the lead distance calculation if speed has changed sufficiently
780         // to prevent spinning (hopefully);
781         if (fabs(speed_diff) > 10) {
782             prevSpeed = speed;
783             fp->setLeadDistance(speed, tgt_heading, curr, next);
784         }
785
786         //cerr << "Done Processing FlightPlan"<< endl;
787     }
788 }
789
790 void FGAIAircraft::initializeFlightPlan() 
791 {
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_ft)/
867         //          (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
868         //        //cerr << "25.1b" << endl;
869         //        tgt_altitude_ft = curr->crossat;
870         //} else {
871         //        //cerr << "25.1c" << endl;
872         //        use_perf_vs = true;
873         //        //cerr << "25.1d" << endl;
874         //        tgt_altitude_ft = prev->altitude;
875         //        //cerr << "Setting target altitude : " <<tgt_altitude_ft << 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     // Only do the proper hitlist stuff if we are within visible range of the viewer.
913     if (!invisible) {
914         double visibility_meters = fgGetDouble("/environment/visibility-m");
915
916         FGViewer* vw = globals->get_current_view();
917         double course, distance;
918
919         SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
920         SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
921         view.CourseAndDistance(current, &course, &distance);
922         if(distance > visibility_meters) {
923             //aip.getSGLocation()->set_cur_elev_m(aptElev);
924             return;
925         }
926
927         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
928         double range = 500.0;
929         if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
930             // Try to shedule tiles for that position.
931             globals->get_tile_mgr()->update( aip.getSGLocation(), range );
932         }
933
934         // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
935         double alt;
936         if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
937             tgt_altitude_ft = alt * SG_METER_TO_FEET;
938
939         //cerr << "Target altitude : " << tgt_altitude_ft << endl;
940         // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
941         //                                            20000.0, alt))
942         //    tgt_altitude_ft = alt * SG_METER_TO_FEET;
943         //cerr << "Target altitude : " << tgt_altitude_ft << endl;
944     }
945 }
946
947
948 void FGAIAircraft::setCallSign(const string& s) {
949     callsign = s;
950 }
951
952
953 void FGAIAircraft::setTACANChannelID(const string& id) {
954     TACAN_channel_id = id;
955 }
956
957
958 void FGAIAircraft::doGroundAltitude() {
959    if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
960        altitude_ft = (tgt_altitude_ft + groundOffset);
961    else
962       altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
963 }
964
965
966 void FGAIAircraft::announcePositionToController() 
967 {
968   if (trafficRef) {
969     //FGTaxiRoute *taxiRoute = fp->getTaxiRoute();
970     
971     int leg = fp->getLeg();
972     
973     // For starters, I'll only do this for departure and arrival taxi. The mechanism
974     // could be extended to include any controller however. 
975     //int node, currentTaxiSegment;
976     //if (taxiRoute->next(&node, &currentTaxiSegment)) {
977     if (fp->getCurrentWaypoint()->routeIndex != 0) {
978       //char buffer[10];
979       //snprintf (buffer, 10, "%d", node);
980       switch (leg) {
981       case 3:
982         cerr << trafficRef->getRegistration() 
983              << " taxiing to runway at segment " 
984              << fp->getCurrentWaypoint()->routeIndex
985              << endl;
986         //cerr << "Match check between taxisegment and taxiroute : " << node << " " 
987         //     << fp->getCurrentWaypoint()->name << endl;
988         if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
989           controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
990         break;
991       case 9:
992         cerr << trafficRef->getRegistration() 
993              << " taxiing to parking at segment " 
994              << fp->getCurrentWaypoint()->routeIndex
995              << endl;
996         if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
997           controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
998         break;
999       default: 
1000         controller = 0;
1001         break;
1002       }
1003     } else {
1004       //fp->deleteTaxiRoute();
1005       controller = 0;
1006     }
1007     if ((controller != prevController) && (prevController != 0)) {
1008       prevController->signOff(getID());
1009       cerr << trafficRef->getRegistration() 
1010            << " signing off " << endl;
1011     }
1012     prevController = controller;
1013     if (controller) {
1014       controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
1015                                    _getLatitude(), _getLongitude(), hdg, speed, altitude_ft, 
1016                                    trafficRef->getRadius());
1017     }
1018   }
1019 }
1020
1021
1022 void FGAIAircraft::processATC(FGATCInstruction instruction)
1023 {
1024   //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
1025   if (instruction.getHoldPattern   ()) {
1026   }
1027   if (instruction.getHoldPosition  ()) {
1028   }
1029   if (instruction.getChangeSpeed   ()) {
1030     AccelTo(instruction.getSpeed());
1031   }else {
1032     if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
1033   }
1034   if (instruction.getChangeHeading ()) { 
1035     hdg_lock = false;
1036     TurnTo(instruction.getHeading());
1037   } else {
1038     if (fp) {hdg_lock = true;}
1039   }
1040   if (instruction.getChangeAltitude()) { 
1041   }
1042
1043 }