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