]> git.mxchange.org Git - flightgear.git/blob - src/Airports/dynamics.cxx
a7d450ccfdce240d84f655ec5439cafee0f19758
[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/sg.h>
30 #include <plib/ul.h>
31
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
43 #include STL_STRING
44 #include <vector>
45
46 SG_USING_STD(string);
47 SG_USING_STD(vector);
48 SG_USING_STD(sort);
49 SG_USING_STD(random_shuffle);
50
51 #include "simple.hxx"
52 #include "dynamics.hxx"
53
54 FGAirportDynamics::FGAirportDynamics(FGAirport* ap) :
55   _ap(ap), rwyPrefs(ap) {
56   lastUpdate = 0;
57   for (int i = 0; i < 10; i++)
58      {
59        //avWindHeading [i] = 0;
60        //avWindSpeed   [i] = 0;
61      }
62 }
63
64 // Note that the ground network should also be copied
65 FGAirportDynamics::FGAirportDynamics(const FGAirportDynamics& other) :
66   rwyPrefs(other.rwyPrefs)
67 {
68   for (FGParkingVecConstIterator ip= other.parkings.begin(); ip != other.parkings.end(); ip++)
69     parkings.push_back(*(ip));
70   // rwyPrefs = other.rwyPrefs;
71   lastUpdate = other.lastUpdate;
72   
73   stringVecConstIterator il;
74   for (il = other.landing.begin(); il != other.landing.end(); il++)
75     landing.push_back(*il);
76   for (il = other.takeoff.begin(); il != other.takeoff.end(); il++)
77     takeoff.push_back(*il);
78   lastUpdate = other.lastUpdate;
79   for (int i = 0; i < 10; i++)
80     {
81       //avWindHeading [i] = other.avWindHeading[i];
82       //avWindSpeed   [i] = other.avWindSpeed  [i];
83     }
84 }
85
86 // Destructor
87 FGAirportDynamics::~FGAirportDynamics()
88 {
89 }
90
91
92 // Initialization required after XMLRead
93 void FGAirportDynamics::init() 
94 {
95   // This may seem a bit weird to first randomly shuffle the parkings
96   // and then sort them again. However, parkings are sorted here by ascending 
97   // radius. Since many parkings have similar radii, with each radius class they will
98   // still be allocated relatively systematically. Randomizing prior to sorting will
99   // prevent any initial orderings to be destroyed, leading (hopefully) to a more 
100   // naturalistic gate assignment. 
101   random_shuffle(parkings.begin(), parkings.end());
102   sort(parkings.begin(), parkings.end());
103   // add the gate positions to the ground network. 
104   groundNetwork.addNodes(&parkings);
105   groundNetwork.init();
106   groundNetwork.setTowerController(&towerController);
107   groundNetwork.setParent(_ap);
108 }
109
110 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon, double *heading, int *gateId, double rad, const string &flType, const string &acType, const string &airline)
111 {
112   bool found = false;
113   bool available = false;
114   //string gateType;
115
116   FGParkingVecIterator i;
117 //   if (flType == "cargo")
118 //     {
119 //       gateType = "RAMP_CARGO";
120 //     }
121 //   else if (flType == "ga")
122 //     {
123 //       gateType = "RAMP_GA";
124 //     }
125 //   else gateType = "GATE";
126   
127   if (parkings.begin() == parkings.end())
128     {
129       //cerr << "Could not find parking spot at " << _ap->getId() << endl;
130       *lat = _ap->getLatitude();
131       *lon = _ap->getLongitude();
132       *heading = 0;
133       found = true;
134     }
135   else
136     {
137       // First try finding a parking with a designated airline code
138       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
139         {
140           //cerr << "Gate Id: " << i->getIndex()
141           //     << " Type  : " << i->getType()
142           //     << " Codes : " << i->getCodes()
143           //     << " Radius: " << i->getRadius()
144           //     << " Name  : " << i->getName()
145           //     << " Available: " << i->isAvailable() << endl;
146           available = true;
147           // Taken by another aircraft
148           if (!(i->isAvailable()))
149             {
150               available = false;
151               continue;
152             }
153           // No airline codes, so skip
154           if (i->getCodes().empty())
155             {
156               available = false;
157               continue;
158             }
159           else // Airline code doesn't match
160             {
161               //cerr << "Code = " << airline << ": Codes " << i->getCodes();
162               if (i->getCodes().find(airline, 0) == string::npos)
163                 {
164                   available = false;
165                   //cerr << "Unavailable" << endl;
166                   continue;
167                 }
168               else
169                 {
170                   //cerr << "Available" << endl;
171                 }
172             }
173           // Type doesn't match
174           if (i->getType() != flType)
175             {
176               available = false;
177               continue;
178             }
179           // too small
180           if (i->getRadius() < rad)
181             {
182               available = false;
183               continue;
184             }
185           
186           if (available)
187             {
188               *lat     = i->getLatitude ();
189               *lon     = i->getLongitude();
190               *heading = i->getHeading  ();
191               *gateId  = i->getIndex    ();
192               i->setAvailable(false);
193               found = true;
194             }
195         }
196       // then try again for those without codes. 
197       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
198         {
199           available = true;
200           if (!(i->isAvailable()))
201             {
202               available = false;
203               continue;
204             }
205           if (!(i->getCodes().empty()))
206             {
207               if ((i->getCodes().find(airline,0) == string::npos))
208           {
209             available = false;
210             continue;
211           }
212             }
213           if (i->getType() != flType)
214             {
215               available = false;
216               continue;
217             }
218               
219           if (i->getRadius() < rad)
220             {
221               available = false;
222               continue;
223             }
224           
225           if (available)
226             {
227               *lat     = i->getLatitude ();
228               *lon     = i->getLongitude();
229               *heading = i->getHeading  ();
230               *gateId  = i->getIndex    ();
231               i->setAvailable(false);
232               found = true;
233             }
234         } 
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++)
237         {
238           available = true;
239           if (!(i->isAvailable()))
240             {
241               available = false;
242               continue;
243             }
244           if (i->getType() != flType)
245             {
246               available = false;
247               continue;
248             }
249           
250           if (i->getRadius() < rad)
251             {
252               available = false;
253               continue;
254             }
255           
256           if (available)
257             {
258               *lat     = i->getLatitude ();
259               *lon     = i->getLongitude();
260               *heading = i->getHeading  ();
261               *gateId  = i->getIndex    ();
262               i->setAvailable(false);
263               found = true;
264             }
265         }
266     }
267   if (!found)
268     {
269       //cerr << "Traffic overflow at" << _ap->getId() 
270       //           << ". flType = " << flType 
271       //           << ". airline = " << airline 
272       //           << " Radius = " <<rad
273       //           << endl;
274       *lat = _ap->getLatitude();
275       *lon = _ap->getLongitude();
276       *heading = 0;
277       *gateId  = -1;
278       //exit(1);
279     }
280   return found;
281 }
282
283 void FGAirportDynamics::getParking (int id, double *lat, double* lon, double *heading)
284 {
285   if (id < 0)
286     {
287       *lat = _ap->getLatitude();
288       *lon = _ap->getLongitude();
289       *heading = 0;
290     }
291   else
292     {
293       FGParkingVecIterator i = parkings.begin();
294       for (i = parkings.begin(); i != parkings.end(); i++)
295         {
296           if (id == i->getIndex())
297             {
298               *lat     = i->getLatitude();
299               *lon     = i->getLongitude();
300               *heading = i->getHeading();
301             }
302         }
303     }
304
305
306 FGParking *FGAirportDynamics::getParking(int i) 
307
308   if (i < (int)parkings.size()) 
309     return &(parkings[i]); 
310   else 
311     return 0;
312 }
313 string FGAirportDynamics::getParkingName(int i) 
314
315   if (i < (int)parkings.size() && i >= 0) 
316     return (parkings[i].getName()); 
317   else 
318     return string("overflow");
319 }
320 void FGAirportDynamics::releaseParking(int id)
321 {
322   if (id >= 0)
323     {
324       
325       FGParkingVecIterator i = parkings.begin();
326       for (i = parkings.begin(); i != parkings.end(); i++)
327         {
328           if (id == i->getIndex())
329             {
330               i -> setAvailable(true);
331             }
332         }
333     }
334 }
335   
336 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
337 {
338   rwyPrefs = ref;
339   //cerr << "Exiting due to not implemented yet" << endl;
340   //exit(1);
341 }
342 void FGAirportDynamics::getActiveRunway(const string &trafficType, int action, string &runway)
343 {
344   double windSpeed;
345   double windHeading;
346   double maxTail;
347   double maxCross;
348   string name;
349   string type;
350
351   if (!(rwyPrefs.available()))
352     {
353       runway = chooseRunwayFallback();
354       return; // generic fall back goes here
355     }
356   else
357     {
358       RunwayGroup *currRunwayGroup = 0;
359       int nrActiveRunways = 0;
360       time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
361       if ((abs((long)(dayStart - lastUpdate)) > 600) || trafficType != prevTrafficType)
362         {
363           landing.clear();
364           takeoff.clear();
365           lastUpdate = dayStart;
366           prevTrafficType = trafficType;
367
368           FGEnvironment 
369             stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
370             ->getEnvironment(getLatitude(), 
371                              getLongitude(), 
372                              getElevation());
373           
374           windSpeed = stationweather.get_wind_speed_kt();
375           windHeading = stationweather.get_wind_from_heading_deg();
376           string scheduleName;
377           //cerr << "finding active Runway for" << _ap->getId() << endl;
378           //cerr << "Nr of seconds since day start << " << dayStart << endl;
379
380           ScheduleTime *currSched;
381           //cerr << "A"<< endl;
382           currSched = rwyPrefs.getSchedule(trafficType.c_str());
383           if (!(currSched))
384             return;
385           //cerr << "B"<< endl;
386           scheduleName = currSched->getName(dayStart);
387           maxTail  = currSched->getTailWind  ();
388           maxCross = currSched->getCrossWind ();
389           //cerr << "SChedule anme = " << scheduleName << endl;
390           if (scheduleName.empty())
391             return;
392           //cerr << "C"<< endl;
393           currRunwayGroup = rwyPrefs.getGroup(scheduleName); 
394           //cerr << "D"<< endl;
395           if (!(currRunwayGroup))
396             return;
397           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
398
399         // Keep a history of the currently active runways, to ensure
400         // that an already established selection of runways will not
401         // be overridden once a more preferred selection becomes 
402         // available as that can lead to random runway swapping.
403         if (trafficType == "com") {
404           currentlyActive = &comActive;
405         } else if (trafficType == "gen") {
406           currentlyActive = &genActive;
407         } else if (trafficType == "mil") {
408           currentlyActive = &milActive;
409         } else if (trafficType == "ul") {
410           currentlyActive = &ulActive;
411         }
412           // 
413           currRunwayGroup->setActive(_ap->getId(), 
414                                      windSpeed, 
415                                      windHeading, 
416                                      maxTail, 
417                                      maxCross, 
418                                      currentlyActive); 
419
420           // Note that I SHOULD keep multiple lists in memory, one for 
421           // general aviation, one for commercial and one for military
422           // traffic.
423           currentlyActive->clear();
424           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
425           //cerr << "Choosing runway for " << trafficType << endl;
426           for (int i = 0; i < nrActiveRunways; i++)
427             {
428               type = "unknown"; // initialize to something other than landing or takeoff
429               currRunwayGroup->getActive(i, name, type);
430               if (type == "landing")
431                 {
432                   landing.push_back(name);
433                   currentlyActive->push_back(name);
434                   //cerr << "Landing " << name << endl; 
435                 }
436               if (type == "takeoff")
437                 {
438                   takeoff.push_back(name);
439                   currentlyActive->push_back(name);
440                   //cerr << "takeoff " << name << endl;
441                 }
442             }
443           //cerr << endl;
444         }
445       if (action == 1) // takeoff 
446         {
447           int nr = takeoff.size();
448           if (nr)
449             {
450               // Note that the randomization below, is just a placeholder to choose between
451               // multiple active runways for this action. This should be
452               // under ATC control.
453               runway = takeoff[(rand() %  nr)];
454             }
455           else
456             { // Fallback
457               runway = chooseRunwayFallback();
458             }
459         } 
460       if (action == 2) // landing
461         {
462           int nr = landing.size();
463           if (nr)
464             {
465               runway = landing[(rand() % nr)];
466             }
467           else
468             {  //fallback
469                runway = chooseRunwayFallback();
470             }
471         } 
472       //runway = globals->get_runways()->search(_ap->getId(), int(windHeading));
473       //cerr << "Seleceted runway: " << runway << endl;
474     }
475 }
476
477 string FGAirportDynamics::chooseRunwayFallback()
478 {   
479   FGEnvironment 
480     stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
481     ->getEnvironment(getLatitude(), 
482                      getLongitude(),
483                      getElevation());
484   
485   double windSpeed = stationweather.get_wind_speed_kt();
486   double windHeading = stationweather.get_wind_from_heading_deg();
487   if (windSpeed == 0) {
488     windHeading = 270;  // This forces West-facing rwys to be used in no-wind situations
489     //which is consistent with Flightgear's initial setup.
490   }
491   
492    return globals->get_runways()->search(_ap->getId(), int(windHeading));
493 }
494
495 void FGAirportDynamics::addParking(FGParking& park) {
496   parkings.push_back(park);
497 }
498
499 double FGAirportDynamics::getLatitude() const {
500   return _ap->getLatitude();
501 }
502
503 double FGAirportDynamics::getLongitude() const {
504   return _ap->getLongitude();
505 }
506
507 double FGAirportDynamics::getElevation() const {
508   return _ap->getElevation();
509 }
510
511 const string& FGAirportDynamics::getId() const {
512   return _ap->getId();
513 }