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