]> git.mxchange.org Git - flightgear.git/blob - src/Airports/simple.cxx
1dc6b7d76ac875674551419f879413d2898657c8
[flightgear.git] / src / Airports / simple.cxx
1 //
2 // simple.cxx -- a really simplistic class to manage airport ID,
3 //               lat, lon of the center of one of it's runways, and
4 //               elevation in feet.
5 //
6 // Written by Curtis Olson, started April 1998.
7 // Updated by Durk Talsma, started December, 2004.
8 //
9 // Copyright (C) 1998  Curtis L. Olson  - http://www.flightgear.org/~curt
10 //
11 // This program is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU General Public License as
13 // published by the Free Software Foundation; either version 2 of the
14 // License, or (at your option) any later version.
15 //
16 // This program is distributed in the hope that it will be useful, but
17 // WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 // General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24 //
25 // $Id$
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #include <math.h>
32 #include <algorithm>
33
34 #include <simgear/compiler.h>
35
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 <Main/globals.hxx>
43 #include <Main/fg_props.hxx>
44 #include <Airports/runways.hxx>
45 #include <Airports/dynamics.hxx>
46
47 #include <string>
48
49 #include "simple.hxx"
50 #include "xmlloader.hxx"
51
52 using std::sort;
53 using std::random_shuffle;
54
55
56
57
58 /***************************************************************************
59  * FGAirport
60  ***************************************************************************/
61
62 FGAirport::FGAirport(const string &id, const SGGeod& location, const SGGeod& tower_location,
63         const string &name, bool has_metar, Type aType) :
64     FGPositioned(aType, id, location),
65     _tower_location(tower_location),
66     _name(name),
67     _has_metar(has_metar),
68     _dynamics(0)
69 {
70 }
71
72
73 FGAirport::~FGAirport()
74 {
75     delete _dynamics;
76 }
77
78 bool FGAirport::isAirport() const
79 {
80   return type() == AIRPORT;
81 }
82
83 bool FGAirport::isSeaport() const
84 {
85   return type() == SEAPORT;
86 }
87
88 bool FGAirport::isHeliport() const
89 {
90   return type() == HELIPORT;
91 }
92
93 FGAirportDynamics * FGAirport::getDynamics()
94 {
95     if (_dynamics != 0) {
96         return _dynamics;
97     } else {
98         //cerr << "Trying to load dynamics for " << _id << endl;
99         _dynamics = new FGAirportDynamics(this);
100         XMLLoader::load(_dynamics);
101
102         FGRunwayPreference rwyPrefs(this);
103         XMLLoader::load(&rwyPrefs);
104         _dynamics->setRwyUse(rwyPrefs);
105    }
106     return _dynamics;
107 }
108
109 unsigned int FGAirport::numRunways() const
110 {
111   return mRunways.size();
112 }
113
114 FGRunway* FGAirport::getRunwayByIndex(unsigned int aIndex) const
115 {
116   assert(aIndex >= 0 && aIndex < mRunways.size());
117   return mRunways[aIndex];
118 }
119
120 bool FGAirport::hasRunwayWithIdent(const string& aIdent) const
121 {
122   return (getIteratorForRunwayIdent(aIdent) != mRunways.end());
123 }
124
125 FGRunway* FGAirport::getRunwayByIdent(const string& aIdent) const
126 {
127   Runway_iterator it = getIteratorForRunwayIdent(aIdent);
128   if (it == mRunways.end()) {
129     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << ident());
130     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
131   }
132   
133   return *it;
134 }
135
136 FGAirport::Runway_iterator
137 FGAirport::getIteratorForRunwayIdent(const string& aIdent) const
138 {
139   string ident(aIdent);
140   if ((aIdent.size() == 1) || !isdigit(aIdent[1])) {
141     ident = "0" + aIdent;
142   }
143
144   Runway_iterator it = mRunways.begin();
145   for (; it != mRunways.end(); ++it) {
146     if ((*it)->ident() == ident) {
147       return it;
148     }
149   }
150
151   return it; // end()
152 }
153
154 static double normaliseBearing(double aBearing)
155 {
156   while (aBearing < -180) {
157     aBearing += 360.0;
158   }
159   
160   while (aBearing > 180.0) {
161     aBearing -= 360.0;
162   }
163   
164   return aBearing;
165 }
166
167 FGRunway* FGAirport::findBestRunwayForHeading(double aHeading) const
168 {
169   Runway_iterator it = mRunways.begin();
170   FGRunway* result = NULL;
171   double currentBestQuality = 0.0;
172   
173   SGPropertyNode *param = fgGetNode("/sim/airport/runways/search", true);
174   double lengthWeight = param->getDoubleValue("length-weight", 0.01);
175   double widthWeight = param->getDoubleValue("width-weight", 0.01);
176   double surfaceWeight = param->getDoubleValue("surface-weight", 10);
177   double deviationWeight = param->getDoubleValue("deviation-weight", 1);
178     
179   for (; it != mRunways.end(); ++it) {
180     double good = (*it)->score(lengthWeight, widthWeight, surfaceWeight);
181     
182     double dev = normaliseBearing(aHeading - (*it)->headingDeg());
183     double bad = fabs(deviationWeight * dev) + 1e-20;
184     double quality = good / bad;
185     
186     if (quality > currentBestQuality) {
187       currentBestQuality = quality;
188       result = *it;
189     }
190   }
191
192   return result;
193 }
194
195 bool FGAirport::hasHardRunwayOfLengthFt(double aLengthFt) const
196 {
197   unsigned int numRunways(mRunways.size());
198   for (unsigned int r=0; r<numRunways; ++r) {
199     FGRunway* rwy = mRunways[r];
200     if (rwy->isReciprocal()) {
201       continue; // we only care about lengths, so don't do work twice
202     }
203     
204     int surface = rwy->surface();
205     if ((surface != 1) && (surface != 2)) {
206       continue; // no hard surface
207     }
208     
209     if (rwy->lengthFt() >= aLengthFt) {
210       return true; // we're done!
211     }
212   } // of runways iteration
213
214   return false;
215 }
216
217 unsigned int FGAirport::numTaxiways() const
218 {
219   return mTaxiways.size();
220 }
221
222 FGRunway* FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
223 {
224   assert(aIndex >= 0 && aIndex < mTaxiways.size());
225   return mTaxiways[aIndex];
226 }
227
228 void FGAirport::addRunway(FGRunway* aRunway)
229 {
230   aRunway->setAirport(this);
231   
232   if (aRunway->isTaxiway()) {
233     mTaxiways.push_back(aRunway);
234   } else {
235     mRunways.push_back(aRunway);
236   }
237 }
238
239 FGRunway* FGAirport::getActiveRunwayForUsage() const
240 {
241   static FGEnvironmentMgr* envMgr = NULL;
242   if (!envMgr) {
243     envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
244   }
245   
246   FGEnvironment stationWeather(envMgr->getEnvironment(mPosition));
247   
248   double windSpeed = stationWeather.get_wind_speed_kt();
249   double hdg = stationWeather.get_wind_from_heading_deg();
250   if (windSpeed <= 0.0) {
251     hdg = 270;  // This forces West-facing rwys to be used in no-wind situations
252     // which is consistent with Flightgear's initial setup.
253   }
254   
255   return findBestRunwayForHeading(hdg);
256 }
257
258 FGAirport* FGAirport::findClosest(const SGGeod& aPos, double aCuttofNm, Filter* filter)
259 {
260   AirportFilter aptFilter;
261   if (filter == NULL) {
262     filter = &aptFilter;
263   }
264   
265   FGPositionedRef r = FGPositioned::findClosest(aPos, aCuttofNm, filter);
266   if (!r) {
267     return NULL;
268   }
269   
270   return static_cast<FGAirport*>(r.ptr());
271 }
272
273 FGAirport::HardSurfaceFilter::HardSurfaceFilter(double minLengthFt) :
274   mMinLengthFt(minLengthFt)
275 {
276 }
277       
278 bool FGAirport::HardSurfaceFilter::pass(FGPositioned* aPos) const
279 {
280   if (aPos->type() != AIRPORT) {
281     return false; // exclude seaports and heliports as well, we need a runways
282   }
283    
284   return static_cast<FGAirport*>(aPos)->hasHardRunwayOfLengthFt(mMinLengthFt);
285 }
286
287 /******************************************************************************
288  * FGAirportList
289  *****************************************************************************/
290
291 // Populates a list of subdirectories of $FG_ROOT/Airports/AI so that
292 // the add() method doesn't have to try opening 2 XML files in each of
293 // thousands of non-existent directories.  FIXME: should probably add
294 // code to free this list after parsing of apt.dat is finished;
295 // non-issue at the moment, however, as there are no AI subdirectories
296 // in the base package.
297 //
298 // Note: 2005/12/23: This is probably not necessary anymore, because I'm
299 // Switching to runtime airport dynamics loading (DT).
300 FGAirportList::FGAirportList()
301 {
302 //     ulDir* d;
303 //     ulDirEnt* dent;
304 //     SGPath aid( globals->get_fg_root() );
305 //     aid.append( "/Airports/AI" );
306 //     if((d = ulOpenDir(aid.c_str())) == NULL)
307 //         return;
308 //     while((dent = ulReadDir(d)) != NULL) {
309 //         SG_LOG( SG_GENERAL, SG_DEBUG, "Dent: " << dent->d_name );
310 //         ai_dirs.insert(dent->d_name);
311 //     }
312 //     ulCloseDir(d);
313 }
314
315
316 FGAirportList::~FGAirportList( void )
317 {
318     for (unsigned int i = 0; i < airports_array.size(); ++i) {
319         delete airports_array[i];
320     }
321 }
322
323
324 // add an entry to the list
325 FGAirport* FGAirportList::add( const string &id, const SGGeod& location, const SGGeod& tower_location,
326                          const string &name, bool has_metar, FGPositioned::Type aType)
327 {
328     FGAirport* a = new FGAirport(id, location, tower_location, name, has_metar, aType);
329     airports_by_id[a->getId()] = a;
330     // try and read in an auxilary file
331
332     airports_array.push_back( a );
333     SG_LOG( SG_GENERAL, SG_BULK, "Adding " << id << " pos = " << location.getLongitudeDeg()
334             << ", " << location.getLatitudeDeg() << " elev = " << location.getElevationFt() );
335             
336     return a;
337 }
338
339
340 // search for the specified id
341 FGAirport* FGAirportList::search( const string& id)
342 {
343     airport_map_iterator itr = airports_by_id.find(id);
344     return (itr == airports_by_id.end() ? NULL : itr->second);
345 }
346
347 // wrap an FGIdentOrdering in an STL-compatible functor. not the most
348 // efficent / pretty thing in the world, but avoids template nastiness in the 
349 // headers, and we're only doing O(log(N)) comparisoms per search
350 class orderingFunctor
351 {
352 public:
353   orderingFunctor(FGIdentOrdering* aOrder) :
354     mOrdering(aOrder)
355   { assert(aOrder); }
356   
357   bool operator()(const airport_map::value_type& aA, const std::string& aB) const
358   {
359     return mOrdering->compare(aA.first,aB);
360   }
361
362   bool operator()(const std::string& aA, const airport_map::value_type& aB) const
363   {
364     return mOrdering->compare(aA, aB.first);
365   }
366
367   bool operator()(const airport_map::value_type& aA, const airport_map::value_type& aB) const
368   {
369     return mOrdering->compare(aA.first, aB.first);
370   }
371   
372 private:
373   FGIdentOrdering* mOrdering;
374 };
375
376 const FGAirport* FGAirportList::findFirstById(const std::string& aIdent, FGIdentOrdering* aOrder)
377 {
378   airport_map_iterator itr;
379   if (aOrder) {
380     orderingFunctor func(aOrder);
381     itr = std::lower_bound(airports_by_id.begin(),airports_by_id.end(), aIdent, func);
382   } else {
383     itr = airports_by_id.lower_bound(aIdent);
384   }
385   
386   if (itr == airports_by_id.end()) {
387     return NULL;
388   }
389   
390   return itr->second;
391 }
392
393 // search for the airport nearest the specified position
394 FGAirport* FGAirportList::search(double lon_deg, double lat_deg, double max_range)
395 {
396     static FGAirportSearchFilter accept_any;
397     return search(lon_deg, lat_deg, max_range, accept_any);
398 }
399
400
401 // search for the airport nearest the specified position and
402 // passing the filter
403 FGAirport* FGAirportList::search(double lon_deg, double lat_deg,
404         double max_range,
405         FGAirportSearchFilter& filter)
406 {
407     double min_dist = max_range;
408
409     airport_list_iterator it = airports_array.begin();
410     airport_list_iterator end = airports_array.end();
411     airport_list_iterator closest = end;
412     for (; it != end; ++it) {
413         if (!filter.pass(*it))
414             continue;
415
416         // crude manhatten distance based on lat/lon difference
417         double d = fabs(lon_deg - (*it)->getLongitude())
418                 + fabs(lat_deg - (*it)->getLatitude());
419         if (d < min_dist) {
420             closest = it;
421             min_dist = d;
422         }
423     }
424     return closest != end ? *closest : 0;
425 }
426
427
428 int
429 FGAirportList::size () const
430 {
431     return airports_array.size();
432 }
433
434
435 const FGAirport *FGAirportList::getAirport( unsigned int index ) const
436 {
437     if (index < airports_array.size()) {
438         return(airports_array[index]);
439     } else {
440         return(NULL);
441     }
442 }
443
444
445 /**
446  * Mark the specified airport record as not having metar
447  */
448 void FGAirportList::no_metar( const string &id )
449 {
450     if(airports_by_id.find(id) != airports_by_id.end()) {
451         airports_by_id[id]->setMetar(false);
452     }
453 }
454
455
456 /**
457  * Mark the specified airport record as (yes) having metar
458  */
459 void FGAirportList::has_metar( const string &id )
460 {
461     if(airports_by_id.find(id) != airports_by_id.end()) {
462         airports_by_id[id]->setMetar(true);
463     }
464 }
465
466
467 // find basic airport location info from airport database
468 const FGAirport *fgFindAirportID( const string& id)
469 {
470     const FGAirport* result = NULL;
471     if ( id.length() ) {
472         SG_LOG( SG_GENERAL, SG_BULK, "Searching for airport code = " << id );
473
474         result = globals->get_airports()->search( id );
475
476         if ( result == NULL ) {
477             SG_LOG( SG_GENERAL, SG_ALERT,
478                     "Failed to find " << id << " in apt.dat.gz" );
479             return NULL;
480         }
481     } else {
482         return NULL;
483     }
484     SG_LOG( SG_GENERAL, SG_BULK,
485             "Position for " << id << " is ("
486             << result->getLongitude() << ", "
487             << result->getLatitude() << ")" );
488
489     return result;
490 }
491
492
493 // get airport elevation
494 double fgGetAirportElev( const string& id )
495 {
496     SG_LOG( SG_GENERAL, SG_BULK,
497             "Finding elevation for airport: " << id );
498
499     const FGAirport *a=fgFindAirportID( id);
500     if (a) {
501         return a->getElevation();
502     } else {
503         return -9999.0;
504     }
505 }
506
507
508 // get airport position
509 Point3D fgGetAirportPos( const string& id )
510 {
511     SG_LOG( SG_ATC, SG_BULK,
512             "Finding position for airport: " << id );
513
514     const FGAirport *a = fgFindAirportID( id);
515
516     if (a) {
517         return Point3D(a->getLongitude(), a->getLatitude(), a->getElevation());
518     } else {
519         return Point3D(0.0, 0.0, -9999.0);
520     }
521 }