]> git.mxchange.org Git - flightgear.git/blob - src/Airports/airport.cxx
TACAN/mobile navaid cleanup and improvements.
[flightgear.git] / src / Airports / airport.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 "airport.hxx"
32
33 #include <algorithm>
34 #include <cassert>
35 #include <boost/foreach.hpp>
36
37 #include <simgear/misc/sg_path.hxx>
38 #include <simgear/props/props.hxx>
39 #include <simgear/props/props_io.hxx>
40 #include <simgear/debug/logstream.hxx>
41 #include <simgear/sg_inlines.h>
42 #include <simgear/structure/exception.hxx>
43
44 #include <Environment/environment_mgr.hxx>
45 #include <Environment/environment.hxx>
46 #include <Main/fg_props.hxx>
47 #include <Airports/runways.hxx>
48 #include <Airports/pavement.hxx>
49 #include <Airports/dynamics.hxx>
50 #include <Airports/xmlloader.hxx>
51 #include <Navaids/procedure.hxx>
52 #include <Navaids/waypoint.hxx>
53 #include <ATC/CommStation.hxx>
54 #include <Navaids/NavDataCache.hxx>
55
56 using std::vector;
57 using std::pair;
58
59 using namespace flightgear;
60
61 /***************************************************************************
62  * FGAirport
63  ***************************************************************************/
64
65 AirportCache FGAirport::airportCache;
66
67 FGAirport::FGAirport( PositionedID aGuid,
68                       const std::string &id,
69                       const SGGeod& location,
70                       const std::string &name,
71                       bool has_metar,
72                       Type aType ):
73     FGPositioned(aGuid, aType, id, location),
74     _name(name),
75     _has_metar(has_metar),
76     _dynamics(0),
77     mTowerDataLoaded(false),
78     mRunwaysLoaded(false),
79     mHelipadsLoaded(false),
80     mTaxiwaysLoaded(false),
81     mProceduresLoaded(false),
82     mILSDataLoaded(false)
83 {
84 }
85
86
87 FGAirport::~FGAirport()
88 {
89     delete _dynamics;
90 }
91
92 bool FGAirport::isAirport() const
93 {
94   return type() == AIRPORT;
95 }
96
97 bool FGAirport::isSeaport() const
98 {
99   return type() == SEAPORT;
100 }
101
102 bool FGAirport::isHeliport() const
103 {
104   return type() == HELIPORT;
105 }
106
107 bool FGAirport::isAirportType(FGPositioned* pos)
108 {
109     if (!pos) {
110         return false;
111     }
112     
113     return (pos->type() >= AIRPORT) && (pos->type() <= SEAPORT);
114 }
115
116 FGAirportDynamics * FGAirport::getDynamics()
117 {
118     if (_dynamics) {
119         return _dynamics;
120     }
121     
122     _dynamics = new FGAirportDynamics(this);
123     XMLLoader::load(_dynamics);
124     _dynamics->init();
125   
126     FGRunwayPreference rwyPrefs(this);
127     XMLLoader::load(&rwyPrefs);
128     _dynamics->setRwyUse(rwyPrefs);
129     
130     return _dynamics;
131 }
132
133 //------------------------------------------------------------------------------
134 unsigned int FGAirport::numRunways() const
135 {
136   loadRunways();
137   return mRunways.size();
138 }
139
140 //------------------------------------------------------------------------------
141 unsigned int FGAirport::numHelipads() const
142 {
143   loadHelipads();
144   return mHelipads.size();
145 }
146
147 //------------------------------------------------------------------------------
148 FGRunwayRef FGAirport::getRunwayByIndex(unsigned int aIndex) const
149 {
150   loadRunways();
151   return loadById<FGRunway>(mRunways, aIndex);
152 }
153
154 //------------------------------------------------------------------------------
155 FGHelipadRef FGAirport::getHelipadByIndex(unsigned int aIndex) const
156 {
157   loadHelipads();
158   return loadById<FGHelipad>(mHelipads, aIndex);
159 }
160
161 //------------------------------------------------------------------------------
162 FGRunwayMap FGAirport::getRunwayMap() const
163 {
164   loadRunways();
165   FGRunwayMap map;
166
167   double minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft");
168
169   BOOST_FOREACH(PositionedID id, mRunways)
170   {
171     FGRunway* rwy = loadById<FGRunway>(id);
172
173     // ignore unusably short runways
174     // TODO other methods don't check this...
175     if( rwy->lengthFt() >= minLengthFt )
176       map[ rwy->ident() ] = rwy;
177   }
178
179   return map;
180 }
181
182 //------------------------------------------------------------------------------
183 FGHelipadMap FGAirport::getHelipadMap() const
184 {
185   loadHelipads();
186   FGHelipadMap map;
187
188   BOOST_FOREACH(PositionedID id, mHelipads)
189   {
190     FGHelipad* rwy = loadById<FGHelipad>(id);
191     map[ rwy->ident() ] = rwy;
192   }
193
194   return map;
195 }
196
197 //------------------------------------------------------------------------------
198 bool FGAirport::hasRunwayWithIdent(const std::string& aIdent) const
199 {
200   return flightgear::NavDataCache::instance()
201     ->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent) != 0;
202 }
203
204 //------------------------------------------------------------------------------
205 bool FGAirport::hasHelipadWithIdent(const std::string& aIdent) const
206 {
207   return flightgear::NavDataCache::instance()
208     ->airportItemWithIdent(guid(), FGPositioned::HELIPAD, aIdent) != 0;
209 }
210
211 //------------------------------------------------------------------------------
212 FGRunwayRef FGAirport::getRunwayByIdent(const std::string& aIdent) const
213 {
214   PositionedID id =
215     flightgear::NavDataCache::instance()
216       ->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent);
217
218   if (id == 0) {
219     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << ident());
220     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
221   }
222   
223   return loadById<FGRunway>(id);
224 }
225
226 //------------------------------------------------------------------------------
227 FGHelipadRef FGAirport::getHelipadByIdent(const std::string& aIdent) const
228 {
229   PositionedID id = flightgear::NavDataCache::instance()->airportItemWithIdent(guid(), FGPositioned::HELIPAD, aIdent);
230   if (id == 0) {
231     SG_LOG(SG_GENERAL, SG_ALERT, "no such helipad '" << aIdent << "' at airport " << ident());
232     throw sg_range_exception("unknown helipad " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
233   }
234
235   return loadById<FGHelipad>(id);
236 }
237
238 //------------------------------------------------------------------------------
239 FGRunwayRef FGAirport::findBestRunwayForHeading(double aHeading, struct FindBestRunwayForHeadingParams * parms ) const
240 {
241   loadRunways();
242   
243   FGRunway* result = NULL;
244   double currentBestQuality = 0.0;
245   
246   struct FindBestRunwayForHeadingParams fbrfhp;
247   if( NULL != parms ) fbrfhp = *parms;
248
249   SGPropertyNode_ptr searchNode = fgGetNode("/sim/airport/runways/search");
250   if( searchNode.valid() ) {
251     fbrfhp.lengthWeight = searchNode->getDoubleValue("length-weight", fbrfhp.lengthWeight );
252     fbrfhp.widthWeight = searchNode->getDoubleValue("width-weight", fbrfhp.widthWeight );
253     fbrfhp.surfaceWeight = searchNode->getDoubleValue("surface-weight", fbrfhp.surfaceWeight );
254     fbrfhp.deviationWeight = searchNode->getDoubleValue("deviation-weight", fbrfhp.deviationWeight );
255     fbrfhp.ilsWeight = searchNode->getDoubleValue("ils-weight", fbrfhp.ilsWeight );
256   }
257     
258   BOOST_FOREACH(PositionedID id, mRunways) {
259     FGRunway* rwy = loadById<FGRunway>(id);
260     // bug http://code.google.com/p/flightgear-bugs/issues/detail?id=1149
261     // (and probably some other issues besides). 
262     if (rwy->type() == FGPositioned::HELIPAD) {
263       continue;
264     }
265       
266     double good = rwy->score( fbrfhp.lengthWeight,  fbrfhp.widthWeight,  fbrfhp.surfaceWeight,  fbrfhp.ilsWeight );
267     double dev = aHeading - rwy->headingDeg();
268     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
269     double bad = fabs( fbrfhp.deviationWeight * dev) + 1e-20;
270     double quality = good / bad;
271     
272     if (quality > currentBestQuality) {
273       currentBestQuality = quality;
274       result = rwy;
275     }
276   }
277
278   return result;
279 }
280
281 //------------------------------------------------------------------------------
282 FGRunwayRef FGAirport::findBestRunwayForPos(const SGGeod& aPos) const
283 {
284   loadRunways();
285   
286   FGRunway* result = NULL;
287   double currentLowestDev = 180.0;
288   
289   BOOST_FOREACH(PositionedID id, mRunways) {
290     FGRunway* rwy = loadById<FGRunway>(id);
291
292     double inboundCourse = SGGeodesy::courseDeg(aPos, rwy->end());
293     double dev = inboundCourse - rwy->headingDeg();
294     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
295
296     dev = fabs(dev);
297     if (dev < currentLowestDev) { // new best match
298       currentLowestDev = dev;
299       result = rwy;
300     }
301   } // of runway iteration
302   
303   return result;
304
305 }
306
307 //------------------------------------------------------------------------------
308 bool FGAirport::hasHardRunwayOfLengthFt(double aLengthFt) const
309 {
310   loadRunways();
311   
312   BOOST_FOREACH(PositionedID id, mRunways) {
313     FGRunway* rwy = loadById<FGRunway>(id);
314     if (rwy->isHardSurface() && (rwy->lengthFt() >= aLengthFt)) {
315       return true; // we're done!
316     }
317   } // of runways iteration
318
319   return false;
320 }
321
322 //------------------------------------------------------------------------------
323 FGRunwayList FGAirport::getRunwaysWithoutReciprocals() const
324 {
325   loadRunways();
326   
327   FGRunwayList r;
328   
329   BOOST_FOREACH(PositionedID id, mRunways) {
330     FGRunway* rwy = loadById<FGRunway>(id);
331     FGRunway* recip = rwy->reciprocalRunway();
332     if (recip) {
333       FGRunwayList::iterator it = std::find(r.begin(), r.end(), recip);
334       if (it != r.end()) {
335         continue; // reciprocal already in result set, don't include us
336       }
337     }
338     
339     r.push_back(rwy);
340   }
341   
342   return r;
343 }
344
345 //------------------------------------------------------------------------------
346 unsigned int FGAirport::numTaxiways() const
347 {
348   loadTaxiways();
349   return mTaxiways.size();
350 }
351
352 //------------------------------------------------------------------------------
353 FGTaxiwayRef FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
354 {
355   loadTaxiways();
356   return loadById<FGTaxiway>(mTaxiways, aIndex);
357 }
358
359 //------------------------------------------------------------------------------
360 FGTaxiwayList FGAirport::getTaxiways() const
361 {
362   loadTaxiways();
363   return loadAllById<FGTaxiway>(mTaxiways);
364 }
365
366 //------------------------------------------------------------------------------
367 unsigned int FGAirport::numPavements() const
368 {
369   loadTaxiways();
370   return mPavements.size();
371 }
372
373 //------------------------------------------------------------------------------
374 FGPavementRef FGAirport::getPavementByIndex(unsigned int aIndex) const
375 {
376   loadTaxiways();
377   return loadById<FGPavement>(mPavements, aIndex);
378 }
379
380 //------------------------------------------------------------------------------
381 FGPavementList FGAirport::getPavements() const
382 {
383   loadTaxiways();
384   return loadAllById<FGPavement>(mPavements);
385 }
386
387 //------------------------------------------------------------------------------
388 FGRunwayRef FGAirport::getActiveRunwayForUsage() const
389 {
390   FGEnvironmentMgr* envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
391   
392   // This forces West-facing rwys to be used in no-wind situations
393   // which is consistent with Flightgear's initial setup.
394   double hdg = 270;
395   
396   if (envMgr) {
397     FGEnvironment stationWeather(envMgr->getEnvironment(geod()));
398   
399     double windSpeed = stationWeather.get_wind_speed_kt();
400     if (windSpeed > 0.0) {
401       hdg = stationWeather.get_wind_from_heading_deg();
402     }
403   }
404   
405   return findBestRunwayForHeading(hdg);
406 }
407
408 //------------------------------------------------------------------------------
409 FGAirportRef FGAirport::findClosest( const SGGeod& aPos,
410                                      double aCuttofNm,
411                                      Filter* filter )
412 {
413   AirportFilter aptFilter;
414   if( !filter )
415     filter = &aptFilter;
416   
417   return static_pointer_cast<FGAirport>
418   (
419     FGPositioned::findClosest(aPos, aCuttofNm, filter)
420   );
421 }
422
423 FGAirport::HardSurfaceFilter::HardSurfaceFilter(double minLengthFt) :
424   mMinLengthFt(minLengthFt)
425 {
426   if (minLengthFt < 0.0) {
427     mMinLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
428   }
429 }
430
431 bool FGAirport::HardSurfaceFilter::passAirport(FGAirport* aApt) const
432 {
433   return aApt->hasHardRunwayOfLengthFt(mMinLengthFt);
434 }
435
436 //------------------------------------------------------------------------------
437 FGAirport::TypeRunwayFilter::TypeRunwayFilter():
438   _type(FGPositioned::AIRPORT),
439   _min_runway_length_ft( fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0) )
440 {
441
442 }
443
444 //------------------------------------------------------------------------------
445 bool FGAirport::TypeRunwayFilter::fromTypeString(const std::string& type)
446 {
447   if(      type == "heliport" ) _type = FGPositioned::HELIPORT;
448   else if( type == "seaport"  ) _type = FGPositioned::SEAPORT;
449   else if( type == "airport"  ) _type = FGPositioned::AIRPORT;
450   else                          return false;
451
452   return true;
453 }
454
455 //------------------------------------------------------------------------------
456 bool FGAirport::TypeRunwayFilter::pass(FGPositioned* pos) const
457 {
458   FGAirport* apt = static_cast<FGAirport*>(pos);
459   if(  (apt->type() == FGPositioned::AIRPORT)
460     && !apt->hasHardRunwayOfLengthFt(_min_runway_length_ft)
461     )
462     return false;
463
464   return true;
465 }
466
467 //------------------------------------------------------------------------------
468 FGAirportRef FGAirport::findByIdent(const std::string& aIdent)
469 {
470   AirportCache::iterator it = airportCache.find(aIdent);
471   if (it != airportCache.end())
472    return it->second;
473
474   PortsFilter filter;
475   FGAirportRef r = static_pointer_cast<FGAirport>
476   (
477     FGPositioned::findFirstWithIdent(aIdent, &filter)
478   );
479
480   // add airport to the cache (even when it's NULL, so we don't need to search in vain again)
481   airportCache[aIdent] = r;
482
483   // we don't warn here when r==NULL, let the caller do that
484   return r;
485 }
486
487 //------------------------------------------------------------------------------
488 FGAirportRef FGAirport::getByIdent(const std::string& aIdent)
489 {
490   FGAirportRef r = findByIdent(aIdent);
491   if (!r)
492     throw sg_range_exception("No such airport with ident: " + aIdent);
493   return r;
494 }
495
496 char** FGAirport::searchNamesAndIdents(const std::string& aFilter)
497 {
498   return NavDataCache::instance()->searchAirportNamesAndIdents(aFilter);
499 }
500
501 // find basic airport location info from airport database
502 const FGAirport *fgFindAirportID( const std::string& id)
503 {
504     if ( id.empty() ) {
505         return NULL;
506     }
507     
508     return FGAirport::findByIdent(id);
509 }
510
511 void FGAirport::loadRunways() const
512 {
513   if (mRunwaysLoaded) {
514     return; // already loaded, great
515   }
516   
517   loadSceneryDefinitions();
518   
519   mRunwaysLoaded = true;
520   mRunways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::RUNWAY);
521 }
522
523 void FGAirport::loadHelipads() const
524 {
525   if (mHelipadsLoaded) {
526     return; // already loaded, great
527   }
528
529   loadSceneryDefinitions();
530
531   mHelipadsLoaded = true;
532   mHelipads = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::HELIPAD);
533 }
534
535 void FGAirport::loadTaxiways() const
536 {
537   if (mTaxiwaysLoaded) {
538     return; // already loaded, great
539   }
540   
541   mTaxiwaysLoaded =  true;
542   mTaxiways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::TAXIWAY);
543 }
544
545 void FGAirport::loadProcedures() const
546 {
547   if (mProceduresLoaded) {
548     return;
549   }
550   
551   mProceduresLoaded = true;
552   SGPath path;
553   if (!XMLLoader::findAirportData(ident(), "procedures", path)) {
554     SG_LOG(SG_GENERAL, SG_INFO, "no procedures data available for " << ident());
555     return;
556   }
557   
558   SG_LOG(SG_GENERAL, SG_INFO, ident() << ": loading procedures from " << path.str());
559   RouteBase::loadAirportProcedures(path, const_cast<FGAirport*>(this));
560 }
561
562 void FGAirport::loadSceneryDefinitions() const
563 {
564   NavDataCache* cache = NavDataCache::instance();
565     if (cache->isReadOnly()) {
566         return;
567     }
568     
569   SGPath path;
570   if (!XMLLoader::findAirportData(ident(), "threshold", path)) {
571     return; // no XML threshold data
572   }
573   
574   if (!cache->isCachedFileModified(path)) {
575     // cached values are correct, we're all done
576     return;
577   }
578   
579     try {
580         flightgear::NavDataCache::Transaction txn(cache);
581         SGPropertyNode_ptr rootNode = new SGPropertyNode;
582         readProperties(path.str(), rootNode);
583         const_cast<FGAirport*>(this)->readThresholdData(rootNode);
584         cache->stampCacheFile(path);
585         txn.commit();
586     } catch (sg_exception& e) {
587         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading threshold XML failed:" << e.getFormattedMessage());
588     }
589 }
590
591 void FGAirport::readThresholdData(SGPropertyNode* aRoot)
592 {
593   SGPropertyNode* runway;
594   int runwayIndex = 0;
595   for (; (runway = aRoot->getChild("runway", runwayIndex)) != NULL; ++runwayIndex) {
596     SGPropertyNode* t0 = runway->getChild("threshold", 0),
597       *t1 = runway->getChild("threshold", 1);
598     assert(t0);
599     assert(t1); // too strict? maybe we should finally allow single-ended runways
600     
601     processThreshold(t0);
602     processThreshold(t1);
603   } // of runways iteration
604 }
605
606 void FGAirport::processThreshold(SGPropertyNode* aThreshold)
607 {
608   // first, let's identify the current runway
609   std::string rwyIdent(aThreshold->getStringValue("rwy"));
610   NavDataCache* cache = NavDataCache::instance(); 
611   PositionedID id = cache->airportItemWithIdent(guid(), FGPositioned::RUNWAY, rwyIdent);
612   if (id == 0) {
613     SG_LOG(SG_GENERAL, SG_DEBUG, "FGAirport::processThreshold: "
614            "found runway not defined in the global data:" << ident() << "/" << rwyIdent);
615     return;
616   }
617   
618   double lon = aThreshold->getDoubleValue("lon"),
619   lat = aThreshold->getDoubleValue("lat");
620   SGGeod newThreshold(SGGeod::fromDegM(lon, lat, elevationM()));
621   
622   double newHeading = aThreshold->getDoubleValue("hdg-deg");
623   double newDisplacedThreshold = aThreshold->getDoubleValue("displ-m");
624   double newStopway = aThreshold->getDoubleValue("stopw-m");
625   
626   cache->updateRunwayThreshold(id, newThreshold,
627                                newHeading, newDisplacedThreshold, newStopway);
628 }
629
630 SGGeod FGAirport::getTowerLocation() const
631 {
632   validateTowerData();
633   
634   NavDataCache* cache = NavDataCache::instance();
635   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
636   if (towers.empty()) {
637     SG_LOG(SG_GENERAL, SG_ALERT, "No towers defined for:" <<ident());
638     return SGGeod();
639   }
640   
641   FGPositionedRef tower = cache->loadById(towers.front());
642   return tower->geod();
643 }
644
645 void FGAirport::validateTowerData() const
646 {
647   if (mTowerDataLoaded) {
648     return;
649   }
650
651   mTowerDataLoaded = true;
652   NavDataCache* cache = NavDataCache::instance();
653     if (cache->isReadOnly()) {
654         return;
655     }
656     
657   SGPath path;
658   if (!XMLLoader::findAirportData(ident(), "twr", path)) {
659     return; // no XML tower data
660   }
661   
662   if (!cache->isCachedFileModified(path)) {
663   // cached values are correct, we're all done
664     return;
665   }
666
667     try {
668         flightgear::NavDataCache::Transaction txn(cache);
669         SGPropertyNode_ptr rootNode = new SGPropertyNode;
670         readProperties(path.str(), rootNode);
671         const_cast<FGAirport*>(this)->readTowerData(rootNode);
672         cache->stampCacheFile(path);
673         txn.commit();
674     } catch (sg_exception& e){
675         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading twr XML failed:" << e.getFormattedMessage());
676     }
677 }
678
679 void FGAirport::readTowerData(SGPropertyNode* aRoot)
680 {
681   SGPropertyNode* twrNode = aRoot->getChild("tower")->getChild("twr");
682   double lat = twrNode->getDoubleValue("lat"), 
683     lon = twrNode->getDoubleValue("lon"), 
684     elevM = twrNode->getDoubleValue("elev-m");  
685 // tower elevation is AGL, not AMSL. Since we don't want to depend on the
686 // scenery for a precise terrain elevation, we use the field elevation
687 // (this is also what the apt.dat code does)
688   double fieldElevationM = elevationM();
689   SGGeod towerLocation(SGGeod::fromDegM(lon, lat, fieldElevationM + elevM));
690   
691   NavDataCache* cache = NavDataCache::instance();
692   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
693   if (towers.empty()) {
694     cache->insertTower(guid(), towerLocation);
695   } else {
696     // update the position
697     cache->updatePosition(towers.front(), towerLocation);
698   }
699 }
700
701 bool FGAirport::validateILSData()
702 {
703   if (mILSDataLoaded) {
704     return false;
705   }
706   
707   mILSDataLoaded = true;
708   NavDataCache* cache = NavDataCache::instance();
709     if (cache->isReadOnly()) {
710         return false;
711     }
712     
713   SGPath path;
714   if (!XMLLoader::findAirportData(ident(), "ils", path)) {
715     return false; // no XML tower data
716   }
717   
718   if (!cache->isCachedFileModified(path)) {
719     // cached values are correct, we're all done
720     return false;
721   }
722   
723     try {
724         SGPropertyNode_ptr rootNode = new SGPropertyNode;
725         readProperties(path.str(), rootNode);
726
727         flightgear::NavDataCache::Transaction txn(cache);
728         readILSData(rootNode);
729         cache->stampCacheFile(path);
730         txn.commit();
731 // we loaded data, tell the caller it might need to reload things
732         return true;
733     } catch (sg_exception& e){
734         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading ils XML failed:" << e.getFormattedMessage());
735     }
736     
737     return false;
738 }
739
740 void FGAirport::readILSData(SGPropertyNode* aRoot)
741 {
742   NavDataCache* cache = NavDataCache::instance();
743   
744   // find the entry matching the runway
745   SGPropertyNode* runwayNode, *ilsNode;
746   for (int i=0; (runwayNode = aRoot->getChild("runway", i)) != NULL; ++i) {
747     for (int j=0; (ilsNode = runwayNode->getChild("ils", j)) != NULL; ++j) {
748       // must match on both nav-ident and runway ident, to support the following:
749       // - runways with multiple distinct ILS installations (KEWD, for example)
750       // - runways where both ends share the same nav ident (LFAT, for example)
751       PositionedID ils = cache->findILS(guid(), ilsNode->getStringValue("rwy"),
752                                         ilsNode->getStringValue("nav-id"));
753       if (ils == 0) {
754         SG_LOG(SG_GENERAL, SG_INFO, "reading ILS data for " << ident() <<
755                ", couldn;t find runway/navaid for:" <<
756                ilsNode->getStringValue("rwy") << "/" <<
757                ilsNode->getStringValue("nav-id"));
758         continue;
759       }
760       
761       double hdgDeg = ilsNode->getDoubleValue("hdg-deg"),
762         lon = ilsNode->getDoubleValue("lon"),
763         lat = ilsNode->getDoubleValue("lat"),
764         elevM = ilsNode->getDoubleValue("elev-m");
765  
766       cache->updateILS(ils, SGGeod::fromDegM(lon, lat, elevM), hdgDeg);
767     } // of ILS iteration
768   } // of runway iteration
769 }
770
771 void FGAirport::addSID(flightgear::SID* aSid)
772 {
773   mSIDs.push_back(aSid);
774 }
775
776 void FGAirport::addSTAR(STAR* aStar)
777 {
778   mSTARs.push_back(aStar);
779 }
780
781 void FGAirport::addApproach(Approach* aApp)
782 {
783   mApproaches.push_back(aApp);
784 }
785
786 //------------------------------------------------------------------------------
787 unsigned int FGAirport::numSIDs() const
788 {
789   loadProcedures();
790   return mSIDs.size();
791 }
792
793 //------------------------------------------------------------------------------
794 flightgear::SID* FGAirport::getSIDByIndex(unsigned int aIndex) const
795 {
796   loadProcedures();
797   return mSIDs[aIndex];
798 }
799
800 //------------------------------------------------------------------------------
801 flightgear::SID* FGAirport::findSIDWithIdent(const std::string& aIdent) const
802 {
803   loadProcedures();
804   for (unsigned int i=0; i<mSIDs.size(); ++i) {
805     if (mSIDs[i]->ident() == aIdent) {
806       return mSIDs[i];
807     }
808   }
809   
810   return NULL;
811 }
812
813 //------------------------------------------------------------------------------
814 flightgear::SIDList FGAirport::getSIDs() const
815 {
816   loadProcedures();
817   return flightgear::SIDList(mSIDs.begin(), mSIDs.end());
818 }
819
820 //------------------------------------------------------------------------------
821 unsigned int FGAirport::numSTARs() const
822 {
823   loadProcedures();
824   return mSTARs.size();
825 }
826
827 //------------------------------------------------------------------------------
828 STAR* FGAirport::getSTARByIndex(unsigned int aIndex) const
829 {
830   loadProcedures();
831   return mSTARs[aIndex];
832 }
833
834 //------------------------------------------------------------------------------
835 STAR* FGAirport::findSTARWithIdent(const std::string& aIdent) const
836 {
837   loadProcedures();
838   for (unsigned int i=0; i<mSTARs.size(); ++i) {
839     if (mSTARs[i]->ident() == aIdent) {
840       return mSTARs[i];
841     }
842   }
843   
844   return NULL;
845 }
846
847 //------------------------------------------------------------------------------
848 STARList FGAirport::getSTARs() const
849 {
850   loadProcedures();
851   return STARList(mSTARs.begin(), mSTARs.end());
852 }
853
854 unsigned int FGAirport::numApproaches() const
855 {
856   loadProcedures();
857   return mApproaches.size();
858 }
859
860 //------------------------------------------------------------------------------
861 Approach* FGAirport::getApproachByIndex(unsigned int aIndex) const
862 {
863   loadProcedures();
864   return mApproaches[aIndex];
865 }
866
867 //------------------------------------------------------------------------------
868 Approach* FGAirport::findApproachWithIdent(const std::string& aIdent) const
869 {
870   loadProcedures();
871   for (unsigned int i=0; i<mApproaches.size(); ++i) {
872     if (mApproaches[i]->ident() == aIdent) {
873       return mApproaches[i];
874     }
875   }
876   
877   return NULL;
878 }
879
880 //------------------------------------------------------------------------------
881 ApproachList FGAirport::getApproaches(ProcedureType type) const
882 {
883   loadProcedures();
884   if( type == PROCEDURE_INVALID )
885     return ApproachList(mApproaches.begin(), mApproaches.end());
886
887   ApproachList ret;
888   for(size_t i = 0; i < mApproaches.size(); ++i)
889   {
890     if( mApproaches[i]->type() == type )
891       ret.push_back(mApproaches[i]);
892   }
893   return ret;
894 }
895
896 CommStationList
897 FGAirport::commStations() const
898 {
899   NavDataCache* cache = NavDataCache::instance();
900   CommStationList result;
901   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(),
902                                                             FGPositioned::FREQ_GROUND,
903                                                             FGPositioned::FREQ_UNICOM))
904   {
905     result.push_back( loadById<CommStation>(pos) );
906   }
907   
908   return result;
909 }
910
911 CommStationList
912 FGAirport::commStationsOfType(FGPositioned::Type aTy) const
913 {
914   NavDataCache* cache = NavDataCache::instance();
915   CommStationList result;
916   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(), aTy)) {
917     result.push_back( loadById<CommStation>(pos) );
918   }
919   
920   return result;
921 }
922
923 class AirportWithSize
924 {
925 public:
926     AirportWithSize(FGPositionedRef pos) :
927         _pos(pos),
928         _sizeMetric(0)
929     {
930         assert(pos->type() == FGPositioned::AIRPORT);
931         FGAirport* apt = static_cast<FGAirport*>(pos.get());
932         BOOST_FOREACH(FGRunway* rwy, apt->getRunwaysWithoutReciprocals()) {
933             _sizeMetric += static_cast<int>(rwy->lengthFt());
934         }
935     }
936     
937     bool operator<(const AirportWithSize& other) const
938     {
939         return _sizeMetric < other._sizeMetric;
940     }
941     
942     FGPositionedRef pos() const
943     { return _pos; }
944 private:
945     FGPositionedRef _pos;
946     unsigned int _sizeMetric;
947     
948 };
949
950 void FGAirport::sortBySize(FGPositionedList& airportList)
951 {
952     std::vector<AirportWithSize> annotated;
953     BOOST_FOREACH(FGPositionedRef p, airportList) {
954         annotated.push_back(AirportWithSize(p));
955     }
956     std::sort(annotated.begin(), annotated.end());
957     
958     for (unsigned int i=0; i<annotated.size(); ++i) {
959         airportList[i] = annotated[i].pos();
960     }
961 }
962
963 // get airport elevation
964 double fgGetAirportElev( const std::string& id )
965 {
966     const FGAirport *a=fgFindAirportID( id);
967     if (a) {
968         return a->getElevation();
969     } else {
970         return -9999.0;
971     }
972 }
973
974
975 // get airport position
976 SGGeod fgGetAirportPos( const std::string& id )
977 {
978     const FGAirport *a = fgFindAirportID( id);
979
980     if (a) {
981         return SGGeod::fromDegM(a->getLongitude(), a->getLatitude(), a->getElevation());
982     } else {
983         return SGGeod::fromDegM(0.0, 0.0, -9999.0);
984     }
985 }