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