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>
32 #include <Environment/environment_mgr.hxx>
33 #include <Environment/environment.hxx>
34 #include <simgear/misc/sg_path.hxx>
35 #include <simgear/props/props.hxx>
36 #include <simgear/structure/subsystem_mgr.hxx>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/route/waypoint.hxx>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Airports/runways.hxx>
42 #include <simgear/xml/easyxml.hxx>
50 SG_USING_STD(random_shuffle);
52 #include "parking.hxx"
53 #include "groundnetwork.hxx"
54 #include "runwayprefs.hxx"
55 #include "dynamics.hxx"
57 /********** FGAirport Dynamics *********************************************/
59 FGAirportDynamics::FGAirportDynamics(double lat, double lon, double elev, string id) :
66 for (int i = 0; i < 10; i++)
68 avWindHeading [i] = 0;
74 // Note that the ground network should also be copied
75 FGAirportDynamics::FGAirportDynamics(const FGAirportDynamics& other)
77 for (FGParkingVecConstIterator ip= other.parkings.begin(); ip != other.parkings.end(); ip++)
78 parkings.push_back(*(ip));
79 rwyPrefs = other.rwyPrefs;
80 lastUpdate = other.lastUpdate;
82 stringVecConstIterator il;
83 for (il = other.landing.begin(); il != other.landing.end(); il++)
84 landing.push_back(*il);
85 for (il = other.takeoff.begin(); il != other.takeoff.end(); il++)
86 takeoff.push_back(*il);
87 lastUpdate = other.lastUpdate;
88 for (int i = 0; i < 10; i++)
90 avWindHeading [i] = other.avWindHeading[i];
91 avWindSpeed [i] = other.avWindSpeed [i];
96 FGAirportDynamics::~FGAirportDynamics()
102 // Initialization required after XMLRead
103 void FGAirportDynamics::init()
105 // This may seem a bit weird to first randomly shuffle the parkings
106 // and then sort them again. However, parkings are sorted here by ascending
107 // radius. Since many parkings have similar radii, with each radius class they will
108 // still be allocated relatively systematically. Randomizing prior to sorting will
109 // prevent any initial orderings to be destroyed, leading (hopefully) to a more
110 // naturalistic gate assignment.
111 random_shuffle(parkings.begin(), parkings.end());
112 sort(parkings.begin(), parkings.end());
113 // add the gate positions to the ground network.
114 groundNetwork.addNodes(&parkings);
115 groundNetwork.init();
118 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon, double *heading, int *gateId, double rad, const string &flType, const string &acType, const string &airline)
121 bool available = false;
124 FGParkingVecIterator i;
125 // if (flType == "cargo")
127 // gateType = "RAMP_CARGO";
129 // else if (flType == "ga")
131 // gateType = "RAMP_GA";
133 // else gateType = "GATE";
135 if (parkings.begin() == parkings.end())
137 //cerr << "Could not find parking spot at " << _id << endl;
145 // First try finding a parking with a designated airline code
146 for (i = parkings.begin(); !(i == parkings.end() || found); i++)
148 //cerr << "Gate Id: " << i->getIndex()
149 // << " Type : " << i->getType()
150 // << " Codes : " << i->getCodes()
151 // << " Radius: " << i->getRadius()
152 // << " Name : " << i->getName()
153 // << " Available: " << i->isAvailable() << endl;
155 // Taken by another aircraft
156 if (!(i->isAvailable()))
161 // No airline codes, so skip
162 if (i->getCodes().empty())
167 else // Airline code doesn't match
168 if (i->getCodes().find(airline, 0) == string::npos)
173 // Type doesn't match
174 if (i->getType() != flType)
180 if (i->getRadius() < rad)
188 *lat = i->getLatitude ();
189 *lon = i->getLongitude();
190 *heading = i->getHeading ();
191 *gateId = i->getIndex ();
192 i->setAvailable(false);
196 // then try again for those without codes.
197 for (i = parkings.begin(); !(i == parkings.end() || found); i++)
200 if (!(i->isAvailable()))
205 if (!(i->getCodes().empty()))
207 if ((i->getCodes().find(airline,0) == string::npos))
213 if (i->getType() != flType)
219 if (i->getRadius() < rad)
227 *lat = i->getLatitude ();
228 *lon = i->getLongitude();
229 *heading = i->getHeading ();
230 *gateId = i->getIndex ();
231 i->setAvailable(false);
235 // And finally once more if that didn't work. Now ignore the airline codes, as a last resort
236 for (i = parkings.begin(); !(i == parkings.end() || found); i++)
239 if (!(i->isAvailable()))
244 if (i->getType() != flType)
250 if (i->getRadius() < rad)
258 *lat = i->getLatitude ();
259 *lon = i->getLongitude();
260 *heading = i->getHeading ();
261 *gateId = i->getIndex ();
262 i->setAvailable(false);
269 //cerr << "Traffic overflow at" << _id
270 // << ". flType = " << flType
271 // << ". airline = " << airline
272 // << " Radius = " <<rad
283 void FGAirportDynamics::getParking (int id, double *lat, double* lon, double *heading)
293 FGParkingVecIterator i = parkings.begin();
294 for (i = parkings.begin(); i != parkings.end(); i++)
296 if (id == i->getIndex())
298 *lat = i->getLatitude();
299 *lon = i->getLongitude();
300 *heading = i->getHeading();
306 FGParking *FGAirportDynamics::getParking(int i)
308 if (i < (int)parkings.size())
309 return &(parkings[i]);
313 string FGAirportDynamics::getParkingName(int i)
315 if (i < (int)parkings.size() && i >= 0)
316 return (parkings[i].getName());
318 return string("overflow");
320 void FGAirportDynamics::releaseParking(int id)
325 FGParkingVecIterator i = parkings.begin();
326 for (i = parkings.begin(); i != parkings.end(); i++)
328 if (id == i->getIndex())
330 i -> setAvailable(true);
336 void FGAirportDynamics::startXML () {
337 //cout << "Start XML" << endl;
340 void FGAirportDynamics::endXML () {
341 //cout << "End XML" << endl;
344 void FGAirportDynamics::startElement (const char * name, const XMLAttributes &atts) {
345 // const char *attval;
348 FGTaxiSegment taxiSegment;
350 taxiSegment.setIndex(index);
351 //cout << "Start element " << name << endl;
358 if (name == string("Parking"))
360 for (int i = 0; i < atts.size(); i++)
362 //cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
363 attname = atts.getName(i);
364 if (attname == string("index"))
365 park.setIndex(atoi(atts.getValue(i)));
366 else if (attname == string("type"))
367 park.setType(atts.getValue(i));
368 else if (attname == string("name"))
369 gateName = atts.getValue(i);
370 else if (attname == string("number"))
371 gateNumber = atts.getValue(i);
372 else if (attname == string("lat"))
373 park.setLatitude(atts.getValue(i));
374 else if (attname == string("lon"))
375 park.setLongitude(atts.getValue(i));
376 else if (attname == string("heading"))
377 park.setHeading(atof(atts.getValue(i)));
378 else if (attname == string("radius")) {
379 string radius = atts.getValue(i);
380 if (radius.find("M") != string::npos)
381 radius = radius.substr(0, radius.find("M",0));
382 //cerr << "Radius " << radius <<endl;
383 park.setRadius(atof(radius.c_str()));
385 else if (attname == string("airlineCodes"))
386 park.setCodes(atts.getValue(i));
388 park.setName((gateName+gateNumber));
389 parkings.push_back(park);
391 if (name == string("node"))
393 for (int i = 0; i < atts.size() ; i++)
395 attname = atts.getName(i);
396 if (attname == string("index"))
397 taxiNode.setIndex(atoi(atts.getValue(i)));
398 if (attname == string("lat"))
399 taxiNode.setLatitude(atts.getValue(i));
400 if (attname == string("lon"))
401 taxiNode.setLongitude(atts.getValue(i));
403 groundNetwork.addNode(taxiNode);
405 if (name == string("arc"))
407 taxiSegment.setIndex(++index);
408 for (int i = 0; i < atts.size() ; i++)
410 attname = atts.getName(i);
411 if (attname == string("begin"))
412 taxiSegment.setStartNodeRef(atoi(atts.getValue(i)));
413 if (attname == string("end"))
414 taxiSegment.setEndNodeRef(atoi(atts.getValue(i)));
416 groundNetwork.addSegment(taxiSegment);
418 // sort by radius, in asending order, so that smaller gates are first in the list
421 void FGAirportDynamics::endElement (const char * name) {
422 //cout << "End element " << name << endl;
426 void FGAirportDynamics::data (const char * s, int len) {
427 string token = string(s,len);
428 //cout << "Character data " << string(s,len) << endl;
429 //if ((token.find(" ") == string::npos && (token.find('\n')) == string::npos))
432 //value = string("");
435 void FGAirportDynamics::pi (const char * target, const char * data) {
436 //cout << "Processing instruction " << target << ' ' << data << endl;
439 void FGAirportDynamics::warning (const char * message, int line, int column) {
440 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
443 void FGAirportDynamics::error (const char * message, int line, int column) {
444 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
447 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
450 //cerr << "Exiting due to not implemented yet" << endl;
453 void FGAirportDynamics::getActiveRunway(const string &trafficType, int action, string &runway)
462 if (!(rwyPrefs.available()))
464 runway = chooseRunwayFallback();
465 return; // generic fall back goes here
469 RunwayGroup *currRunwayGroup = 0;
470 int nrActiveRunways = 0;
471 time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
472 if (((dayStart - lastUpdate) > 600) || trafficType != prevTrafficType)
476 //lastUpdate = dayStart;
477 prevTrafficType = trafficType;
480 stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
481 ->getEnvironment(getLatitude(),
485 windSpeed = stationweather.get_wind_speed_kt();
486 windHeading = stationweather.get_wind_from_heading_deg();
487 // double averageWindSpeed = 0;
488 // double averageWindHeading = 0;
489 // double cosHeading = 0;
490 // double sinHeading = 0;
491 // // Initialize at the beginning of the next day or startup
492 // if ((lastUpdate == 0) || (dayStart < lastUpdate))
494 // for (int i = 0; i < 10; i++)
496 // avWindHeading [i] = windHeading;
497 // avWindSpeed [i] = windSpeed;
502 // if (windSpeed != avWindSpeed[9]) // update if new metar data
504 // // shift the running average
505 // for (int i = 0; i < 9 ; i++)
507 // avWindHeading[i] = avWindHeading[i+1];
508 // avWindSpeed [i] = avWindSpeed [i+1];
511 // avWindHeading[9] = windHeading;
512 // avWindSpeed [9] = windSpeed;
515 // for (int i = 0; i < 10; i++)
517 // averageWindSpeed += avWindSpeed [i];
518 // //averageWindHeading += avWindHeading [i];
519 // cosHeading += cos(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
520 // sinHeading += sin(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
522 // averageWindSpeed /= 10;
523 // //averageWindHeading /= 10;
526 // averageWindHeading = atan2(sinHeading, cosHeading) *SG_RADIANS_TO_DEGREES;
527 // if (averageWindHeading < 0)
528 // averageWindHeading += 360.0;
529 // //cerr << "Wind Heading " << windHeading << " average " << averageWindHeading << endl;
530 // //cerr << "Wind Speed " << windSpeed << " average " << averageWindSpeed << endl;
531 // lastUpdate = dayStart;
532 // //if (wind_speed == 0) {
533 // // wind_heading = 270; This forces West-facing rwys to be used in no-wind situations
534 // // which is consistent with Flightgear's initial setup.
537 //string rwy_no = globals->get_runways()->search(apt->getId(), int(wind_heading));
539 //cerr << "finding active Runway for" << _id << endl;
540 //cerr << "Nr of seconds since day start << " << dayStart << endl;
542 ScheduleTime *currSched;
543 //cerr << "A"<< endl;
544 currSched = rwyPrefs.getSchedule(trafficType.c_str());
547 //cerr << "B"<< endl;
548 scheduleName = currSched->getName(dayStart);
549 maxTail = currSched->getTailWind ();
550 maxCross = currSched->getCrossWind ();
551 //cerr << "SChedule anme = " << scheduleName << endl;
552 if (scheduleName.empty())
554 //cerr << "C"<< endl;
555 currRunwayGroup = rwyPrefs.getGroup(scheduleName);
556 //cerr << "D"<< endl;
557 if (!(currRunwayGroup))
559 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
560 //cerr << "Nr of Active Runways = " << nrActiveRunways << endl;
563 currRunwayGroup->setActive(_id,
570 // Note that I SHOULD keep three lists in memory, one for
571 // general aviation, one for commercial and one for military
573 currentlyActive.clear();
574 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
575 for (int i = 0; i < nrActiveRunways; i++)
577 type = "unknown"; // initialize to something other than landing or takeoff
578 currRunwayGroup->getActive(i, name, type);
579 if (type == "landing")
581 landing.push_back(name);
582 currentlyActive.push_back(name);
583 //cerr << "Landing " << name << endl;
585 if (type == "takeoff")
587 takeoff.push_back(name);
588 currentlyActive.push_back(name);
589 //cerr << "takeoff " << name << endl;
593 if (action == 1) // takeoff
595 int nr = takeoff.size();
598 // Note that the randomization below, is just a placeholder to choose between
599 // multiple active runways for this action. This should be
600 // under ATC control.
601 runway = takeoff[(rand() % nr)];
605 runway = chooseRunwayFallback();
608 if (action == 2) // landing
610 int nr = landing.size();
613 runway = landing[(rand() % nr)];
617 runway = chooseRunwayFallback();
621 //runway = globals->get_runways()->search(_id, int(windHeading));
622 //cerr << "Seleceted runway: " << runway << endl;
626 string FGAirportDynamics::chooseRunwayFallback()
629 stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
630 ->getEnvironment(getLatitude(),
634 double windSpeed = stationweather.get_wind_speed_kt();
635 double windHeading = stationweather.get_wind_from_heading_deg();
636 if (windSpeed == 0) {
637 windHeading = 270; // This forces West-facing rwys to be used in no-wind situations
638 //which is consistent with Flightgear's initial setup.
641 return globals->get_runways()->search(_id, int(windHeading));