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