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