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