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 <Airports/groundnetwork.hxx>
38 #include "AIAircraft.hxx"
39 #include "performancedata.hxx"
41 #include <Main/fg_props.hxx>
42 #include <Environment/environment_mgr.hxx>
43 #include <Environment/environment.hxx>
44 #include <FDM/LaRCsim/basic_aero.h>
45 #include <Navaids/navrecord.hxx>
46 #include <Traffic/Schedule.hxx>
50 /* FGAIFlightPlan::create()
51 * dynamically create a flight plan for AI traffic, based on data provided by the
52 * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10)
54 * This is the top-level function, and the only one that is publicly available.
59 // Check lat/lon values during initialization;
60 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
61 FGAirport * arr, int legNr, double alt,
62 double speed, double latitude,
63 double longitude, bool firstFlight,
64 double radius, const string & fltType,
65 const string & aircraftType,
66 const string & airline, double distance)
69 int currWpt = wpt_iterator - waypoints.begin();
72 retVal = createPushBack(ac, firstFlight, dep,
73 radius, fltType, aircraftType, airline);
74 // Pregenerate the taxi leg.
76 // waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
77 // retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
81 retVal = createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
82 aircraftType, airline);
85 retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
88 retVal = createClimb(ac, firstFlight, dep, arr, speed, alt, fltType);
91 retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
95 retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
99 retVal = createLanding(ac, arr, fltType);
102 retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
105 retVal = createParking(ac, arr, radius);
109 SG_LOG(SG_AI, SG_ALERT,
110 "AIFlightPlan::create() attempting to create unknown leg"
111 " this is probably an internal program error");
114 wpt_iterator = waypoints.begin() + currWpt;
115 //don't increment leg right away, but only once we pass the actual last waypoint that was created.
116 // to do so, mark the last waypoint with a special status flag
118 waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
119 // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
127 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
128 const std::string & aName,
129 const SGGeod & aPos, double aElev,
132 FGAIWaypoint *wpt = new FGAIWaypoint;
133 wpt->setName (aName );
134 wpt->setLongitude (aPos.getLongitudeDeg() );
135 wpt->setLatitude (aPos.getLatitudeDeg() );
136 wpt->setAltitude (aElev );
137 wpt->setSpeed (aSpeed );
138 wpt->setCrossat (-10000.1 );
139 wpt->setGear_down (true );
140 wpt->setFlaps_down (true );
141 wpt->setFinished (false );
142 wpt->setOn_ground (true );
143 wpt->setRouteIndex (0 );
147 FGAIWaypoint * FGAIFlightPlan::createInAir(FGAIAircraft * ac,
148 const std::string & aName,
149 const SGGeod & aPos, double aElev,
152 FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
153 wpt->setGear_down (false );
154 wpt->setFlaps_down (false );
155 wpt->setOn_ground (false );
156 wpt->setCrossat (aElev );
160 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
162 FGAIWaypoint *wpt = new FGAIWaypoint;
163 wpt->setName ( aWpt->getName () );
164 wpt->setLongitude ( aWpt->getLongitude() );
165 wpt->setLatitude ( aWpt->getLatitude() );
166 wpt->setAltitude ( aWpt->getAltitude() );
167 wpt->setSpeed ( aWpt->getSpeed() );
168 wpt->setCrossat ( aWpt->getCrossat() );
169 wpt->setGear_down ( aWpt->getGear_down() );
170 wpt->setFlaps_down ( aWpt->getFlaps_down() );
171 wpt->setFinished ( aWpt->isFinished() );
172 wpt->setOn_ground ( aWpt->getOn_ground() );
173 wpt->setRouteIndex ( 0 );
179 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
180 const std::string & aName,
183 FGAIWaypoint *wpt = clone(aWpt);
184 wpt->setName ( aName );
185 wpt->setLongitude ( aPos.getLongitudeDeg () );
186 wpt->setLatitude ( aPos.getLatitudeDeg () );
193 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
194 FGAirport * aAirport,
197 SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
198 double airportElev = aAirport->getElevation();
202 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
203 ac->getPerformance()->vTaxi());
204 pushBackWaypoint(wpt);
206 createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
207 ac->getPerformance()->vTaxi());
208 pushBackWaypoint(wpt);
211 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
214 const string & fltType,
215 const string & acType,
216 const string & airline)
219 // If this function is called during initialization,
220 // make sure we obtain a valid gate ID first
221 // and place the model at the location of the gate.
222 if (firstFlight && apt->getDynamics()->hasParkings()) {
223 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
225 if (!gate.isValid()) {
226 SG_LOG(SG_AI, SG_WARN, "Could not find parking for a " <<
228 " of flight type " << fltType <<
229 " of airline " << airline <<
230 " at airport " << apt->getId());
234 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
236 // Only set this if it hasn't been set by ATC already.
237 if (activeRunway.empty()) {
238 //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
239 double depHeading = ac->getTrafficRef()->getCourse();
240 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
243 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
244 assert( rwy != NULL );
245 SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
247 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
249 createDefaultTakeoffTaxi(ac, apt, rwy);
253 FGTaxiNodeRef runwayNode;
254 if (gn->getVersion() > 0) {
255 FGTaxiNodeRef runwayNode = gn->findNearestNodeOnRunway(runwayTakeoff);
257 FGTaxiNodeRef runwayNode = gn->findNearestNode(runwayTakeoff);
260 // A negative gateId indicates an overflow parking, use a
261 // fallback mechanism for this.
262 // Starting from gate 0 in this case is a bit of a hack
263 // which requires a more proper solution later on.
265 // taxiRoute = new FGTaxiRoute;
267 // Determine which node to start from.
269 // Find out which node to start from
270 FGParking *park = gate.parking();
272 node = park->getPushBackPoint();
274 // Handle case where parking doesn't have a node
278 node = lastNodeVisited;
283 FGTaxiRoute taxiRoute;
285 taxiRoute = gn->findShortestRoute(node, runwayNode);
287 if (taxiRoute.empty()) {
288 createDefaultTakeoffTaxi(ac, apt, rwy);
293 FGTaxiNodeRef skipNode;
295 //bool isPushBackPoint = false;
297 // If this is called during initialization, randomly
298 // skip a number of waypoints to get a more realistic
300 int nrWaypointsToSkip = rand() % taxiRoute.size();
301 // but make sure we always keep two active waypoints
302 // to prevent a segmentation fault
303 for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
304 taxiRoute.next(skipNode, &route);
307 gate.release(); // free up our gate as required
309 if (taxiRoute.size() > 1) {
310 taxiRoute.next(skipNode, &route); // chop off the first waypoint, because that is already the last of the pushback route
314 // push each node on the taxi route as a waypoint
316 //cerr << "Building taxi route" << endl;
318 // Note that the line wpt->setRouteIndex was commented out by revision [afcdbd] 2012-01-01,
319 // which breaks the rendering functions.
320 // These can probably be generated on the fly however.
321 while (taxiRoute.next(node, &route)) {
323 snprintf(buffer, 10, "%d", node->getIndex());
325 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
326 ac->getPerformance()->vTaxi());
327 wpt->setRouteIndex(route);
328 //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
329 if (taxiRoute.nodesLeft() == 1) {
330 // Note that we actually have hold points in the ground network, but this is just an initial test.
331 //cerr << "Setting departurehold point: " << endl;
332 wpt->setName( wpt->getName() + string("DepartureHold"));
334 if (taxiRoute.nodesLeft() == 0) {
335 wpt->setName(wpt->getName() + string("Accel"));
337 pushBackWaypoint(wpt);
339 // Acceleration point, 105 meters into the runway,
340 SGGeod accelPoint = rwy->pointOnCenterline(105.0);
341 FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
342 pushBackWaypoint(wpt);
344 //cerr << "[done]" << endl;
348 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
349 FGAirport * aAirport)
352 SGGeod::fromDeg(waypoints.back()->getLongitude(),
353 waypoints.back()->getLatitude());
354 double airportElev = aAirport->getElevation();
358 createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
359 ac->getPerformance()->vTaxi());
360 pushBackWaypoint(wpt);
362 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
363 ac->getPerformance()->vTaxi());
364 pushBackWaypoint(wpt);
366 if (gate.isValid()) {
367 wpt = createOnGround(ac, "ENDtaxi", gate.parking()->geod(), airportElev,
368 ac->getPerformance()->vTaxi());
369 pushBackWaypoint(wpt);
373 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
375 const string & fltType,
376 const string & acType,
377 const string & airline)
380 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
383 SGGeod lastWptPos = waypoints.back()->getPos();
384 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
386 // Find a route from runway end to parking/gate.
388 createDefaultLandingTaxi(ac, apt);
392 FGTaxiNodeRef runwayNode;
393 if (gn->getVersion() == 1) {
394 runwayNode = gn->findNearestNodeOnRunway(lastWptPos);
396 runwayNode = gn->findNearestNode(lastWptPos);
398 //cerr << "Using network node " << runwayId << endl;
399 // A negative gateId indicates an overflow parking, use a
400 // fallback mechanism for this.
401 // Starting from gate 0 doesn't work, so don't try it
402 FGTaxiRoute taxiRoute;
404 taxiRoute = gn->findShortestRoute(runwayNode, gate.parking());
406 if (taxiRoute.empty()) {
407 createDefaultLandingTaxi(ac, apt);
413 int size = taxiRoute.size();
414 // Omit the last two waypoints, as
415 // those are created by createParking()
417 for (int i = 0; i < size - 2; i++) {
418 taxiRoute.next(node, &route);
420 snprintf(buffer, 10, "%d", node->getIndex());
422 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
423 ac->getPerformance()->vTaxi());
425 wpt->setRouteIndex(route);
426 pushBackWaypoint(wpt);
431 static double accelDistance(double v0, double v1, double accel)
433 double t = fabs(v1 - v0) / accel; // time in seconds to change velocity
434 // area under the v/t graph: (t * v0) + (dV / 2t) where (dV = v1 - v0)
435 return t * 0.5 * (v1 + v0);
438 // find the horizontal distance to gain the specific altiude, holding
439 // a constant pitch angle. Used to compute distance based on standard FD/AP
440 // PITCH mode prior to VS or CLIMB engaging. Visually, we want to avoid
441 // a dip in the nose angle after rotation, during initial climb-out.
442 static double pitchDistance(double pitchAngleDeg, double altGainM)
444 return altGainM / tan(pitchAngleDeg * SG_DEGREES_TO_RADIANS);
447 /*******************************************************************
450 * - Speed -> knots -> nm/hour
451 * - distance along runway =-> meters
452 * - accel / decel -> is given as knots/hour, but this is highly questionable:
453 * for a jet_transport performance class, a accel / decel rate of 5 / 2 is
454 * given respectively. According to performance data.cxx, a value of kts / second seems
455 * more likely however.
457 ******************************************************************/
458 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
459 FGAirport * apt, double speed,
460 const string & fltType)
462 const double ACCEL_POINT = 105.0;
463 // climb-out angle in degrees. could move this to the perf-db but this
464 // value is pretty sane
465 const double INITIAL_PITCH_ANGLE = 10.0;
467 double accel = ac->getPerformance()->acceleration();
468 double vTaxi = ac->getPerformance()->vTaxi();
469 double vRotate = ac->getPerformance()->vRotate();
470 double vTakeoff = ac->getPerformance()->vTakeoff();
472 double accelMetric = accel * SG_KT_TO_MPS;
473 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
474 double vRotateMetric = vRotate * SG_KT_TO_MPS;
477 // Get the current active runway, based on code from David Luff
478 // This should actually be unified and extended to include
479 // Preferential runway use schema's
480 // NOTE: DT (2009-01-18: IIRC, this is currently already the case,
481 // because the getActive runway function takes care of that.
483 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
484 double heading = ac->getTrafficRef()->getCourse();
485 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
489 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
490 assert( rwy != NULL );
491 double airportElev = apt->getElevation();
493 double d = accelDistance(vTaxiMetric, vRotateMetric, accelMetric) + ACCEL_POINT;
495 SGGeod accelPoint = rwy->pointOnCenterline(d);
496 wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
497 pushBackWaypoint(wpt);
499 double vRef = vTakeoff + 20; // climb-out at v2 + 20kts
501 double gearUpDist = d + pitchDistance(INITIAL_PITCH_ANGLE, 400 * SG_FEET_TO_METER);
502 accelPoint = rwy->pointOnCenterline(gearUpDist);
504 wpt = cloneWithPos(ac, wpt, "gear-up", accelPoint);
506 wpt->setCrossat(airportElev + 400);
507 wpt->setOn_ground(false);
508 wpt->setGear_down(false);
509 pushBackWaypoint(wpt);
511 // limit climbout speed to 240kts below 10000'
512 double vClimbBelow10000 = std::min(240.0, ac->getPerformance()->vClimb());
514 // create two climb-out points. This is important becuase the first climb point will
515 // be a (sometimes large) turn towards the destination, and we don't want to
516 // commence that turn below 2000'
517 double climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2000 * SG_FEET_TO_METER);
518 accelPoint = rwy->pointOnCenterline(climbOut);
519 wpt = createInAir(ac, "2000'", accelPoint, airportElev + 2000, vClimbBelow10000);
520 pushBackWaypoint(wpt);
522 climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2500 * SG_FEET_TO_METER);
523 accelPoint = rwy->pointOnCenterline(climbOut);
524 wpt = createInAir(ac, "2500'", accelPoint, airportElev + 2500, vClimbBelow10000);
525 pushBackWaypoint(wpt);
530 /*******************************************************************
532 * initialize the Aircraft at the parking location
533 ******************************************************************/
534 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
535 FGAirport * apt, FGAirport* arrival,
536 double speed, double alt,
537 const string & fltType)
541 double vClimb = ac->getPerformance()->vClimb();
544 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
545 double heading = ac->getTrafficRef()->getCourse();
546 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
550 for (wpt_vector_iterator i = sid->getFirstWayPoint();
551 i != sid->getLastWayPoint(); i++) {
552 pushBackWaypoint(clone(*(i)));
553 //cerr << " Cloning waypoint " << endl;
556 FGRunway* runway = apt->getRunwayByIdent(activeRunway);
557 SGGeod cur = runway->end();
558 if (!waypoints.empty()) {
559 cur = waypoints.back()->getPos();
562 // compute course towards destination
563 double course = SGGeodesy::courseDeg(cur, arrival->geod());
565 SGGeod climb1 = SGGeodesy::direct(cur, course, 10 * SG_NM_TO_METER);
566 wpt = createInAir(ac, "10000ft climb", climb1, 10000, vClimb);
567 wpt->setGear_down(true);
568 wpt->setFlaps_down(true);
569 pushBackWaypoint(wpt);
571 SGGeod climb2 = SGGeodesy::direct(cur, course, 20 * SG_NM_TO_METER);
572 wpt = createInAir(ac, "18000ft climb", climb2, 18000, vClimb);
573 pushBackWaypoint(wpt);
580 /*******************************************************************
582 * Generate a flight path from the last waypoint of the cruise to
583 * the permission to land point
584 ******************************************************************/
585 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
586 double latitude, double longitude,
587 double speed, double alt,
588 const string & fltType,
589 double requiredDistance)
591 bool reposition = false;
593 double vDescent = ac->getPerformance()->vDescent();
594 double vApproach = ac->getPerformance()->vApproach();
596 //Beginning of Descent
597 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
598 double heading = ac->getTrafficRef()->getCourse();
599 apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
601 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
602 assert( rwy != NULL );
604 // Create a slow descent path that ends 250 lateral to the runway.
605 double initialTurnRadius = getTurnRadius(vDescent, true);
606 //double finalTurnRadius = getTurnRadius(vApproach, true);
608 // get length of the downwind leg for the intended runway
609 double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance(); //12 * SG_NM_TO_METER;
610 //time_t previousArrivalTime= apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
613 SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
614 SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
615 SGGeod refPoint = rwy->pointOnCenterline(0);
616 double distance = SGGeodesy::distanceM(current, initialTarget);
617 double azimuth = SGGeodesy::courseDeg(current, initialTarget);
620 // To prevent absurdly steep approaches, compute the origin from where the approach should have started
623 if (ac->getTrafficRef()->getCallSign() ==
624 fgGetString("/ai/track-callsign")) {
625 //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
629 if (distance < requiredDistance * 0.8) {
631 SGGeodesy::direct(initialTarget, azimuth,
632 -requiredDistance, origin, dummyAz2);
634 distance = SGGeodesy::distanceM(current, initialTarget);
635 azimuth = SGGeodesy::courseDeg(current, initialTarget);
640 double dAlt = 0; // = alt - (apt->getElevation() + 2000);
642 if (apt->getDynamics()->getGroundNetwork()) {
643 tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
647 dAlt = alt - ((tn->getElevationFt()) + 2000);
649 dAlt = alt - (apt->getElevation() + 2000);
652 double nPoints = 100;
655 // The descent path contains the following phases:
656 // 1) a linear glide path from the initial position to
657 // 2) a semi circle turn to final
660 //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
661 // Create an initial destination point on a semicircle
662 //cerr << "lateral offset : " << lateralOffset << endl;
663 //cerr << "Distance : " << distance << endl;
664 //cerr << "Azimuth : " << azimuth << endl;
665 //cerr << "Initial Lateral point: " << lateralOffset << endl;
666 // double lat = refPoint.getLatitudeDeg();
667 // double lon = refPoint.getLongitudeDeg();
668 //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
669 // lat = initialTarget.getLatitudeDeg();
670 // lon = initialTarget.getLongitudeDeg();
671 //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
673 double ratio = initialTurnRadius / distance;
679 double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
681 cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
682 //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
683 double side = azimuth - rwy->headingDeg();
684 double lateralOffset = initialTurnRadius;
690 // Calculate the ETA at final, based on remaining distance, and approach speed.
691 // distance should really consist of flying time to terniary target, plus circle
692 // but the distance to secondary target should work as a reasonable approximation
693 // aditionally add the amount of distance covered by making a turn of "side"
694 double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
696 (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
697 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
698 //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
699 // cerr << " Arrival time estimation: turn angle " << side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
703 time_t eta = now + remaining;
704 //choose a distance to the runway such that it will take at least 60 seconds more
705 // time to get there than the previous aircraft.
706 // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
710 if (reposition == false) {
712 apt->getDynamics()->getApproachController()->getRunway(rwy->
715 requestTimeSlot(eta);
719 //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
720 arrivalTime = newEta;
721 time_t additionalTimeNeeded = newEta - eta;
722 double distanceCovered =
723 ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
724 distanceOut += distanceCovered;
725 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
726 //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
728 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
730 //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
732 SGGeod secondaryTarget =
733 rwy->pointOffCenterline(-distanceOut, lateralOffset);
734 initialTarget = rwy->pointOnCenterline(-distanceOut);
735 distance = SGGeodesy::distanceM(origin, secondaryTarget);
736 azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
739 // lat = secondaryTarget.getLatitudeDeg();
740 // lon = secondaryTarget.getLongitudeDeg();
741 //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
742 //cerr << "Distance : " << distance << endl;
743 //cerr << "Azimuth : " << azimuth << endl;
746 ratio = initialTurnRadius / distance;
751 newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
752 newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
753 //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
755 azimuth += newHeading;
757 azimuth -= newHeading;
760 SGGeod tertiaryTarget;
761 SGGeodesy::direct(origin, azimuth,
762 newDistance, tertiaryTarget, dummyAz2);
764 // lat = tertiaryTarget.getLatitudeDeg();
765 // lon = tertiaryTarget.getLongitudeDeg();
766 //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
769 for (int i = 1; i < nPoints; i++) {
771 double currentDist = i * (newDistance / nPoints);
772 double currentAltitude = alt - (i * (dAlt / nPoints));
773 SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
774 snprintf(buffer, 16, "descent%03d", i);
775 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
776 wpt->setCrossat(currentAltitude);
777 wpt->setTrackLength((newDistance / nPoints));
778 pushBackWaypoint(wpt);
779 //cerr << "Track Length : " << wpt->trackLength;
780 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
783 //cerr << "Phase 2: Circle " << endl;
784 double initialAzimuth =
785 SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
786 double finalAzimuth =
787 SGGeodesy::courseDeg(secondaryTarget, initialTarget);
789 //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
790 int increment, startval, endval;
791 // circle right around secondary target if orig of position is to the right of the runway
792 // i.e. use negative angles; else circle leftward and use postivi
795 startval = floor(initialAzimuth);
796 endval = ceil(finalAzimuth);
797 if (endval > startval) {
802 startval = ceil(initialAzimuth);
803 endval = floor(finalAzimuth);
804 if (endval < startval) {
810 //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
811 //FGTaxiNode * tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(initialTarget);
812 double currentAltitude = 0;
814 currentAltitude = (tn->getElevationFt()) + 2000;
816 currentAltitude = apt->getElevation() + 2000;
819 double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
820 for (int i = startval; i != endval; i += increment) {
822 //double currentAltitude = apt->getElevation() + 2000;
824 SGGeodesy::direct(secondaryTarget, i,
825 initialTurnRadius, result, dummyAz2);
826 snprintf(buffer, 16, "turn%03d", i);
827 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
828 wpt->setCrossat(currentAltitude);
829 wpt->setTrackLength(trackLength);
830 //cerr << "Track Length : " << wpt->trackLength;
831 pushBackWaypoint(wpt);
832 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
836 // The approach leg should bring the aircraft to approximately 4-6 nm out, after which the landing phase should take over.
837 //cerr << "Phase 3: Approach" << endl;
839 //cerr << "Done" << endl;
841 // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
842 IncrementWaypoint(true);
843 IncrementWaypoint(true);
847 //double minDistance = HUGE_VAL;
849 tempDistance = SGGeodesy::distanceM(current, initialTarget);
851 tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
853 apt->getDynamics()->getApproachController()->getRunway(rwy->
856 requestTimeSlot(eta);
857 arrivalTime = newEta;
859 ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
860 //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
861 IncrementWaypoint(true); // remove waypoint BOD2
862 while (checkTrackLength("final001") > newDistance) {
863 IncrementWaypoint(true);
865 //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
866 ac->resetPositionFromFlightPlan();
868 waypoints[1]->setName( (waypoints[1]->getName() + string("legend")));
873 * compute the distance along the centerline, to the ILS glideslope
874 * transmitter. Return -1 if there's no GS for the runway
876 static double runwayGlideslopeTouchdownDistance(FGRunway* rwy)
878 FGNavRecord* gs = rwy->glideslope();
883 SGVec3d runwayPosCart = SGVec3d::fromGeod(rwy->pointOnCenterline(0.0));
884 // compute a unit vector in ECF cartesian space, from the runway beginning to the end
885 SGVec3d runwayDirectionVec = normalize(SGVec3d::fromGeod(rwy->end()) - runwayPosCart);
886 SGVec3d gsTransmitterVec = gs->cart() - runwayPosCart;
888 // project the gsTransmitterVec along the runwayDirctionVec to get out
889 // final value (in metres)
890 double dist = dot(runwayDirectionVec, gsTransmitterVec);
894 /*******************************************************************
896 * Create a flight path from the "permision to land" point (currently
897 hardcoded at 5000 meters from the threshold) to the threshold, at
898 a standard glide slope angle of 3 degrees.
899 Position : 50.0354 8.52592 384 364 11112
900 ******************************************************************/
901 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
902 const string & fltType)
904 double vTouchdown = ac->getPerformance()->vTouchdown();
905 double vTaxi = ac->getPerformance()->vTaxi();
906 double decel = ac->getPerformance()->decelerationOnGround();
907 double vApproach = ac->getPerformance()->vApproach();
909 double vTouchdownMetric = vTouchdown * SG_KT_TO_MPS;
910 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
911 double decelMetric = decel * SG_KT_TO_MPS;
914 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
915 assert( rwy != NULL );
916 SGGeod threshold = rwy->threshold();
917 double currElev = threshold.getElevationFt();
919 double touchdownDistance = runwayGlideslopeTouchdownDistance(rwy);
920 if (touchdownDistance < 0.0) {
921 double landingLength = rwy->lengthM() - (rwy->displacedThresholdM());
922 // touchdown 25% of the way along the landing area
923 touchdownDistance = rwy->displacedThresholdM() + (landingLength * 0.25);
927 // find glideslope entry point, 2000' above touchdown elevation
928 double glideslopeEntry = -((2000 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
929 FGAIWaypoint *wpt = createInAir(ac, "Glideslope begin", rwy->pointOnCenterline(glideslopeEntry),
930 currElev + 2000, vApproach);
931 pushBackWaypoint(wpt);
933 // deceleration point, 500' above touchdown elevation - slow from approach speed
934 // to touchdown speed
935 double decelPoint = -((500 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
936 wpt = createInAir(ac, "500' decel", rwy->pointOnCenterline(decelPoint),
937 currElev + 2000, vTouchdown);
938 pushBackWaypoint(wpt);
940 // compute elevation above the runway start, based on a 3-degree glideslope
941 double heightAboveRunwayStart = touchdownDistance *
942 tan(3.0 * SG_DEGREES_TO_RADIANS) * SG_METER_TO_FEET;
943 wpt = createInAir(ac, "CrossThreshold", rwy->begin(),
944 heightAboveRunwayStart + currElev, vTouchdown);
945 pushBackWaypoint(wpt);
947 double rolloutDistance = accelDistance(vTouchdownMetric, vTaxiMetric, decelMetric);
950 for (int i = 1; i < nPoints; i++) {
951 snprintf(buffer, 12, "landing03%d", i);
952 double t = ((double) i) / nPoints;
953 coord = rwy->pointOnCenterline(touchdownDistance + (rolloutDistance * t));
954 double vel = (vTouchdownMetric * (1.0 - t)) + (vTaxiMetric * t);
955 wpt = createOnGround(ac, buffer, coord, currElev, vel);
956 wpt->setCrossat(currElev);
957 pushBackWaypoint(wpt);
960 wpt->setSpeed(vTaxi);
961 double mindist = (1.1 * rolloutDistance) + touchdownDistance;
963 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
968 coord = rwy->pointOnCenterline(mindist);
970 if (gn->getVersion() > 0) {
971 tn = gn->findNearestNodeOnRunway(coord, rwy);
973 tn = gn->findNearestNode(coord);
977 wpt = createOnGround(ac, buffer, tn->geod(), currElev, vTaxi);
978 pushBackWaypoint(wpt);
984 /*******************************************************************
986 * initialize the Aircraft at the parking location
987 ******************************************************************/
988 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
992 double aptElev = apt->getElevation();
993 double vTaxi = ac->getPerformance()->vTaxi();
994 double vTaxiReduced = vTaxi * (2.0 / 3.0);
995 if (!gate.isValid()) {
996 wpt = createOnGround(ac, "END-Parking", apt->geod(), aptElev,
998 pushBackWaypoint(wpt);
1002 FGParking* parking = gate.parking();
1003 double heading = SGMiscd::normalizePeriodic(0, 360, parking->getHeading() + 180.0);
1004 double az; // unused
1007 SGGeodesy::direct(parking->geod(), heading, 2.2 * parking->getRadius(),
1010 wpt = createOnGround(ac, "taxiStart", pos, aptElev, vTaxiReduced);
1011 pushBackWaypoint(wpt);
1013 SGGeodesy::direct(parking->geod(), heading, 0.1 * parking->getRadius(),
1015 wpt = createOnGround(ac, "taxiStart2", pos, aptElev, vTaxiReduced);
1016 pushBackWaypoint(wpt);
1018 wpt = createOnGround(ac, "END-Parking", parking->geod(), aptElev,
1020 pushBackWaypoint(wpt);
1026 * @param fltType a string describing the type of
1027 * traffic, normally used for gate assignments
1028 * @return a converted string that gives the runway
1029 * preference schedule to be used at aircraft having
1030 * a preferential runway schedule implemented (i.e.
1031 * having a rwyprefs.xml file
1033 * Currently valid traffic types for gate assignment:
1034 * - gate (commercial gate)
1035 * - cargo (commercial gargo),
1036 * - ga (general aviation) ,
1037 * - ul (ultralight),
1038 * - mil-fighter (military - fighter),
1039 * - mil-transport (military - transport)
1041 * Valid runway classes:
1042 * - com (commercial traffic: jetliners, passenger and cargo)
1043 * - gen (general aviation)
1044 * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
1045 * - mil (all military traffic)
1047 const char* FGAIFlightPlan::getRunwayClassFromTrafficType(const string& fltType)
1049 if ((fltType == "gate") || (fltType == "cargo")) {
1052 if (fltType == "ga") {
1055 if (fltType == "ul") {
1058 if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1065 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
1068 if (inAir == false) {
1069 turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
1071 turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank