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