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