]> git.mxchange.org Git - flightgear.git/blob - src/Airports/simple.cxx
769e4abcc8bd07f5e9e0a198c18d9f54db9d9d7f
[flightgear.git] / src / Airports / simple.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 "simple.hxx"
32
33 #include <cassert>
34 #include <boost/foreach.hpp>
35
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/props/props.hxx>
38 #include <simgear/props/props_io.hxx>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/sg_inlines.h>
41 #include <simgear/structure/exception.hxx>
42
43 #include <Environment/environment_mgr.hxx>
44 #include <Environment/environment.hxx>
45 #include <Main/fg_props.hxx>
46 #include <Airports/runways.hxx>
47 #include <Airports/pavement.hxx>
48 #include <Airports/dynamics.hxx>
49 #include <Airports/xmlloader.hxx>
50 #include <Navaids/procedure.hxx>
51 #include <Navaids/waypoint.hxx>
52 #include <ATC/CommStation.hxx>
53 #include <Navaids/NavDataCache.hxx>
54
55 using std::vector;
56 using std::pair;
57
58 using namespace flightgear;
59
60
61 /***************************************************************************
62  * FGAirport
63  ***************************************************************************/
64
65 AirportCache FGAirport::airportCache;
66
67 FGAirport::FGAirport(PositionedID aGuid, const string &id, const SGGeod& location,
68         const string &name, bool has_metar, Type aType) :
69     FGPositioned(aGuid, aType, id, location),
70     _name(name),
71     _has_metar(has_metar),
72     _dynamics(0),
73     mTowerDataLoaded(false),
74     mRunwaysLoaded(false),
75     mTaxiwaysLoaded(false),
76     mProceduresLoaded(false),
77     mILSDataLoaded(false)
78 {
79 }
80
81
82 FGAirport::~FGAirport()
83 {
84     delete _dynamics;
85 }
86
87 bool FGAirport::isAirport() const
88 {
89   return type() == AIRPORT;
90 }
91
92 bool FGAirport::isSeaport() const
93 {
94   return type() == SEAPORT;
95 }
96
97 bool FGAirport::isHeliport() const
98 {
99   return type() == HELIPORT;
100 }
101
102 bool FGAirport::isAirportType(FGPositioned* pos)
103 {
104     if (!pos) {
105         return false;
106     }
107     
108     return (pos->type() >= AIRPORT) && (pos->type() <= SEAPORT);
109 }
110
111 FGAirportDynamics * FGAirport::getDynamics()
112 {
113     if (_dynamics) {
114         return _dynamics;
115     }
116     
117     _dynamics = new FGAirportDynamics(this);
118     XMLLoader::load(_dynamics);
119     _dynamics->init();
120   
121     FGRunwayPreference rwyPrefs(this);
122     XMLLoader::load(&rwyPrefs);
123     _dynamics->setRwyUse(rwyPrefs);
124     
125     return _dynamics;
126 }
127
128 unsigned int FGAirport::numRunways() const
129 {
130   loadRunways();
131   return mRunways.size();
132 }
133
134 FGRunway* FGAirport::getRunwayByIndex(unsigned int aIndex) const
135 {
136   loadRunways();
137   
138   assert(aIndex >= 0 && aIndex < mRunways.size());
139   return (FGRunway*) flightgear::NavDataCache::instance()->loadById(mRunways[aIndex]);
140 }
141
142 bool FGAirport::hasRunwayWithIdent(const string& aIdent) const
143 {
144   return flightgear::NavDataCache::instance()->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent) != 0;
145 }
146
147 FGRunway* FGAirport::getRunwayByIdent(const string& aIdent) const
148 {
149   PositionedID id = flightgear::NavDataCache::instance()->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent);  
150   if (id == 0) {
151     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << ident());
152     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
153   }
154   
155   return (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
156 }
157
158
159 FGRunway* FGAirport::findBestRunwayForHeading(double aHeading) const
160 {
161   loadRunways();
162   
163   FGRunway* result = NULL;
164   double currentBestQuality = 0.0;
165   
166   SGPropertyNode *param = fgGetNode("/sim/airport/runways/search", true);
167   double lengthWeight = param->getDoubleValue("length-weight", 0.01);
168   double widthWeight = param->getDoubleValue("width-weight", 0.01);
169   double surfaceWeight = param->getDoubleValue("surface-weight", 10);
170   double deviationWeight = param->getDoubleValue("deviation-weight", 1);
171     
172   BOOST_FOREACH(PositionedID id, mRunways) {
173     FGRunway* rwy = (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
174     double good = rwy->score(lengthWeight, widthWeight, surfaceWeight);
175     double dev = aHeading - rwy->headingDeg();
176     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
177     double bad = fabs(deviationWeight * dev) + 1e-20;
178     double quality = good / bad;
179     
180     if (quality > currentBestQuality) {
181       currentBestQuality = quality;
182       result = rwy;
183     }
184   }
185
186   return result;
187 }
188
189 FGRunway* FGAirport::findBestRunwayForPos(const SGGeod& aPos) const
190 {
191   loadRunways();
192   
193   FGRunway* result = NULL;
194   double currentLowestDev = 180.0;
195   
196   BOOST_FOREACH(PositionedID id, mRunways) {
197     FGRunway* rwy = (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
198
199     double inboundCourse = SGGeodesy::courseDeg(aPos, rwy->end());
200     double dev = inboundCourse - rwy->headingDeg();
201     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
202
203     dev = fabs(dev);
204     if (dev < currentLowestDev) { // new best match
205       currentLowestDev = dev;
206       result = rwy;
207     }
208   } // of runway iteration
209   
210   return result;
211
212 }
213
214 bool FGAirport::hasHardRunwayOfLengthFt(double aLengthFt) const
215 {
216   loadRunways();
217   
218   BOOST_FOREACH(PositionedID id, mRunways) {
219     FGRunway* rwy = (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
220
221     if (rwy->isReciprocal()) {
222       continue; // we only care about lengths, so don't do work twice
223     }
224
225     if (rwy->isHardSurface() && (rwy->lengthFt() >= aLengthFt)) {
226       return true; // we're done!
227     }
228   } // of runways iteration
229
230   return false;
231 }
232
233 unsigned int FGAirport::numTaxiways() const
234 {
235   loadTaxiways();
236   return mTaxiways.size();
237 }
238
239 FGTaxiway* FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
240 {
241   loadTaxiways();
242   
243   assert(aIndex >= 0 && aIndex < mTaxiways.size());
244   return (FGTaxiway*) flightgear::NavDataCache::instance()->loadById(mTaxiways[aIndex]);
245 }
246
247 unsigned int FGAirport::numPavements() const
248 {
249   loadTaxiways();
250   return mPavements.size();
251 }
252
253 FGPavement* FGAirport::getPavementByIndex(unsigned int aIndex) const
254 {
255   loadTaxiways();
256   assert(aIndex >= 0 && aIndex < mPavements.size());
257   return (FGPavement*) flightgear::NavDataCache::instance()->loadById(mPavements[aIndex]);
258 }
259
260 FGRunway* FGAirport::getActiveRunwayForUsage() const
261 {
262   FGEnvironmentMgr* envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
263   
264   // This forces West-facing rwys to be used in no-wind situations
265   // which is consistent with Flightgear's initial setup.
266   double hdg = 270;
267   
268   if (envMgr) {
269     FGEnvironment stationWeather(envMgr->getEnvironment(mPosition));
270   
271     double windSpeed = stationWeather.get_wind_speed_kt();
272     if (windSpeed > 0.0) {
273       hdg = stationWeather.get_wind_from_heading_deg();
274     }
275   }
276   
277   return findBestRunwayForHeading(hdg);
278 }
279
280 FGAirport* FGAirport::findClosest(const SGGeod& aPos, double aCuttofNm, Filter* filter)
281 {
282   AirportFilter aptFilter;
283   if (filter == NULL) {
284     filter = &aptFilter;
285   }
286   
287   FGPositionedRef r = FGPositioned::findClosest(aPos, aCuttofNm, filter);
288   if (!r) {
289     return NULL;
290   }
291   
292   return static_cast<FGAirport*>(r.ptr());
293 }
294
295 FGAirport::HardSurfaceFilter::HardSurfaceFilter(double minLengthFt) :
296   mMinLengthFt(minLengthFt)
297 {
298   if (minLengthFt < 0.0) {
299     mMinLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
300   }
301 }
302       
303 bool FGAirport::HardSurfaceFilter::passAirport(FGAirport* aApt) const
304 {
305   return aApt->hasHardRunwayOfLengthFt(mMinLengthFt);
306 }
307
308 FGAirport* FGAirport::findByIdent(const std::string& aIdent)
309 {
310   AirportCache::iterator it = airportCache.find(aIdent);
311   if (it != airportCache.end())
312    return it->second;
313
314   PortsFilter filter;
315   FGAirport* r = static_cast<FGAirport*> (FGPositioned::findFirstWithIdent(aIdent, &filter).get());
316
317   // add airport to the cache (even when it's NULL, so we don't need to search in vain again)
318   airportCache[aIdent] = r;
319
320   // we don't warn here when r==NULL, let the caller do that
321   return r;
322 }
323
324 FGAirport* FGAirport::getByIdent(const std::string& aIdent)
325 {
326   FGAirport* r = findByIdent(aIdent);
327   if (!r)
328     throw sg_range_exception("No such airport with ident: " + aIdent);
329   return r;
330 }
331
332 char** FGAirport::searchNamesAndIdents(const std::string& aFilter)
333 {
334   return NavDataCache::instance()->searchAirportNamesAndIdents(aFilter);
335 }
336
337 // find basic airport location info from airport database
338 const FGAirport *fgFindAirportID( const string& id)
339 {
340     if ( id.empty() ) {
341         return NULL;
342     }
343     
344     return FGAirport::findByIdent(id);
345 }
346
347 void FGAirport::loadRunways() const
348 {
349   if (mRunwaysLoaded) {
350     return; // already loaded, great
351   }
352   
353   loadSceneryDefinitions();
354   
355   mRunwaysLoaded = true;
356   mRunways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::RUNWAY);
357 }
358
359 void FGAirport::loadTaxiways() const
360 {
361   if (mTaxiwaysLoaded) {
362     return; // already loaded, great
363   }
364   
365   mTaxiwaysLoaded =  true;
366   mTaxiways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::TAXIWAY);
367 }
368
369 void FGAirport::loadProcedures() const
370 {
371   if (mProceduresLoaded) {
372     return;
373   }
374   
375   mProceduresLoaded = true;
376   SGPath path;
377   if (!XMLLoader::findAirportData(ident(), "procedures", path)) {
378     SG_LOG(SG_GENERAL, SG_INFO, "no procedures data available for " << ident());
379     return;
380   }
381   
382   SG_LOG(SG_GENERAL, SG_INFO, ident() << ": loading procedures from " << path.str());
383   RouteBase::loadAirportProcedures(path, const_cast<FGAirport*>(this));
384 }
385
386 void FGAirport::loadSceneryDefinitions() const
387 {
388   NavDataCache* cache = NavDataCache::instance();
389   SGPath path;
390   if (!XMLLoader::findAirportData(ident(), "threshold", path)) {
391     return; // no XML threshold data
392   }
393   
394   if (!cache->isCachedFileModified(path)) {
395     // cached values are correct, we're all done
396     return;
397   }
398   
399     flightgear::NavDataCache::Transaction txn(cache);
400     SGPropertyNode_ptr rootNode = new SGPropertyNode;
401     readProperties(path.str(), rootNode);
402     const_cast<FGAirport*>(this)->readThresholdData(rootNode);
403     cache->stampCacheFile(path);
404     txn.commit();
405 }
406
407 void FGAirport::readThresholdData(SGPropertyNode* aRoot)
408 {
409   SGPropertyNode* runway;
410   int runwayIndex = 0;
411   for (; (runway = aRoot->getChild("runway", runwayIndex)) != NULL; ++runwayIndex) {
412     SGPropertyNode* t0 = runway->getChild("threshold", 0),
413       *t1 = runway->getChild("threshold", 1);
414     assert(t0);
415     assert(t1); // too strict? maybe we should finally allow single-ended runways
416     
417     processThreshold(t0);
418     processThreshold(t1);
419   } // of runways iteration
420 }
421
422 void FGAirport::processThreshold(SGPropertyNode* aThreshold)
423 {
424   // first, let's identify the current runway
425   string rwyIdent(aThreshold->getStringValue("rwy"));
426   NavDataCache* cache = NavDataCache::instance(); 
427   PositionedID id = cache->airportItemWithIdent(guid(), FGPositioned::RUNWAY, rwyIdent);
428   if (id == 0) {
429     SG_LOG(SG_GENERAL, SG_DEBUG, "FGAirport::processThreshold: "
430            "found runway not defined in the global data:" << ident() << "/" << rwyIdent);
431     return;
432   }
433   
434   double lon = aThreshold->getDoubleValue("lon"),
435   lat = aThreshold->getDoubleValue("lat");
436   SGGeod newThreshold(SGGeod::fromDegM(lon, lat, mPosition.getElevationM()));
437   
438   double newHeading = aThreshold->getDoubleValue("hdg-deg");
439   double newDisplacedThreshold = aThreshold->getDoubleValue("displ-m") * SG_METER_TO_FEET;
440   double newStopway = aThreshold->getDoubleValue("stopw-m") * SG_METER_TO_FEET;
441   
442   cache->updateRunwayThreshold(id, newThreshold,
443                                newHeading, newDisplacedThreshold, newStopway);
444 }
445
446 SGGeod FGAirport::getTowerLocation() const
447 {
448   validateTowerData();
449   
450   NavDataCache* cache = NavDataCache::instance();
451   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
452   if (towers.empty()) {
453     SG_LOG(SG_GENERAL, SG_ALERT, "No towers defined for:" <<ident());
454     return SGGeod();
455   }
456   
457   FGPositionedRef tower = cache->loadById(towers.front());
458   return tower->geod();
459 }
460
461 void FGAirport::validateTowerData() const
462 {
463   if (mTowerDataLoaded) {
464     return;
465   }
466
467   mTowerDataLoaded = true;
468   NavDataCache* cache = NavDataCache::instance();
469   SGPath path;
470   if (!XMLLoader::findAirportData(ident(), "twr", path)) {
471     return; // no XML tower data
472   }
473   
474   if (!cache->isCachedFileModified(path)) {
475   // cached values are correct, we're all done
476     return;
477   }
478    
479   flightgear::NavDataCache::Transaction txn(cache);
480   SGPropertyNode_ptr rootNode = new SGPropertyNode;
481   readProperties(path.str(), rootNode);
482   const_cast<FGAirport*>(this)->readTowerData(rootNode);
483   cache->stampCacheFile(path);
484   txn.commit();
485 }
486
487 void FGAirport::readTowerData(SGPropertyNode* aRoot)
488 {
489   SGPropertyNode* twrNode = aRoot->getChild("tower")->getChild("twr");
490   double lat = twrNode->getDoubleValue("lat"), 
491     lon = twrNode->getDoubleValue("lon"), 
492     elevM = twrNode->getDoubleValue("elev-m");  
493 // tower elevation is AGL, not AMSL. Since we don't want to depend on the
494 // scenery for a precise terrain elevation, we use the field elevation
495 // (this is also what the apt.dat code does)
496   double fieldElevationM = geod().getElevationM();
497   SGGeod towerLocation(SGGeod::fromDegM(lon, lat, fieldElevationM + elevM));
498   
499   NavDataCache* cache = NavDataCache::instance();
500   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
501   if (towers.empty()) {
502     cache->insertTower(guid(), towerLocation);
503   } else {
504     // update the position
505     cache->updatePosition(towers.front(), towerLocation);
506   }
507 }
508
509 bool FGAirport::validateILSData()
510 {
511   if (mILSDataLoaded) {
512     return false;
513   }
514   
515   mILSDataLoaded = true;
516   NavDataCache* cache = NavDataCache::instance();
517   SGPath path;
518   if (!XMLLoader::findAirportData(ident(), "ils", path)) {
519     return false; // no XML tower data
520   }
521   
522   if (!cache->isCachedFileModified(path)) {
523     // cached values are correct, we're all done
524     return false;
525   }
526   
527   SGPropertyNode_ptr rootNode = new SGPropertyNode;
528   readProperties(path.str(), rootNode);
529
530   flightgear::NavDataCache::Transaction txn(cache);
531   readILSData(rootNode);
532   cache->stampCacheFile(path);
533   txn.commit();
534     
535 // we loaded data, tell the caller it might need to reload things
536   return true;
537 }
538
539 void FGAirport::readILSData(SGPropertyNode* aRoot)
540 {
541   NavDataCache* cache = NavDataCache::instance();
542   
543   // find the entry matching the runway
544   SGPropertyNode* runwayNode, *ilsNode;
545   for (int i=0; (runwayNode = aRoot->getChild("runway", i)) != NULL; ++i) {
546     for (int j=0; (ilsNode = runwayNode->getChild("ils", j)) != NULL; ++j) {
547       // must match on both nav-ident and runway ident, to support the following:
548       // - runways with multiple distinct ILS installations (KEWD, for example)
549       // - runways where both ends share the same nav ident (LFAT, for example)
550       PositionedID ils = cache->findILS(guid(), ilsNode->getStringValue("rwy"),
551                                         ilsNode->getStringValue("nav-id"));
552       if (ils == 0) {
553         SG_LOG(SG_GENERAL, SG_INFO, "reading ILS data for " << ident() <<
554                ", couldn;t find runway/navaid for:" <<
555                ilsNode->getStringValue("rwy") << "/" <<
556                ilsNode->getStringValue("nav-id"));
557         continue;
558       }
559       
560       double hdgDeg = ilsNode->getDoubleValue("hdg-deg"),
561         lon = ilsNode->getDoubleValue("lon"),
562         lat = ilsNode->getDoubleValue("lat"),
563         elevM = ilsNode->getDoubleValue("elev-m");
564  
565       cache->updateILS(ils, SGGeod::fromDegM(lon, lat, elevM), hdgDeg);
566     } // of ILS iteration
567   } // of runway iteration
568 }
569
570 void FGAirport::addSID(flightgear::SID* aSid)
571 {
572   mSIDs.push_back(aSid);
573 }
574
575 void FGAirport::addSTAR(STAR* aStar)
576 {
577   mSTARs.push_back(aStar);
578 }
579
580 void FGAirport::addApproach(Approach* aApp)
581 {
582   mApproaches.push_back(aApp);
583 }
584
585 unsigned int FGAirport::numSIDs() const
586 {
587   loadProcedures();
588   return mSIDs.size();
589 }
590
591 flightgear::SID* FGAirport::getSIDByIndex(unsigned int aIndex) const
592 {
593   loadProcedures();
594   return mSIDs[aIndex];
595 }
596
597 flightgear::SID* FGAirport::findSIDWithIdent(const std::string& aIdent) const
598 {
599   loadProcedures();
600   for (unsigned int i=0; i<mSIDs.size(); ++i) {
601     if (mSIDs[i]->ident() == aIdent) {
602       return mSIDs[i];
603     }
604   }
605   
606   return NULL;
607 }
608
609 unsigned int FGAirport::numSTARs() const
610 {
611   loadProcedures();
612   return mSTARs.size();
613 }
614
615 STAR* FGAirport::getSTARByIndex(unsigned int aIndex) const
616 {
617   loadProcedures();
618   return mSTARs[aIndex];
619 }
620
621 STAR* FGAirport::findSTARWithIdent(const std::string& aIdent) const
622 {
623   loadProcedures();
624   for (unsigned int i=0; i<mSTARs.size(); ++i) {
625     if (mSTARs[i]->ident() == aIdent) {
626       return mSTARs[i];
627     }
628   }
629   
630   return NULL;
631 }
632
633 unsigned int FGAirport::numApproaches() const
634 {
635   loadProcedures();
636   return mApproaches.size();
637 }
638
639 Approach* FGAirport::getApproachByIndex(unsigned int aIndex) const
640 {
641   loadProcedures();
642   return mApproaches[aIndex];
643 }
644
645 Approach* FGAirport::findApproachWithIdent(const std::string& aIdent) const
646 {
647   loadProcedures();
648   for (unsigned int i=0; i<mApproaches.size(); ++i) {
649     if (mApproaches[i]->ident() == aIdent) {
650       return mApproaches[i];
651     }
652   }
653   
654   return NULL;
655 }
656
657 CommStationList
658 FGAirport::commStations() const
659 {
660   NavDataCache* cache = NavDataCache::instance();
661   CommStationList result;
662   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(),
663                                                             FGPositioned::FREQ_GROUND,
664                                                             FGPositioned::FREQ_UNICOM))
665   {
666     result.push_back((CommStation*) cache->loadById(pos));
667   }
668   
669   return result;
670 }
671
672 CommStationList
673 FGAirport::commStationsOfType(FGPositioned::Type aTy) const
674 {
675   NavDataCache* cache = NavDataCache::instance();
676   CommStationList result;
677   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(), aTy)) {
678     result.push_back((CommStation*) cache->loadById(pos));
679   }
680   
681   return result;
682 }
683
684 // get airport elevation
685 double fgGetAirportElev( const string& id )
686 {
687     const FGAirport *a=fgFindAirportID( id);
688     if (a) {
689         return a->getElevation();
690     } else {
691         return -9999.0;
692     }
693 }
694
695
696 // get airport position
697 SGGeod fgGetAirportPos( const string& id )
698 {
699     const FGAirport *a = fgFindAirportID( id);
700
701     if (a) {
702         return SGGeod::fromDegM(a->getLongitude(), a->getLatitude(), a->getElevation());
703     } else {
704         return SGGeod::fromDegM(0.0, 0.0, -9999.0);
705     }
706 }