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