]> git.mxchange.org Git - flightgear.git/blob - src/Airports/simple.cxx
9a0a4dab40ca849962a2e6ff729dde35ef0dd4b8
[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 <plib/sg.h>
37 #include <plib/ul.h>
38
39 #include <Environment/environment_mgr.hxx>
40 #include <Environment/environment.hxx>
41 #include <simgear/misc/sg_path.hxx>
42 #include <simgear/props/props.hxx>
43 #include <simgear/structure/subsystem_mgr.hxx>
44 //#include <simgear/route/waypoint.hxx>
45 #include <simgear/debug/logstream.hxx>
46 #include <Main/globals.hxx>
47 #include <Main/fg_props.hxx>
48 #include <Airports/runways.hxx>
49 #include <Airports/dynamics.hxx>
50 #include <Airports/runways.hxx>
51
52 #include <string>
53
54 #include "simple.hxx"
55 #include "xmlloader.hxx"
56
57 using std::sort;
58 using std::random_shuffle;
59
60
61
62
63 /***************************************************************************
64  * FGAirport
65  ***************************************************************************/
66 FGAirport::FGAirport() : _dynamics(0)
67 {
68 }
69
70 FGAirport::FGAirport(const string &id, const SGGeod& location, const SGGeod& tower_location,
71         const string &name, bool has_metar, bool is_airport, bool is_seaport,
72         bool is_heliport) :
73     _id(id),
74     _location(location),
75     _tower_location(tower_location),
76     _name(name),
77     _has_metar(has_metar),
78     _is_airport(is_airport),
79     _is_seaport(is_seaport),
80     _is_heliport(is_heliport),
81     _dynamics(0)
82 {
83 }
84
85
86 FGAirport::~FGAirport()
87 {
88     delete _dynamics;
89 }
90
91
92 FGAirportDynamics * FGAirport::getDynamics()
93 {
94     if (_dynamics != 0) {
95         return _dynamics;
96     } else {
97         //cerr << "Trying to load dynamics for " << _id << endl;
98         _dynamics = new FGAirportDynamics(this);
99         XMLLoader::load(_dynamics);
100
101         FGRunwayPreference rwyPrefs(this);
102         XMLLoader::load(&rwyPrefs);
103         _dynamics->setRwyUse(rwyPrefs);
104    }
105     return _dynamics;
106 }
107
108 unsigned int FGAirport::numRunways() const
109 {
110   return mRunways.size();
111 }
112
113 FGRunway* FGAirport::getRunwayByIndex(unsigned int aIndex) const
114 {
115   assert(aIndex >= 0 && aIndex < mRunways.size());
116   return mRunways[aIndex];
117 }
118
119 bool FGAirport::hasRunwayWithIdent(const string& aIdent) const
120 {
121   return (getIteratorForRunwayIdent(aIdent) != mRunways.end());
122 }
123
124 FGRunway* FGAirport::getRunwayByIdent(const string& aIdent) const
125 {
126   Runway_iterator it = getIteratorForRunwayIdent(aIdent);
127   if (it == mRunways.end()) {
128     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << _id);
129     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + _id, "FGAirport::getRunwayByIdent");
130   }
131   
132   return *it;
133 }
134
135 FGAirport::Runway_iterator
136 FGAirport::getIteratorForRunwayIdent(const string& aIdent) const
137 {
138   string ident(aIdent);
139   if ((aIdent.size() == 1) || !isdigit(aIdent[1])) {
140     ident = "0" + aIdent;
141   }
142
143   Runway_iterator it = mRunways.begin();
144   for (; it != mRunways.end(); ++it) {
145     if ((*it)->ident() == ident) {
146       return it;
147     }
148   }
149
150   return it; // end()
151 }
152
153 static double normaliseBearing(double aBearing)
154 {
155   while (aBearing < 0.0) {
156     aBearing += 360.0;
157   }
158   
159   while (aBearing > 360.0) {
160     aBearing -= 360.0;
161   }
162   
163   return aBearing;
164 }
165
166 FGRunway* FGAirport::findBestRunwayForHeading(double aHeading) const
167 {
168   Runway_iterator it = mRunways.begin();
169   FGRunway* result = NULL;
170   double currentBestQuality = 0.0;
171   
172   SGPropertyNode *param = fgGetNode("/sim/airport/runways/search", true);
173   double lengthWeight = param->getDoubleValue("length-weight", 0.01);
174   double widthWeight = param->getDoubleValue("width-weight", 0.01);
175   double surfaceWeight = param->getDoubleValue("surface-weight", 10);
176   double deviationWeight = param->getDoubleValue("deviation-weight", 1);
177     
178   for (; it != mRunways.end(); ++it) {
179     double good = (*it)->score(lengthWeight, widthWeight, surfaceWeight);
180     
181     double dev = normaliseBearing(aHeading - (*it)->headingDeg());
182     double bad = fabs(deviationWeight * dev) + 1e-20;
183     double quality = good / bad;
184     
185     if (quality > currentBestQuality) {
186       currentBestQuality = quality;
187       result = *it;
188     }
189   }
190
191   return result;
192 }
193
194 unsigned int FGAirport::numTaxiways() const
195 {
196   return mTaxiways.size();
197 }
198
199 FGRunway* FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
200 {
201   assert(aIndex >= 0 && aIndex < mTaxiways.size());
202   return mTaxiways[aIndex];
203 }
204
205 void FGAirport::addRunway(FGRunway* aRunway)
206 {
207   aRunway->setAirport(this);
208   
209   if (aRunway->isTaxiway()) {
210     mTaxiways.push_back(aRunway);
211   } else {
212     mRunways.push_back(aRunway);
213   }
214 }
215
216 FGRunway* FGAirport::getActiveRunwayForUsage() const
217 {
218   static FGEnvironmentMgr* envMgr = NULL;
219   if (!envMgr) {
220     envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
221   }
222   
223   FGEnvironment stationWeather(envMgr->getEnvironment(_location));
224   
225   double windSpeed = stationWeather.get_wind_speed_kt();
226   double hdg = stationWeather.get_wind_from_heading_deg();
227   if (windSpeed <= 0.0) {
228     hdg = 270;  // This forces West-facing rwys to be used in no-wind situations
229     // which is consistent with Flightgear's initial setup.
230   }
231   
232   return findBestRunwayForHeading(hdg);
233 }
234
235 /******************************************************************************
236  * FGAirportList
237  *****************************************************************************/
238
239 // Populates a list of subdirectories of $FG_ROOT/Airports/AI so that
240 // the add() method doesn't have to try opening 2 XML files in each of
241 // thousands of non-existent directories.  FIXME: should probably add
242 // code to free this list after parsing of apt.dat is finished;
243 // non-issue at the moment, however, as there are no AI subdirectories
244 // in the base package.
245 //
246 // Note: 2005/12/23: This is probably not necessary anymore, because I'm
247 // Switching to runtime airport dynamics loading (DT).
248 FGAirportList::FGAirportList()
249 {
250 //     ulDir* d;
251 //     ulDirEnt* dent;
252 //     SGPath aid( globals->get_fg_root() );
253 //     aid.append( "/Airports/AI" );
254 //     if((d = ulOpenDir(aid.c_str())) == NULL)
255 //         return;
256 //     while((dent = ulReadDir(d)) != NULL) {
257 //         SG_LOG( SG_GENERAL, SG_DEBUG, "Dent: " << dent->d_name );
258 //         ai_dirs.insert(dent->d_name);
259 //     }
260 //     ulCloseDir(d);
261 }
262
263
264 FGAirportList::~FGAirportList( void )
265 {
266     for (unsigned int i = 0; i < airports_array.size(); ++i) {
267         delete airports_array[i];
268     }
269 }
270
271
272 // add an entry to the list
273 FGAirport* FGAirportList::add( const string &id, const SGGeod& location, const SGGeod& tower_location,
274                          const string &name, bool has_metar, bool is_airport, bool is_seaport,
275                          bool is_heliport)
276 {
277     FGAirport* a = new FGAirport(id, location, tower_location, name, has_metar,
278             is_airport, is_seaport, is_heliport);
279
280     airports_by_id[a->getId()] = a;
281     // try and read in an auxilary file
282
283     airports_array.push_back( a );
284     SG_LOG( SG_GENERAL, SG_BULK, "Adding " << id << " pos = " << location.getLongitudeDeg()
285             << ", " << location.getLatitudeDeg() << " elev = " << location.getElevationFt() );
286             
287     return a;
288 }
289
290
291 // search for the specified id
292 FGAirport* FGAirportList::search( const string& id)
293 {
294     airport_map_iterator itr = airports_by_id.find(id);
295     return (itr == airports_by_id.end() ? NULL : itr->second);
296 }
297
298 // wrap an FGIdentOrdering in an STL-compatible functor. not the most
299 // efficent / pretty thing in the world, but avoids template nastiness in the 
300 // headers, and we're only doing O(log(N)) comparisoms per search
301 class orderingFunctor
302 {
303 public:
304   orderingFunctor(FGIdentOrdering* aOrder) :
305     mOrdering(aOrder)
306   { assert(aOrder); }
307   
308   bool operator()(const airport_map::value_type& aA, const std::string& aB) const
309   {
310     return mOrdering->compare(aA.first,aB);
311   }
312
313   bool operator()(const std::string& aA, const airport_map::value_type& aB) const
314   {
315     return mOrdering->compare(aA, aB.first);
316   }
317
318   bool operator()(const airport_map::value_type& aA, const airport_map::value_type& aB) const
319   {
320     return mOrdering->compare(aA.first, aB.first);
321   }
322   
323 private:
324   FGIdentOrdering* mOrdering;
325 };
326
327 const FGAirport* FGAirportList::findFirstById(const std::string& aIdent, FGIdentOrdering* aOrder)
328 {
329   airport_map_iterator itr;
330   if (aOrder) {
331     orderingFunctor func(aOrder);
332     itr = std::lower_bound(airports_by_id.begin(),airports_by_id.end(), aIdent, func);
333   } else {
334     itr = airports_by_id.lower_bound(aIdent);
335   }
336   
337   if (itr == airports_by_id.end()) {
338     return NULL;
339   }
340   
341   return itr->second;
342 }
343
344 // search for the airport nearest the specified position
345 FGAirport* FGAirportList::search(double lon_deg, double lat_deg, double max_range)
346 {
347     static FGAirportSearchFilter accept_any;
348     return search(lon_deg, lat_deg, max_range, accept_any);
349 }
350
351
352 // search for the airport nearest the specified position and
353 // passing the filter
354 FGAirport* FGAirportList::search(double lon_deg, double lat_deg,
355         double max_range,
356         FGAirportSearchFilter& filter)
357 {
358     double min_dist = max_range;
359
360     airport_list_iterator it = airports_array.begin();
361     airport_list_iterator end = airports_array.end();
362     airport_list_iterator closest = end;
363     for (; it != end; ++it) {
364         if (!filter.pass(*it))
365             continue;
366
367         // crude manhatten distance based on lat/lon difference
368         double d = fabs(lon_deg - (*it)->getLongitude())
369                 + fabs(lat_deg - (*it)->getLatitude());
370         if (d < min_dist) {
371             closest = it;
372             min_dist = d;
373         }
374     }
375     return closest != end ? *closest : 0;
376 }
377
378
379 int
380 FGAirportList::size () const
381 {
382     return airports_array.size();
383 }
384
385
386 const FGAirport *FGAirportList::getAirport( unsigned int index ) const
387 {
388     if (index < airports_array.size()) {
389         return(airports_array[index]);
390     } else {
391         return(NULL);
392     }
393 }
394
395
396 /**
397  * Mark the specified airport record as not having metar
398  */
399 void FGAirportList::no_metar( const string &id )
400 {
401     if(airports_by_id.find(id) != airports_by_id.end()) {
402         airports_by_id[id]->setMetar(false);
403     }
404 }
405
406
407 /**
408  * Mark the specified airport record as (yes) having metar
409  */
410 void FGAirportList::has_metar( const string &id )
411 {
412     if(airports_by_id.find(id) != airports_by_id.end()) {
413         airports_by_id[id]->setMetar(true);
414     }
415 }
416
417
418 // find basic airport location info from airport database
419 const FGAirport *fgFindAirportID( const string& id)
420 {
421     const FGAirport* result = NULL;
422     if ( id.length() ) {
423         SG_LOG( SG_GENERAL, SG_BULK, "Searching for airport code = " << id );
424
425         result = globals->get_airports()->search( id );
426
427         if ( result == NULL ) {
428             SG_LOG( SG_GENERAL, SG_ALERT,
429                     "Failed to find " << id << " in apt.dat.gz" );
430             return NULL;
431         }
432     } else {
433         return NULL;
434     }
435     SG_LOG( SG_GENERAL, SG_BULK,
436             "Position for " << id << " is ("
437             << result->getLongitude() << ", "
438             << result->getLatitude() << ")" );
439
440     return result;
441 }
442
443
444 // get airport elevation
445 double fgGetAirportElev( const string& id )
446 {
447     SG_LOG( SG_GENERAL, SG_BULK,
448             "Finding elevation for airport: " << id );
449
450     const FGAirport *a=fgFindAirportID( id);
451     if (a) {
452         return a->getElevation();
453     } else {
454         return -9999.0;
455     }
456 }
457
458
459 // get airport position
460 Point3D fgGetAirportPos( const string& id )
461 {
462     SG_LOG( SG_ATC, SG_BULK,
463             "Finding position for airport: " << id );
464
465     const FGAirport *a = fgFindAirportID( id);
466
467     if (a) {
468         return Point3D(a->getLongitude(), a->getLatitude(), a->getElevation());
469     } else {
470         return Point3D(0.0, 0.0, -9999.0);
471     }
472 }