1 // dynamics.cxx - Code to manage the higher order airport ground activities
2 // Written by Durk Talsma, started December 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.
27 #include <simgear/compiler.h>
29 #include <Environment/environment_mgr.hxx>
30 #include <Environment/environment.hxx>
31 #include <simgear/misc/sg_path.hxx>
32 #include <simgear/props/props.hxx>
33 #include <simgear/structure/subsystem_mgr.hxx>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/route/waypoint.hxx>
36 #include <Main/globals.hxx>
37 #include <Main/fg_props.hxx>
38 #include <Airports/runways.hxx>
39 #include <ATCDCL/ATCutils.hxx>
47 using std::random_shuffle;
50 #include "dynamics.hxx"
52 FGAirportDynamics::FGAirportDynamics(FGAirport * ap):
53 _ap(ap), rwyPrefs(ap), SIDs(ap),
54 atisSequenceIndex(-1),
55 atisSequenceTimeStamp(0.0)
61 FGAirportDynamics::~FGAirportDynamics()
66 // Initialization required after XMLRead
67 void FGAirportDynamics::init()
69 // This may seem a bit weird to first randomly shuffle the parkings
70 // and then sort them again. However, parkings are sorted here by ascending
71 // radius. Since many parkings have similar radii, with each radius class they will
72 // still be allocated relatively systematically. Randomizing prior to sorting will
73 // prevent any initial orderings to be destroyed, leading (hopefully) to a more
74 // naturalistic gate assignment.
75 random_shuffle(parkings.begin(), parkings.end());
76 sort(parkings.begin(), parkings.end());
77 // add the gate positions to the ground network.
78 groundNetwork.addNodes(&parkings);
80 groundNetwork.setTowerController(&towerController);
81 groundNetwork.setParent(_ap);
84 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon,
85 double *heading, int *gateId,
87 const string & flType,
88 const string & acType,
89 const string & airline)
92 bool available = false;
95 FGParkingVecIterator i;
96 if (parkings.begin() == parkings.end()) {
97 //cerr << "Could not find parking spot at " << _ap->getId() << endl;
98 *lat = _ap->getLatitude();
99 *lon = _ap->getLongitude();
103 // First try finding a parking with a designated airline code
104 for (i = parkings.begin(); !(i == parkings.end() || found); i++) {
106 // Taken by another aircraft
107 if (!(i->isAvailable())) {
111 // No airline codes, so skip
112 if (i->getCodes().empty()) {
115 } else { // Airline code doesn't match
116 //cerr << "Code = " << airline << ": Codes " << i->getCodes();
117 if (i->getCodes().find(airline, 0) == string::npos) {
119 //cerr << "Unavailable" << endl;
122 //cerr << "Available" << endl;
125 // Type doesn't match
126 if (i->getType() != flType) {
131 if (i->getRadius() < rad) {
137 *lat = i->getLatitude();
138 *lon = i->getLongitude();
139 *heading = i->getHeading();
140 *gateId = i->getIndex();
141 i->setAvailable(false);
145 // then try again for those without codes.
146 for (i = parkings.begin(); !(i == parkings.end() || found); i++) {
148 if (!(i->isAvailable())) {
152 if (!(i->getCodes().empty())) {
153 if ((i->getCodes().find(airline, 0) == string::npos)) {
158 if (i->getType() != flType) {
163 if (i->getRadius() < rad) {
169 *lat = i->getLatitude();
170 *lon = i->getLongitude();
171 *heading = i->getHeading();
172 *gateId = i->getIndex();
173 i->setAvailable(false);
177 // And finally once more if that didn't work. Now ignore the airline codes, as a last resort
178 for (i = parkings.begin(); !(i == parkings.end() || found); i++) {
180 if (!(i->isAvailable())) {
184 if (i->getType() != flType) {
189 if (i->getRadius() < rad) {
195 *lat = i->getLatitude();
196 *lon = i->getLongitude();
197 *heading = i->getHeading();
198 *gateId = i->getIndex();
199 i->setAvailable(false);
205 //cerr << "Traffic overflow at" << _ap->getId()
206 // << ". flType = " << flType
207 // << ". airline = " << airline
208 // << " Radius = " <<rad
210 *lat = _ap->getLatitude();
211 *lon = _ap->getLongitude();
219 void FGAirportDynamics::getParking(int id, double *lat, double *lon,
223 *lat = _ap->getLatitude();
224 *lon = _ap->getLongitude();
227 FGParkingVecIterator i = parkings.begin();
228 for (i = parkings.begin(); i != parkings.end(); i++) {
229 if (id == i->getIndex()) {
230 *lat = i->getLatitude();
231 *lon = i->getLongitude();
232 *heading = i->getHeading();
238 FGParking *FGAirportDynamics::getParking(int id)
240 FGParkingVecIterator i = parkings.begin();
241 for (i = parkings.begin(); i != parkings.end(); i++) {
242 if (id == i->getIndex()) {
249 string FGAirportDynamics::getParkingName(int id)
251 FGParkingVecIterator i = parkings.begin();
252 for (i = parkings.begin(); i != parkings.end(); i++) {
253 if (id == i->getIndex()) {
258 return string("overflow");
261 void FGAirportDynamics::releaseParking(int id)
265 FGParkingVecIterator i = parkings.begin();
266 for (i = parkings.begin(); i != parkings.end(); i++) {
267 if (id == i->getIndex()) {
268 i->setAvailable(true);
274 void FGAirportDynamics::setRwyUse(const FGRunwayPreference & ref)
277 //cerr << "Exiting due to not implemented yet" << endl;
281 bool FGAirportDynamics::innerGetActiveRunway(const string & trafficType,
282 int action, string & runway,
292 if (!rwyPrefs.available()) {
296 RunwayGroup *currRunwayGroup = 0;
297 int nrActiveRunways = 0;
298 time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
299 if ((abs((long) (dayStart - lastUpdate)) > 600)
300 || trafficType != prevTrafficType) {
303 lastUpdate = dayStart;
304 prevTrafficType = trafficType;
308 ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
309 ->getEnvironment(getLatitude(), getLongitude(),
312 windSpeed = fgGetInt("/environment/metar/base-wind-speed-kt"); //stationweather.get_wind_speed_kt();
313 windHeading = fgGetInt("/environment/metar/base-wind-dir-deg");
314 //stationweather.get_wind_from_heading_deg();
316 //cerr << "finding active Runway for : " << _ap->getId() << endl;
317 //cerr << "Wind Heading : " << windHeading << endl;
318 //cerr << "Wind Speed : " << windSpeed << endl;
320 //cerr << "Nr of seconds since day start << " << dayStart << endl;
322 ScheduleTime *currSched;
323 //cerr << "A"<< endl;
324 currSched = rwyPrefs.getSchedule(trafficType.c_str());
327 //cerr << "B"<< endl;
328 scheduleName = currSched->getName(dayStart);
329 maxTail = currSched->getTailWind();
330 maxCross = currSched->getCrossWind();
331 //cerr << "Current Schedule = : " << scheduleName << endl;
332 if (scheduleName.empty())
334 //cerr << "C"<< endl;
335 currRunwayGroup = rwyPrefs.getGroup(scheduleName);
336 //cerr << "D"<< endl;
337 if (!(currRunwayGroup))
339 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
341 // Keep a history of the currently active runways, to ensure
342 // that an already established selection of runways will not
343 // be overridden once a more preferred selection becomes
344 // available as that can lead to random runway swapping.
345 if (trafficType == "com") {
346 currentlyActive = &comActive;
347 } else if (trafficType == "gen") {
348 currentlyActive = &genActive;
349 } else if (trafficType == "mil") {
350 currentlyActive = &milActive;
351 } else if (trafficType == "ul") {
352 currentlyActive = &ulActive;
355 //cerr << "Durrently active selection for " << trafficType << ": ";
356 for (stringVecIterator it = currentlyActive->begin();
357 it != currentlyActive->end(); it++) {
358 //cerr << (*it) << " ";
362 currRunwayGroup->setActive(_ap,
365 maxTail, maxCross, currentlyActive);
367 // Note that I SHOULD keep multiple lists in memory, one for
368 // general aviation, one for commercial and one for military
370 currentlyActive->clear();
371 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
372 //cerr << "Choosing runway for " << trafficType << endl;
373 for (int i = 0; i < nrActiveRunways; i++) {
374 type = "unknown"; // initialize to something other than landing or takeoff
375 currRunwayGroup->getActive(i, name, type);
376 if (type == "landing") {
377 landing.push_back(name);
378 currentlyActive->push_back(name);
379 //cerr << "Landing " << name << endl;
381 if (type == "takeoff") {
382 takeoff.push_back(name);
383 currentlyActive->push_back(name);
384 //cerr << "takeoff " << name << endl;
390 if (action == 1) // takeoff
392 int nr = takeoff.size();
394 // Note that the randomization below, is just a placeholder to choose between
395 // multiple active runways for this action. This should be
396 // under ATC control.
397 runway = chooseRwyByHeading(takeoff, heading);
399 runway = chooseRunwayFallback();
403 if (action == 2) // landing
405 int nr = landing.size();
407 runway = chooseRwyByHeading(landing, heading);
409 runway = chooseRunwayFallback();
416 string FGAirportDynamics::chooseRwyByHeading(stringVec rwys,
419 double bestError = 360.0;
420 double rwyHeading, headingError;
422 for (stringVecIterator i = rwys.begin(); i != rwys.end(); i++) {
423 if (!_ap->hasRunwayWithIdent(*i)) {
424 SG_LOG(SG_ATC, SG_WARN, "chooseRwyByHeading: runway " << *i <<
425 " not found at " << _ap->ident());
429 FGRunway *rwy = _ap->getRunwayByIdent((*i));
430 rwyHeading = rwy->headingDeg();
431 headingError = fabs(heading - rwyHeading);
432 if (headingError > 180)
433 headingError = fabs(headingError - 360);
434 if (headingError < bestError) {
436 bestError = headingError;
439 //cerr << "Using active runway " << runway << " for heading " << heading << endl;
443 void FGAirportDynamics::getActiveRunway(const string & trafficType,
444 int action, string & runway,
447 bool ok = innerGetActiveRunway(trafficType, action, runway, heading);
449 runway = chooseRunwayFallback();
453 string FGAirportDynamics::chooseRunwayFallback()
455 FGRunway *rwy = _ap->getActiveRunwayForUsage();
459 void FGAirportDynamics::addParking(FGParking & park)
461 parkings.push_back(park);
464 double FGAirportDynamics::getLatitude() const
466 return _ap->getLatitude();
469 double FGAirportDynamics::getLongitude() const
471 return _ap->getLongitude();
474 double FGAirportDynamics::getElevation() const
476 return _ap->getElevation();
479 const string & FGAirportDynamics::getId() const
484 // Experimental: Return a different ground frequency depending on the leg of the
485 // Flight. Leg should always have a minimum value of two when this function is called.
486 // Note that in this scheme, the assignment of various frequencies to various ground
487 // operations is completely arbitrary. As such, is a short cut I need to take now,
488 // so that at least I can start working on assigning different frequencies to different
491 int FGAirportDynamics::getGroundFrequency(unsigned leg)
493 //return freqGround.size() ? freqGround[0] : 0; };
496 SG_LOG(SG_ATC, SG_ALERT,
497 "Leg value is smaller than two at " << SG_ORIGIN);
499 if (freqGround.size() == 0) {
502 if ((freqGround.size() > leg - 1) && (leg > 1)) {
503 groundFreq = freqGround[leg - 1];
505 if ((freqGround.size() < leg - 1) && (leg > 1)) {
508 (leg - 1)) ? freqGround[freqGround.size() -
509 1] : freqGround[leg - 2];
511 if ((freqGround.size() >= leg - 1) && (leg > 1)) {
512 groundFreq = freqGround[leg - 2];
517 FGAIFlightPlan *FGAirportDynamics::getSID(string activeRunway,
520 return SIDs.getBest(activeRunway, heading);
523 const std::string FGAirportDynamics::getAtisSequence()
525 if (atisSequenceIndex == -1) {
526 updateAtisSequence(1, false);
529 return GetPhoneticLetter(atisSequenceIndex);
532 int FGAirportDynamics::updateAtisSequence(int interval, bool forceUpdate)
534 double now = globals->get_sim_time_sec();
535 if (atisSequenceIndex == -1) {
537 atisSequenceTimeStamp = now;
538 atisSequenceIndex = rand() % LTRS; // random initial sequence letters
539 return atisSequenceIndex;
542 int steps = static_cast<int>((now - atisSequenceTimeStamp) / interval);
543 atisSequenceTimeStamp += (interval * steps);
544 if (forceUpdate && (steps == 0)) {
545 ++steps; // a "special" ATIS update is required
548 atisSequenceIndex = (atisSequenceIndex + steps) % LTRS;
549 // return a huge value if no update occurred
550 return (atisSequenceIndex + (steps ? 0 : LTRS*1000));