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