]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlanCreate.cxx
toggle fullscreen: also adapt GUI plane when resizing
[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 #include <Navaids/navrecord.hxx>
42
43
44 /* FGAIFlightPlan::create()
45  * dynamically create a flight plan for AI traffic, based on data provided by the
46  * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10) 
47  *
48  * This is the top-level function, and the only one that is publicly available.
49  *
50  */
51
52
53 // Check lat/lon values during initialization;
54 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
55                             FGAirport * arr, int legNr, double alt,
56                             double speed, double latitude,
57                             double longitude, bool firstFlight,
58                             double radius, const string & fltType,
59                             const string & aircraftType,
60                             const string & airline, double distance)
61 {
62     bool retVal = true;
63     int currWpt = wpt_iterator - waypoints.begin();
64     switch (legNr) {
65     case 1:
66         retVal = createPushBack(ac, firstFlight, dep,
67                                 radius, fltType, aircraftType, airline);
68         // Pregenerate the taxi leg.
69         //if (retVal) {
70         //    waypoints.back()->setName( waypoints.back()->getName() + string("legend")); 
71         //    retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
72         //}
73         break;
74     case 2:
75         retVal =  createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
76                           aircraftType, airline);
77         break;
78     case 3:
79         retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
80         break;
81     case 4:
82         retVal = createClimb(ac, firstFlight, dep, arr, speed, alt, fltType);
83         break;
84     case 5:
85         retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
86                      alt, fltType);
87         break;
88     case 6:
89         retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
90                       distance);
91         break;
92     case 7:
93         retVal = createLanding(ac, arr, fltType);
94         break;
95     case 8:
96         retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
97         break;
98     case 9:
99         retVal = createParking(ac, arr, radius);
100         break;
101     default:
102         //exit(1);
103         SG_LOG(SG_AI, SG_ALERT,
104                "AIFlightPlan::create() attempting to create unknown leg"
105                " this is probably an internal program error");
106     }
107     wpt_iterator = waypoints.begin() + currWpt;
108     //don't  increment leg right away, but only once we pass the actual last waypoint that was created.
109     // to do so, mark the last waypoint with a special status flag
110    if (retVal) {
111         waypoints.back()->setName( waypoints.back()->getName() + string("legend")); 
112         // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
113    }
114
115
116     //leg++;
117     return retVal;
118 }
119
120 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
121                                    const std::string & aName,
122                                    const SGGeod & aPos, double aElev,
123                                    double aSpeed)
124 {
125     FGAIWaypoint *wpt  = new FGAIWaypoint;
126     wpt->setName       (aName                  );
127     wpt->setLongitude  (aPos.getLongitudeDeg() );
128     wpt->setLatitude   (aPos.getLatitudeDeg()  );
129     wpt->setAltitude   (aElev                  );
130     wpt->setSpeed      (aSpeed                 );
131     wpt->setCrossat    (-10000.1               );
132     wpt->setGear_down  (true                   );
133     wpt->setFlaps_down (true                   );
134     wpt->setFinished   (false                  );
135     wpt->setOn_ground  (true                   );
136     wpt->setRouteIndex (0                      );
137     return wpt;
138 }
139
140 FGAIWaypoint *    FGAIFlightPlan::createInAir(FGAIAircraft * ac,
141                                 const std::string & aName,
142                                 const SGGeod & aPos, double aElev,
143                                 double aSpeed)
144 {
145     FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
146     wpt->setGear_down  (false                   );
147     wpt->setFlaps_down (false                   );
148     wpt->setOn_ground  (false                   );
149     wpt->setCrossat    (aElev                   );
150     return wpt;
151 }
152
153 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
154 {
155     FGAIWaypoint *wpt = new FGAIWaypoint;
156     wpt->setName       ( aWpt->getName ()      );
157     wpt->setLongitude  ( aWpt->getLongitude()  );
158     wpt->setLatitude   ( aWpt->getLatitude()   );
159     wpt->setAltitude   ( aWpt->getAltitude()   );
160     wpt->setSpeed      ( aWpt->getSpeed()      );
161     wpt->setCrossat    ( aWpt->getCrossat()    );
162     wpt->setGear_down  ( aWpt->getGear_down()  );
163     wpt->setFlaps_down ( aWpt->getFlaps_down() );
164     wpt->setFinished   ( aWpt->isFinished()    );
165     wpt->setOn_ground  ( aWpt->getOn_ground()  );
166     wpt->setRouteIndex ( 0                     );
167
168     return wpt;
169 }
170
171
172 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
173                                  const std::string & aName,
174                                  const SGGeod & aPos)
175 {
176     FGAIWaypoint *wpt = clone(aWpt);
177     wpt->setName       ( aName                   );
178     wpt->setLongitude  ( aPos.getLongitudeDeg () );
179     wpt->setLatitude   ( aPos.getLatitudeDeg  () );
180
181     return wpt;
182 }
183
184
185
186 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
187                                               FGAirport * aAirport,
188                                               FGRunway * aRunway)
189 {
190     SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
191     double airportElev = aAirport->getElevation();
192
193     FGAIWaypoint *wpt;
194     wpt =
195         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
196                        ac->getPerformance()->vTaxi());
197     pushBackWaypoint(wpt);
198     wpt =
199         createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
200                        ac->getPerformance()->vTaxi());
201     pushBackWaypoint(wpt);
202 }
203
204 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
205                                        FGAirport * apt,
206                                        double radius,
207                                        const string & fltType,
208                                        const string & acType,
209                                        const string & airline)
210 {
211
212     // If this function is called during initialization,
213     // make sure we obtain a valid gate ID first
214     // and place the model at the location of the gate.
215     if (firstFlight)
216     {
217       gate =  apt->getDynamics()->getAvailableParking(radius, fltType,
218                                                         acType, airline);
219       if (!gate.isValid()) {
220         SG_LOG(SG_AI, SG_WARN, "Could not find parking for a " <<
221                acType <<
222                " of flight type " << fltType <<
223                " of airline     " << airline <<
224                " at airport     " << apt->getId());
225       }
226     }
227
228     string rwyClass = getRunwayClassFromTrafficType(fltType);
229
230     // Only set this if it hasn't been set by ATC already.
231     if (activeRunway.empty()) {
232         //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
233         double depHeading = ac->getTrafficRef()->getCourse();
234         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
235                                             depHeading);
236     }
237     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
238     assert( rwy != NULL );
239     SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
240
241     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
242     if (!gn->exists()) {
243         createDefaultTakeoffTaxi(ac, apt, rwy);
244         return true;
245     }
246
247     intVec ids;
248     PositionedID runwayId = 0;
249     if (gn->getVersion() > 0) {
250         runwayId = gn->findNearestNodeOnRunway(runwayTakeoff);
251     } else {
252         runwayId = gn->findNearestNode(runwayTakeoff);
253     }
254
255     // A negative gateId indicates an overflow parking, use a
256     // fallback mechanism for this. 
257     // Starting from gate 0 in this case is a bit of a hack
258     // which requires a more proper solution later on.
259   //  delete taxiRoute;
260   //  taxiRoute = new FGTaxiRoute;
261
262     // Determine which node to start from.
263     PositionedID node = 0;
264     // Find out which node to start from
265     FGParking *park = gate.parking();
266     if (park) {
267         node = park->getPushBackPoint();
268         if (node == -1) {
269             node = park->guid();
270         } else if (node == 0) {
271             // HAndle case where parking doens't have a node
272             if (firstFlight) {
273                 node = park->guid();
274             } else {
275                 node = lastNodeVisited;
276             }
277         }
278     }
279     
280     FGTaxiRoute taxiRoute = gn->findShortestRoute(node, runwayId);
281     intVecIterator i;
282
283     if (taxiRoute.empty()) {
284         createDefaultTakeoffTaxi(ac, apt, rwy);
285         return true;
286     }
287
288     taxiRoute.first();
289     //bool isPushBackPoint = false;
290     if (firstFlight) {
291         // If this is called during initialization, randomly
292         // skip a number of waypoints to get a more realistic
293         // taxi situation.
294         int nrWaypointsToSkip = rand() % taxiRoute.size();
295         // but make sure we always keep two active waypoints
296         // to prevent a segmentation fault
297         for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
298             taxiRoute.next(&node);
299         }
300         
301         gate.release(); // free up our gate as required
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)) {
312         char buffer[10];
313         snprintf(buffer, 10, "%lld", 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     if (gate.isValid()) {
359         wpt = createOnGround(ac, "ENDtaxi", gate.parking()->geod(), airportElev,
360                          ac->getPerformance()->vTaxi());
361         pushBackWaypoint(wpt);
362     }
363 }
364
365 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
366                                        double radius,
367                                        const string & fltType,
368                                        const string & acType,
369                                        const string & airline)
370 {
371     gate = apt->getDynamics()->getAvailableParking(radius, fltType,
372                                             acType, airline);
373
374     SGGeod lastWptPos = waypoints.back()->getPos();
375     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
376
377     // Find a route from runway end to parking/gate.
378     if (!gn->exists()) {
379         createDefaultLandingTaxi(ac, apt);
380         return true;
381     }
382
383     intVec ids;
384     PositionedID runwayId = 0;
385     if (gn->getVersion() == 1) {
386         runwayId = gn->findNearestNodeOnRunway(lastWptPos);
387     } else {
388         runwayId = gn->findNearestNode(lastWptPos);
389     }
390     //cerr << "Using network node " << runwayId << endl;
391     // A negative gateId indicates an overflow parking, use a
392     // fallback mechanism for this. 
393     // Starting from gate 0 is a bit of a hack...
394     //FGTaxiRoute route;
395   //  delete taxiRoute;
396    // taxiRoute = new FGTaxiRoute;
397     FGTaxiRoute taxiRoute;
398     if (gate.isValid())
399         taxiRoute = gn->findShortestRoute(runwayId, gate.parking()->guid());
400     else
401         taxiRoute = gn->findShortestRoute(runwayId, 0);
402     intVecIterator i;
403
404     if (taxiRoute.empty()) {
405         createDefaultLandingTaxi(ac, apt);
406         return true;
407     }
408
409     PositionedID node;
410     taxiRoute.first();
411     int size = taxiRoute.size();
412     // Omit the last two waypoints, as 
413     // those are created by createParking()
414    // int route;
415     for (int i = 0; i < size - 2; i++) {
416         taxiRoute.next(&node);
417         char buffer[10];
418         snprintf(buffer, 10, "%lld", node);
419         FGTaxiNode *tn = gn->findNode(node);
420         FGAIWaypoint *wpt =
421             createOnGround(ac, buffer, tn->geod(), apt->getElevation(),
422                            ac->getPerformance()->vTaxi());
423        // wpt->setRouteIndex(route);
424         pushBackWaypoint(wpt);
425     }
426     return true;
427 }
428
429 static double accelDistance(double v0, double v1, double accel)
430 {
431   double t = fabs(v1 - v0) / accel; // time in seconds to change velocity
432   // area under the v/t graph: (t * v0) + (dV / 2t) where (dV = v1 - v0)
433   return t * 0.5 * (v1 + v0); 
434 }
435
436 // find the horizontal distance to gain the specific altiude, holding
437 // a constant pitch angle. Used to compute distance based on standard FD/AP
438 // PITCH mode prior to VS or CLIMB engaging. Visually, we want to avoid
439 // a dip in the nose angle after rotation, during initial climb-out.
440 static double pitchDistance(double pitchAngleDeg, double altGainM)
441 {
442   return altGainM / tan(pitchAngleDeg * SG_DEGREES_TO_RADIANS);
443 }
444
445 /*******************************************************************
446  * CreateTakeOff 
447  * A note on units: 
448  *  - Speed -> knots -> nm/hour
449  *  - distance along runway =-> meters 
450  *  - accel / decel -> is given as knots/hour, but this is highly questionable:
451  *  for a jet_transport performance class, a accel / decel rate of 5 / 2 is 
452  *  given respectively. According to performance data.cxx, a value of kts / second seems
453  *  more likely however. 
454  * 
455  ******************************************************************/
456 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
457                                    FGAirport * apt, double speed,
458                                    const string & fltType)
459 {
460     const double ACCEL_POINT = 105.0;
461   // climb-out angle in degrees. could move this to the perf-db but this
462   // value is pretty sane
463     const double INITIAL_PITCH_ANGLE = 10.0;
464   
465     double accel = ac->getPerformance()->acceleration();
466     double vTaxi = ac->getPerformance()->vTaxi();
467     double vRotate = ac->getPerformance()->vRotate();
468     double vTakeoff = ac->getPerformance()->vTakeoff();
469
470     double accelMetric = accel * SG_KT_TO_MPS;
471     double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
472     double vRotateMetric = vRotate * SG_KT_TO_MPS;
473    
474     FGAIWaypoint *wpt;
475     // Get the current active runway, based on code from David Luff
476     // This should actually be unified and extended to include 
477     // Preferential runway use schema's 
478     // NOTE: DT (2009-01-18: IIRC, this is currently already the case, 
479     // because the getActive runway function takes care of that.
480     if (firstFlight) {
481         string rwyClass = getRunwayClassFromTrafficType(fltType);
482         double heading = ac->getTrafficRef()->getCourse();
483         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
484                                             heading);
485     }
486   
487     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
488     assert( rwy != NULL );
489     double airportElev = apt->getElevation();
490     
491     double d = accelDistance(vTaxiMetric, vRotateMetric, accelMetric) + ACCEL_POINT;
492   
493     SGGeod accelPoint = rwy->pointOnCenterline(d);
494     wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
495     pushBackWaypoint(wpt);
496
497     double vRef = vTakeoff + 20; // climb-out at v2 + 20kts
498   
499     double gearUpDist = d + pitchDistance(INITIAL_PITCH_ANGLE, 400 * SG_FEET_TO_METER);
500     accelPoint = rwy->pointOnCenterline(gearUpDist);
501     
502     wpt = cloneWithPos(ac, wpt, "gear-up", accelPoint);
503     wpt->setSpeed(vRef);
504     wpt->setCrossat(airportElev + 400);
505     wpt->setOn_ground(false);
506     wpt->setGear_down(false);
507     pushBackWaypoint(wpt);
508   
509   // limit climbout speed to 240kts below 10000'
510     double vClimbBelow10000 = std::min(240.0, ac->getPerformance()->vClimb());
511   
512   // create two climb-out points. This is important becuase the first climb point will
513   // be a (sometimes large) turn towards the destination, and we don't want to
514   // commence that turn below 2000'
515     double climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2000 * SG_FEET_TO_METER);
516     accelPoint = rwy->pointOnCenterline(climbOut);
517     wpt = createInAir(ac, "2000'", accelPoint, airportElev + 2000, vClimbBelow10000);
518     pushBackWaypoint(wpt);
519   
520     climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2500 * SG_FEET_TO_METER);
521     accelPoint = rwy->pointOnCenterline(climbOut);
522     wpt = createInAir(ac, "2500'", accelPoint, airportElev + 2500, vClimbBelow10000);
523     pushBackWaypoint(wpt);
524
525     return true;
526 }
527
528 /*******************************************************************
529  * CreateClimb
530  * initialize the Aircraft at the parking location
531  ******************************************************************/
532 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
533                                  FGAirport * apt, FGAirport* arrival,
534                                  double speed, double alt,
535                                  const string & fltType)
536 {
537     FGAIWaypoint *wpt;
538   //  string fPLName;
539     double vClimb = ac->getPerformance()->vClimb();
540   
541     if (firstFlight) {
542         string rwyClass = getRunwayClassFromTrafficType(fltType);
543         double heading = ac->getTrafficRef()->getCourse();
544         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
545                                             heading);
546     }
547     if (sid) {
548         for (wpt_vector_iterator i = sid->getFirstWayPoint();
549              i != sid->getLastWayPoint(); i++) {
550             pushBackWaypoint(clone(*(i)));
551             //cerr << " Cloning waypoint " << endl;
552         }
553     } else {
554         FGRunway* runway = apt->getRunwayByIdent(activeRunway);
555         SGGeod cur = runway->end();
556         if (!waypoints.empty()) {
557           cur = waypoints.back()->getPos();
558         }
559       
560       // compute course towards destination
561         double course = SGGeodesy::courseDeg(cur, arrival->geod());
562       
563         SGGeod climb1 = SGGeodesy::direct(cur, course, 10 * SG_NM_TO_METER);
564         wpt = createInAir(ac, "10000ft climb", climb1, 10000, vClimb);
565         wpt->setGear_down(true);
566         wpt->setFlaps_down(true);
567         pushBackWaypoint(wpt);
568
569         SGGeod climb2 = SGGeodesy::direct(cur, course, 20 * SG_NM_TO_METER);
570         wpt = createInAir(ac, "18000ft climb", climb2, 18000, vClimb);
571         pushBackWaypoint(wpt);
572     }
573     return true;
574 }
575
576
577
578 /*******************************************************************
579  * CreateDescent
580  * Generate a flight path from the last waypoint of the cruise to 
581  * the permission to land point
582  ******************************************************************/
583 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
584                                    double latitude, double longitude,
585                                    double speed, double alt,
586                                    const string & fltType,
587                                    double requiredDistance)
588 {
589     bool reposition = false;
590     FGAIWaypoint *wpt;
591     double vDescent = ac->getPerformance()->vDescent();
592     double vApproach = ac->getPerformance()->vApproach();
593
594     //Beginning of Descent 
595     string rwyClass = getRunwayClassFromTrafficType(fltType);
596     double heading = ac->getTrafficRef()->getCourse();
597     apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
598                                         heading);
599     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
600     assert( rwy != NULL );
601
602     // Create a slow descent path that ends 250 lateral to the runway.
603     double initialTurnRadius = getTurnRadius(vDescent, true);
604     //double finalTurnRadius = getTurnRadius(vApproach, true);
605
606 // get length of the downwind leg for the intended runway
607     double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance();    //12 * SG_NM_TO_METER;
608     //time_t previousArrivalTime=  apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
609
610
611     SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
612     SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
613     SGGeod refPoint = rwy->pointOnCenterline(0);
614     double distance = SGGeodesy::distanceM(current, initialTarget);
615     double azimuth = SGGeodesy::courseDeg(current, initialTarget);
616     double dummyAz2;
617
618     // To prevent absurdly steep approaches, compute the origin from where the approach should have started
619     SGGeod origin;
620
621     if (ac->getTrafficRef()->getCallSign() ==
622         fgGetString("/ai/track-callsign")) {
623         //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
624         //exit(1);
625     }
626
627     if (distance < requiredDistance * 0.8) {
628         reposition = true;
629         SGGeodesy::direct(initialTarget, azimuth,
630                           -requiredDistance, origin, dummyAz2);
631
632         distance = SGGeodesy::distanceM(current, initialTarget);
633         azimuth = SGGeodesy::courseDeg(current, initialTarget);
634     } else {
635         origin = current;
636     }
637
638     double dAlt = 0; //  = alt - (apt->getElevation() + 2000);
639     FGTaxiNode * tn = 0;
640     if (apt->getDynamics()->getGroundNetwork()) {
641         int node = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
642         tn = apt->getDynamics()->getGroundNetwork()->findNode(node);
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     int nodeId = 0;
969     if (gn->getVersion() > 0) {
970         nodeId = gn->findNearestNodeOnRunway(coord, rwy);
971     } else {
972         nodeId = gn->findNearestNode(coord);
973     }
974       
975     FGTaxiNode* tn = gn->findNode(nodeId);
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 string FGAIFlightPlan::getRunwayClassFromTrafficType(string fltType)
1048 {
1049     if ((fltType == "gate") || (fltType == "cargo")) {
1050         return string("com");
1051     }
1052     if (fltType == "ga") {
1053         return string("gen");
1054     }
1055     if (fltType == "ul") {
1056         return string("ul");
1057     }
1058     if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1059         return string("mil");
1060     }
1061     return string("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 }