]> git.mxchange.org Git - flightgear.git/blob - src/Airports/airport.cxx
Navaid diagram for launcher
[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     // increase tower elevation by 20 metres above the field elevation
684     mTowerPosition.setElevationM(geod().getElevationM() + 20.0);
685   } else {
686     FGPositionedRef tower = cache->loadById(towers.front());
687     mTowerPosition = tower->geod();
688     mHasTower = true;
689   }
690   
691   SGPath path;
692   if (!XMLLoader::findAirportData(ident(), "twr", path)) {
693     return; // no XML tower data, base position is fine
694   }
695   
696   try {
697     SGPropertyNode_ptr rootNode = new SGPropertyNode;
698     readProperties(path.str(), rootNode);
699     const_cast<FGAirport*>(this)->readTowerData(rootNode);
700     mHasTower = true;
701   } catch (sg_exception& e){
702     SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading twr XML failed:" << e.getFormattedMessage());
703   }
704 }
705
706 void FGAirport::readTowerData(SGPropertyNode* aRoot)
707 {
708   SGPropertyNode* twrNode = aRoot->getChild("tower")->getChild("twr");
709   double lat = twrNode->getDoubleValue("lat"), 
710     lon = twrNode->getDoubleValue("lon"), 
711     elevM = twrNode->getDoubleValue("elev-m");  
712 // tower elevation is AGL, not AMSL. Since we don't want to depend on the
713 // scenery for a precise terrain elevation, we use the field elevation
714 // (this is also what the apt.dat code does)
715   double fieldElevationM = geod().getElevationM();
716   mTowerPosition = SGGeod::fromDegM(lon, lat, fieldElevationM + elevM);
717 }
718
719 void FGAirport::validateILSData()
720 {
721   if (mILSDataLoaded) {
722     return;
723   }
724   
725   // to avoid re-entrancy on this code-path, ensure we set loaded
726   // immediately.
727   mILSDataLoaded = true;
728     
729   SGPath path;
730   if (!XMLLoader::findAirportData(ident(), "ils", path)) {
731     return; // no XML tower data
732   }
733   
734   try {
735       SGPropertyNode_ptr rootNode = new SGPropertyNode;
736       readProperties(path.str(), rootNode);
737       readILSData(rootNode);
738   } catch (sg_exception& e){
739       SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading ils XML failed:" << e.getFormattedMessage());
740   }
741 }
742
743 bool FGAirport::hasTower() const
744 {
745     validateTowerData();
746     return mHasTower;
747 }
748
749 void FGAirport::readILSData(SGPropertyNode* aRoot)
750 {  
751   NavDataCache* cache = NavDataCache::instance();
752   // find the entry matching the runway
753   SGPropertyNode* runwayNode, *ilsNode;
754   for (int i=0; (runwayNode = aRoot->getChild("runway", i)) != NULL; ++i) {
755     for (int j=0; (ilsNode = runwayNode->getChild("ils", j)) != NULL; ++j) {
756       // must match on both nav-ident and runway ident, to support the following:
757       // - runways with multiple distinct ILS installations (KEWD, for example)
758       // - runways where both ends share the same nav ident (LFAT, for example)
759       PositionedID ils = cache->findILS(guid(), ilsNode->getStringValue("rwy"),
760                                         ilsNode->getStringValue("nav-id"));
761       if (ils == 0) {
762         SG_LOG(SG_GENERAL, SG_INFO, "reading ILS data for " << ident() <<
763                ", couldn't find runway/navaid for:" <<
764                ilsNode->getStringValue("rwy") << "/" <<
765                ilsNode->getStringValue("nav-id"));
766         continue;
767       }
768       
769       double hdgDeg = ilsNode->getDoubleValue("hdg-deg"),
770         lon = ilsNode->getDoubleValue("lon"),
771         lat = ilsNode->getDoubleValue("lat"),
772         elevM = ilsNode->getDoubleValue("elev-m");
773  
774       FGNavRecordRef nav(FGPositioned::loadById<FGNavRecord>(ils));
775       assert(nav.valid());
776       nav->updateFromXML(SGGeod::fromDegM(lon, lat, elevM), hdgDeg);
777     } // of ILS iteration
778   } // of runway iteration
779 }
780
781 void FGAirport::addSID(flightgear::SID* aSid)
782 {
783   mSIDs.push_back(aSid);
784 }
785
786 void FGAirport::addSTAR(STAR* aStar)
787 {
788   mSTARs.push_back(aStar);
789 }
790
791 void FGAirport::addApproach(Approach* aApp)
792 {
793   mApproaches.push_back(aApp);
794 }
795
796 //------------------------------------------------------------------------------
797 unsigned int FGAirport::numSIDs() const
798 {
799   loadProcedures();
800   return mSIDs.size();
801 }
802
803 //------------------------------------------------------------------------------
804 flightgear::SID* FGAirport::getSIDByIndex(unsigned int aIndex) const
805 {
806   loadProcedures();
807   return mSIDs[aIndex];
808 }
809
810 //------------------------------------------------------------------------------
811 flightgear::SID* FGAirport::findSIDWithIdent(const std::string& aIdent) const
812 {
813   loadProcedures();
814   for (unsigned int i=0; i<mSIDs.size(); ++i) {
815     if (mSIDs[i]->ident() == aIdent) {
816       return mSIDs[i];
817     }
818   }
819   
820   return NULL;
821 }
822
823 //------------------------------------------------------------------------------
824 flightgear::SIDList FGAirport::getSIDs() const
825 {
826   loadProcedures();
827   return flightgear::SIDList(mSIDs.begin(), mSIDs.end());
828 }
829
830 //------------------------------------------------------------------------------
831 unsigned int FGAirport::numSTARs() const
832 {
833   loadProcedures();
834   return mSTARs.size();
835 }
836
837 //------------------------------------------------------------------------------
838 STAR* FGAirport::getSTARByIndex(unsigned int aIndex) const
839 {
840   loadProcedures();
841   return mSTARs[aIndex];
842 }
843
844 //------------------------------------------------------------------------------
845 STAR* FGAirport::findSTARWithIdent(const std::string& aIdent) const
846 {
847   loadProcedures();
848   for (unsigned int i=0; i<mSTARs.size(); ++i) {
849     if (mSTARs[i]->ident() == aIdent) {
850       return mSTARs[i];
851     }
852   }
853   
854   return NULL;
855 }
856
857 //------------------------------------------------------------------------------
858 STARList FGAirport::getSTARs() const
859 {
860   loadProcedures();
861   return STARList(mSTARs.begin(), mSTARs.end());
862 }
863
864 unsigned int FGAirport::numApproaches() const
865 {
866   loadProcedures();
867   return mApproaches.size();
868 }
869
870 //------------------------------------------------------------------------------
871 Approach* FGAirport::getApproachByIndex(unsigned int aIndex) const
872 {
873   loadProcedures();
874   return mApproaches[aIndex];
875 }
876
877 //------------------------------------------------------------------------------
878 Approach* FGAirport::findApproachWithIdent(const std::string& aIdent) const
879 {
880   loadProcedures();
881   for (unsigned int i=0; i<mApproaches.size(); ++i) {
882     if (mApproaches[i]->ident() == aIdent) {
883       return mApproaches[i];
884     }
885   }
886   
887   return NULL;
888 }
889
890 //------------------------------------------------------------------------------
891 ApproachList FGAirport::getApproaches(ProcedureType type) const
892 {
893   loadProcedures();
894   if( type == PROCEDURE_INVALID )
895     return ApproachList(mApproaches.begin(), mApproaches.end());
896
897   ApproachList ret;
898   for(size_t i = 0; i < mApproaches.size(); ++i)
899   {
900     if( mApproaches[i]->type() == type )
901       ret.push_back(mApproaches[i]);
902   }
903   return ret;
904 }
905
906 CommStationList
907 FGAirport::commStations() const
908 {
909   NavDataCache* cache = NavDataCache::instance();
910   CommStationList result;
911   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(),
912                                                             FGPositioned::FREQ_GROUND,
913                                                             FGPositioned::FREQ_UNICOM))
914   {
915     result.push_back( loadById<CommStation>(pos) );
916   }
917   
918   return result;
919 }
920
921 CommStationList
922 FGAirport::commStationsOfType(FGPositioned::Type aTy) const
923 {
924   NavDataCache* cache = NavDataCache::instance();
925   CommStationList result;
926   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(), aTy)) {
927     result.push_back( loadById<CommStation>(pos) );
928   }
929   
930   return result;
931 }
932
933 class AirportWithSize
934 {
935 public:
936     AirportWithSize(FGPositionedRef pos) :
937         _pos(pos),
938         _sizeMetric(0)
939     {
940         assert(pos->type() == FGPositioned::AIRPORT);
941         FGAirport* apt = static_cast<FGAirport*>(pos.get());
942         BOOST_FOREACH(FGRunway* rwy, apt->getRunwaysWithoutReciprocals()) {
943             _sizeMetric += static_cast<int>(rwy->lengthFt());
944         }
945     }
946     
947     bool operator<(const AirportWithSize& other) const
948     {
949         return _sizeMetric < other._sizeMetric;
950     }
951     
952     FGPositionedRef pos() const
953     { return _pos; }
954 private:
955     FGPositionedRef _pos;
956     unsigned int _sizeMetric;
957     
958 };
959
960 void FGAirport::sortBySize(FGPositionedList& airportList)
961 {
962     std::vector<AirportWithSize> annotated;
963     BOOST_FOREACH(FGPositionedRef p, airportList) {
964         annotated.push_back(AirportWithSize(p));
965     }
966     std::sort(annotated.begin(), annotated.end());
967     
968     for (unsigned int i=0; i<annotated.size(); ++i) {
969         airportList[i] = annotated[i].pos();
970     }
971 }
972
973 // get airport elevation
974 double fgGetAirportElev( const std::string& id )
975 {
976     const FGAirport *a=fgFindAirportID( id);
977     if (a) {
978         return a->getElevation();
979     } else {
980         return -9999.0;
981     }
982 }
983
984
985 // get airport position
986 SGGeod fgGetAirportPos( const std::string& id )
987 {
988     const FGAirport *a = fgFindAirportID( id);
989
990     if (a) {
991         return SGGeod::fromDegM(a->getLongitude(), a->getLatitude(), a->getElevation());
992     } else {
993         return SGGeod::fromDegM(0.0, 0.0, -9999.0);
994     }
995 }