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