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