]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlanCreate.cxx
Move some code from the header file to the source file.
[flightgear.git] / src / AIModel / AIFlightPlanCreate.cxx
1 /******************************************************************************
2  * AIFlightPlanCreate.cxx
3  * Written by Durk Talsma, started May, 2004.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  *
19  **************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25
26 #include "AIFlightPlan.hxx"
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/props/props.hxx>
29 #include <simgear/props/props_io.hxx>
30
31 #include <Airports/simple.hxx>
32 #include <Airports/runways.hxx>
33 #include <Airports/dynamics.hxx>
34 #include "AIAircraft.hxx"
35 #include "performancedata.hxx"
36
37 #include <Environment/environment_mgr.hxx>
38 #include <Environment/environment.hxx>
39 #include <FDM/LaRCsim/basic_aero.h>
40
41
42 /* FGAIFlightPlan::create()
43  * dynamically create a flight plan for AI traffic, based on data provided by the
44  * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10) 
45  *
46  * This is the top-level function, and the only one that is publicly available.
47  *
48  */
49
50
51 // Check lat/lon values during initialization;
52 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
53                             FGAirport * arr, int legNr, double alt,
54                             double speed, double latitude,
55                             double longitude, bool firstFlight,
56                             double radius, const string & fltType,
57                             const string & aircraftType,
58                             const string & airline, double distance)
59 {
60     bool retVal = true;
61     int currWpt = wpt_iterator - waypoints.begin();
62     switch (legNr) {
63     case 1:
64         retVal = createPushBack(ac, firstFlight, dep, latitude, longitude,
65                                 radius, fltType, aircraftType, airline);
66         // Pregenerate the 
67         if (retVal) {
68             waypoints.back()->setName( waypoints.back()->getName() + string("legend")); 
69             retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
70         }
71         break;
72     case 2:
73         retVal =  createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
74                           aircraftType, airline);
75         break;
76     case 3:
77         retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
78         break;
79     case 4:
80         retVal = createClimb(ac, firstFlight, dep, speed, alt, fltType);
81         break;
82     case 5:
83         retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
84                      alt, fltType);
85         break;
86     case 6:
87         retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
88                       distance);
89         break;
90     case 7:
91         retVal = createLanding(ac, arr, fltType);
92         break;
93     case 8:
94         retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
95         break;
96     case 9:
97         retVal = createParking(ac, arr, radius);
98         break;
99     default:
100         //exit(1);
101         SG_LOG(SG_INPUT, SG_ALERT,
102                "AIFlightPlan::create() attempting to create unknown leg"
103                " this is probably an internal program error");
104     }
105     wpt_iterator = waypoints.begin() + currWpt;
106     //don't  increment leg right away, but only once we pass the actual last waypoint that was created.
107     // to do so, mark the last waypoint with a special status flag
108    if (retVal) {
109         waypoints.back()->setName( waypoints.back()->getName() + string("legend")); 
110         // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
111    }
112
113
114     //leg++;
115     return retVal;
116 }
117
118 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
119                                    const std::string & aName,
120                                    const SGGeod & aPos, double aElev,
121                                    double aSpeed)
122 {
123     FGAIWaypoint *wpt  = new FGAIWaypoint;
124     wpt->setName       (aName                  );
125     wpt->setLongitude  (aPos.getLongitudeDeg() );
126     wpt->setLatitude   (aPos.getLatitudeDeg()  );
127     wpt->setAltitude   (aElev                  );
128     wpt->setSpeed      (aSpeed                 );
129     wpt->setCrossat    (-10000.1               );
130     wpt->setGear_down  (true                   );
131     wpt->setFlaps_down (true                   );
132     wpt->setFinished   (false                  );
133     wpt->setOn_ground  (true                   );
134     wpt->setRouteIndex (0                      );
135     return wpt;
136 }
137
138 FGAIWaypoint *    FGAIFlightPlan::createInAir(FGAIAircraft * ac,
139                                 const std::string & aName,
140                                 const SGGeod & aPos, double aElev,
141                                 double aSpeed)
142 {
143     FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
144     wpt->setGear_down  (false                   );
145     wpt->setFlaps_down (false                   );
146     wpt->setOn_ground  (false                   );
147     return wpt;
148 }
149
150 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
151 {
152     FGAIWaypoint *wpt = new FGAIWaypoint;
153     wpt->setName       ( aWpt->getName ()      );
154     wpt->setLongitude  ( aWpt->getLongitude()  );
155     wpt->setLatitude   ( aWpt->getLatitude()   );
156     wpt->setAltitude   ( aWpt->getAltitude()   );
157     wpt->setSpeed      ( aWpt->getSpeed()      );
158     wpt->setCrossat    ( aWpt->getCrossat()    );
159     wpt->setGear_down  ( aWpt->getGear_down()  );
160     wpt->setFlaps_down ( aWpt->getFlaps_down() );
161     wpt->setFinished   ( aWpt->isFinished()    );
162     wpt->setOn_ground  ( aWpt->getOn_ground()  );
163     wpt->setRouteIndex ( 0                     );
164
165     return wpt;
166 }
167
168
169 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
170                                  const std::string & aName,
171                                  const SGGeod & aPos)
172 {
173     FGAIWaypoint *wpt = clone(aWpt);
174     wpt->setName       ( aName                   );
175     wpt->setLongitude  ( aPos.getLongitudeDeg () );
176     wpt->setLatitude   ( aPos.getLatitudeDeg  () );
177
178     return wpt;
179 }
180
181
182
183 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
184                                               FGAirport * aAirport,
185                                               FGRunway * aRunway)
186 {
187     SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
188     double airportElev = aAirport->getElevation();
189
190     FGAIWaypoint *wpt;
191     wpt =
192         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
193                        ac->getPerformance()->vTaxi());
194     pushBackWaypoint(wpt);
195     wpt =
196         createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
197                        ac->getPerformance()->vTaxi());
198     pushBackWaypoint(wpt);
199 }
200
201 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
202                                        FGAirport * apt,
203                                        double radius,
204                                        const string & fltType,
205                                        const string & acType,
206                                        const string & airline)
207 {
208     double heading, lat, lon;
209
210     // If this function is called during initialization,
211     // make sure we obtain a valid gate ID first
212     // and place the model at the location of the gate.
213     if (firstFlight) {
214         if (!(apt->getDynamics()->getAvailableParking(&lat, &lon,
215                                                       &heading, &gateId,
216                                                       radius, fltType,
217                                                       acType, airline))) {
218             SG_LOG(SG_INPUT, SG_WARN, "Could not find parking for a " <<
219                    acType <<
220                    " of flight type " << fltType <<
221                    " of airline     " << airline <<
222                    " at airport     " << apt->getId());
223         }
224     }
225
226     string rwyClass = getRunwayClassFromTrafficType(fltType);
227
228     // Only set this if it hasn't been set by ATC already.
229     if (activeRunway.empty()) {
230         //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
231         double depHeading = ac->getTrafficRef()->getCourse();
232         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
233                                             depHeading);
234     }
235     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
236     assert( rwy != NULL );
237     SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
238
239     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
240     if (!gn->exists()) {
241         createDefaultTakeoffTaxi(ac, apt, rwy);
242         return true;
243     }
244
245     intVec ids;
246     int runwayId = 0;
247     if (gn->getVersion() > 0) {
248         runwayId = gn->findNearestNodeOnRunway(runwayTakeoff);
249     } else {
250         runwayId = gn->findNearestNode(runwayTakeoff);
251     }
252
253     // A negative gateId indicates an overflow parking, use a
254     // fallback mechanism for this. 
255     // Starting from gate 0 in this case is a bit of a hack
256     // which requires a more proper solution later on.
257     delete taxiRoute;
258     taxiRoute = new FGTaxiRoute;
259
260     // Determine which node to start from.
261     int node = 0;
262     // Find out which node to start from
263     FGParking *park = apt->getDynamics()->getParking(gateId);
264     if (park) {
265         node = park->getPushBackPoint();
266     }
267
268     if (node == -1) {
269         node = gateId;
270     }
271     // HAndle case where parking doens't have a node
272     if ((node == 0) && park) {
273         if (firstFlight) {
274             node = gateId;
275         } else {
276             node = lastNodeVisited;
277         }
278     }
279
280     *taxiRoute = gn->findShortestRoute(node, runwayId);
281     intVecIterator i;
282
283     if (taxiRoute->empty()) {
284         createDefaultTakeoffTaxi(ac, apt, rwy);
285         return true;
286     }
287
288     taxiRoute->first();
289     //bool isPushBackPoint = false;
290     if (firstFlight) {
291         // If this is called during initialization, randomly
292         // skip a number of waypoints to get a more realistic
293         // taxi situation.
294         int nrWaypointsToSkip = rand() % taxiRoute->size();
295         // but make sure we always keep two active waypoints
296         // to prevent a segmentation fault
297         for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
298             taxiRoute->next(&node);
299         }
300         apt->getDynamics()->releaseParking(gateId);
301     } else {
302         if (taxiRoute->size() > 1) {
303             taxiRoute->next(&node);     // chop off the first waypoint, because that is already the last of the pushback route
304         }
305     }
306
307     // push each node on the taxi route as a waypoint
308     int route;
309     //cerr << "Building taxi route" << endl;
310     while (taxiRoute->next(&node, &route)) {
311         char buffer[10];
312         snprintf(buffer, 10, "%d", node);
313         FGTaxiNode *tn =
314             apt->getDynamics()->getGroundNetwork()->findNode(node);
315         FGAIWaypoint *wpt =
316             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
317                            ac->getPerformance()->vTaxi());
318         wpt->setRouteIndex(route);
319         //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
320         if (taxiRoute->nodesLeft() == 1) {
321             // Note that we actually have hold points in the ground network, but this is just an initial test.
322             //cerr << "Setting departurehold point: " << endl;
323             wpt->setName( wpt->getName() + string("DepartureHold"));
324         }
325         if (taxiRoute->nodesLeft() == 0) {
326             wpt->setName(wpt->getName() + string("Accel"));
327         }
328         pushBackWaypoint(wpt);
329     }
330     // Acceleration point, 105 meters into the runway,
331     SGGeod accelPoint = rwy->pointOnCenterline(105.0);
332     FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
333     pushBackWaypoint(wpt);
334
335     //cerr << "[done]" << endl;
336     return true;
337 }
338
339 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
340                                               FGAirport * aAirport)
341 {
342     SGGeod lastWptPos =
343         SGGeod::fromDeg(waypoints.back()->getLongitude(),
344                         waypoints.back()->getLatitude());
345     double airportElev = aAirport->getElevation();
346
347     FGAIWaypoint *wpt;
348     wpt =
349         createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
350                        ac->getPerformance()->vTaxi());
351     pushBackWaypoint(wpt);
352     wpt =
353         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
354                        ac->getPerformance()->vTaxi());
355     pushBackWaypoint(wpt);
356
357     double heading, lat, lon;
358     aAirport->getDynamics()->getParking(gateId, &lat, &lon, &heading);
359     wpt =
360         createOnGround(ac, "ENDtaxi", SGGeod::fromDeg(lon, lat), airportElev,
361                        ac->getPerformance()->vTaxi());
362     pushBackWaypoint(wpt);
363 }
364
365 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
366                                        double radius,
367                                        const string & fltType,
368                                        const string & acType,
369                                        const string & airline)
370 {
371     double heading, lat, lon;
372     apt->getDynamics()->getAvailableParking(&lat, &lon, &heading,
373                                             &gateId, radius, fltType,
374                                             acType, airline);
375
376     SGGeod lastWptPos =
377         SGGeod::fromDeg(waypoints.back()->getLongitude(),
378                         waypoints.back()->getLatitude());
379     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
380
381     // Find a route from runway end to parking/gate.
382     if (!gn->exists()) {
383         createDefaultLandingTaxi(ac, apt);
384         return true;
385     }
386
387     intVec ids;
388     int runwayId = 0;
389     if (gn->getVersion() == 1) {
390         runwayId = gn->findNearestNodeOnRunway(lastWptPos);
391     } else {
392         runwayId = gn->findNearestNode(lastWptPos);
393     }
394     //cerr << "Using network node " << runwayId << endl;
395     // A negative gateId indicates an overflow parking, use a
396     // fallback mechanism for this. 
397     // Starting from gate 0 is a bit of a hack...
398     //FGTaxiRoute route;
399     delete taxiRoute;
400     taxiRoute = new FGTaxiRoute;
401     if (gateId >= 0)
402         *taxiRoute = gn->findShortestRoute(runwayId, gateId);
403     else
404         *taxiRoute = gn->findShortestRoute(runwayId, 0);
405     intVecIterator i;
406
407     if (taxiRoute->empty()) {
408         createDefaultLandingTaxi(ac, apt);
409         return true;
410     }
411
412     int node;
413     taxiRoute->first();
414     int size = taxiRoute->size();
415     // Omit the last two waypoints, as 
416     // those are created by createParking()
417     int route;
418     for (int i = 0; i < size - 2; i++) {
419         taxiRoute->next(&node, &route);
420         char buffer[10];
421         snprintf(buffer, 10, "%d", node);
422         FGTaxiNode *tn = gn->findNode(node);
423         FGAIWaypoint *wpt =
424             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
425                            ac->getPerformance()->vTaxi());
426         wpt->setRouteIndex(route);
427         pushBackWaypoint(wpt);
428     }
429     return true;
430 }
431
432 /*******************************************************************
433  * CreateTakeOff 
434  * A note on units: 
435  *  - Speed -> knots -> nm/hour
436  *  - distance along runway =-> meters 
437  *  - accel / decel -> is given as knots/hour, but this is highly questionable:
438  *  for a jet_transport performance class, a accel / decel rate of 5 / 2 is 
439  *  given respectively. According to performance data.cxx, a value of kts / second seems
440  *  more likely however. 
441  * 
442  ******************************************************************/
443 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
444                                    FGAirport * apt, double speed,
445                                    const string & fltType)
446 {
447     double accel = ac->getPerformance()->acceleration();
448     double vTaxi = ac->getPerformance()->vTaxi();
449     double vRotate = ac->getPerformance()->vRotate();
450     double vTakeoff = ac->getPerformance()->vTakeoff();
451     //double vClimb = ac->getPerformance()->vClimb();
452
453     double accelMetric = (accel * SG_NM_TO_METER) / 3600;
454     double vTaxiMetric = (vTaxi * SG_NM_TO_METER) / 3600;
455     double vRotateMetric = (vRotate * SG_NM_TO_METER) / 3600;
456     double vTakeoffMetric = (vTakeoff * SG_NM_TO_METER) / 3600;
457     //double vClimbMetric = (vClimb * SG_NM_TO_METER) / 3600;
458     // Acceleration = dV / dT
459     // Acceleration X dT = dV
460     // dT = dT / Acceleration
461     //d = (Vf^2 - Vo^2) / (2*a)
462     //double accelTime = (vRotate - vTaxi) / accel;
463     //cerr << "Using " << accelTime << " as total acceleration time" << endl;
464     double accelDistance =
465         (vRotateMetric * vRotateMetric -
466          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
467     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vRotateMetric << endl;
468     FGAIWaypoint *wpt;
469     // Get the current active runway, based on code from David Luff
470     // This should actually be unified and extended to include 
471     // Preferential runway use schema's 
472     // NOTE: DT (2009-01-18: IIRC, this is currently already the case, 
473     // because the getActive runway function takes care of that.
474     if (firstFlight) {
475         string rwyClass = getRunwayClassFromTrafficType(fltType);
476         double heading = ac->getTrafficRef()->getCourse();
477         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
478                                             heading);
479     }
480     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
481     assert( rwy != NULL );
482
483     double airportElev = apt->getElevation();
484     
485
486     accelDistance =
487         (vTakeoffMetric * vTakeoffMetric -
488          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
489     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
490     SGGeod accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
491     wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
492     pushBackWaypoint(wpt);
493
494     accelDistance =
495         ((vTakeoffMetric * 1.1) * (vTakeoffMetric * 1.1) -
496          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
497     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
498     accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
499     wpt =
500         createOnGround(ac, "rotate", accelPoint, airportElev + 1000,
501                        vTakeoff * 1.1);
502     wpt->setOn_ground(false);
503     pushBackWaypoint(wpt);
504
505     wpt = cloneWithPos(ac, wpt, "3000 ft", rwy->end());
506     wpt->setAltitude(airportElev + 3000);
507     pushBackWaypoint(wpt);
508
509     // Finally, add two more waypoints, so that aircraft will remain under
510     // Tower control until they have reached the 3000 ft climb point
511     SGGeod pt = rwy->pointOnCenterline(5000 + rwy->lengthM() * 0.5);
512     wpt = cloneWithPos(ac, wpt, "5000 ft", pt);
513     wpt->setAltitude(airportElev + 5000);
514     pushBackWaypoint(wpt);
515     return true;
516 }
517
518 /*******************************************************************
519  * CreateClimb
520  * initialize the Aircraft at the parking location
521  ******************************************************************/
522 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
523                                  FGAirport * apt, double speed, double alt,
524                                  const string & fltType)
525 {
526     FGAIWaypoint *wpt;
527 //  bool planLoaded = false;
528     string fPLName;
529     double vClimb = ac->getPerformance()->vClimb();
530
531     if (firstFlight) {
532         string rwyClass = getRunwayClassFromTrafficType(fltType);
533         double heading = ac->getTrafficRef()->getCourse();
534         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
535                                             heading);
536     }
537     if (sid) {
538         for (wpt_vector_iterator i = sid->getFirstWayPoint();
539              i != sid->getLastWayPoint(); i++) {
540             pushBackWaypoint(clone(*(i)));
541             //cerr << " Cloning waypoint " << endl;
542         }
543     } else {
544         FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
545         assert( rwy != NULL );
546
547         SGGeod climb1 = rwy->pointOnCenterline(10 * SG_NM_TO_METER);
548         wpt = createInAir(ac, "10000ft climb", climb1, 10000, vClimb);
549         wpt->setGear_down(true);
550         wpt->setFlaps_down(true);
551         pushBackWaypoint(wpt);
552
553         SGGeod climb2 = rwy->pointOnCenterline(20 * SG_NM_TO_METER);
554         wpt = cloneWithPos(ac, wpt, "18000ft climb", climb2);
555         wpt->setAltitude(18000);
556         pushBackWaypoint(wpt);
557     }
558     return true;
559 }
560
561
562
563 /*******************************************************************
564  * CreateDescent
565  * Generate a flight path from the last waypoint of the cruise to 
566  * the permission to land point
567  ******************************************************************/
568 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
569                                    double latitude, double longitude,
570                                    double speed, double alt,
571                                    const string & fltType,
572                                    double requiredDistance)
573 {
574     bool reposition = false;
575     FGAIWaypoint *wpt;
576     double vDescent = ac->getPerformance()->vDescent();
577     double vApproach = ac->getPerformance()->vApproach();
578     double vTouchdown = ac->getPerformance()->vTouchdown();
579
580
581     //Beginning of Descent 
582     string rwyClass = getRunwayClassFromTrafficType(fltType);
583     double heading = ac->getTrafficRef()->getCourse();
584     apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
585                                         heading);
586     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
587     assert( rwy != NULL );
588
589     // Create a slow descent path that ends 250 lateral to the runway.
590     double initialTurnRadius = getTurnRadius(vDescent, true);
591     //double finalTurnRadius = getTurnRadius(vApproach, true);
592
593 // get length of the downwind leg for the intended runway
594     double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance();    //12 * SG_NM_TO_METER;
595     //time_t previousArrivalTime=  apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
596
597
598     SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
599     SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
600     SGGeod refPoint = rwy->pointOnCenterline(0);
601     double distance = SGGeodesy::distanceM(current, initialTarget);
602     double azimuth = SGGeodesy::courseDeg(current, initialTarget);
603     double dummyAz2;
604
605     // To prevent absurdly steep approaches, compute the origin from where the approach should have started
606     SGGeod origin;
607
608     if (ac->getTrafficRef()->getCallSign() ==
609         fgGetString("/ai/track-callsign")) {
610         //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
611         //exit(1);
612     }
613
614     if (distance < requiredDistance * 0.8) {
615         reposition = true;
616         SGGeodesy::direct(initialTarget, azimuth,
617                           -requiredDistance, origin, dummyAz2);
618
619         distance = SGGeodesy::distanceM(current, initialTarget);
620         azimuth = SGGeodesy::courseDeg(current, initialTarget);
621     } else {
622         origin = current;
623     }
624
625
626     double dAlt = 0; //  = alt - (apt->getElevation() + 2000);
627     FGTaxiNode * tn = 0;
628     if (apt->getDynamics()->getGroundNetwork()) {
629         int node = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
630         tn = apt->getDynamics()->getGroundNetwork()->findNode(node);
631     }
632     if (tn) {
633         dAlt = alt - ((tn->getElevationFt(apt->getElevation())) + 2000);
634     } else {
635         dAlt = alt - (apt->getElevation() + 2000);
636     }
637
638     double nPoints = 100;
639
640     char buffer[16];
641
642     // The descent path contains the following phases:
643     // 1) a linear glide path from the initial position to
644     // 2) a semi circle turn to final
645     // 3) approach
646
647     //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
648     // Create an initial destination point on a semicircle
649     //cerr << "lateral offset : " << lateralOffset << endl;
650     //cerr << "Distance       : " << distance      << endl;
651     //cerr << "Azimuth        : " << azimuth       << endl;
652     //cerr << "Initial Lateral point: " << lateralOffset << endl;
653     double lat = refPoint.getLatitudeDeg();
654     double lon = refPoint.getLongitudeDeg();
655     //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
656     lat = initialTarget.getLatitudeDeg();
657     lon = initialTarget.getLongitudeDeg();
658     //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
659
660     double ratio = initialTurnRadius / distance;
661     if (ratio > 1.0)
662         ratio = 1.0;
663     if (ratio < -1.0)
664         ratio = -1.0;
665
666     double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
667     double newDistance =
668         cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
669     //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
670     double side = azimuth - rwy->headingDeg();
671     double lateralOffset = initialTurnRadius;
672     if (side < 0)
673         side += 360;
674     if (side < 180) {
675         lateralOffset *= -1;
676     }
677     // Calculate the ETA at final, based on remaining distance, and approach speed.
678     // distance should really consist of flying time to terniary target, plus circle 
679     // but the distance to secondary target should work as a reasonable approximation
680     // aditionally add the amount of distance covered by making a turn of "side"
681     double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
682     time_t remaining =
683         (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
684     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
685     //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
686     //     cerr << "   Arrival time estimation: turn angle " <<  side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
687     //     //exit(1);
688     //}
689
690     time_t eta = now + remaining;
691     //choose a distance to the runway such that it will take at least 60 seconds more
692     // time to get there than the previous aircraft.
693     // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
694
695     time_t newEta;
696
697     if (reposition == false) {
698         newEta =
699             apt->getDynamics()->getApproachController()->getRunway(rwy->
700                                                                    name
701                                                                    ())->
702             requestTimeSlot(eta);
703     } else {
704         newEta = eta;
705     }
706     //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
707     arrivalTime = newEta;
708     time_t additionalTimeNeeded = newEta - eta;
709     double distanceCovered =
710         ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
711     distanceOut += distanceCovered;
712     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
713     //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
714     //} else {
715     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
716     //}
717     //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
718
719     SGGeod secondaryTarget =
720         rwy->pointOffCenterline(-distanceOut, lateralOffset);
721     initialTarget = rwy->pointOnCenterline(-distanceOut);
722     distance = SGGeodesy::distanceM(origin, secondaryTarget);
723     azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
724
725
726     lat = secondaryTarget.getLatitudeDeg();
727     lon = secondaryTarget.getLongitudeDeg();
728     //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
729     //cerr << "Distance       : " << distance      << endl;
730     //cerr << "Azimuth        : " << azimuth       << endl;
731
732
733     ratio = initialTurnRadius / distance;
734     if (ratio > 1.0)
735         ratio = 1.0;
736     if (ratio < -1.0)
737         ratio = -1.0;
738     newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
739     newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
740     //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
741     if (side < 180) {
742         azimuth += newHeading;
743     } else {
744         azimuth -= newHeading;
745     }
746
747     SGGeod tertiaryTarget;
748     SGGeodesy::direct(origin, azimuth,
749                       newDistance, tertiaryTarget, dummyAz2);
750
751     lat = tertiaryTarget.getLatitudeDeg();
752     lon = tertiaryTarget.getLongitudeDeg();
753     //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
754
755
756     for (int i = 1; i < nPoints; i++) {
757         SGGeod result;
758         double currentDist = i * (newDistance / nPoints);
759         double currentAltitude = alt - (i * (dAlt / nPoints));
760         SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
761         snprintf(buffer, 16, "descent%03d", i);
762         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
763         wpt->setCrossat(currentAltitude);
764         wpt->setTrackLength((newDistance / nPoints));
765         pushBackWaypoint(wpt);
766         //cerr << "Track Length : " << wpt->trackLength;
767         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
768     }
769
770     //cerr << "Phase 2: Circle " << endl;
771     double initialAzimuth =
772         SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
773     double finalAzimuth =
774         SGGeodesy::courseDeg(secondaryTarget, initialTarget);
775
776     //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
777     int increment, startval, endval;
778     // circle right around secondary target if orig of position is to the right of the runway
779     // i.e. use negative angles; else circle leftward and use postivi
780     if (side < 180) {
781         increment = -1;
782         startval = floor(initialAzimuth);
783         endval = ceil(finalAzimuth);
784         if (endval > startval) {
785             endval -= 360;
786         }
787     } else {
788         increment = 1;
789         startval = ceil(initialAzimuth);
790         endval = floor(finalAzimuth);
791         if (endval < startval) {
792             endval += 360;
793         }
794
795     }
796
797     //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
798     //FGTaxiNode * tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(initialTarget);
799     double currentAltitude = 0;
800     if (tn) {
801         currentAltitude = (tn->getElevationFt(apt->getElevation())) + 2000;
802     } else {
803         currentAltitude = apt->getElevation() + 2000;
804     }
805         
806     double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
807     for (int i = startval; i != endval; i += increment) {
808         SGGeod result;
809         //double currentAltitude = apt->getElevation() + 2000;
810         
811         SGGeodesy::direct(secondaryTarget, i,
812                           initialTurnRadius, result, dummyAz2);
813         snprintf(buffer, 16, "turn%03d", i);
814         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
815         wpt->setCrossat(currentAltitude);
816         wpt->setTrackLength(trackLength);
817         //cerr << "Track Length : " << wpt->trackLength;
818         pushBackWaypoint(wpt);
819         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
820     }
821
822
823     // The approach leg should bring the aircraft to approximately 4-6 nm out, after which the landing phase should take over. 
824     //cerr << "Phase 3: Approach" << endl;
825     double tgt_speed = vApproach;
826     distanceOut -= distanceCovered;
827     double touchDownPoint = 0; //(rwy->lengthM() * 0.1);
828     for (int i = 1; i < nPoints; i++) {
829         SGGeod result;
830         double currentDist = i * (distanceOut / nPoints);
831         //double currentAltitude =
832         //    apt->getElevation() + 2000 - (i * 2000 / (nPoints-1));
833         double alt = currentAltitude -  (i * 2000 / (nPoints - 1));
834         snprintf(buffer, 16, "final%03d", i);
835         result = rwy->pointOnCenterline((-distanceOut) + currentDist + touchDownPoint);
836         if (i == nPoints - 30) {
837             tgt_speed = vTouchdown;
838         }
839         wpt = createInAir(ac, buffer, result, alt, tgt_speed);
840         wpt->setCrossat(alt);
841         wpt->setTrackLength((distanceOut / nPoints));
842         // account for the extra distance due to an extended downwind leg
843         if (i == 1) {
844             wpt->setTrackLength(wpt->getTrackLength() + distanceCovered);
845         }
846         //cerr << "Track Length : " << wpt->trackLength;
847         pushBackWaypoint(wpt);
848         //if (apt->ident() == fgGetString("/sim/presets/airport-id")) {
849         //    cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << " " << apt->getElevation() << " " << distanceOut << endl;
850         //}
851     }
852
853     //cerr << "Done" << endl;
854
855     // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
856     IncrementWaypoint(true);
857     IncrementWaypoint(true);
858
859     if (reposition) {
860         double tempDistance;
861         //double minDistance = HUGE_VAL;
862         string wptName;
863         tempDistance = SGGeodesy::distanceM(current, initialTarget);
864         time_t eta =
865             tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
866         time_t newEta =
867             apt->getDynamics()->getApproachController()->getRunway(rwy->
868                                                                    name
869                                                                    ())->
870             requestTimeSlot(eta);
871         arrivalTime = newEta;
872         double newDistance =
873             ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
874         //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
875         IncrementWaypoint(true);        // remove waypoint BOD2
876         while (checkTrackLength("final001") > newDistance) {
877             IncrementWaypoint(true);
878         }
879         //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
880         ac->resetPositionFromFlightPlan();
881     }
882     waypoints[1]->setName( (waypoints[1]->getName() + string("legend"))); 
883     waypoints.back()->setName(waypoints.back()->getName() + "LandingThreshold");
884     return true;
885 }
886
887 /*******************************************************************
888  * CreateLanding
889  * Create a flight path from the "permision to land" point (currently
890    hardcoded at 5000 meters from the threshold) to the threshold, at
891    a standard glide slope angle of 3 degrees. 
892    Position : 50.0354 8.52592 384 364 11112
893  ******************************************************************/
894 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
895                                    const string & fltType)
896 {
897     double vTouchdown = ac->getPerformance()->vTouchdown();
898     double vTaxi      = ac->getPerformance()->vTaxi();
899     double decel     = ac->getPerformance()->deceleration() * 1.4;
900     
901     double vTouchdownMetric = (vTouchdown  * SG_NM_TO_METER) / 3600;
902     double vTaxiMetric      = (vTaxi       * SG_NM_TO_METER) / 3600;
903     double decelMetric      = (decel       * SG_NM_TO_METER) / 3600;
904
905     //string rwyClass = getRunwayClassFromTrafficType(fltType);
906     //double heading = ac->getTrafficRef()->getCourse();
907     //apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway, heading);
908     //rwy = apt->getRunwayByIdent(activeRunway);
909
910
911     FGAIWaypoint *wpt;
912     double aptElev = apt->getElevation();
913     double currElev = 0;
914     char buffer[12];
915     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
916     assert( rwy != NULL );
917     SGGeod refPoint = rwy->pointOnCenterline(0);
918     FGTaxiNode *tn = 0;
919     if (apt->getDynamics()->getGroundNetwork()) {
920         int node = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
921         tn = apt->getDynamics()->getGroundNetwork()->findNode(node);
922     }
923     if (tn) {
924         currElev = tn->getElevationFt(apt->getElevation());
925     } else {
926         currElev = apt->getElevation();
927     }
928
929
930     SGGeod coord;
931     
932
933     /*double distanceOut = rwy->lengthM() * .1;
934     double nPoints = 20;
935     for (int i = 1; i < nPoints; i++) {
936         snprintf(buffer, 12, "flare%d", i);
937         double currentDist = i * (distanceOut / nPoints);
938         double currentAltitude = apt->getElevation() + 20 - (i * 20 / nPoints);
939         coord = rwy->pointOnCenterline((currentDist * (i / nPoints)));
940         wpt = createInAir(ac, buffer, coord, currentAltitude, (vTouchdown));
941     }*/
942     double rolloutDistance =
943         (vTouchdownMetric * vTouchdownMetric - vTaxiMetric * vTaxiMetric) / (2 * decelMetric);
944     //cerr << " touchdown speed = " << vTouchdown << ". Rollout distance " << rolloutDistance << endl;
945     int nPoints = 50;
946     for (int i = 1; i < nPoints; i++) {
947         snprintf(buffer, 12, "landing03%d", i);
948         
949         coord = rwy->pointOnCenterline((rolloutDistance * ((double) i / (double) nPoints)));
950         wpt = createOnGround(ac, buffer, coord, currElev, 2*vTaxi);
951         wpt->setCrossat(currElev);
952         pushBackWaypoint(wpt);
953     }
954     wpt->setSpeed(vTaxi);
955     double mindist = 1.1 * rolloutDistance;
956     double maxdist = rwy->lengthM();
957     //cerr << "Finding nearest exit" << endl;
958     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
959     if (gn) {
960         double min = 0;
961         for (int i = ceil(mindist); i < floor(maxdist); i++) {
962             coord = rwy->pointOnCenterline(mindist);
963             int nodeId = 0;
964             if (gn->getVersion() > 0) {
965                 nodeId = gn->findNearestNodeOnRunway(coord);
966             } else {
967                 nodeId = gn->findNearestNode(coord);
968             }
969             if (tn)
970                 tn = gn->findNode(nodeId);
971             else {
972                 break;
973             }
974             
975             double dist = SGGeodesy::distanceM(coord, tn->getGeod());
976             if (dist < (min + 0.75)) {
977                 break;
978             }
979             min = dist;
980         }
981         if (tn) {
982             wpt = createOnGround(ac, buffer, tn->getGeod(), currElev, vTaxi);
983             pushBackWaypoint(wpt);
984         }
985     }
986     //cerr << "Done. " << endl;
987
988     /*
989        //Runway Threshold
990        wpt = createOnGround(ac, "Threshold", rwy->threshold(), aptElev, vTouchdown);
991        wpt->crossat = apt->getElevation();
992        pushBackWaypoint(wpt); 
993
994        // Roll-out
995        wpt = createOnGround(ac, "Center", rwy->geod(), aptElev, vTaxi*2);
996        pushBackWaypoint(wpt);
997
998        SGGeod rollOut = rwy->pointOnCenterline(rwy->lengthM() * 0.9);
999        wpt = createOnGround(ac, "Roll Out", rollOut, aptElev, vTaxi);
1000        wpt->crossat   = apt->getElevation();
1001        pushBackWaypoint(wpt); 
1002      */
1003     return true;
1004 }
1005
1006 /*******************************************************************
1007  * CreateParking
1008  * initialize the Aircraft at the parking location
1009  ******************************************************************/
1010 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
1011                                    double radius)
1012 {
1013     FGAIWaypoint *wpt;
1014     double aptElev = apt->getElevation();
1015     double lat = 0.0, lat2 = 0.0;
1016     double lon = 0.0, lon2 = 0.0;
1017     double az2 = 0.0;
1018     double heading = 0.0;
1019
1020     double vTaxi = ac->getPerformance()->vTaxi();
1021     double vTaxiReduced = vTaxi * (2.0 / 3.0);
1022     apt->getDynamics()->getParking(gateId, &lat, &lon, &heading);
1023     heading += 180.0;
1024     if (heading > 360)
1025         heading -= 360;
1026     geo_direct_wgs_84(0, lat, lon, heading,
1027                       2.2 * radius, &lat2, &lon2, &az2);
1028     wpt =
1029         createOnGround(ac, "taxiStart", SGGeod::fromDeg(lon2, lat2),
1030                        aptElev, vTaxiReduced);
1031     pushBackWaypoint(wpt);
1032
1033     geo_direct_wgs_84(0, lat, lon, heading,
1034                       0.1 * radius, &lat2, &lon2, &az2);
1035
1036     wpt =
1037         createOnGround(ac, "taxiStart2", SGGeod::fromDeg(lon2, lat2),
1038                        aptElev, vTaxiReduced);
1039     pushBackWaypoint(wpt);
1040
1041     wpt =
1042         createOnGround(ac, "END-Parking", SGGeod::fromDeg(lon, lat), aptElev,
1043                        vTaxiReduced);
1044     pushBackWaypoint(wpt);
1045     return true;
1046 }
1047
1048 /**
1049  *
1050  * @param fltType a string describing the type of
1051  * traffic, normally used for gate assignments
1052  * @return a converted string that gives the runway
1053  * preference schedule to be used at aircraft having
1054  * a preferential runway schedule implemented (i.e.
1055  * having a rwyprefs.xml file
1056  * 
1057  * Currently valid traffic types for gate assignment:
1058  * - gate (commercial gate)
1059  * - cargo (commercial gargo),
1060  * - ga (general aviation) ,
1061  * - ul (ultralight),
1062  * - mil-fighter (military - fighter),
1063  * - mil-transport (military - transport)
1064  *
1065  * Valid runway classes:
1066  * - com (commercial traffic: jetliners, passenger and cargo)
1067  * - gen (general aviation)
1068  * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
1069  * - mil (all military traffic)
1070  */
1071 string FGAIFlightPlan::getRunwayClassFromTrafficType(string fltType)
1072 {
1073     if ((fltType == "gate") || (fltType == "cargo")) {
1074         return string("com");
1075     }
1076     if (fltType == "ga") {
1077         return string("gen");
1078     }
1079     if (fltType == "ul") {
1080         return string("ul");
1081     }
1082     if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1083         return string("mil");
1084     }
1085     return string("com");
1086 }
1087
1088
1089 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
1090 {
1091     double turn_radius;
1092     if (inAir == false) {
1093         turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
1094     } else {
1095         turn_radius = 0.1911 * speed * speed;   // an estimate for 25 degrees bank
1096     }
1097     return turn_radius;
1098 }