]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlanCreate.cxx
Merge branch 'next' into comm-subsystem
[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         waypoints.push_back(wpt);
320     }
321     // Acceleration point, 105 meters into the runway,
322     SGGeod accelPoint = rwy->pointOnCenterline(105.0);
323     FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
324     waypoints.push_back(wpt);
325
326     //cerr << "[done]" << endl;
327     return true;
328 }
329
330 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
331                                               FGAirport * aAirport)
332 {
333     SGGeod lastWptPos =
334         SGGeod::fromDeg(waypoints.back()->getLongitude(),
335                         waypoints.back()->getLatitude());
336     double airportElev = aAirport->getElevation();
337
338     FGAIWaypoint *wpt;
339     wpt =
340         createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
341                        ac->getPerformance()->vTaxi());
342     waypoints.push_back(wpt);
343     wpt =
344         createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
345                        ac->getPerformance()->vTaxi());
346     waypoints.push_back(wpt);
347
348     double heading, lat, lon;
349     aAirport->getDynamics()->getParking(gateId, &lat, &lon, &heading);
350     wpt =
351         createOnGround(ac, "END", SGGeod::fromDeg(lon, lat), airportElev,
352                        ac->getPerformance()->vTaxi());
353     waypoints.push_back(wpt);
354 }
355
356 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
357                                        double radius,
358                                        const string & fltType,
359                                        const string & acType,
360                                        const string & airline)
361 {
362     double heading, lat, lon;
363     apt->getDynamics()->getAvailableParking(&lat, &lon, &heading,
364                                             &gateId, radius, fltType,
365                                             acType, airline);
366
367     SGGeod lastWptPos =
368         SGGeod::fromDeg(waypoints.back()->getLongitude(),
369                         waypoints.back()->getLatitude());
370     FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
371
372     // Find a route from runway end to parking/gate.
373     if (!gn->exists()) {
374         createDefaultLandingTaxi(ac, apt);
375         return true;
376     }
377
378     intVec ids;
379     int runwayId = gn->findNearestNode(lastWptPos);
380     // A negative gateId indicates an overflow parking, use a
381     // fallback mechanism for this. 
382     // Starting from gate 0 is a bit of a hack...
383     //FGTaxiRoute route;
384     delete taxiRoute;
385     taxiRoute = new FGTaxiRoute;
386     if (gateId >= 0)
387         *taxiRoute = gn->findShortestRoute(runwayId, gateId);
388     else
389         *taxiRoute = gn->findShortestRoute(runwayId, 0);
390     intVecIterator i;
391
392     if (taxiRoute->empty()) {
393         createDefaultLandingTaxi(ac, apt);
394         return true;
395     }
396
397     int node;
398     taxiRoute->first();
399     int size = taxiRoute->size();
400     // Omit the last two waypoints, as 
401     // those are created by createParking()
402     int route;
403     for (int i = 0; i < size - 2; i++) {
404         taxiRoute->next(&node, &route);
405         char buffer[10];
406         snprintf(buffer, 10, "%d", node);
407         FGTaxiNode *tn = gn->findNode(node);
408         FGAIWaypoint *wpt =
409             createOnGround(ac, buffer, tn->getGeod(), apt->getElevation(),
410                            ac->getPerformance()->vTaxi());
411         wpt->setRouteIndex(route);
412         waypoints.push_back(wpt);
413     }
414     return true;
415 }
416
417 /*******************************************************************
418  * CreateTakeOff 
419  * A note on units: 
420  *  - Speed -> knots -> nm/hour
421  *  - distance along runway =-> meters 
422  *  - accel / decel -> is given as knots/hour, but this is highly questionable:
423  *  for a jet_transport performance class, a accel / decel rate of 5 / 2 is 
424  *  given respectively. According to performance data.cxx, a value of kts / second seems
425  *  more likely however. 
426  * 
427  ******************************************************************/
428 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
429                                    FGAirport * apt, double speed,
430                                    const string & fltType)
431 {
432     double accel = ac->getPerformance()->acceleration();
433     double vTaxi = ac->getPerformance()->vTaxi();
434     double vRotate = ac->getPerformance()->vRotate();
435     double vTakeoff = ac->getPerformance()->vTakeoff();
436     //double vClimb = ac->getPerformance()->vClimb();
437
438     double accelMetric = (accel * SG_NM_TO_METER) / 3600;
439     double vTaxiMetric = (vTaxi * SG_NM_TO_METER) / 3600;
440     double vRotateMetric = (vRotate * SG_NM_TO_METER) / 3600;
441     double vTakeoffMetric = (vTakeoff * SG_NM_TO_METER) / 3600;
442     //double vClimbMetric = (vClimb * SG_NM_TO_METER) / 3600;
443     // Acceleration = dV / dT
444     // Acceleration X dT = dV
445     // dT = dT / Acceleration
446     //d = (Vf^2 - Vo^2) / (2*a)
447     //double accelTime = (vRotate - vTaxi) / accel;
448     //cerr << "Using " << accelTime << " as total acceleration time" << endl;
449     double accelDistance =
450         (vRotateMetric * vRotateMetric -
451          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
452     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vRotateMetric << endl;
453     FGAIWaypoint *wpt;
454     // Get the current active runway, based on code from David Luff
455     // This should actually be unified and extended to include 
456     // Preferential runway use schema's 
457     // NOTE: DT (2009-01-18: IIRC, this is currently already the case, 
458     // because the getActive runway function takes care of that.
459     if (firstFlight) {
460         string rwyClass = getRunwayClassFromTrafficType(fltType);
461         double heading = ac->getTrafficRef()->getCourse();
462         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
463                                             heading);
464     }
465     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
466     assert( rwy != NULL );
467
468     double airportElev = apt->getElevation();
469     
470
471     accelDistance =
472         (vTakeoffMetric * vTakeoffMetric -
473          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
474     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
475     SGGeod accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
476     wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
477     waypoints.push_back(wpt);
478
479     accelDistance =
480         ((vTakeoffMetric * 1.1) * (vTakeoffMetric * 1.1) -
481          vTaxiMetric * vTaxiMetric) / (2 * accelMetric);
482     //cerr << "Using " << accelDistance << " " << accelMetric << " " << vTakeoffMetric << endl;
483     accelPoint = rwy->pointOnCenterline(105.0 + accelDistance);
484     wpt =
485         createOnGround(ac, "rotate", accelPoint, airportElev + 1000,
486                        vTakeoff * 1.1);
487     wpt->setOn_ground(false);
488     waypoints.push_back(wpt);
489
490     wpt = cloneWithPos(ac, wpt, "3000 ft", rwy->end());
491     wpt->setAltitude(airportElev + 3000);
492     waypoints.push_back(wpt);
493
494     // Finally, add two more waypoints, so that aircraft will remain under
495     // Tower control until they have reached the 3000 ft climb point
496     SGGeod pt = rwy->pointOnCenterline(5000 + rwy->lengthM() * 0.5);
497     wpt = cloneWithPos(ac, wpt, "5000 ft", pt);
498     wpt->setAltitude(airportElev + 5000);
499     waypoints.push_back(wpt);
500     return true;
501 }
502
503 /*******************************************************************
504  * CreateClimb
505  * initialize the Aircraft at the parking location
506  ******************************************************************/
507 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
508                                  FGAirport * apt, double speed, double alt,
509                                  const string & fltType)
510 {
511     FGAIWaypoint *wpt;
512 //  bool planLoaded = false;
513     string fPLName;
514     double vClimb = ac->getPerformance()->vClimb();
515
516     if (firstFlight) {
517         string rwyClass = getRunwayClassFromTrafficType(fltType);
518         double heading = ac->getTrafficRef()->getCourse();
519         apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
520                                             heading);
521     }
522     if (sid) {
523         for (wpt_vector_iterator i = sid->getFirstWayPoint();
524              i != sid->getLastWayPoint(); i++) {
525             waypoints.push_back(clone(*(i)));
526             //cerr << " Cloning waypoint " << endl;
527         }
528     } else {
529         FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
530         assert( rwy != NULL );
531
532         SGGeod climb1 = rwy->pointOnCenterline(10 * SG_NM_TO_METER);
533         wpt = createInAir(ac, "10000ft climb", climb1, vClimb, 10000);
534         wpt->setGear_down(true);
535         wpt->setFlaps_down(true);
536         waypoints.push_back(wpt);
537
538         SGGeod climb2 = rwy->pointOnCenterline(20 * SG_NM_TO_METER);
539         wpt = cloneWithPos(ac, wpt, "18000ft climb", climb2);
540         wpt->setAltitude(18000);
541         waypoints.push_back(wpt);
542     }
543     return true;
544 }
545
546
547
548 /*******************************************************************
549  * CreateDescent
550  * Generate a flight path from the last waypoint of the cruise to 
551  * the permission to land point
552  ******************************************************************/
553 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
554                                    double latitude, double longitude,
555                                    double speed, double alt,
556                                    const string & fltType,
557                                    double requiredDistance)
558 {
559     bool reposition = false;
560     FGAIWaypoint *wpt;
561     double vDescent = ac->getPerformance()->vDescent();
562     double vApproach = ac->getPerformance()->vApproach();
563
564
565     //Beginning of Descent 
566     string rwyClass = getRunwayClassFromTrafficType(fltType);
567     double heading = ac->getTrafficRef()->getCourse();
568     apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
569                                         heading);
570     FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
571     assert( rwy != NULL );
572
573     // Create a slow descent path that ends 250 lateral to the runway.
574     double initialTurnRadius = getTurnRadius(vDescent, true);
575     //double finalTurnRadius = getTurnRadius(vApproach, true);
576
577 // get length of the downwind leg for the intended runway
578     double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance();    //12 * SG_NM_TO_METER;
579     //time_t previousArrivalTime=  apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
580
581
582     SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
583     SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
584     SGGeod refPoint = rwy->pointOnCenterline(0);
585     double distance = SGGeodesy::distanceM(current, initialTarget);
586     double azimuth = SGGeodesy::courseDeg(current, initialTarget);
587     double dummyAz2;
588
589     // To prevent absurdly steep approaches, compute the origin from where the approach should have started
590     SGGeod origin;
591
592     if (ac->getTrafficRef()->getCallSign() ==
593         fgGetString("/ai/track-callsign")) {
594         //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
595         //exit(1);
596     }
597
598     if (distance < requiredDistance * 0.8) {
599         reposition = true;
600         SGGeodesy::direct(initialTarget, azimuth,
601                           -requiredDistance, origin, dummyAz2);
602
603         distance = SGGeodesy::distanceM(current, initialTarget);
604         azimuth = SGGeodesy::courseDeg(current, initialTarget);
605     } else {
606         origin = current;
607     }
608
609
610     double dAlt = alt - (apt->getElevation() + 2000);
611
612     double nPoints = 100;
613
614     char buffer[16];
615
616     // The descent path contains the following phases:
617     // 1) a linear glide path from the initial position to
618     // 2) a semi circle turn to final
619     // 3) approach
620
621     //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
622     // Create an initial destination point on a semicircle
623     //cerr << "lateral offset : " << lateralOffset << endl;
624     //cerr << "Distance       : " << distance      << endl;
625     //cerr << "Azimuth        : " << azimuth       << endl;
626     //cerr << "Initial Lateral point: " << lateralOffset << endl;
627     double lat = refPoint.getLatitudeDeg();
628     double lon = refPoint.getLongitudeDeg();
629     //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
630     lat = initialTarget.getLatitudeDeg();
631     lon = initialTarget.getLongitudeDeg();
632     //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
633
634     double ratio = initialTurnRadius / distance;
635     if (ratio > 1.0)
636         ratio = 1.0;
637     if (ratio < -1.0)
638         ratio = -1.0;
639
640     double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
641     double newDistance =
642         cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
643     //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
644     double side = azimuth - rwy->headingDeg();
645     double lateralOffset = initialTurnRadius;
646     if (side < 0)
647         side += 360;
648     if (side < 180) {
649         lateralOffset *= -1;
650     }
651     // Calculate the ETA at final, based on remaining distance, and approach speed.
652     // distance should really consist of flying time to terniary target, plus circle 
653     // but the distance to secondary target should work as a reasonable approximation
654     // aditionally add the amount of distance covered by making a turn of "side"
655     double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
656     time_t remaining =
657         (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
658     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
659     //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
660     //     cerr << "   Arrival time estimation: turn angle " <<  side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
661     //     //exit(1);
662     //}
663
664     time_t eta = now + remaining;
665     //choose a distance to the runway such that it will take at least 60 seconds more
666     // time to get there than the previous aircraft.
667     // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
668
669     time_t newEta;
670
671     if (reposition == false) {
672         newEta =
673             apt->getDynamics()->getApproachController()->getRunway(rwy->
674                                                                    name
675                                                                    ())->
676             requestTimeSlot(eta);
677     } else {
678         newEta = eta;
679     }
680     //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
681     arrivalTime = newEta;
682     time_t additionalTimeNeeded = newEta - eta;
683     double distanceCovered =
684         ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
685     distanceOut += distanceCovered;
686     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
687     //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
688     //} else {
689     //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
690     //}
691     //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
692
693     SGGeod secondaryTarget =
694         rwy->pointOffCenterline(-distanceOut, lateralOffset);
695     initialTarget = rwy->pointOnCenterline(-distanceOut);
696     distance = SGGeodesy::distanceM(origin, secondaryTarget);
697     azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
698
699
700     lat = secondaryTarget.getLatitudeDeg();
701     lon = secondaryTarget.getLongitudeDeg();
702     //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
703     //cerr << "Distance       : " << distance      << endl;
704     //cerr << "Azimuth        : " << azimuth       << endl;
705
706
707     ratio = initialTurnRadius / distance;
708     if (ratio > 1.0)
709         ratio = 1.0;
710     if (ratio < -1.0)
711         ratio = -1.0;
712     newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
713     newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
714     //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
715     if (side < 180) {
716         azimuth += newHeading;
717     } else {
718         azimuth -= newHeading;
719     }
720
721     SGGeod tertiaryTarget;
722     SGGeodesy::direct(origin, azimuth,
723                       newDistance, tertiaryTarget, dummyAz2);
724
725     lat = tertiaryTarget.getLatitudeDeg();
726     lon = tertiaryTarget.getLongitudeDeg();
727     //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
728
729
730     for (int i = 1; i < nPoints; i++) {
731         SGGeod result;
732         double currentDist = i * (newDistance / nPoints);
733         double currentAltitude = alt - (i * (dAlt / nPoints));
734         SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
735         snprintf(buffer, 16, "descent%03d", i);
736         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
737         wpt->setCrossat(currentAltitude);
738         wpt->setTrackLength((newDistance / nPoints));
739         waypoints.push_back(wpt);
740         //cerr << "Track Length : " << wpt->trackLength;
741         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
742     }
743
744     //cerr << "Phase 2: Circle " << endl;
745     double initialAzimuth =
746         SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
747     double finalAzimuth =
748         SGGeodesy::courseDeg(secondaryTarget, initialTarget);
749
750     //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
751     int increment, startval, endval;
752     // circle right around secondary target if orig of position is to the right of the runway
753     // i.e. use negative angles; else circle leftward and use postivi
754     if (side < 180) {
755         increment = -1;
756         startval = floor(initialAzimuth);
757         endval = ceil(finalAzimuth);
758         if (endval > startval) {
759             endval -= 360;
760         }
761     } else {
762         increment = 1;
763         startval = ceil(initialAzimuth);
764         endval = floor(finalAzimuth);
765         if (endval < startval) {
766             endval += 360;
767         }
768
769     }
770
771     //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
772     double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
773     for (int i = startval; i != endval; i += increment) {
774         SGGeod result;
775         double currentAltitude = apt->getElevation() + 2000;
776         SGGeodesy::direct(secondaryTarget, i,
777                           initialTurnRadius, result, dummyAz2);
778         snprintf(buffer, 16, "turn%03d", i);
779         wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
780         wpt->setCrossat(currentAltitude);
781         wpt->setTrackLength(trackLength);
782         //cerr << "Track Length : " << wpt->trackLength;
783         waypoints.push_back(wpt);
784         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
785     }
786
787
788     // The approach leg should bring the aircraft to approximately 4-6 out, after which the landing phase should take over. 
789     //cerr << "Phase 3: Approach" << endl;
790     distanceOut -= distanceCovered;
791     for (int i = 1; i < nPoints; i++) {
792         SGGeod result;
793         double currentDist = i * (distanceOut / nPoints);
794         double currentAltitude =
795             apt->getElevation() + 2000 - (i * 2000 / nPoints);
796         snprintf(buffer, 16, "final%03d", i);
797         result = rwy->pointOnCenterline((-distanceOut) + currentDist);
798         wpt = createInAir(ac, buffer, result, currentAltitude, vApproach);
799         wpt->setCrossat(currentAltitude);
800         wpt->setTrackLength((distanceOut / nPoints));
801         // account for the extra distance due to an extended downwind leg
802         if (i == 1) {
803             wpt->setTrackLength(wpt->getTrackLength() + distanceCovered);
804         }
805         //cerr << "Track Length : " << wpt->trackLength;
806         waypoints.push_back(wpt);
807         //cerr << "  Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
808     }
809
810     //cerr << "Done" << endl;
811
812     // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
813     IncrementWaypoint(true);
814     IncrementWaypoint(true);
815
816     if (reposition) {
817         double tempDistance;
818         //double minDistance = HUGE_VAL;
819         string wptName;
820         tempDistance = SGGeodesy::distanceM(current, initialTarget);
821         time_t eta =
822             tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
823         time_t newEta =
824             apt->getDynamics()->getApproachController()->getRunway(rwy->
825                                                                    name
826                                                                    ())->
827             requestTimeSlot(eta);
828         arrivalTime = newEta;
829         double newDistance =
830             ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
831         //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
832         IncrementWaypoint(true);        // remove waypoint BOD2
833         while (checkTrackLength("final001") > newDistance) {
834             IncrementWaypoint(true);
835         }
836         //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
837         ac->resetPositionFromFlightPlan();
838     }
839     waypoints[1]->setName( (waypoints[1]->getName() + string("legend"))); 
840     return true;
841 }
842
843 /*******************************************************************
844  * CreateLanding
845  * Create a flight path from the "permision to land" point (currently
846    hardcoded at 5000 meters from the threshold) to the threshold, at
847    a standard glide slope angle of 3 degrees. 
848  ******************************************************************/
849 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
850                                    const string & fltType)
851 {
852     double vTouchdown = ac->getPerformance()->vTouchdown();
853     //double vTaxi = ac->getPerformance()->vTaxi();
854
855     //string rwyClass = getRunwayClassFromTrafficType(fltType);
856     //double heading = ac->getTrafficRef()->getCourse();
857     //apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway, heading);
858     //rwy = apt->getRunwayByIdent(activeRunway);
859
860
861     FGAIWaypoint *wpt;
862     double aptElev = apt->getElevation();
863
864     SGGeod coord;
865     char buffer[12];
866     for (int i = 1; i < 10; i++) {
867         snprintf(buffer, 12, "wpt%d", i);
868         FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
869         assert( rwy != NULL );
870
871         coord = rwy->pointOnCenterline(rwy->lengthM() * (i / 10.0));
872         wpt = createOnGround(ac, buffer, coord, aptElev, (vTouchdown / i));
873         wpt->setCrossat(apt->getElevation());
874         waypoints.push_back(wpt);
875     }
876
877     /*
878        //Runway Threshold
879        wpt = createOnGround(ac, "Threshold", rwy->threshold(), aptElev, vTouchdown);
880        wpt->crossat = apt->getElevation();
881        waypoints.push_back(wpt); 
882
883        // Roll-out
884        wpt = createOnGround(ac, "Center", rwy->geod(), aptElev, vTaxi*2);
885        waypoints.push_back(wpt);
886
887        SGGeod rollOut = rwy->pointOnCenterline(rwy->lengthM() * 0.9);
888        wpt = createOnGround(ac, "Roll Out", rollOut, aptElev, vTaxi);
889        wpt->crossat   = apt->getElevation();
890        waypoints.push_back(wpt); 
891      */
892     return true;
893 }
894
895 /*******************************************************************
896  * CreateParking
897  * initialize the Aircraft at the parking location
898  ******************************************************************/
899 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
900                                    double radius)
901 {
902     FGAIWaypoint *wpt;
903     double aptElev = apt->getElevation();
904     double lat = 0.0, lat2 = 0.0;
905     double lon = 0.0, lon2 = 0.0;
906     double az2 = 0.0;
907     double heading = 0.0;
908
909     double vTaxi = ac->getPerformance()->vTaxi();
910     double vTaxiReduced = vTaxi * (2.0 / 3.0);
911     apt->getDynamics()->getParking(gateId, &lat, &lon, &heading);
912     heading += 180.0;
913     if (heading > 360)
914         heading -= 360;
915     geo_direct_wgs_84(0, lat, lon, heading,
916                       2.2 * radius, &lat2, &lon2, &az2);
917     wpt =
918         createOnGround(ac, "taxiStart", SGGeod::fromDeg(lon2, lat2),
919                        aptElev, vTaxiReduced);
920     waypoints.push_back(wpt);
921
922     geo_direct_wgs_84(0, lat, lon, heading,
923                       0.1 * radius, &lat2, &lon2, &az2);
924
925     wpt =
926         createOnGround(ac, "taxiStart2", SGGeod::fromDeg(lon2, lat2),
927                        aptElev, vTaxiReduced);
928     waypoints.push_back(wpt);
929
930     wpt =
931         createOnGround(ac, "END", SGGeod::fromDeg(lon, lat), aptElev,
932                        vTaxiReduced);
933     waypoints.push_back(wpt);
934     return true;
935 }
936
937 /**
938  *
939  * @param fltType a string describing the type of
940  * traffic, normally used for gate assignments
941  * @return a converted string that gives the runway
942  * preference schedule to be used at aircraft having
943  * a preferential runway schedule implemented (i.e.
944  * having a rwyprefs.xml file
945  * 
946  * Currently valid traffic types for gate assignment:
947  * - gate (commercial gate)
948  * - cargo (commercial gargo),
949  * - ga (general aviation) ,
950  * - ul (ultralight),
951  * - mil-fighter (military - fighter),
952  * - mil-transport (military - transport)
953  *
954  * Valid runway classes:
955  * - com (commercial traffic: jetliners, passenger and cargo)
956  * - gen (general aviation)
957  * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
958  * - mil (all military traffic)
959  */
960 string FGAIFlightPlan::getRunwayClassFromTrafficType(string fltType)
961 {
962     if ((fltType == "gate") || (fltType == "cargo")) {
963         return string("com");
964     }
965     if (fltType == "ga") {
966         return string("gen");
967     }
968     if (fltType == "ul") {
969         return string("ul");
970     }
971     if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
972         return string("mil");
973     }
974     return string("com");
975 }
976
977
978 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
979 {
980     double turn_radius;
981     if (inAir == false) {
982         turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
983     } else {
984         turn_radius = 0.1911 * speed * speed;   // an estimate for 25 degrees bank
985     }
986     return turn_radius;
987 }