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