]> git.mxchange.org Git - flightgear.git/blob - src/Airports/dynamics.cxx
Update FGRunway to process information from threshold.xml files.
[flightgear.git] / src / Airports / dynamics.cxx
1 // dynamics.cxx - Code to manage the higher order airport ground activities
2 // Written by Durk Talsma, started December 2004.
3 //
4 //
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.
9 //
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.
14 //
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.
18 //
19 // $Id$
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <algorithm>
26
27 #include <simgear/compiler.h>
28
29 #include <plib/ul.h>
30
31 #include <Environment/environment_mgr.hxx>
32 #include <Environment/environment.hxx>
33 #include <simgear/misc/sg_path.hxx>
34 #include <simgear/props/props.hxx>
35 #include <simgear/structure/subsystem_mgr.hxx>
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/route/waypoint.hxx>
38 #include <Main/globals.hxx>
39 #include <Main/fg_props.hxx>
40 #include <Airports/runways.hxx>
41
42 #include <string>
43 #include <vector>
44
45 using std::string;
46 using std::vector;
47 using std::sort;
48 using std::random_shuffle;
49
50 #include "simple.hxx"
51 #include "dynamics.hxx"
52
53 FGAirportDynamics::FGAirportDynamics(FGAirport* ap) :
54   _ap(ap), rwyPrefs(ap), SIDs(ap) {
55   lastUpdate = 0;
56
57   // For testing only. This needs to be refined when we move ATIS functionality over.
58   atisInformation = "Sierra";
59 }
60
61 // Note that the ground network should also be copied
62 FGAirportDynamics::FGAirportDynamics(const FGAirportDynamics& other) :
63   rwyPrefs(other.rwyPrefs),
64   SIDs(other.SIDs)
65 {
66   for (FGParkingVecConstIterator ip= other.parkings.begin(); ip != other.parkings.end(); ip++)
67     parkings.push_back(*(ip));
68   // rwyPrefs = other.rwyPrefs;
69   lastUpdate = other.lastUpdate;
70   
71   stringVecConstIterator il;
72   for (il = other.landing.begin(); il != other.landing.end(); il++)
73     landing.push_back(*il);
74   for (il = other.takeoff.begin(); il != other.takeoff.end(); il++)
75     takeoff.push_back(*il);
76   lastUpdate = other.lastUpdate;
77   atisInformation = other.atisInformation; 
78 }
79
80 // Destructor
81 FGAirportDynamics::~FGAirportDynamics()
82 {
83 }
84
85
86 // Initialization required after XMLRead
87 void FGAirportDynamics::init() 
88 {
89   // This may seem a bit weird to first randomly shuffle the parkings
90   // and then sort them again. However, parkings are sorted here by ascending 
91   // radius. Since many parkings have similar radii, with each radius class they will
92   // still be allocated relatively systematically. Randomizing prior to sorting will
93   // prevent any initial orderings to be destroyed, leading (hopefully) to a more 
94   // naturalistic gate assignment. 
95   random_shuffle(parkings.begin(), parkings.end());
96   sort(parkings.begin(), parkings.end());
97   // add the gate positions to the ground network. 
98   groundNetwork.addNodes(&parkings);
99   groundNetwork.init();
100   groundNetwork.setTowerController(&towerController);
101   groundNetwork.setParent(_ap);
102 }
103
104 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon, double *heading, int *gateId, double rad, const string &flType, const string &acType, const string &airline)
105 {
106   bool found = false;
107   bool available = false;
108   //string gateType;
109
110   FGParkingVecIterator i;
111 //   if (flType == "cargo")
112 //     {
113 //       gateType = "RAMP_CARGO";
114 //     }
115 //   else if (flType == "ga")
116 //     {
117 //       gateType = "RAMP_GA";
118 //     }
119 //   else gateType = "GATE";
120   
121   if (parkings.begin() == parkings.end())
122     {
123       //cerr << "Could not find parking spot at " << _ap->getId() << endl;
124       *lat = _ap->getLatitude();
125       *lon = _ap->getLongitude();
126       *heading = 0;
127       found = true;
128     }
129   else
130     {
131       // First try finding a parking with a designated airline code
132       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
133         {
134           //cerr << "Gate Id: " << i->getIndex()
135           //     << " Type  : " << i->getType()
136           //     << " Codes : " << i->getCodes()
137           //     << " Radius: " << i->getRadius()
138           //     << " Name  : " << i->getName()
139           //     << " Available: " << i->isAvailable() << endl;
140           available = true;
141           // Taken by another aircraft
142           if (!(i->isAvailable()))
143             {
144               available = false;
145               continue;
146             }
147           // No airline codes, so skip
148           if (i->getCodes().empty())
149             {
150               available = false;
151               continue;
152             }
153           else // Airline code doesn't match
154             {
155               //cerr << "Code = " << airline << ": Codes " << i->getCodes();
156               if (i->getCodes().find(airline, 0) == string::npos)
157                 {
158                   available = false;
159                   //cerr << "Unavailable" << endl;
160                   continue;
161                 }
162               else
163                 {
164                   //cerr << "Available" << endl;
165                 }
166             }
167           // Type doesn't match
168           if (i->getType() != flType)
169             {
170               available = false;
171               continue;
172             }
173           // too small
174           if (i->getRadius() < rad)
175             {
176               available = false;
177               continue;
178             }
179           
180           if (available)
181             {
182               *lat     = i->getLatitude ();
183               *lon     = i->getLongitude();
184               *heading = i->getHeading  ();
185               *gateId  = i->getIndex    ();
186               i->setAvailable(false);
187               found = true;
188             }
189         }
190       // then try again for those without codes. 
191       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
192         {
193           available = true;
194           if (!(i->isAvailable()))
195             {
196               available = false;
197               continue;
198             }
199           if (!(i->getCodes().empty()))
200             {
201               if ((i->getCodes().find(airline,0) == string::npos))
202                 {
203                     available = false;
204                     continue;
205                 }
206             }
207           if (i->getType() != flType)
208             {
209               available = false;
210               continue;
211             }
212               
213           if (i->getRadius() < rad)
214             {
215               available = false;
216               continue;
217             }
218           
219           if (available)
220             {
221               *lat     = i->getLatitude ();
222               *lon     = i->getLongitude();
223               *heading = i->getHeading  ();
224               *gateId  = i->getIndex    ();
225               i->setAvailable(false);
226               found = true;
227             }
228         }
229       // And finally once more if that didn't work. Now ignore the airline codes, as a last resort
230       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
231         {
232           available = true;
233           if (!(i->isAvailable()))
234             {
235               available = false;
236               continue;
237             }
238           if (i->getType() != flType)
239             {
240               available = false;
241               continue;
242             }
243           
244           if (i->getRadius() < rad)
245             {
246               available = false;
247               continue;
248             }
249           
250           if (available)
251             {
252               *lat     = i->getLatitude ();
253               *lon     = i->getLongitude();
254               *heading = i->getHeading  ();
255               *gateId  = i->getIndex    ();
256               i->setAvailable(false);
257               found = true;
258             }
259         }
260     }
261   if (!found)
262     {
263       //cerr << "Traffic overflow at" << _ap->getId() 
264       //           << ". flType = " << flType 
265       //           << ". airline = " << airline 
266       //           << " Radius = " <<rad
267       //           << endl;
268       *lat = _ap->getLatitude();
269       *lon = _ap->getLongitude();
270       *heading = 0;
271       *gateId  = -1;
272       //exit(1);
273     }
274   return found;
275 }
276
277 void FGAirportDynamics::getParking (int id, double *lat, double* lon, double *heading)
278 {
279   if (id < 0)
280     {
281       *lat = _ap->getLatitude();
282       *lon = _ap->getLongitude();
283       *heading = 0;
284     }
285   else
286     {
287       FGParkingVecIterator i = parkings.begin();
288       for (i = parkings.begin(); i != parkings.end(); i++)
289         {
290           if (id == i->getIndex())
291             {
292               *lat     = i->getLatitude();
293               *lon     = i->getLongitude();
294               *heading = i->getHeading();
295             }
296         }
297     }
298
299
300 FGParking *FGAirportDynamics::getParking(int id) 
301
302     FGParkingVecIterator i = parkings.begin();
303     for (i = parkings.begin(); i != parkings.end(); i++)
304         {
305           if (id == i->getIndex()) {
306                return &(*i);
307           }
308         }
309     return 0;
310 }
311 string FGAirportDynamics::getParkingName(int id) 
312
313     FGParkingVecIterator i = parkings.begin();
314     for (i = parkings.begin(); i != parkings.end(); i++)
315         {
316           if (id == i->getIndex()) {
317                return i->getName();
318           }
319         }
320
321     return string("overflow");
322 }
323 void FGAirportDynamics::releaseParking(int id)
324 {
325   if (id >= 0)
326     {
327       
328       FGParkingVecIterator i = parkings.begin();
329       for (i = parkings.begin(); i != parkings.end(); i++)
330         {
331           if (id == i->getIndex())
332             {
333               i -> setAvailable(true);
334             }
335         }
336     }
337 }
338   
339 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
340 {
341   rwyPrefs = ref;
342   //cerr << "Exiting due to not implemented yet" << endl;
343   //exit(1);
344 }
345
346 bool FGAirportDynamics::innerGetActiveRunway(const string &trafficType, int action, string &runway, double heading)
347 {
348 double windSpeed;
349   double windHeading;
350   double maxTail;
351   double maxCross;
352   string name;
353   string type;
354
355   if (!rwyPrefs.available()) {
356     return false;
357   }
358   
359   RunwayGroup *currRunwayGroup = 0;
360   int nrActiveRunways = 0;
361   time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
362   if ((abs((long)(dayStart - lastUpdate)) > 600) || trafficType != prevTrafficType)
363         {
364           landing.clear();
365           takeoff.clear();
366           lastUpdate = dayStart;
367           prevTrafficType = trafficType;
368
369           FGEnvironment 
370             stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
371             ->getEnvironment(getLatitude(), 
372                              getLongitude(), 
373                              getElevation());
374           
375           windSpeed = stationweather.get_wind_speed_kt();
376           windHeading = stationweather.get_wind_from_heading_deg();
377           string scheduleName;
378           //cerr << "finding active Runway for" << _ap->getId() << endl;
379           //cerr << "Nr of seconds since day start << " << dayStart << endl;
380
381           ScheduleTime *currSched;
382           //cerr << "A"<< endl;
383           currSched = rwyPrefs.getSchedule(trafficType.c_str());
384           if (!(currSched))
385             return false;
386           //cerr << "B"<< endl;
387           scheduleName = currSched->getName(dayStart);
388           maxTail  = currSched->getTailWind  ();
389           maxCross = currSched->getCrossWind ();
390           //cerr << "SChedule anme = " << scheduleName << endl;
391           if (scheduleName.empty())
392             return false;
393           //cerr << "C"<< endl;
394           currRunwayGroup = rwyPrefs.getGroup(scheduleName); 
395           //cerr << "D"<< endl;
396           if (!(currRunwayGroup))
397             return false;
398           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
399
400         // Keep a history of the currently active runways, to ensure
401         // that an already established selection of runways will not
402         // be overridden once a more preferred selection becomes 
403         // available as that can lead to random runway swapping.
404         if (trafficType == "com") {
405           currentlyActive = &comActive;
406         } else if (trafficType == "gen") {
407           currentlyActive = &genActive;
408         } else if (trafficType == "mil") {
409           currentlyActive = &milActive;
410         } else if (trafficType == "ul") {
411           currentlyActive = &ulActive;
412         }
413           // 
414           currRunwayGroup->setActive(_ap, 
415                                      windSpeed, 
416                                      windHeading, 
417                                      maxTail, 
418                                      maxCross, 
419                                      currentlyActive); 
420
421           // Note that I SHOULD keep multiple lists in memory, one for 
422           // general aviation, one for commercial and one for military
423           // traffic.
424           currentlyActive->clear();
425           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
426           //cerr << "Choosing runway for " << trafficType << endl;
427           for (int i = 0; i < nrActiveRunways; i++)
428             {
429               type = "unknown"; // initialize to something other than landing or takeoff
430               currRunwayGroup->getActive(i, name, type);
431               if (type == "landing")
432                 {
433                   landing.push_back(name);
434                   currentlyActive->push_back(name);
435                   //cerr << "Landing " << name << endl; 
436                 }
437               if (type == "takeoff")
438                 {
439                   takeoff.push_back(name);
440                   currentlyActive->push_back(name);
441                   //cerr << "takeoff " << name << endl;
442                 }
443             }
444           //cerr << endl;
445         }
446   
447   if (action == 1) // takeoff 
448         {
449           int nr = takeoff.size();
450           if (nr)
451             {
452               // Note that the randomization below, is just a placeholder to choose between
453               // multiple active runways for this action. This should be
454               // under ATC control.
455               runway = chooseRwyByHeading (takeoff, heading);
456             }
457           else
458             { // Fallback
459               runway = chooseRunwayFallback();
460             }
461         } 
462   
463   if (action == 2) // landing
464         {
465           int nr = landing.size();
466           if (nr)
467             {
468               runway = chooseRwyByHeading (landing, heading);
469             }
470           else
471             {  //fallback
472                runway = chooseRunwayFallback();
473             }
474         } 
475
476   return true;
477 }
478
479 string FGAirportDynamics::chooseRwyByHeading(stringVec rwys, double heading) {
480    double bestError = 360.0;
481    double rwyHeading, headingError;
482    string runway;
483    for (stringVecIterator i = rwys.begin(); i != rwys.end(); i++) {
484        FGRunway *rwy = _ap->getRunwayByIdent((*i));
485        rwyHeading = rwy->headingDeg();
486        headingError = fabs(heading - rwyHeading);
487         if (headingError > 180)
488             headingError = fabs(headingError - 360);
489         if (headingError < bestError) {
490             runway = (*i);
491             bestError = headingError;
492         }
493    }
494    //cerr << "Using active runway " << runway << " for heading " << heading << endl;
495    return runway;
496 }
497
498 void FGAirportDynamics::getActiveRunway(const string &trafficType, int action, string &runway, double heading)
499 {
500   bool ok = innerGetActiveRunway(trafficType, action, runway, heading);
501   if (!ok) {
502     runway = chooseRunwayFallback();
503   }
504 }
505
506 string FGAirportDynamics::chooseRunwayFallback()
507 {   
508   FGRunway* rwy = _ap->getActiveRunwayForUsage();
509   return rwy->ident();
510 }
511
512 void FGAirportDynamics::addParking(FGParking& park) {
513   parkings.push_back(park);
514 }
515
516 double FGAirportDynamics::getLatitude() const {
517   return _ap->getLatitude();
518 }
519
520 double FGAirportDynamics::getLongitude() const {
521   return _ap->getLongitude();
522 }
523
524 double FGAirportDynamics::getElevation() const {
525   return _ap->getElevation();
526 }
527
528 const string& FGAirportDynamics::getId() const {
529   return _ap->getId();
530 }
531
532 // Experimental: Return a different ground frequency depending on the leg of the
533 // Flight. Leg should always have a minimum value of two when this function is called. 
534 // Note that in this scheme, the assignment of various frequencies to various ground 
535 // operations is completely arbitrary. As such, is a short cut I need to take now,
536 // so that at least I can start working on assigning different frequencies to different
537 // operations.
538
539 int FGAirportDynamics::getGroundFrequency(unsigned leg) { 
540      //return freqGround.size() ? freqGround[0] : 0; };
541      int groundFreq = 0;
542      if (leg < 2) {
543          SG_LOG(SG_ATC, SG_ALERT, "Leg value is smaller than two at " << SG_ORIGIN);
544      }
545      if (freqGround.size() == 0) {
546          return 0;
547      }
548      if ((freqGround.size() > leg-1) && (leg > 1)) {
549           groundFreq =  freqGround[leg-1];
550      }
551      if ((freqGround.size() < leg-1) && (leg > 1)) {
552           groundFreq = (freqGround.size() < (leg-1)) ? freqGround[freqGround.size()-1] : freqGround[leg-2];
553      }
554      if ((freqGround.size() >= leg-1) && (leg > 1)) {
555           groundFreq = freqGround[leg-2];
556      }
557     return groundFreq;
558 }
559
560 FGAIFlightPlan *FGAirportDynamics::getSID(string activeRunway, double heading)
561 {
562    return SIDs.getBest(activeRunway, heading);
563 }