1 /******************************************************************************
2 * AIFlightPlanCreate.cxx
3 * Written by Durk Talsma, started May, 2004.
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.
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.
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.
19 **************************************************************************/
28 #include "AIFlightPlan.hxx"
29 #include <simgear/math/sg_geodesy.hxx>
30 #include <simgear/props/props.hxx>
31 #include <simgear/props/props_io.hxx>
33 #include <Airports/airport.hxx>
34 #include <Airports/runways.hxx>
35 #include <Airports/dynamics.hxx>
36 #include "AIAircraft.hxx"
37 #include "performancedata.hxx"
39 #include <Environment/environment_mgr.hxx>
40 #include <Environment/environment.hxx>
41 #include <FDM/LaRCsim/basic_aero.h>
42 #include <Navaids/navrecord.hxx>
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)
50 * This is the top-level function, and the only one that is publicly available.
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)
65 int currWpt = wpt_iterator - waypoints.begin();
68 retVal = createPushBack(ac, firstFlight, dep,
69 radius, fltType, aircraftType, airline);
70 // Pregenerate the taxi leg.
72 // waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
73 // retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
77 retVal = createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
78 aircraftType, airline);
81 retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
84 retVal = createClimb(ac, firstFlight, dep, arr, speed, alt, fltType);
87 retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
91 retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
95 retVal = createLanding(ac, arr, fltType);
98 retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
101 retVal = createParking(ac, arr, radius);
105 SG_LOG(SG_AI, SG_ALERT,
106 "AIFlightPlan::create() attempting to create unknown leg"
107 " this is probably an internal program error");
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
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)
123 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
124 const std::string & aName,
125 const SGGeod & aPos, double aElev,
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 );
143 FGAIWaypoint * FGAIFlightPlan::createInAir(FGAIAircraft * ac,
144 const std::string & aName,
145 const SGGeod & aPos, double aElev,
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 );
156 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
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 );
175 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
176 const std::string & aName,
179 FGAIWaypoint *wpt = clone(aWpt);
180 wpt->setName ( aName );
181 wpt->setLongitude ( aPos.getLongitudeDeg () );
182 wpt->setLatitude ( aPos.getLatitudeDeg () );
189 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
190 FGAirport * aAirport,
193 SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
194 double airportElev = aAirport->getElevation();
198 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
199 ac->getPerformance()->vTaxi());
200 pushBackWaypoint(wpt);
202 createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
203 ac->getPerformance()->vTaxi());
204 pushBackWaypoint(wpt);
207 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
210 const string & fltType,
211 const string & acType,
212 const string & airline)
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.
220 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
222 if (!gate.isValid()) {
223 SG_LOG(SG_AI, SG_WARN, "Could not find parking for a " <<
225 " of flight type " << fltType <<
226 " of airline " << airline <<
227 " at airport " << apt->getId());
231 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
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,
240 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
241 assert( rwy != NULL );
242 SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
244 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
246 createDefaultTakeoffTaxi(ac, apt, rwy);
250 FGTaxiNodeRef runwayNode;
251 if (gn->getVersion() > 0) {
252 FGTaxiNodeRef runwayNode = gn->findNearestNodeOnRunway(runwayTakeoff);
254 FGTaxiNodeRef runwayNode = gn->findNearestNode(runwayTakeoff);
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.
262 // taxiRoute = new FGTaxiRoute;
264 // Determine which node to start from.
266 // Find out which node to start from
267 FGParking *park = gate.parking();
269 node = park->getPushBackPoint();
271 // Handle case where parking doesn't have a node
275 node = lastNodeVisited;
280 FGTaxiRoute taxiRoute;
282 taxiRoute = gn->findShortestRoute(node, runwayNode);
284 if (taxiRoute.empty()) {
285 createDefaultTakeoffTaxi(ac, apt, rwy);
290 FGTaxiNodeRef skipNode;
292 //bool isPushBackPoint = false;
294 // If this is called during initialization, randomly
295 // skip a number of waypoints to get a more realistic
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(skipNode, &route);
304 gate.release(); // free up our gate as required
306 if (taxiRoute.size() > 1) {
307 taxiRoute.next(skipNode, &route); // chop off the first waypoint, because that is already the last of the pushback route
311 // push each node on the taxi route as a waypoint
313 //cerr << "Building taxi route" << endl;
315 // Note that the line wpt->setRouteIndex was commented out by revision [afcdbd] 2012-01-01,
316 // which breaks the rendering functions.
317 // These can probably be generated on the fly however.
318 while (taxiRoute.next(node, &route)) {
320 snprintf(buffer, 10, "%d", node->getIndex());
322 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
323 ac->getPerformance()->vTaxi());
324 wpt->setRouteIndex(route);
325 //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
326 if (taxiRoute.nodesLeft() == 1) {
327 // Note that we actually have hold points in the ground network, but this is just an initial test.
328 //cerr << "Setting departurehold point: " << endl;
329 wpt->setName( wpt->getName() + string("DepartureHold"));
331 if (taxiRoute.nodesLeft() == 0) {
332 wpt->setName(wpt->getName() + string("Accel"));
334 pushBackWaypoint(wpt);
336 // Acceleration point, 105 meters into the runway,
337 SGGeod accelPoint = rwy->pointOnCenterline(105.0);
338 FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
339 pushBackWaypoint(wpt);
341 //cerr << "[done]" << endl;
345 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
346 FGAirport * aAirport)
349 SGGeod::fromDeg(waypoints.back()->getLongitude(),
350 waypoints.back()->getLatitude());
351 double airportElev = aAirport->getElevation();
355 createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
356 ac->getPerformance()->vTaxi());
357 pushBackWaypoint(wpt);
359 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
360 ac->getPerformance()->vTaxi());
361 pushBackWaypoint(wpt);
363 if (gate.isValid()) {
364 wpt = createOnGround(ac, "ENDtaxi", gate.parking()->geod(), airportElev,
365 ac->getPerformance()->vTaxi());
366 pushBackWaypoint(wpt);
370 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
372 const string & fltType,
373 const string & acType,
374 const string & airline)
377 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
380 SGGeod lastWptPos = waypoints.back()->getPos();
381 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
383 // Find a route from runway end to parking/gate.
385 createDefaultLandingTaxi(ac, apt);
389 FGTaxiNodeRef runwayNode;
390 if (gn->getVersion() == 1) {
391 runwayNode = gn->findNearestNodeOnRunway(lastWptPos);
393 runwayNode = gn->findNearestNode(lastWptPos);
395 //cerr << "Using network node " << runwayId << endl;
396 // A negative gateId indicates an overflow parking, use a
397 // fallback mechanism for this.
398 // Starting from gate 0 doesn't work, so don't try it
399 FGTaxiRoute taxiRoute;
401 taxiRoute = gn->findShortestRoute(runwayNode, gate.parking());
403 if (taxiRoute.empty()) {
404 createDefaultLandingTaxi(ac, apt);
410 int size = taxiRoute.size();
411 // Omit the last two waypoints, as
412 // those are created by createParking()
414 for (int i = 0; i < size - 2; i++) {
415 taxiRoute.next(node, &route);
417 snprintf(buffer, 10, "%d", node->getIndex());
419 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
420 ac->getPerformance()->vTaxi());
422 wpt->setRouteIndex(route);
423 pushBackWaypoint(wpt);
428 static double accelDistance(double v0, double v1, double accel)
430 double t = fabs(v1 - v0) / accel; // time in seconds to change velocity
431 // area under the v/t graph: (t * v0) + (dV / 2t) where (dV = v1 - v0)
432 return t * 0.5 * (v1 + v0);
435 // find the horizontal distance to gain the specific altiude, holding
436 // a constant pitch angle. Used to compute distance based on standard FD/AP
437 // PITCH mode prior to VS or CLIMB engaging. Visually, we want to avoid
438 // a dip in the nose angle after rotation, during initial climb-out.
439 static double pitchDistance(double pitchAngleDeg, double altGainM)
441 return altGainM / tan(pitchAngleDeg * SG_DEGREES_TO_RADIANS);
444 /*******************************************************************
447 * - Speed -> knots -> nm/hour
448 * - distance along runway =-> meters
449 * - accel / decel -> is given as knots/hour, but this is highly questionable:
450 * for a jet_transport performance class, a accel / decel rate of 5 / 2 is
451 * given respectively. According to performance data.cxx, a value of kts / second seems
452 * more likely however.
454 ******************************************************************/
455 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
456 FGAirport * apt, double speed,
457 const string & fltType)
459 const double ACCEL_POINT = 105.0;
460 // climb-out angle in degrees. could move this to the perf-db but this
461 // value is pretty sane
462 const double INITIAL_PITCH_ANGLE = 10.0;
464 double accel = ac->getPerformance()->acceleration();
465 double vTaxi = ac->getPerformance()->vTaxi();
466 double vRotate = ac->getPerformance()->vRotate();
467 double vTakeoff = ac->getPerformance()->vTakeoff();
469 double accelMetric = accel * SG_KT_TO_MPS;
470 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
471 double vRotateMetric = vRotate * SG_KT_TO_MPS;
474 // Get the current active runway, based on code from David Luff
475 // This should actually be unified and extended to include
476 // Preferential runway use schema's
477 // NOTE: DT (2009-01-18: IIRC, this is currently already the case,
478 // because the getActive runway function takes care of that.
480 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
481 double heading = ac->getTrafficRef()->getCourse();
482 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
486 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
487 assert( rwy != NULL );
488 double airportElev = apt->getElevation();
490 double d = accelDistance(vTaxiMetric, vRotateMetric, accelMetric) + ACCEL_POINT;
492 SGGeod accelPoint = rwy->pointOnCenterline(d);
493 wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
494 pushBackWaypoint(wpt);
496 double vRef = vTakeoff + 20; // climb-out at v2 + 20kts
498 double gearUpDist = d + pitchDistance(INITIAL_PITCH_ANGLE, 400 * SG_FEET_TO_METER);
499 accelPoint = rwy->pointOnCenterline(gearUpDist);
501 wpt = cloneWithPos(ac, wpt, "gear-up", accelPoint);
503 wpt->setCrossat(airportElev + 400);
504 wpt->setOn_ground(false);
505 wpt->setGear_down(false);
506 pushBackWaypoint(wpt);
508 // limit climbout speed to 240kts below 10000'
509 double vClimbBelow10000 = std::min(240.0, ac->getPerformance()->vClimb());
511 // create two climb-out points. This is important becuase the first climb point will
512 // be a (sometimes large) turn towards the destination, and we don't want to
513 // commence that turn below 2000'
514 double climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2000 * SG_FEET_TO_METER);
515 accelPoint = rwy->pointOnCenterline(climbOut);
516 wpt = createInAir(ac, "2000'", accelPoint, airportElev + 2000, vClimbBelow10000);
517 pushBackWaypoint(wpt);
519 climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2500 * SG_FEET_TO_METER);
520 accelPoint = rwy->pointOnCenterline(climbOut);
521 wpt = createInAir(ac, "2500'", accelPoint, airportElev + 2500, vClimbBelow10000);
522 pushBackWaypoint(wpt);
527 /*******************************************************************
529 * initialize the Aircraft at the parking location
530 ******************************************************************/
531 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
532 FGAirport * apt, FGAirport* arrival,
533 double speed, double alt,
534 const string & fltType)
538 double vClimb = ac->getPerformance()->vClimb();
541 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
542 double heading = ac->getTrafficRef()->getCourse();
543 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
547 for (wpt_vector_iterator i = sid->getFirstWayPoint();
548 i != sid->getLastWayPoint(); i++) {
549 pushBackWaypoint(clone(*(i)));
550 //cerr << " Cloning waypoint " << endl;
553 FGRunway* runway = apt->getRunwayByIdent(activeRunway);
554 SGGeod cur = runway->end();
555 if (!waypoints.empty()) {
556 cur = waypoints.back()->getPos();
559 // compute course towards destination
560 double course = SGGeodesy::courseDeg(cur, arrival->geod());
562 SGGeod climb1 = SGGeodesy::direct(cur, course, 10 * SG_NM_TO_METER);
563 wpt = createInAir(ac, "10000ft climb", climb1, 10000, vClimb);
564 wpt->setGear_down(true);
565 wpt->setFlaps_down(true);
566 pushBackWaypoint(wpt);
568 SGGeod climb2 = SGGeodesy::direct(cur, course, 20 * SG_NM_TO_METER);
569 wpt = createInAir(ac, "18000ft climb", climb2, 18000, vClimb);
570 pushBackWaypoint(wpt);
577 /*******************************************************************
579 * Generate a flight path from the last waypoint of the cruise to
580 * the permission to land point
581 ******************************************************************/
582 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
583 double latitude, double longitude,
584 double speed, double alt,
585 const string & fltType,
586 double requiredDistance)
588 bool reposition = false;
590 double vDescent = ac->getPerformance()->vDescent();
591 double vApproach = ac->getPerformance()->vApproach();
593 //Beginning of Descent
594 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
595 double heading = ac->getTrafficRef()->getCourse();
596 apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
598 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
599 assert( rwy != NULL );
601 // Create a slow descent path that ends 250 lateral to the runway.
602 double initialTurnRadius = getTurnRadius(vDescent, true);
603 //double finalTurnRadius = getTurnRadius(vApproach, true);
605 // get length of the downwind leg for the intended runway
606 double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance(); //12 * SG_NM_TO_METER;
607 //time_t previousArrivalTime= apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
610 SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
611 SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
612 SGGeod refPoint = rwy->pointOnCenterline(0);
613 double distance = SGGeodesy::distanceM(current, initialTarget);
614 double azimuth = SGGeodesy::courseDeg(current, initialTarget);
617 // To prevent absurdly steep approaches, compute the origin from where the approach should have started
620 if (ac->getTrafficRef()->getCallSign() ==
621 fgGetString("/ai/track-callsign")) {
622 //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
626 if (distance < requiredDistance * 0.8) {
628 SGGeodesy::direct(initialTarget, azimuth,
629 -requiredDistance, origin, dummyAz2);
631 distance = SGGeodesy::distanceM(current, initialTarget);
632 azimuth = SGGeodesy::courseDeg(current, initialTarget);
637 double dAlt = 0; // = alt - (apt->getElevation() + 2000);
639 if (apt->getDynamics()->getGroundNetwork()) {
640 tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
644 dAlt = alt - ((tn->getElevationFt()) + 2000);
646 dAlt = alt - (apt->getElevation() + 2000);
649 double nPoints = 100;
652 // The descent path contains the following phases:
653 // 1) a linear glide path from the initial position to
654 // 2) a semi circle turn to final
657 //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
658 // Create an initial destination point on a semicircle
659 //cerr << "lateral offset : " << lateralOffset << endl;
660 //cerr << "Distance : " << distance << endl;
661 //cerr << "Azimuth : " << azimuth << endl;
662 //cerr << "Initial Lateral point: " << lateralOffset << endl;
663 // double lat = refPoint.getLatitudeDeg();
664 // double lon = refPoint.getLongitudeDeg();
665 //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
666 // lat = initialTarget.getLatitudeDeg();
667 // lon = initialTarget.getLongitudeDeg();
668 //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
670 double ratio = initialTurnRadius / distance;
676 double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
678 cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
679 //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
680 double side = azimuth - rwy->headingDeg();
681 double lateralOffset = initialTurnRadius;
687 // Calculate the ETA at final, based on remaining distance, and approach speed.
688 // distance should really consist of flying time to terniary target, plus circle
689 // but the distance to secondary target should work as a reasonable approximation
690 // aditionally add the amount of distance covered by making a turn of "side"
691 double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
693 (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
694 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
695 //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
696 // cerr << " Arrival time estimation: turn angle " << side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
700 time_t eta = now + remaining;
701 //choose a distance to the runway such that it will take at least 60 seconds more
702 // time to get there than the previous aircraft.
703 // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
707 if (reposition == false) {
709 apt->getDynamics()->getApproachController()->getRunway(rwy->
712 requestTimeSlot(eta);
716 //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
717 arrivalTime = newEta;
718 time_t additionalTimeNeeded = newEta - eta;
719 double distanceCovered =
720 ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
721 distanceOut += distanceCovered;
722 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
723 //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
725 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
727 //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
729 SGGeod secondaryTarget =
730 rwy->pointOffCenterline(-distanceOut, lateralOffset);
731 initialTarget = rwy->pointOnCenterline(-distanceOut);
732 distance = SGGeodesy::distanceM(origin, secondaryTarget);
733 azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
736 // lat = secondaryTarget.getLatitudeDeg();
737 // lon = secondaryTarget.getLongitudeDeg();
738 //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
739 //cerr << "Distance : " << distance << endl;
740 //cerr << "Azimuth : " << azimuth << endl;
743 ratio = initialTurnRadius / distance;
748 newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
749 newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
750 //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
752 azimuth += newHeading;
754 azimuth -= newHeading;
757 SGGeod tertiaryTarget;
758 SGGeodesy::direct(origin, azimuth,
759 newDistance, tertiaryTarget, dummyAz2);
761 // lat = tertiaryTarget.getLatitudeDeg();
762 // lon = tertiaryTarget.getLongitudeDeg();
763 //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
766 for (int i = 1; i < nPoints; i++) {
768 double currentDist = i * (newDistance / nPoints);
769 double currentAltitude = alt - (i * (dAlt / nPoints));
770 SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
771 snprintf(buffer, 16, "descent%03d", i);
772 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
773 wpt->setCrossat(currentAltitude);
774 wpt->setTrackLength((newDistance / nPoints));
775 pushBackWaypoint(wpt);
776 //cerr << "Track Length : " << wpt->trackLength;
777 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
780 //cerr << "Phase 2: Circle " << endl;
781 double initialAzimuth =
782 SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
783 double finalAzimuth =
784 SGGeodesy::courseDeg(secondaryTarget, initialTarget);
786 //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
787 int increment, startval, endval;
788 // circle right around secondary target if orig of position is to the right of the runway
789 // i.e. use negative angles; else circle leftward and use postivi
792 startval = floor(initialAzimuth);
793 endval = ceil(finalAzimuth);
794 if (endval > startval) {
799 startval = ceil(initialAzimuth);
800 endval = floor(finalAzimuth);
801 if (endval < startval) {
807 //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
808 //FGTaxiNode * tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(initialTarget);
809 double currentAltitude = 0;
811 currentAltitude = (tn->getElevationFt()) + 2000;
813 currentAltitude = apt->getElevation() + 2000;
816 double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
817 for (int i = startval; i != endval; i += increment) {
819 //double currentAltitude = apt->getElevation() + 2000;
821 SGGeodesy::direct(secondaryTarget, i,
822 initialTurnRadius, result, dummyAz2);
823 snprintf(buffer, 16, "turn%03d", i);
824 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
825 wpt->setCrossat(currentAltitude);
826 wpt->setTrackLength(trackLength);
827 //cerr << "Track Length : " << wpt->trackLength;
828 pushBackWaypoint(wpt);
829 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
833 // The approach leg should bring the aircraft to approximately 4-6 nm out, after which the landing phase should take over.
834 //cerr << "Phase 3: Approach" << endl;
836 //cerr << "Done" << endl;
838 // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
839 IncrementWaypoint(true);
840 IncrementWaypoint(true);
844 //double minDistance = HUGE_VAL;
846 tempDistance = SGGeodesy::distanceM(current, initialTarget);
848 tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
850 apt->getDynamics()->getApproachController()->getRunway(rwy->
853 requestTimeSlot(eta);
854 arrivalTime = newEta;
856 ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
857 //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
858 IncrementWaypoint(true); // remove waypoint BOD2
859 while (checkTrackLength("final001") > newDistance) {
860 IncrementWaypoint(true);
862 //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
863 ac->resetPositionFromFlightPlan();
865 waypoints[1]->setName( (waypoints[1]->getName() + string("legend")));
870 * compute the distance along the centerline, to the ILS glideslope
871 * transmitter. Return -1 if there's no GS for the runway
873 static double runwayGlideslopeTouchdownDistance(FGRunway* rwy)
875 FGNavRecord* gs = rwy->glideslope();
880 SGVec3d runwayPosCart = SGVec3d::fromGeod(rwy->pointOnCenterline(0.0));
881 // compute a unit vector in ECF cartesian space, from the runway beginning to the end
882 SGVec3d runwayDirectionVec = normalize(SGVec3d::fromGeod(rwy->end()) - runwayPosCart);
883 SGVec3d gsTransmitterVec = gs->cart() - runwayPosCart;
885 // project the gsTransmitterVec along the runwayDirctionVec to get out
886 // final value (in metres)
887 double dist = dot(runwayDirectionVec, gsTransmitterVec);
891 /*******************************************************************
893 * Create a flight path from the "permision to land" point (currently
894 hardcoded at 5000 meters from the threshold) to the threshold, at
895 a standard glide slope angle of 3 degrees.
896 Position : 50.0354 8.52592 384 364 11112
897 ******************************************************************/
898 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
899 const string & fltType)
901 double vTouchdown = ac->getPerformance()->vTouchdown();
902 double vTaxi = ac->getPerformance()->vTaxi();
903 double decel = ac->getPerformance()->decelerationOnGround();
904 double vApproach = ac->getPerformance()->vApproach();
906 double vTouchdownMetric = vTouchdown * SG_KT_TO_MPS;
907 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
908 double decelMetric = decel * SG_KT_TO_MPS;
911 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
912 assert( rwy != NULL );
913 SGGeod threshold = rwy->threshold();
914 double currElev = threshold.getElevationFt();
916 double touchdownDistance = runwayGlideslopeTouchdownDistance(rwy);
917 if (touchdownDistance < 0.0) {
918 double landingLength = rwy->lengthM() - (rwy->displacedThresholdM());
919 // touchdown 25% of the way along the landing area
920 touchdownDistance = rwy->displacedThresholdM() + (landingLength * 0.25);
924 // find glideslope entry point, 2000' above touchdown elevation
925 double glideslopeEntry = -((2000 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
926 FGAIWaypoint *wpt = createInAir(ac, "Glideslope begin", rwy->pointOnCenterline(glideslopeEntry),
927 currElev + 2000, vApproach);
928 pushBackWaypoint(wpt);
930 // deceleration point, 500' above touchdown elevation - slow from approach speed
931 // to touchdown speed
932 double decelPoint = -((500 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
933 wpt = createInAir(ac, "500' decel", rwy->pointOnCenterline(decelPoint),
934 currElev + 2000, vTouchdown);
935 pushBackWaypoint(wpt);
937 // compute elevation above the runway start, based on a 3-degree glideslope
938 double heightAboveRunwayStart = touchdownDistance *
939 tan(3.0 * SG_DEGREES_TO_RADIANS) * SG_METER_TO_FEET;
940 wpt = createInAir(ac, "CrossThreshold", rwy->begin(),
941 heightAboveRunwayStart + currElev, vTouchdown);
942 pushBackWaypoint(wpt);
944 double rolloutDistance = accelDistance(vTouchdownMetric, vTaxiMetric, decelMetric);
947 for (int i = 1; i < nPoints; i++) {
948 snprintf(buffer, 12, "landing03%d", i);
949 double t = ((double) i) / nPoints;
950 coord = rwy->pointOnCenterline(touchdownDistance + (rolloutDistance * t));
951 double vel = (vTouchdownMetric * (1.0 - t)) + (vTaxiMetric * t);
952 wpt = createOnGround(ac, buffer, coord, currElev, vel);
953 wpt->setCrossat(currElev);
954 pushBackWaypoint(wpt);
957 wpt->setSpeed(vTaxi);
958 double mindist = (1.1 * rolloutDistance) + touchdownDistance;
960 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
965 coord = rwy->pointOnCenterline(mindist);
967 if (gn->getVersion() > 0) {
968 tn = gn->findNearestNodeOnRunway(coord, rwy);
970 tn = gn->findNearestNode(coord);
974 wpt = createOnGround(ac, buffer, tn->geod(), currElev, vTaxi);
975 pushBackWaypoint(wpt);
981 /*******************************************************************
983 * initialize the Aircraft at the parking location
984 ******************************************************************/
985 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
989 double aptElev = apt->getElevation();
990 double vTaxi = ac->getPerformance()->vTaxi();
991 double vTaxiReduced = vTaxi * (2.0 / 3.0);
992 if (!gate.isValid()) {
993 wpt = createOnGround(ac, "END-Parking", apt->geod(), aptElev,
995 pushBackWaypoint(wpt);
999 FGParking* parking = gate.parking();
1000 double heading = SGMiscd::normalizePeriodic(0, 360, parking->getHeading() + 180.0);
1001 double az; // unused
1004 SGGeodesy::direct(parking->geod(), heading, 2.2 * parking->getRadius(),
1007 wpt = createOnGround(ac, "taxiStart", pos, aptElev, vTaxiReduced);
1008 pushBackWaypoint(wpt);
1010 SGGeodesy::direct(parking->geod(), heading, 0.1 * parking->getRadius(),
1012 wpt = createOnGround(ac, "taxiStart2", pos, aptElev, vTaxiReduced);
1013 pushBackWaypoint(wpt);
1015 wpt = createOnGround(ac, "END-Parking", parking->geod(), aptElev,
1017 pushBackWaypoint(wpt);
1023 * @param fltType a string describing the type of
1024 * traffic, normally used for gate assignments
1025 * @return a converted string that gives the runway
1026 * preference schedule to be used at aircraft having
1027 * a preferential runway schedule implemented (i.e.
1028 * having a rwyprefs.xml file
1030 * Currently valid traffic types for gate assignment:
1031 * - gate (commercial gate)
1032 * - cargo (commercial gargo),
1033 * - ga (general aviation) ,
1034 * - ul (ultralight),
1035 * - mil-fighter (military - fighter),
1036 * - mil-transport (military - transport)
1038 * Valid runway classes:
1039 * - com (commercial traffic: jetliners, passenger and cargo)
1040 * - gen (general aviation)
1041 * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
1042 * - mil (all military traffic)
1044 const char* FGAIFlightPlan::getRunwayClassFromTrafficType(const string& fltType)
1046 if ((fltType == "gate") || (fltType == "cargo")) {
1049 if (fltType == "ga") {
1052 if (fltType == "ul") {
1055 if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1062 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
1065 if (inAir == false) {
1066 turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
1068 turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank