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/simple.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>
45 /* FGAIFlightPlan::create()
46 * dynamically create a flight plan for AI traffic, based on data provided by the
47 * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10)
49 * This is the top-level function, and the only one that is publicly available.
54 // Check lat/lon values during initialization;
55 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
56 FGAirport * arr, int legNr, double alt,
57 double speed, double latitude,
58 double longitude, bool firstFlight,
59 double radius, const string & fltType,
60 const string & aircraftType,
61 const string & airline, double distance)
64 int currWpt = wpt_iterator - waypoints.begin();
67 retVal = createPushBack(ac, firstFlight, dep,
68 radius, fltType, aircraftType, airline);
69 // Pregenerate the taxi leg.
71 // waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
72 // retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
76 retVal = createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
77 aircraftType, airline);
80 retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
83 retVal = createClimb(ac, firstFlight, dep, arr, speed, alt, fltType);
86 retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
90 retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
94 retVal = createLanding(ac, arr, fltType);
97 retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
100 retVal = createParking(ac, arr, radius);
104 SG_LOG(SG_AI, SG_ALERT,
105 "AIFlightPlan::create() attempting to create unknown leg"
106 " this is probably an internal program error");
109 wpt_iterator = waypoints.begin() + currWpt;
110 //don't increment leg right away, but only once we pass the actual last waypoint that was created.
111 // to do so, mark the last waypoint with a special status flag
113 waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
114 // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
122 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
123 const std::string & aName,
124 const SGGeod & aPos, double aElev,
127 FGAIWaypoint *wpt = new FGAIWaypoint;
128 wpt->setName (aName );
129 wpt->setLongitude (aPos.getLongitudeDeg() );
130 wpt->setLatitude (aPos.getLatitudeDeg() );
131 wpt->setAltitude (aElev );
132 wpt->setSpeed (aSpeed );
133 wpt->setCrossat (-10000.1 );
134 wpt->setGear_down (true );
135 wpt->setFlaps_down (true );
136 wpt->setFinished (false );
137 wpt->setOn_ground (true );
138 wpt->setRouteIndex (0 );
142 FGAIWaypoint * FGAIFlightPlan::createInAir(FGAIAircraft * ac,
143 const std::string & aName,
144 const SGGeod & aPos, double aElev,
147 FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
148 wpt->setGear_down (false );
149 wpt->setFlaps_down (false );
150 wpt->setOn_ground (false );
151 wpt->setCrossat (aElev );
155 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
157 FGAIWaypoint *wpt = new FGAIWaypoint;
158 wpt->setName ( aWpt->getName () );
159 wpt->setLongitude ( aWpt->getLongitude() );
160 wpt->setLatitude ( aWpt->getLatitude() );
161 wpt->setAltitude ( aWpt->getAltitude() );
162 wpt->setSpeed ( aWpt->getSpeed() );
163 wpt->setCrossat ( aWpt->getCrossat() );
164 wpt->setGear_down ( aWpt->getGear_down() );
165 wpt->setFlaps_down ( aWpt->getFlaps_down() );
166 wpt->setFinished ( aWpt->isFinished() );
167 wpt->setOn_ground ( aWpt->getOn_ground() );
168 wpt->setRouteIndex ( 0 );
174 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
175 const std::string & aName,
178 FGAIWaypoint *wpt = clone(aWpt);
179 wpt->setName ( aName );
180 wpt->setLongitude ( aPos.getLongitudeDeg () );
181 wpt->setLatitude ( aPos.getLatitudeDeg () );
188 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
189 FGAirport * aAirport,
192 SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
193 double airportElev = aAirport->getElevation();
197 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
198 ac->getPerformance()->vTaxi());
199 pushBackWaypoint(wpt);
201 createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
202 ac->getPerformance()->vTaxi());
203 pushBackWaypoint(wpt);
206 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
209 const string & fltType,
210 const string & acType,
211 const string & airline)
214 // If this function is called during initialization,
215 // make sure we obtain a valid gate ID first
216 // and place the model at the location of the gate.
219 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
221 if (!gate.isValid()) {
222 SG_LOG(SG_AI, SG_WARN, "Could not find parking for a " <<
224 " of flight type " << fltType <<
225 " of airline " << airline <<
226 " at airport " << apt->getId());
230 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
232 // Only set this if it hasn't been set by ATC already.
233 if (activeRunway.empty()) {
234 //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
235 double depHeading = ac->getTrafficRef()->getCourse();
236 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
239 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
240 assert( rwy != NULL );
241 SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
243 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
245 createDefaultTakeoffTaxi(ac, apt, rwy);
250 PositionedID runwayId = 0;
251 if (gn->getVersion() > 0) {
252 runwayId = gn->findNearestNodeOnRunway(runwayTakeoff);
254 runwayId = 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.
265 PositionedID node = 0;
266 // Find out which node to start from
267 FGParking *park = gate.parking();
269 node = park->getPushBackPoint();
272 } else if (node == 0) {
273 // HAndle case where parking doens't have a node
277 node = lastNodeVisited;
282 FGTaxiRoute taxiRoute = gn->findShortestRoute(node, runwayId);
285 if (taxiRoute.empty()) {
286 createDefaultTakeoffTaxi(ac, apt, rwy);
291 //bool isPushBackPoint = false;
293 // If this is called during initialization, randomly
294 // skip a number of waypoints to get a more realistic
296 int nrWaypointsToSkip = rand() % taxiRoute.size();
297 // but make sure we always keep two active waypoints
298 // to prevent a segmentation fault
299 for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
300 taxiRoute.next(&node);
303 gate.release(); // free up our gate as required
305 if (taxiRoute.size() > 1) {
306 taxiRoute.next(&node); // chop off the first waypoint, because that is already the last of the pushback route
310 // push each node on the taxi route as a waypoint
312 //cerr << "Building taxi route" << endl;
313 while (taxiRoute.next(&node)) {
315 snprintf(buffer, 10, "%lld", (long long int) node);
317 apt->getDynamics()->getGroundNetwork()->findNode(node);
319 createOnGround(ac, buffer, tn->geod(), apt->getElevation(),
320 ac->getPerformance()->vTaxi());
321 // wpt->setRouteIndex(route);
322 //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
323 if (taxiRoute.nodesLeft() == 1) {
324 // Note that we actually have hold points in the ground network, but this is just an initial test.
325 //cerr << "Setting departurehold point: " << endl;
326 wpt->setName( wpt->getName() + string("DepartureHold"));
328 if (taxiRoute.nodesLeft() == 0) {
329 wpt->setName(wpt->getName() + string("Accel"));
331 pushBackWaypoint(wpt);
333 // Acceleration point, 105 meters into the runway,
334 SGGeod accelPoint = rwy->pointOnCenterline(105.0);
335 FGAIWaypoint *wpt = createOnGround(ac, "accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
336 pushBackWaypoint(wpt);
338 //cerr << "[done]" << endl;
342 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
343 FGAirport * aAirport)
346 SGGeod::fromDeg(waypoints.back()->getLongitude(),
347 waypoints.back()->getLatitude());
348 double airportElev = aAirport->getElevation();
352 createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
353 ac->getPerformance()->vTaxi());
354 pushBackWaypoint(wpt);
356 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
357 ac->getPerformance()->vTaxi());
358 pushBackWaypoint(wpt);
360 if (gate.isValid()) {
361 wpt = createOnGround(ac, "ENDtaxi", gate.parking()->geod(), airportElev,
362 ac->getPerformance()->vTaxi());
363 pushBackWaypoint(wpt);
367 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
369 const string & fltType,
370 const string & acType,
371 const string & airline)
373 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
376 SGGeod lastWptPos = waypoints.back()->getPos();
377 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
379 // Find a route from runway end to parking/gate.
381 createDefaultLandingTaxi(ac, apt);
386 PositionedID runwayId = 0;
387 if (gn->getVersion() == 1) {
388 runwayId = gn->findNearestNodeOnRunway(lastWptPos);
390 runwayId = gn->findNearestNode(lastWptPos);
392 //cerr << "Using network node " << runwayId << endl;
393 // A negative gateId indicates an overflow parking, use a
394 // fallback mechanism for this.
395 // Starting from gate 0 is a bit of a hack...
398 // taxiRoute = new FGTaxiRoute;
399 FGTaxiRoute taxiRoute;
401 taxiRoute = gn->findShortestRoute(runwayId, gate.parking()->guid());
403 taxiRoute = gn->findShortestRoute(runwayId, 0);
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);
420 snprintf(buffer, 10, "%lld", (long long int) node);
421 FGTaxiNode *tn = gn->findNode(node);
423 createOnGround(ac, buffer, tn->geod(), apt->getElevation(),
424 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 int node = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
644 tn = apt->getDynamics()->getGroundNetwork()->findNode(node);
648 dAlt = alt - ((tn->getElevationFt()) + 2000);
650 dAlt = alt - (apt->getElevation() + 2000);
653 double nPoints = 100;
656 // The descent path contains the following phases:
657 // 1) a linear glide path from the initial position to
658 // 2) a semi circle turn to final
661 //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
662 // Create an initial destination point on a semicircle
663 //cerr << "lateral offset : " << lateralOffset << endl;
664 //cerr << "Distance : " << distance << endl;
665 //cerr << "Azimuth : " << azimuth << endl;
666 //cerr << "Initial Lateral point: " << lateralOffset << endl;
667 // double lat = refPoint.getLatitudeDeg();
668 // double lon = refPoint.getLongitudeDeg();
669 //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
670 // lat = initialTarget.getLatitudeDeg();
671 // lon = initialTarget.getLongitudeDeg();
672 //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
674 double ratio = initialTurnRadius / distance;
680 double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
682 cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
683 //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
684 double side = azimuth - rwy->headingDeg();
685 double lateralOffset = initialTurnRadius;
691 // Calculate the ETA at final, based on remaining distance, and approach speed.
692 // distance should really consist of flying time to terniary target, plus circle
693 // but the distance to secondary target should work as a reasonable approximation
694 // aditionally add the amount of distance covered by making a turn of "side"
695 double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
697 (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
698 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
699 //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
700 // cerr << " Arrival time estimation: turn angle " << side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
704 time_t eta = now + remaining;
705 //choose a distance to the runway such that it will take at least 60 seconds more
706 // time to get there than the previous aircraft.
707 // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
711 if (reposition == false) {
713 apt->getDynamics()->getApproachController()->getRunway(rwy->
716 requestTimeSlot(eta);
720 //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
721 arrivalTime = newEta;
722 time_t additionalTimeNeeded = newEta - eta;
723 double distanceCovered =
724 ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
725 distanceOut += distanceCovered;
726 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
727 //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
729 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
731 //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
733 SGGeod secondaryTarget =
734 rwy->pointOffCenterline(-distanceOut, lateralOffset);
735 initialTarget = rwy->pointOnCenterline(-distanceOut);
736 distance = SGGeodesy::distanceM(origin, secondaryTarget);
737 azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
740 // lat = secondaryTarget.getLatitudeDeg();
741 // lon = secondaryTarget.getLongitudeDeg();
742 //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
743 //cerr << "Distance : " << distance << endl;
744 //cerr << "Azimuth : " << azimuth << endl;
747 ratio = initialTurnRadius / distance;
752 newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
753 newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
754 //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
756 azimuth += newHeading;
758 azimuth -= newHeading;
761 SGGeod tertiaryTarget;
762 SGGeodesy::direct(origin, azimuth,
763 newDistance, tertiaryTarget, dummyAz2);
765 // lat = tertiaryTarget.getLatitudeDeg();
766 // lon = tertiaryTarget.getLongitudeDeg();
767 //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
770 for (int i = 1; i < nPoints; i++) {
772 double currentDist = i * (newDistance / nPoints);
773 double currentAltitude = alt - (i * (dAlt / nPoints));
774 SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
775 snprintf(buffer, 16, "descent%03d", i);
776 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
777 wpt->setCrossat(currentAltitude);
778 wpt->setTrackLength((newDistance / nPoints));
779 pushBackWaypoint(wpt);
780 //cerr << "Track Length : " << wpt->trackLength;
781 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
784 //cerr << "Phase 2: Circle " << endl;
785 double initialAzimuth =
786 SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
787 double finalAzimuth =
788 SGGeodesy::courseDeg(secondaryTarget, initialTarget);
790 //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
791 int increment, startval, endval;
792 // circle right around secondary target if orig of position is to the right of the runway
793 // i.e. use negative angles; else circle leftward and use postivi
796 startval = floor(initialAzimuth);
797 endval = ceil(finalAzimuth);
798 if (endval > startval) {
803 startval = ceil(initialAzimuth);
804 endval = floor(finalAzimuth);
805 if (endval < startval) {
811 //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
812 //FGTaxiNode * tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(initialTarget);
813 double currentAltitude = 0;
815 currentAltitude = (tn->getElevationFt()) + 2000;
817 currentAltitude = apt->getElevation() + 2000;
820 double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
821 for (int i = startval; i != endval; i += increment) {
823 //double currentAltitude = apt->getElevation() + 2000;
825 SGGeodesy::direct(secondaryTarget, i,
826 initialTurnRadius, result, dummyAz2);
827 snprintf(buffer, 16, "turn%03d", i);
828 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
829 wpt->setCrossat(currentAltitude);
830 wpt->setTrackLength(trackLength);
831 //cerr << "Track Length : " << wpt->trackLength;
832 pushBackWaypoint(wpt);
833 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
837 // The approach leg should bring the aircraft to approximately 4-6 nm out, after which the landing phase should take over.
838 //cerr << "Phase 3: Approach" << endl;
840 //cerr << "Done" << endl;
842 // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
843 IncrementWaypoint(true);
844 IncrementWaypoint(true);
848 //double minDistance = HUGE_VAL;
850 tempDistance = SGGeodesy::distanceM(current, initialTarget);
852 tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
854 apt->getDynamics()->getApproachController()->getRunway(rwy->
857 requestTimeSlot(eta);
858 arrivalTime = newEta;
860 ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
861 //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
862 IncrementWaypoint(true); // remove waypoint BOD2
863 while (checkTrackLength("final001") > newDistance) {
864 IncrementWaypoint(true);
866 //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
867 ac->resetPositionFromFlightPlan();
869 waypoints[1]->setName( (waypoints[1]->getName() + string("legend")));
874 * compute the distance along the centerline, to the ILS glideslope
875 * transmitter. Return -1 if there's no GS for the runway
877 static double runwayGlideslopeTouchdownDistance(FGRunway* rwy)
879 FGNavRecord* gs = rwy->glideslope();
884 SGVec3d runwayPosCart = SGVec3d::fromGeod(rwy->pointOnCenterline(0.0));
885 // compute a unit vector in ECF cartesian space, from the runway beginning to the end
886 SGVec3d runwayDirectionVec = normalize(SGVec3d::fromGeod(rwy->end()) - runwayPosCart);
887 SGVec3d gsTransmitterVec = gs->cart() - runwayPosCart;
889 // project the gsTransmitterVec along the runwayDirctionVec to get out
890 // final value (in metres)
891 double dist = dot(runwayDirectionVec, gsTransmitterVec);
895 /*******************************************************************
897 * Create a flight path from the "permision to land" point (currently
898 hardcoded at 5000 meters from the threshold) to the threshold, at
899 a standard glide slope angle of 3 degrees.
900 Position : 50.0354 8.52592 384 364 11112
901 ******************************************************************/
902 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
903 const string & fltType)
905 double vTouchdown = ac->getPerformance()->vTouchdown();
906 double vTaxi = ac->getPerformance()->vTaxi();
907 double decel = ac->getPerformance()->decelerationOnGround();
908 double vApproach = ac->getPerformance()->vApproach();
910 double vTouchdownMetric = vTouchdown * SG_KT_TO_MPS;
911 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
912 double decelMetric = decel * SG_KT_TO_MPS;
915 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
916 assert( rwy != NULL );
917 SGGeod threshold = rwy->threshold();
918 double currElev = threshold.getElevationFt();
920 double touchdownDistance = runwayGlideslopeTouchdownDistance(rwy);
921 if (touchdownDistance < 0.0) {
922 double landingLength = rwy->lengthM() - (rwy->displacedThresholdM());
923 // touchdown 25% of the way along the landing area
924 touchdownDistance = rwy->displacedThresholdM() + (landingLength * 0.25);
928 // find glideslope entry point, 2000' above touchdown elevation
929 double glideslopeEntry = -((2000 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
930 FGAIWaypoint *wpt = createInAir(ac, "Glideslope begin", rwy->pointOnCenterline(glideslopeEntry),
931 currElev + 2000, vApproach);
932 pushBackWaypoint(wpt);
934 // deceleration point, 500' above touchdown elevation - slow from approach speed
935 // to touchdown speed
936 double decelPoint = -((500 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
937 wpt = createInAir(ac, "500' decel", rwy->pointOnCenterline(decelPoint),
938 currElev + 2000, vTouchdown);
939 pushBackWaypoint(wpt);
941 // compute elevation above the runway start, based on a 3-degree glideslope
942 double heightAboveRunwayStart = touchdownDistance *
943 tan(3.0 * SG_DEGREES_TO_RADIANS) * SG_METER_TO_FEET;
944 wpt = createInAir(ac, "CrossThreshold", rwy->begin(),
945 heightAboveRunwayStart + currElev, vTouchdown);
946 pushBackWaypoint(wpt);
948 double rolloutDistance = accelDistance(vTouchdownMetric, vTaxiMetric, decelMetric);
951 for (int i = 1; i < nPoints; i++) {
952 snprintf(buffer, 12, "landing03%d", i);
953 double t = ((double) i) / nPoints;
954 coord = rwy->pointOnCenterline(touchdownDistance + (rolloutDistance * t));
955 double vel = (vTouchdownMetric * (1.0 - t)) + (vTaxiMetric * t);
956 wpt = createOnGround(ac, buffer, coord, currElev, vel);
957 wpt->setCrossat(currElev);
958 pushBackWaypoint(wpt);
961 wpt->setSpeed(vTaxi);
962 double mindist = (1.1 * rolloutDistance) + touchdownDistance;
964 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
969 coord = rwy->pointOnCenterline(mindist);
971 if (gn->getVersion() > 0) {
972 nodeId = gn->findNearestNodeOnRunway(coord, rwy);
974 nodeId = gn->findNearestNode(coord);
977 FGTaxiNode* tn = gn->findNode(nodeId);
979 wpt = createOnGround(ac, buffer, tn->geod(), currElev, vTaxi);
980 pushBackWaypoint(wpt);
986 /*******************************************************************
988 * initialize the Aircraft at the parking location
989 ******************************************************************/
990 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
994 double aptElev = apt->getElevation();
995 double vTaxi = ac->getPerformance()->vTaxi();
996 double vTaxiReduced = vTaxi * (2.0 / 3.0);
997 if (!gate.isValid()) {
998 wpt = createOnGround(ac, "END-Parking", apt->geod(), aptElev,
1000 pushBackWaypoint(wpt);
1004 FGParking* parking = gate.parking();
1005 double heading = SGMiscd::normalizePeriodic(0, 360, parking->getHeading() + 180.0);
1006 double az; // unused
1009 SGGeodesy::direct(parking->geod(), heading, 2.2 * parking->getRadius(),
1012 wpt = createOnGround(ac, "taxiStart", pos, aptElev, vTaxiReduced);
1013 pushBackWaypoint(wpt);
1015 SGGeodesy::direct(parking->geod(), heading, 0.1 * parking->getRadius(),
1017 wpt = createOnGround(ac, "taxiStart2", pos, aptElev, vTaxiReduced);
1018 pushBackWaypoint(wpt);
1020 wpt = createOnGround(ac, "END-Parking", parking->geod(), aptElev,
1022 pushBackWaypoint(wpt);
1028 * @param fltType a string describing the type of
1029 * traffic, normally used for gate assignments
1030 * @return a converted string that gives the runway
1031 * preference schedule to be used at aircraft having
1032 * a preferential runway schedule implemented (i.e.
1033 * having a rwyprefs.xml file
1035 * Currently valid traffic types for gate assignment:
1036 * - gate (commercial gate)
1037 * - cargo (commercial gargo),
1038 * - ga (general aviation) ,
1039 * - ul (ultralight),
1040 * - mil-fighter (military - fighter),
1041 * - mil-transport (military - transport)
1043 * Valid runway classes:
1044 * - com (commercial traffic: jetliners, passenger and cargo)
1045 * - gen (general aviation)
1046 * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
1047 * - mil (all military traffic)
1049 const char* FGAIFlightPlan::getRunwayClassFromTrafficType(const string& fltType)
1051 if ((fltType == "gate") || (fltType == "cargo")) {
1054 if (fltType == "ga") {
1057 if (fltType == "ul") {
1060 if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1067 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
1070 if (inAir == false) {
1071 turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
1073 turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank