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., 675 Mass Ave, Cambridge, MA 02139, USA.
26 # define _USE_MATH_DEFINES
31 #include <simgear/compiler.h>
36 #include <Environment/environment_mgr.hxx>
37 #include <Environment/environment.hxx>
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/props/props.hxx>
40 #include <simgear/structure/subsystem_mgr.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/route/waypoint.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Airports/runways.hxx>
46 #include <simgear/xml/easyxml.hxx>
54 SG_USING_STD(random_shuffle);
56 #include "parking.hxx"
57 #include "groundnetwork.hxx"
58 #include "runwayprefs.hxx"
59 #include "dynamics.hxx"
61 /********** FGAirport Dynamics *********************************************/
63 FGAirportDynamics::FGAirportDynamics(double lat, double lon, double elev, string id) :
70 for (int i = 0; i < 10; i++)
72 avWindHeading [i] = 0;
78 // Note that the ground network should also be copied
79 FGAirportDynamics::FGAirportDynamics(const FGAirportDynamics& other)
81 for (FGParkingVecConstIterator ip= other.parkings.begin(); ip != other.parkings.end(); ip++)
82 parkings.push_back(*(ip));
83 rwyPrefs = other.rwyPrefs;
84 lastUpdate = other.lastUpdate;
86 stringVecConstIterator il;
87 for (il = other.landing.begin(); il != other.landing.end(); il++)
88 landing.push_back(*il);
89 for (il = other.takeoff.begin(); il != other.takeoff.end(); il++)
90 takeoff.push_back(*il);
91 lastUpdate = other.lastUpdate;
92 for (int i = 0; i < 10; i++)
94 avWindHeading [i] = other.avWindHeading[i];
95 avWindSpeed [i] = other.avWindSpeed [i];
100 FGAirportDynamics::~FGAirportDynamics()
106 // Initialization required after XMLRead
107 void FGAirportDynamics::init()
109 // This may seem a bit weird to first randomly shuffle the parkings
110 // and then sort them again. However, parkings are sorted here by ascending
111 // radius. Since many parkings have similar radii, with each radius class they will
112 // still be allocated relatively systematically. Randomizing prior to sorting will
113 // prevent any initial orderings to be destroyed, leading (hopefully) to a more
114 // naturalistic gate assignment.
115 random_shuffle(parkings.begin(), parkings.end());
116 sort(parkings.begin(), parkings.end());
117 // add the gate positions to the ground network.
118 groundNetwork.addNodes(&parkings);
119 groundNetwork.init();
122 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon, double *heading, int *gateId, double rad, const string &flType, const string &acType, const string &airline)
125 bool available = false;
128 FGParkingVecIterator i;
129 // if (flType == "cargo")
131 // gateType = "RAMP_CARGO";
133 // else if (flType == "ga")
135 // gateType = "RAMP_GA";
137 // else gateType = "GATE";
139 if (parkings.begin() == parkings.end())
141 //cerr << "Could not find parking spot at " << _id << endl;
149 // First try finding a parking with a designated airline code
150 for (i = parkings.begin(); !(i == parkings.end() || found); i++)
152 //cerr << "Gate Id: " << i->getIndex()
153 // << " Type : " << i->getType()
154 // << " Codes : " << i->getCodes()
155 // << " Radius: " << i->getRadius()
156 // << " Name : " << i->getName()
157 // << " Available: " << i->isAvailable() << endl;
159 // Taken by another aircraft
160 if (!(i->isAvailable()))
165 // No airline codes, so skip
166 if (i->getCodes().empty())
171 else // Airline code doesn't match
172 if (i->getCodes().find(airline, 0) == string::npos)
177 // Type doesn't match
178 if (i->getType() != flType)
184 if (i->getRadius() < rad)
192 *lat = i->getLatitude ();
193 *lon = i->getLongitude();
194 *heading = i->getHeading ();
195 *gateId = i->getIndex ();
196 i->setAvailable(false);
200 // then try again for those without codes.
201 for (i = parkings.begin(); !(i == parkings.end() || found); i++)
204 if (!(i->isAvailable()))
209 if (!(i->getCodes().empty()))
211 if ((i->getCodes().find(airline,0) == string::npos))
217 if (i->getType() != flType)
223 if (i->getRadius() < rad)
231 *lat = i->getLatitude ();
232 *lon = i->getLongitude();
233 *heading = i->getHeading ();
234 *gateId = i->getIndex ();
235 i->setAvailable(false);
239 // And finally once more if that didn't work. Now ignore the airline codes, as a last resort
240 for (i = parkings.begin(); !(i == parkings.end() || found); i++)
243 if (!(i->isAvailable()))
248 if (i->getType() != flType)
254 if (i->getRadius() < rad)
262 *lat = i->getLatitude ();
263 *lon = i->getLongitude();
264 *heading = i->getHeading ();
265 *gateId = i->getIndex ();
266 i->setAvailable(false);
273 //cerr << "Traffic overflow at" << _id
274 // << ". flType = " << flType
275 // << ". airline = " << airline
276 // << " Radius = " <<rad
287 void FGAirportDynamics::getParking (int id, double *lat, double* lon, double *heading)
297 FGParkingVecIterator i = parkings.begin();
298 for (i = parkings.begin(); i != parkings.end(); i++)
300 if (id == i->getIndex())
302 *lat = i->getLatitude();
303 *lon = i->getLongitude();
304 *heading = i->getLongitude();
310 FGParking *FGAirportDynamics::getParking(int i)
312 if (i < (int)parkings.size())
313 return &(parkings[i]);
317 string FGAirportDynamics::getParkingName(int i)
319 if (i < (int)parkings.size() && i >= 0)
320 return (parkings[i].getName());
322 return string("overflow");
324 void FGAirportDynamics::releaseParking(int id)
329 FGParkingVecIterator i = parkings.begin();
330 for (i = parkings.begin(); i != parkings.end(); i++)
332 if (id == i->getIndex())
334 i -> setAvailable(true);
340 void FGAirportDynamics::startXML () {
341 //cout << "Start XML" << endl;
344 void FGAirportDynamics::endXML () {
345 //cout << "End XML" << endl;
348 void FGAirportDynamics::startElement (const char * name, const XMLAttributes &atts) {
349 // const char *attval;
352 FGTaxiSegment taxiSegment;
354 taxiSegment.setIndex(index);
355 //cout << "Start element " << name << endl;
362 if (name == string("Parking"))
364 for (int i = 0; i < atts.size(); i++)
366 //cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
367 attname = atts.getName(i);
368 if (attname == string("index"))
369 park.setIndex(atoi(atts.getValue(i)));
370 else if (attname == string("type"))
371 park.setType(atts.getValue(i));
372 else if (attname == string("name"))
373 gateName = atts.getValue(i);
374 else if (attname == string("number"))
375 gateNumber = atts.getValue(i);
376 else if (attname == string("lat"))
377 park.setLatitude(atts.getValue(i));
378 else if (attname == string("lon"))
379 park.setLongitude(atts.getValue(i));
380 else if (attname == string("heading"))
381 park.setHeading(atof(atts.getValue(i)));
382 else if (attname == string("radius")) {
383 string radius = atts.getValue(i);
384 if (radius.find("M") != string::npos)
385 radius = radius.substr(0, radius.find("M",0));
386 //cerr << "Radius " << radius <<endl;
387 park.setRadius(atof(radius.c_str()));
389 else if (attname == string("airlineCodes"))
390 park.setCodes(atts.getValue(i));
392 park.setName((gateName+gateNumber));
393 parkings.push_back(park);
395 if (name == string("node"))
397 for (int i = 0; i < atts.size() ; i++)
399 attname = atts.getName(i);
400 if (attname == string("index"))
401 taxiNode.setIndex(atoi(atts.getValue(i)));
402 if (attname == string("lat"))
403 taxiNode.setLatitude(atts.getValue(i));
404 if (attname == string("lon"))
405 taxiNode.setLongitude(atts.getValue(i));
407 groundNetwork.addNode(taxiNode);
409 if (name == string("arc"))
411 taxiSegment.setIndex(++index);
412 for (int i = 0; i < atts.size() ; i++)
414 attname = atts.getName(i);
415 if (attname == string("begin"))
416 taxiSegment.setStartNodeRef(atoi(atts.getValue(i)));
417 if (attname == string("end"))
418 taxiSegment.setEndNodeRef(atoi(atts.getValue(i)));
420 groundNetwork.addSegment(taxiSegment);
422 // sort by radius, in asending order, so that smaller gates are first in the list
425 void FGAirportDynamics::endElement (const char * name) {
426 //cout << "End element " << name << endl;
430 void FGAirportDynamics::data (const char * s, int len) {
431 string token = string(s,len);
432 //cout << "Character data " << string(s,len) << endl;
433 //if ((token.find(" ") == string::npos && (token.find('\n')) == string::npos))
436 //value = string("");
439 void FGAirportDynamics::pi (const char * target, const char * data) {
440 //cout << "Processing instruction " << target << ' ' << data << endl;
443 void FGAirportDynamics::warning (const char * message, int line, int column) {
444 cout << "Warning: " << message << " (" << line << ',' << column << ')'
448 void FGAirportDynamics::error (const char * message, int line, int column) {
449 cout << "Error: " << message << " (" << line << ',' << column << ')'
453 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
456 //cerr << "Exiting due to not implemented yet" << endl;
459 void FGAirportDynamics::getActiveRunway(const string &trafficType, int action, string &runway)
468 if (!(rwyPrefs.available()))
470 runway = chooseRunwayFallback();
471 return; // generic fall back goes here
475 RunwayGroup *currRunwayGroup = 0;
476 int nrActiveRunways = 0;
477 time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
478 if (((dayStart - lastUpdate) > 600) || trafficType != prevTrafficType)
482 //lastUpdate = dayStart;
483 prevTrafficType = trafficType;
486 stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
487 ->getEnvironment(getLatitude(),
491 windSpeed = stationweather.get_wind_speed_kt();
492 windHeading = stationweather.get_wind_from_heading_deg();
493 double averageWindSpeed = 0;
494 double averageWindHeading = 0;
495 double cosHeading = 0;
496 double sinHeading = 0;
497 // Initialize at the beginning of the next day or startup
498 if ((lastUpdate == 0) || (dayStart < lastUpdate))
500 for (int i = 0; i < 10; i++)
502 avWindHeading [i] = windHeading;
503 avWindSpeed [i] = windSpeed;
508 if (windSpeed != avWindSpeed[9]) // update if new metar data
510 // shift the running average
511 for (int i = 0; i < 9 ; i++)
513 avWindHeading[i] = avWindHeading[i+1];
514 avWindSpeed [i] = avWindSpeed [i+1];
517 avWindHeading[9] = windHeading;
518 avWindSpeed [9] = windSpeed;
521 for (int i = 0; i < 10; i++)
523 averageWindSpeed += avWindSpeed [i];
524 //averageWindHeading += avWindHeading [i];
525 cosHeading += cos(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
526 sinHeading += sin(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
528 averageWindSpeed /= 10;
529 //averageWindHeading /= 10;
532 averageWindHeading = atan2(sinHeading, cosHeading) *SG_RADIANS_TO_DEGREES;
533 if (averageWindHeading < 0)
534 averageWindHeading += 360.0;
535 //cerr << "Wind Heading " << windHeading << " average " << averageWindHeading << endl;
536 //cerr << "Wind Speed " << windSpeed << " average " << averageWindSpeed << endl;
537 lastUpdate = dayStart;
538 //if (wind_speed == 0) {
539 // wind_heading = 270; This forces West-facing rwys to be used in no-wind situations
540 // which is consistent with Flightgear's initial setup.
543 //string rwy_no = globals->get_runways()->search(apt->getId(), int(wind_heading));
545 //cerr << "finding active Runway for" << _id << endl;
546 //cerr << "Nr of seconds since day start << " << dayStart << endl;
547 ScheduleTime *currSched;
548 //cerr << "A"<< endl;
549 currSched = rwyPrefs.getSchedule(trafficType.c_str());
552 //cerr << "B"<< endl;
553 scheduleName = currSched->getName(dayStart);
554 maxTail = currSched->getTailWind ();
555 maxCross = currSched->getCrossWind ();
556 //cerr << "SChedule anme = " << scheduleName << endl;
557 if (scheduleName.empty())
559 //cerr << "C"<< endl;
560 currRunwayGroup = rwyPrefs.getGroup(scheduleName);
561 //cerr << "D"<< endl;
562 if (!(currRunwayGroup))
564 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
565 //cerr << "Nr of Active Runways = " << nrActiveRunways << endl;
566 currRunwayGroup->setActive(_id, averageWindSpeed, averageWindHeading, maxTail, maxCross);
567 nrActiveRunways = currRunwayGroup->getNrActiveRunways();
568 for (int i = 0; i < nrActiveRunways; i++)
570 type = "unknown"; // initialize to something other than landing or takeoff
571 currRunwayGroup->getActive(i, name, type);
572 if (type == "landing")
574 landing.push_back(name);
575 //cerr << "Landing " << name << endl;
577 if (type == "takeoff")
579 takeoff.push_back(name);
580 //cerr << "takeoff " << name << endl;
584 if (action == 1) // takeoff
586 int nr = takeoff.size();
589 runway = takeoff[(rand() % nr)];
593 runway = chooseRunwayFallback();
596 if (action == 2) // landing
598 int nr = landing.size();
601 runway = landing[(rand() % nr)];
605 runway = chooseRunwayFallback();
609 //runway = globals->get_runways()->search(_id, int(windHeading));
610 //cerr << "Seleceted runway: " << runway << endl;
614 string FGAirportDynamics::chooseRunwayFallback()
617 stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
618 ->getEnvironment(getLatitude(),
622 double windSpeed = stationweather.get_wind_speed_kt();
623 double windHeading = stationweather.get_wind_from_heading_deg();
624 if (windSpeed == 0) {
625 windHeading = 270; // This forces West-facing rwys to be used in no-wind situations
626 //which is consistent with Flightgear's initial setup.
629 return globals->get_runways()->search(_id, int(windHeading));