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