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