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