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>
32 #include <simgear/timing/sg_time.hxx>
34 #include <Airports/airport.hxx>
35 #include <Airports/runways.hxx>
36 #include <Airports/dynamics.hxx>
37 #include <Airports/groundnetwork.hxx>
39 #include "AIAircraft.hxx"
40 #include "performancedata.hxx"
42 #include <Main/fg_props.hxx>
43 #include <Environment/environment_mgr.hxx>
44 #include <Environment/environment.hxx>
45 #include <FDM/LaRCsim/basic_aero.h>
46 #include <Navaids/navrecord.hxx>
47 #include <Traffic/Schedule.hxx>
51 /* FGAIFlightPlan::create()
52 * dynamically create a flight plan for AI traffic, based on data provided by the
53 * Traffic Manager, when reading a filed flightplan failes. (DT, 2004/07/10)
55 * This is the top-level function, and the only one that is publicly available.
60 // Check lat/lon values during initialization;
61 bool FGAIFlightPlan::create(FGAIAircraft * ac, FGAirport * dep,
62 FGAirport * arr, int legNr, double alt,
63 double speed, double latitude,
64 double longitude, bool firstFlight,
65 double radius, const string & fltType,
66 const string & aircraftType,
67 const string & airline, double distance)
70 int currWpt = wpt_iterator - waypoints.begin();
73 retVal = createPushBack(ac, firstFlight, dep,
74 radius, fltType, aircraftType, airline);
75 // Pregenerate the taxi leg.
77 // waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
78 // retVal = createTakeoffTaxi(ac, false, dep, radius, fltType, aircraftType, airline);
82 retVal = createTakeoffTaxi(ac, firstFlight, dep, radius, fltType,
83 aircraftType, airline);
86 retVal = createTakeOff(ac, firstFlight, dep, speed, fltType);
89 retVal = createClimb(ac, firstFlight, dep, arr, speed, alt, fltType);
92 retVal = createCruise(ac, firstFlight, dep, arr, latitude, longitude, speed,
96 retVal = createDescent(ac, arr, latitude, longitude, speed, alt, fltType,
100 retVal = createLanding(ac, arr, fltType);
103 retVal = createLandingTaxi(ac, arr, radius, fltType, aircraftType, airline);
106 retVal = createParking(ac, arr, radius);
110 SG_LOG(SG_AI, SG_ALERT,
111 "AIFlightPlan::create() attempting to create unknown leg"
112 " this is probably an internal program error");
115 wpt_iterator = waypoints.begin() + currWpt;
116 //don't increment leg right away, but only once we pass the actual last waypoint that was created.
117 // to do so, mark the last waypoint with a special status flag
119 waypoints.back()->setName( waypoints.back()->getName() + string("legend"));
120 // "It's pronounced Leg-end" (Roger Glover (Deep Purple): come Hell or High Water DvD, 1993)
128 FGAIWaypoint * FGAIFlightPlan::createOnGround(FGAIAircraft * ac,
129 const std::string & aName,
130 const SGGeod & aPos, double aElev,
133 FGAIWaypoint *wpt = new FGAIWaypoint;
134 wpt->setName (aName );
135 wpt->setLongitude (aPos.getLongitudeDeg() );
136 wpt->setLatitude (aPos.getLatitudeDeg() );
137 wpt->setAltitude (aElev );
138 wpt->setSpeed (aSpeed );
139 wpt->setCrossat (-10000.1 );
140 wpt->setGear_down (true );
141 wpt->setFlaps_down (true );
142 wpt->setFinished (false );
143 wpt->setOn_ground (true );
144 wpt->setRouteIndex (0 );
148 FGAIWaypoint * FGAIFlightPlan::createInAir(FGAIAircraft * ac,
149 const std::string & aName,
150 const SGGeod & aPos, double aElev,
153 FGAIWaypoint * wpt = createOnGround(ac, aName, aPos, aElev, aSpeed);
154 wpt->setGear_down (false );
155 wpt->setFlaps_down (false );
156 wpt->setOn_ground (false );
157 wpt->setCrossat (aElev );
161 FGAIWaypoint * FGAIFlightPlan::clone(FGAIWaypoint * aWpt)
163 FGAIWaypoint *wpt = new FGAIWaypoint;
164 wpt->setName ( aWpt->getName () );
165 wpt->setLongitude ( aWpt->getLongitude() );
166 wpt->setLatitude ( aWpt->getLatitude() );
167 wpt->setAltitude ( aWpt->getAltitude() );
168 wpt->setSpeed ( aWpt->getSpeed() );
169 wpt->setCrossat ( aWpt->getCrossat() );
170 wpt->setGear_down ( aWpt->getGear_down() );
171 wpt->setFlaps_down ( aWpt->getFlaps_down() );
172 wpt->setFinished ( aWpt->isFinished() );
173 wpt->setOn_ground ( aWpt->getOn_ground() );
174 wpt->setRouteIndex ( 0 );
180 FGAIWaypoint * FGAIFlightPlan::cloneWithPos(FGAIAircraft * ac, FGAIWaypoint * aWpt,
181 const std::string & aName,
184 FGAIWaypoint *wpt = clone(aWpt);
185 wpt->setName ( aName );
186 wpt->setLongitude ( aPos.getLongitudeDeg () );
187 wpt->setLatitude ( aPos.getLatitudeDeg () );
194 void FGAIFlightPlan::createDefaultTakeoffTaxi(FGAIAircraft * ac,
195 FGAirport * aAirport,
198 SGGeod runwayTakeoff = aRunway->pointOnCenterline(5.0);
199 double airportElev = aAirport->getElevation();
203 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
204 ac->getPerformance()->vTaxi());
205 pushBackWaypoint(wpt);
207 createOnGround(ac, "Runway Takeoff", runwayTakeoff, airportElev,
208 ac->getPerformance()->vTaxi());
210 pushBackWaypoint(wpt);
212 // Acceleration point, 105 meters into the runway,
213 SGGeod accelPoint = aRunway->pointOnCenterline(105.0);
214 wpt = createOnGround(ac, "Accel", accelPoint, airportElev,
215 ac->getPerformance()->vRotate());
216 pushBackWaypoint(wpt);
219 bool FGAIFlightPlan::createTakeoffTaxi(FGAIAircraft * ac, bool firstFlight,
222 const string & fltType,
223 const string & acType,
224 const string & airline)
227 // If this function is called during initialization,
228 // make sure we obtain a valid gate ID first
229 // and place the model at the location of the gate.
230 if (firstFlight && apt->getDynamics()->hasParkings()) {
231 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
233 if (!gate.isValid()) {
234 SG_LOG(SG_AI, SG_WARN, "Could not find parking for a " <<
236 " of flight type " << fltType <<
237 " of airline " << airline <<
238 " at airport " << apt->getId());
242 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
244 // Only set this if it hasn't been set by ATC already.
245 if (activeRunway.empty()) {
246 //cerr << "Getting runway for " << ac->getTrafficRef()->getCallSign() << " at " << apt->getId() << endl;
247 double depHeading = ac->getTrafficRef()->getCourse();
248 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
251 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
252 assert( rwy != NULL );
253 SGGeod runwayTakeoff = rwy->pointOnCenterline(5.0);
255 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
257 createDefaultTakeoffTaxi(ac, apt, rwy);
261 FGTaxiNodeRef runwayNode;
262 if (gn->getVersion() > 0) {
263 runwayNode = gn->findNearestNodeOnRunway(runwayTakeoff);
265 runwayNode = gn->findNearestNode(runwayTakeoff);
268 // A negative gateId indicates an overflow parking, use a
269 // fallback mechanism for this.
270 // Starting from gate 0 in this case is a bit of a hack
271 // which requires a more proper solution later on.
273 // taxiRoute = new FGTaxiRoute;
275 // Determine which node to start from.
277 // Find out which node to start from
278 FGParking *park = gate.parking();
280 node = park->getPushBackPoint();
282 // Handle case where parking doesn't have a node
286 node = lastNodeVisited;
291 FGTaxiRoute taxiRoute;
293 taxiRoute = gn->findShortestRoute(node, runwayNode);
295 if (taxiRoute.empty()) {
296 createDefaultTakeoffTaxi(ac, apt, rwy);
301 FGTaxiNodeRef skipNode;
303 //bool isPushBackPoint = false;
305 // If this is called during initialization, randomly
306 // skip a number of waypoints to get a more realistic
308 int nrWaypointsToSkip = rand() % taxiRoute.size();
309 // but make sure we always keep two active waypoints
310 // to prevent a segmentation fault
311 for (int i = 0; i < nrWaypointsToSkip - 3; i++) {
312 taxiRoute.next(skipNode, &route);
315 gate.release(); // free up our gate as required
317 if (taxiRoute.size() > 1) {
318 taxiRoute.next(skipNode, &route); // chop off the first waypoint, because that is already the last of the pushback route
322 // push each node on the taxi route as a waypoint
324 //cerr << "Building taxi route" << endl;
326 // Note that the line wpt->setRouteIndex was commented out by revision [afcdbd] 2012-01-01,
327 // which breaks the rendering functions.
328 // These can probably be generated on the fly however.
329 while (taxiRoute.next(node, &route)) {
331 snprintf(buffer, 10, "%d", node->getIndex());
333 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
334 ac->getPerformance()->vTaxi());
335 wpt->setRouteIndex(route);
336 //cerr << "Nodes left " << taxiRoute->nodesLeft() << " ";
337 if (taxiRoute.nodesLeft() == 1) {
338 // Note that we actually have hold points in the ground network, but this is just an initial test.
339 //cerr << "Setting departurehold point: " << endl;
340 wpt->setName( wpt->getName() + string("DepartureHold"));
342 if (taxiRoute.nodesLeft() == 0) {
343 wpt->setName(wpt->getName() + string("Accel"));
345 pushBackWaypoint(wpt);
347 // Acceleration point, 105 meters into the runway,
348 SGGeod accelPoint = rwy->pointOnCenterline(105.0);
349 FGAIWaypoint *wpt = createOnGround(ac, "Accel", accelPoint, apt->getElevation(), ac->getPerformance()->vRotate());
350 pushBackWaypoint(wpt);
352 //cerr << "[done]" << endl;
356 void FGAIFlightPlan::createDefaultLandingTaxi(FGAIAircraft * ac,
357 FGAirport * aAirport)
360 SGGeod::fromDeg(waypoints.back()->getLongitude(),
361 waypoints.back()->getLatitude());
362 double airportElev = aAirport->getElevation();
366 createOnGround(ac, "Runway Exit", lastWptPos, airportElev,
367 ac->getPerformance()->vTaxi());
368 pushBackWaypoint(wpt);
370 createOnGround(ac, "Airport Center", aAirport->geod(), airportElev,
371 ac->getPerformance()->vTaxi());
372 pushBackWaypoint(wpt);
374 if (gate.isValid()) {
375 wpt = createOnGround(ac, "ENDtaxi", gate.parking()->geod(), airportElev,
376 ac->getPerformance()->vTaxi());
377 pushBackWaypoint(wpt);
381 bool FGAIFlightPlan::createLandingTaxi(FGAIAircraft * ac, FGAirport * apt,
383 const string & fltType,
384 const string & acType,
385 const string & airline)
388 gate = apt->getDynamics()->getAvailableParking(radius, fltType,
391 SGGeod lastWptPos = waypoints.back()->getPos();
392 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
394 // Find a route from runway end to parking/gate.
396 createDefaultLandingTaxi(ac, apt);
400 FGTaxiNodeRef runwayNode;
401 if (gn->getVersion() == 1) {
402 runwayNode = gn->findNearestNodeOnRunway(lastWptPos);
404 runwayNode = gn->findNearestNode(lastWptPos);
406 //cerr << "Using network node " << runwayId << endl;
407 // A negative gateId indicates an overflow parking, use a
408 // fallback mechanism for this.
409 // Starting from gate 0 doesn't work, so don't try it
410 FGTaxiRoute taxiRoute;
412 taxiRoute = gn->findShortestRoute(runwayNode, gate.parking());
414 if (taxiRoute.empty()) {
415 createDefaultLandingTaxi(ac, apt);
421 int size = taxiRoute.size();
422 // Omit the last two waypoints, as
423 // those are created by createParking()
425 for (int i = 0; i < size - 2; i++) {
426 taxiRoute.next(node, &route);
428 snprintf(buffer, 10, "%d", node->getIndex());
430 createOnGround(ac, buffer, node->geod(), apt->getElevation(),
431 ac->getPerformance()->vTaxi());
433 wpt->setRouteIndex(route);
434 pushBackWaypoint(wpt);
439 static double accelDistance(double v0, double v1, double accel)
441 double t = fabs(v1 - v0) / accel; // time in seconds to change velocity
442 // area under the v/t graph: (t * v0) + (dV / 2t) where (dV = v1 - v0)
443 return t * 0.5 * (v1 + v0);
446 // find the horizontal distance to gain the specific altiude, holding
447 // a constant pitch angle. Used to compute distance based on standard FD/AP
448 // PITCH mode prior to VS or CLIMB engaging. Visually, we want to avoid
449 // a dip in the nose angle after rotation, during initial climb-out.
450 static double pitchDistance(double pitchAngleDeg, double altGainM)
452 return altGainM / tan(pitchAngleDeg * SG_DEGREES_TO_RADIANS);
455 /*******************************************************************
458 * - Speed -> knots -> nm/hour
459 * - distance along runway =-> meters
460 * - accel / decel -> is given as knots/hour, but this is highly questionable:
461 * for a jet_transport performance class, a accel / decel rate of 5 / 2 is
462 * given respectively. According to performance data.cxx, a value of kts / second seems
463 * more likely however.
465 ******************************************************************/
466 bool FGAIFlightPlan::createTakeOff(FGAIAircraft * ac, bool firstFlight,
467 FGAirport * apt, double speed,
468 const string & fltType)
470 const double ACCEL_POINT = 105.0;
471 // climb-out angle in degrees. could move this to the perf-db but this
472 // value is pretty sane
473 const double INITIAL_PITCH_ANGLE = 10.0;
475 double accel = ac->getPerformance()->acceleration();
476 double vTaxi = ac->getPerformance()->vTaxi();
477 double vRotate = ac->getPerformance()->vRotate();
478 double vTakeoff = ac->getPerformance()->vTakeoff();
480 double accelMetric = accel * SG_KT_TO_MPS;
481 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
482 double vRotateMetric = vRotate * SG_KT_TO_MPS;
485 // Get the current active runway, based on code from David Luff
486 // This should actually be unified and extended to include
487 // Preferential runway use schema's
488 // NOTE: DT (2009-01-18: IIRC, this is currently already the case,
489 // because the getActive runway function takes care of that.
491 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
492 double heading = ac->getTrafficRef()->getCourse();
493 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
497 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
498 assert( rwy != NULL );
499 double airportElev = apt->getElevation();
501 double d = accelDistance(vTaxiMetric, vRotateMetric, accelMetric) + ACCEL_POINT;
503 SGGeod accelPoint = rwy->pointOnCenterline(d);
504 wpt = createOnGround(ac, "rotate", accelPoint, airportElev, vTakeoff);
505 pushBackWaypoint(wpt);
507 double vRef = vTakeoff + 20; // climb-out at v2 + 20kts
509 double gearUpDist = d + pitchDistance(INITIAL_PITCH_ANGLE, 400 * SG_FEET_TO_METER);
510 accelPoint = rwy->pointOnCenterline(gearUpDist);
512 wpt = cloneWithPos(ac, wpt, "gear-up", accelPoint);
514 wpt->setCrossat(airportElev + 400);
515 wpt->setOn_ground(false);
516 wpt->setGear_down(false);
517 pushBackWaypoint(wpt);
519 // limit climbout speed to 240kts below 10000'
520 double vClimbBelow10000 = std::min(240.0, ac->getPerformance()->vClimb());
522 // create two climb-out points. This is important becuase the first climb point will
523 // be a (sometimes large) turn towards the destination, and we don't want to
524 // commence that turn below 2000'
525 double climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2000 * SG_FEET_TO_METER);
526 accelPoint = rwy->pointOnCenterline(climbOut);
527 wpt = createInAir(ac, "2000'", accelPoint, airportElev + 2000, vClimbBelow10000);
528 pushBackWaypoint(wpt);
530 climbOut = d + pitchDistance(INITIAL_PITCH_ANGLE, 2500 * SG_FEET_TO_METER);
531 accelPoint = rwy->pointOnCenterline(climbOut);
532 wpt = createInAir(ac, "2500'", accelPoint, airportElev + 2500, vClimbBelow10000);
533 pushBackWaypoint(wpt);
538 /*******************************************************************
540 * initialize the Aircraft at the parking location
541 ******************************************************************/
542 bool FGAIFlightPlan::createClimb(FGAIAircraft * ac, bool firstFlight,
543 FGAirport * apt, FGAirport* arrival,
544 double speed, double alt,
545 const string & fltType)
549 double vClimb = ac->getPerformance()->vClimb();
552 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
553 double heading = ac->getTrafficRef()->getCourse();
554 apt->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
558 for (wpt_vector_iterator i = sid->getFirstWayPoint();
559 i != sid->getLastWayPoint(); i++) {
560 pushBackWaypoint(clone(*(i)));
561 //cerr << " Cloning waypoint " << endl;
564 FGRunway* runway = apt->getRunwayByIdent(activeRunway);
565 SGGeod cur = runway->end();
566 if (!waypoints.empty()) {
567 cur = waypoints.back()->getPos();
570 // compute course towards destination
571 double course = SGGeodesy::courseDeg(cur, arrival->geod());
573 SGGeod climb1 = SGGeodesy::direct(cur, course, 10 * SG_NM_TO_METER);
574 wpt = createInAir(ac, "10000ft climb", climb1, 10000, vClimb);
575 wpt->setGear_down(true);
576 wpt->setFlaps_down(true);
577 pushBackWaypoint(wpt);
579 SGGeod climb2 = SGGeodesy::direct(cur, course, 20 * SG_NM_TO_METER);
580 wpt = createInAir(ac, "18000ft climb", climb2, 18000, vClimb);
581 pushBackWaypoint(wpt);
588 /*******************************************************************
590 * Generate a flight path from the last waypoint of the cruise to
591 * the permission to land point
592 ******************************************************************/
593 bool FGAIFlightPlan::createDescent(FGAIAircraft * ac, FGAirport * apt,
594 double latitude, double longitude,
595 double speed, double alt,
596 const string & fltType,
597 double requiredDistance)
599 bool reposition = false;
601 double vDescent = ac->getPerformance()->vDescent();
602 double vApproach = ac->getPerformance()->vApproach();
604 //Beginning of Descent
605 const string& rwyClass = getRunwayClassFromTrafficType(fltType);
606 double heading = ac->getTrafficRef()->getCourse();
607 apt->getDynamics()->getActiveRunway(rwyClass, 2, activeRunway,
609 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
610 assert( rwy != NULL );
612 // Create a slow descent path that ends 250 lateral to the runway.
613 double initialTurnRadius = getTurnRadius(vDescent, true);
614 //double finalTurnRadius = getTurnRadius(vApproach, true);
616 // get length of the downwind leg for the intended runway
617 double distanceOut = apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getApproachDistance(); //12 * SG_NM_TO_METER;
618 //time_t previousArrivalTime= apt->getDynamics()->getApproachController()->getRunway(rwy->name())->getEstApproachTime();
621 SGGeod current = SGGeod::fromDegM(longitude, latitude, 0);
622 SGGeod initialTarget = rwy->pointOnCenterline(-distanceOut);
623 SGGeod refPoint = rwy->pointOnCenterline(0);
624 double distance = SGGeodesy::distanceM(current, initialTarget);
625 double azimuth = SGGeodesy::courseDeg(current, initialTarget);
628 // To prevent absurdly steep approaches, compute the origin from where the approach should have started
631 if (ac->getTrafficRef()->getCallSign() ==
632 fgGetString("/ai/track-callsign")) {
633 //cerr << "Reposition information: Actual distance " << distance << ". required distance " << requiredDistance << endl;
637 if (distance < requiredDistance * 0.8) {
639 SGGeodesy::direct(initialTarget, azimuth,
640 -requiredDistance, origin, dummyAz2);
642 distance = SGGeodesy::distanceM(current, initialTarget);
643 azimuth = SGGeodesy::courseDeg(current, initialTarget);
648 double dAlt = 0; // = alt - (apt->getElevation() + 2000);
650 if (apt->getDynamics()->getGroundNetwork()) {
651 tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(refPoint);
655 dAlt = alt - ((tn->getElevationFt()) + 2000);
657 dAlt = alt - (apt->getElevation() + 2000);
660 double nPoints = 100;
663 // The descent path contains the following phases:
664 // 1) a linear glide path from the initial position to
665 // 2) a semi circle turn to final
668 //cerr << "Phase 1: Linear Descent path to runway" << rwy->name() << endl;
669 // Create an initial destination point on a semicircle
670 //cerr << "lateral offset : " << lateralOffset << endl;
671 //cerr << "Distance : " << distance << endl;
672 //cerr << "Azimuth : " << azimuth << endl;
673 //cerr << "Initial Lateral point: " << lateralOffset << endl;
674 // double lat = refPoint.getLatitudeDeg();
675 // double lon = refPoint.getLongitudeDeg();
676 //cerr << "Reference point (" << lat << ", " << lon << ")." << endl;
677 // lat = initialTarget.getLatitudeDeg();
678 // lon = initialTarget.getLongitudeDeg();
679 //cerr << "Initial Target point (" << lat << ", " << lon << ")." << endl;
681 double ratio = initialTurnRadius / distance;
687 double newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
689 cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
690 //cerr << "new distance " << newDistance << ". additional Heading " << newHeading << endl;
691 double side = azimuth - rwy->headingDeg();
692 double lateralOffset = initialTurnRadius;
698 // Calculate the ETA at final, based on remaining distance, and approach speed.
699 // distance should really consist of flying time to terniary target, plus circle
700 // but the distance to secondary target should work as a reasonable approximation
701 // aditionally add the amount of distance covered by making a turn of "side"
702 double turnDistance = (2 * M_PI * initialTurnRadius) * (side / 360.0);
704 (turnDistance + distance) / ((vDescent * SG_NM_TO_METER) / 3600.0);
705 time_t now = globals->get_time_params()->get_cur_time();
707 //if (ac->getTrafficRef()->getCallSign() == fgGetString("/ai/track-callsign")) {
708 // cerr << " Arrival time estimation: turn angle " << side << ". Turn distance " << turnDistance << ". Linear distance " << distance << ". Time to go " << remaining << endl;
712 time_t eta = now + remaining;
713 //choose a distance to the runway such that it will take at least 60 seconds more
714 // time to get there than the previous aircraft.
715 // Don't bother when aircraft need to be repositioned, because that marks the initialization phased...
719 if (reposition == false) {
721 apt->getDynamics()->getApproachController()->getRunway(rwy->
724 requestTimeSlot(eta);
728 //if ((eta < (previousArrivalTime+60)) && (reposition == false)) {
729 arrivalTime = newEta;
730 time_t additionalTimeNeeded = newEta - eta;
731 double distanceCovered =
732 ((vApproach * SG_NM_TO_METER) / 3600.0) * additionalTimeNeeded;
733 distanceOut += distanceCovered;
734 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta+additionalTimeNeeded);
735 //cerr << "Adding additional distance: " << distanceCovered << " to allow " << additionalTimeNeeded << " seconds of flying time" << endl << endl;
737 //apt->getDynamics()->getApproachController()->getRunway(rwy->name())->setEstApproachTime(eta);
739 //cerr << "Timing information : Previous eta: " << previousArrivalTime << ". Current ETA : " << eta << endl;
741 SGGeod secondaryTarget =
742 rwy->pointOffCenterline(-distanceOut, lateralOffset);
743 initialTarget = rwy->pointOnCenterline(-distanceOut);
744 distance = SGGeodesy::distanceM(origin, secondaryTarget);
745 azimuth = SGGeodesy::courseDeg(origin, secondaryTarget);
748 // lat = secondaryTarget.getLatitudeDeg();
749 // lon = secondaryTarget.getLongitudeDeg();
750 //cerr << "Secondary Target point (" << lat << ", " << lon << ")." << endl;
751 //cerr << "Distance : " << distance << endl;
752 //cerr << "Azimuth : " << azimuth << endl;
755 ratio = initialTurnRadius / distance;
760 newHeading = asin(ratio) * SG_RADIANS_TO_DEGREES;
761 newDistance = cos(newHeading * SG_DEGREES_TO_RADIANS) * distance;
762 //cerr << "new distance realative to secondary target: " << newDistance << ". additional Heading " << newHeading << endl;
764 azimuth += newHeading;
766 azimuth -= newHeading;
769 SGGeod tertiaryTarget;
770 SGGeodesy::direct(origin, azimuth,
771 newDistance, tertiaryTarget, dummyAz2);
773 // lat = tertiaryTarget.getLatitudeDeg();
774 // lon = tertiaryTarget.getLongitudeDeg();
775 //cerr << "tertiary Target point (" << lat << ", " << lon << ")." << endl;
778 for (int i = 1; i < nPoints; i++) {
780 double currentDist = i * (newDistance / nPoints);
781 double currentAltitude = alt - (i * (dAlt / nPoints));
782 SGGeodesy::direct(origin, azimuth, currentDist, result, dummyAz2);
783 snprintf(buffer, 16, "descent%03d", i);
784 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
785 wpt->setCrossat(currentAltitude);
786 wpt->setTrackLength((newDistance / nPoints));
787 pushBackWaypoint(wpt);
788 //cerr << "Track Length : " << wpt->trackLength;
789 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
792 //cerr << "Phase 2: Circle " << endl;
793 double initialAzimuth =
794 SGGeodesy::courseDeg(secondaryTarget, tertiaryTarget);
795 double finalAzimuth =
796 SGGeodesy::courseDeg(secondaryTarget, initialTarget);
798 //cerr << "Angles from secondary target: " << initialAzimuth << " " << finalAzimuth << endl;
799 int increment, startval, endval;
800 // circle right around secondary target if orig of position is to the right of the runway
801 // i.e. use negative angles; else circle leftward and use postivi
804 startval = floor(initialAzimuth);
805 endval = ceil(finalAzimuth);
806 if (endval > startval) {
811 startval = ceil(initialAzimuth);
812 endval = floor(finalAzimuth);
813 if (endval < startval) {
819 //cerr << "creating circle between " << startval << " and " << endval << " using " << increment << endl;
820 //FGTaxiNode * tn = apt->getDynamics()->getGroundNetwork()->findNearestNode(initialTarget);
821 double currentAltitude = 0;
823 currentAltitude = (tn->getElevationFt()) + 2000;
825 currentAltitude = apt->getElevation() + 2000;
828 double trackLength = (2 * M_PI * initialTurnRadius) / 360.0;
829 for (int i = startval; i != endval; i += increment) {
831 //double currentAltitude = apt->getElevation() + 2000;
833 SGGeodesy::direct(secondaryTarget, i,
834 initialTurnRadius, result, dummyAz2);
835 snprintf(buffer, 16, "turn%03d", i);
836 wpt = createInAir(ac, buffer, result, currentAltitude, vDescent);
837 wpt->setCrossat(currentAltitude);
838 wpt->setTrackLength(trackLength);
839 //cerr << "Track Length : " << wpt->trackLength;
840 pushBackWaypoint(wpt);
841 //cerr << " Position : " << result.getLatitudeDeg() << " " << result.getLongitudeDeg() << " " << currentAltitude << endl;
845 // The approach leg should bring the aircraft to approximately 4-6 nm out, after which the landing phase should take over.
846 //cerr << "Phase 3: Approach" << endl;
848 //cerr << "Done" << endl;
850 // Erase the two bogus BOD points: Note check for conflicts with scripted AI flightPlans
851 IncrementWaypoint(true);
852 IncrementWaypoint(true);
856 //double minDistance = HUGE_VAL;
858 tempDistance = SGGeodesy::distanceM(current, initialTarget);
860 tempDistance / ((vDescent * SG_NM_TO_METER) / 3600.0) + now;
862 apt->getDynamics()->getApproachController()->getRunway(rwy->
865 requestTimeSlot(eta);
866 arrivalTime = newEta;
868 ((vDescent * SG_NM_TO_METER) / 3600.0) * (newEta - now);
869 //cerr << "Repositioning information : eta" << eta << ". New ETA " << newEta << ". Diff = " << (newEta - eta) << ". Distance = " << tempDistance << ". New distance = " << newDistance << endl;
870 IncrementWaypoint(true); // remove waypoint BOD2
871 while (checkTrackLength("final001") > newDistance) {
872 IncrementWaypoint(true);
874 //cerr << "Repositioning to waypoint " << (*waypoints.begin())->name << endl;
875 ac->resetPositionFromFlightPlan();
877 waypoints[1]->setName( (waypoints[1]->getName() + string("legend")));
882 * compute the distance along the centerline, to the ILS glideslope
883 * transmitter. Return -1 if there's no GS for the runway
885 static double runwayGlideslopeTouchdownDistance(FGRunway* rwy)
887 FGNavRecord* gs = rwy->glideslope();
892 SGVec3d runwayPosCart = SGVec3d::fromGeod(rwy->pointOnCenterline(0.0));
893 // compute a unit vector in ECF cartesian space, from the runway beginning to the end
894 SGVec3d runwayDirectionVec = normalize(SGVec3d::fromGeod(rwy->end()) - runwayPosCart);
895 SGVec3d gsTransmitterVec = gs->cart() - runwayPosCart;
897 // project the gsTransmitterVec along the runwayDirctionVec to get out
898 // final value (in metres)
899 double dist = dot(runwayDirectionVec, gsTransmitterVec);
903 /*******************************************************************
905 * Create a flight path from the "permision to land" point (currently
906 hardcoded at 5000 meters from the threshold) to the threshold, at
907 a standard glide slope angle of 3 degrees.
908 Position : 50.0354 8.52592 384 364 11112
909 ******************************************************************/
910 bool FGAIFlightPlan::createLanding(FGAIAircraft * ac, FGAirport * apt,
911 const string & fltType)
913 double vTouchdown = ac->getPerformance()->vTouchdown();
914 double vTaxi = ac->getPerformance()->vTaxi();
915 double decel = ac->getPerformance()->decelerationOnGround();
916 double vApproach = ac->getPerformance()->vApproach();
918 double vTouchdownMetric = vTouchdown * SG_KT_TO_MPS;
919 double vTaxiMetric = vTaxi * SG_KT_TO_MPS;
920 double decelMetric = decel * SG_KT_TO_MPS;
923 FGRunway * rwy = apt->getRunwayByIdent(activeRunway);
924 assert( rwy != NULL );
925 SGGeod threshold = rwy->threshold();
926 double currElev = threshold.getElevationFt();
928 double touchdownDistance = runwayGlideslopeTouchdownDistance(rwy);
929 if (touchdownDistance < 0.0) {
930 double landingLength = rwy->lengthM() - (rwy->displacedThresholdM());
931 // touchdown 25% of the way along the landing area
932 touchdownDistance = rwy->displacedThresholdM() + (landingLength * 0.25);
936 // find glideslope entry point, 2000' above touchdown elevation
937 double glideslopeEntry = -((2000 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
938 FGAIWaypoint *wpt = createInAir(ac, "Glideslope begin", rwy->pointOnCenterline(glideslopeEntry),
939 currElev + 2000, vApproach);
940 pushBackWaypoint(wpt);
942 // deceleration point, 500' above touchdown elevation - slow from approach speed
943 // to touchdown speed
944 double decelPoint = -((500 * SG_FEET_TO_METER) / tan(3.0)) + touchdownDistance;
945 wpt = createInAir(ac, "500' decel", rwy->pointOnCenterline(decelPoint),
946 currElev + 2000, vTouchdown);
947 pushBackWaypoint(wpt);
949 // compute elevation above the runway start, based on a 3-degree glideslope
950 double heightAboveRunwayStart = touchdownDistance *
951 tan(3.0 * SG_DEGREES_TO_RADIANS) * SG_METER_TO_FEET;
952 wpt = createInAir(ac, "CrossThreshold", rwy->begin(),
953 heightAboveRunwayStart + currElev, vTouchdown);
954 pushBackWaypoint(wpt);
956 double rolloutDistance = accelDistance(vTouchdownMetric, vTaxiMetric, decelMetric);
959 for (int i = 1; i < nPoints; i++) {
960 snprintf(buffer, 12, "landing03%d", i);
961 double t = ((double) i) / nPoints;
962 coord = rwy->pointOnCenterline(touchdownDistance + (rolloutDistance * t));
963 double vel = (vTouchdownMetric * (1.0 - t)) + (vTaxiMetric * t);
964 wpt = createOnGround(ac, buffer, coord, currElev, vel);
965 wpt->setCrossat(currElev);
966 pushBackWaypoint(wpt);
969 wpt->setSpeed(vTaxi);
970 double mindist = (1.1 * rolloutDistance) + touchdownDistance;
972 FGGroundNetwork *gn = apt->getDynamics()->getGroundNetwork();
977 coord = rwy->pointOnCenterline(mindist);
979 if (gn->getVersion() > 0) {
980 tn = gn->findNearestNodeOnRunway(coord, rwy);
982 tn = gn->findNearestNode(coord);
986 wpt = createOnGround(ac, buffer, tn->geod(), currElev, vTaxi);
987 pushBackWaypoint(wpt);
993 /*******************************************************************
995 * initialize the Aircraft at the parking location
996 ******************************************************************/
997 bool FGAIFlightPlan::createParking(FGAIAircraft * ac, FGAirport * apt,
1001 double aptElev = apt->getElevation();
1002 double vTaxi = ac->getPerformance()->vTaxi();
1003 double vTaxiReduced = vTaxi * (2.0 / 3.0);
1004 if (!gate.isValid()) {
1005 wpt = createOnGround(ac, "END-Parking", apt->geod(), aptElev,
1007 pushBackWaypoint(wpt);
1011 FGParking* parking = gate.parking();
1012 double heading = SGMiscd::normalizePeriodic(0, 360, parking->getHeading() + 180.0);
1013 double az; // unused
1016 SGGeodesy::direct(parking->geod(), heading, 2.2 * parking->getRadius(),
1019 wpt = createOnGround(ac, "taxiStart", pos, aptElev, vTaxiReduced);
1020 pushBackWaypoint(wpt);
1022 SGGeodesy::direct(parking->geod(), heading, 0.1 * parking->getRadius(),
1024 wpt = createOnGround(ac, "taxiStart2", pos, aptElev, vTaxiReduced);
1025 pushBackWaypoint(wpt);
1027 wpt = createOnGround(ac, "END-Parking", parking->geod(), aptElev,
1029 pushBackWaypoint(wpt);
1035 * @param fltType a string describing the type of
1036 * traffic, normally used for gate assignments
1037 * @return a converted string that gives the runway
1038 * preference schedule to be used at aircraft having
1039 * a preferential runway schedule implemented (i.e.
1040 * having a rwyprefs.xml file
1042 * Currently valid traffic types for gate assignment:
1043 * - gate (commercial gate)
1044 * - cargo (commercial gargo),
1045 * - ga (general aviation) ,
1046 * - ul (ultralight),
1047 * - mil-fighter (military - fighter),
1048 * - mil-transport (military - transport)
1050 * Valid runway classes:
1051 * - com (commercial traffic: jetliners, passenger and cargo)
1052 * - gen (general aviation)
1053 * - ul (ultralight: I can imagine that these may share a runway with ga on some airports)
1054 * - mil (all military traffic)
1056 const char* FGAIFlightPlan::getRunwayClassFromTrafficType(const string& fltType)
1058 if ((fltType == "gate") || (fltType == "cargo")) {
1061 if (fltType == "ga") {
1064 if (fltType == "ul") {
1067 if ((fltType == "mil-fighter") || (fltType == "mil-transport")) {
1074 double FGAIFlightPlan::getTurnRadius(double speed, bool inAir)
1077 if (inAir == false) {
1078 turn_radius = ((360 / 30) * fabs(speed)) / (2 * M_PI);
1080 turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank