]> git.mxchange.org Git - flightgear.git/blob - src/Airports/simple.cxx
Merge branch 'next' into durk-atc
[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
35 #include <simgear/misc/sg_path.hxx>
36 #include <simgear/props/props.hxx>
37 #include <simgear/props/props_io.hxx>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/sg_inlines.h>
40
41 #include <Environment/environment_mgr.hxx>
42 #include <Environment/environment.hxx>
43 #include <Main/fg_props.hxx>
44 #include <Airports/runways.hxx>
45 #include <Airports/pavement.hxx>
46 #include <Airports/dynamics.hxx>
47 #include <Airports/xmlloader.hxx>
48 #include <Navaids/procedure.hxx>
49 #include <Navaids/waypoint.hxx>
50 #include <Navaids/PositionedBinding.hxx>
51 #include <ATC/CommStation.hxx>
52
53 using std::vector;
54 using namespace flightgear;
55
56 // magic import of a helper which uses FGPositioned internals
57 extern char** searchAirportNamesAndIdents(const std::string& aFilter);
58
59 /***************************************************************************
60  * FGAirport
61  ***************************************************************************/
62
63 FGAirport::FGAirport(const string &id, const SGGeod& location, const SGGeod& tower_location,
64         const string &name, bool has_metar, Type aType) :
65     FGPositioned(aType, id, location),
66     _tower_location(tower_location),
67     _name(name),
68     _has_metar(has_metar),
69     _dynamics(0),
70     mRunwaysLoaded(false),
71     mTaxiwaysLoaded(true)
72 {
73   init(true); // init FGPositioned
74 }
75
76
77 FGAirport::~FGAirport()
78 {
79     delete _dynamics;
80 }
81
82 bool FGAirport::isAirport() const
83 {
84   return type() == AIRPORT;
85 }
86
87 bool FGAirport::isSeaport() const
88 {
89   return type() == SEAPORT;
90 }
91
92 bool FGAirport::isHeliport() const
93 {
94   return type() == HELIPORT;
95 }
96
97 FGAirportDynamics * FGAirport::getDynamics()
98 {
99     if (_dynamics) {
100         return _dynamics;
101     }
102     
103     _dynamics = new FGAirportDynamics(this);
104     XMLLoader::load(_dynamics);
105
106     FGRunwayPreference rwyPrefs(this);
107     XMLLoader::load(&rwyPrefs);
108     _dynamics->setRwyUse(rwyPrefs);
109     XMLLoader::load(_dynamics->getSIDs());
110     
111     return _dynamics;
112 }
113
114 unsigned int FGAirport::numRunways() const
115 {
116   loadRunways();
117   return mRunways.size();
118 }
119
120 FGRunway* FGAirport::getRunwayByIndex(unsigned int aIndex) const
121 {
122   loadRunways();
123   
124   assert(aIndex >= 0 && aIndex < mRunways.size());
125   return mRunways[aIndex];
126 }
127
128 bool FGAirport::hasRunwayWithIdent(const string& aIdent) const
129 {
130   return (getIteratorForRunwayIdent(aIdent) != mRunways.end());
131 }
132
133 FGRunway* FGAirport::getRunwayByIdent(const string& aIdent) const
134 {
135   Runway_iterator it = getIteratorForRunwayIdent(aIdent);
136   if (it == mRunways.end()) {
137     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << ident());
138     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
139   }
140   
141   return *it;
142 }
143
144 FGAirport::Runway_iterator
145 FGAirport::getIteratorForRunwayIdent(const string& aIdent) const
146 {
147   if (aIdent.empty())
148     return mRunways.end();
149
150   loadRunways();
151   
152   string ident(aIdent);
153   if ((aIdent.size() == 1) || !isdigit(aIdent[1])) {
154     ident = "0" + aIdent;
155   }
156
157   Runway_iterator it = mRunways.begin();
158   for (; it != mRunways.end(); ++it) {
159     if ((*it)->ident() == ident) {
160       return it;
161     }
162   }
163
164   return it; // end()
165 }
166
167 FGRunway* FGAirport::findBestRunwayForHeading(double aHeading) const
168 {
169   loadRunways();
170   
171   Runway_iterator it = mRunways.begin();
172   FGRunway* result = NULL;
173   double currentBestQuality = 0.0;
174   
175   SGPropertyNode *param = fgGetNode("/sim/airport/runways/search", true);
176   double lengthWeight = param->getDoubleValue("length-weight", 0.01);
177   double widthWeight = param->getDoubleValue("width-weight", 0.01);
178   double surfaceWeight = param->getDoubleValue("surface-weight", 10);
179   double deviationWeight = param->getDoubleValue("deviation-weight", 1);
180     
181   for (; it != mRunways.end(); ++it) {
182     double good = (*it)->score(lengthWeight, widthWeight, surfaceWeight);
183     
184     double dev = aHeading - (*it)->headingDeg();
185     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
186     double bad = fabs(deviationWeight * dev) + 1e-20;
187     double quality = good / bad;
188     
189     if (quality > currentBestQuality) {
190       currentBestQuality = quality;
191       result = *it;
192     }
193   }
194
195   return result;
196 }
197
198 FGRunway* FGAirport::findBestRunwayForPos(const SGGeod& aPos) const
199 {
200   loadRunways();
201   
202   Runway_iterator it = mRunways.begin();
203   FGRunway* result = NULL;
204   double currentLowestDev = 180.0;
205   
206   for (; it != mRunways.end(); ++it) {
207     double inboundCourse = SGGeodesy::courseDeg(aPos, (*it)->end());
208     double dev = inboundCourse - (*it)->headingDeg();
209     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
210
211     dev = fabs(dev);
212     if (dev < currentLowestDev) { // new best match
213       currentLowestDev = dev;
214       result = *it;
215     }
216   } // of runway iteration
217   
218   return result;
219
220 }
221
222 bool FGAirport::hasHardRunwayOfLengthFt(double aLengthFt) const
223 {
224   loadRunways();
225   
226   unsigned int numRunways(mRunways.size());
227   for (unsigned int r=0; r<numRunways; ++r) {
228     FGRunway* rwy = mRunways[r];
229     if (rwy->isReciprocal()) {
230       continue; // we only care about lengths, so don't do work twice
231     }
232
233     if (rwy->isHardSurface() && (rwy->lengthFt() >= aLengthFt)) {
234       return true; // we're done!
235     }
236   } // of runways iteration
237
238   return false;
239 }
240
241 unsigned int FGAirport::numTaxiways() const
242 {
243   loadTaxiways();
244   return mTaxiways.size();
245 }
246
247 FGTaxiway* FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
248 {
249   loadTaxiways();
250   assert(aIndex >= 0 && aIndex < mTaxiways.size());
251   return mTaxiways[aIndex];
252 }
253
254 unsigned int FGAirport::numPavements() const
255 {
256   loadTaxiways();
257   return mPavements.size();
258 }
259
260 FGPavement* FGAirport::getPavementByIndex(unsigned int aIndex) const
261 {
262   loadTaxiways();
263   assert(aIndex >= 0 && aIndex < mPavements.size());
264   return mPavements[aIndex];
265 }
266
267 void FGAirport::setRunwaysAndTaxiways(vector<FGRunwayPtr>& rwys,
268        vector<FGTaxiwayPtr>& txwys,
269        vector<FGPavementPtr>& pvts)
270 {
271   mRunways.swap(rwys);
272   Runway_iterator it = mRunways.begin();
273   for (; it != mRunways.end(); ++it) {
274     (*it)->setAirport(this);
275   }
276
277   mTaxiways.swap(txwys);
278   mPavements.swap(pvts);
279 }
280
281 FGRunway* FGAirport::getActiveRunwayForUsage() const
282 {
283   static FGEnvironmentMgr* envMgr = NULL;
284   if (!envMgr) {
285     envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
286   }
287   
288   // This forces West-facing rwys to be used in no-wind situations
289   // which is consistent with Flightgear's initial setup.
290   double hdg = 270;
291   
292   if (envMgr) {
293     FGEnvironment stationWeather(envMgr->getEnvironment(mPosition));
294   
295     double windSpeed = stationWeather.get_wind_speed_kt();
296     if (windSpeed > 0.0) {
297       hdg = stationWeather.get_wind_from_heading_deg();
298     }
299   }
300   
301   return findBestRunwayForHeading(hdg);
302 }
303
304 FGAirport* FGAirport::findClosest(const SGGeod& aPos, double aCuttofNm, Filter* filter)
305 {
306   AirportFilter aptFilter;
307   if (filter == NULL) {
308     filter = &aptFilter;
309   }
310   
311   FGPositionedRef r = FGPositioned::findClosest(aPos, aCuttofNm, filter);
312   if (!r) {
313     return NULL;
314   }
315   
316   return static_cast<FGAirport*>(r.ptr());
317 }
318
319 FGAirport::HardSurfaceFilter::HardSurfaceFilter(double minLengthFt) :
320   mMinLengthFt(minLengthFt)
321 {
322 }
323       
324 bool FGAirport::HardSurfaceFilter::passAirport(FGAirport* aApt) const
325 {
326   return aApt->hasHardRunwayOfLengthFt(mMinLengthFt);
327 }
328
329 FGAirport* FGAirport::findByIdent(const std::string& aIdent)
330 {
331   FGPositionedRef r;
332   PortsFilter filter;
333   r = FGPositioned::findNextWithPartialId(r, aIdent, &filter);
334   if (!r) {
335     return NULL; // we don't warn here, let the caller do that
336   }
337   return static_cast<FGAirport*>(r.ptr());
338 }
339
340 FGAirport* FGAirport::getByIdent(const std::string& aIdent)
341 {
342   FGPositionedRef r;
343   PortsFilter filter;
344   r = FGPositioned::findNextWithPartialId(r, aIdent, &filter);
345   if (!r) {
346     throw sg_range_exception("No such airport with ident: " + aIdent);
347   }
348   return static_cast<FGAirport*>(r.ptr());
349 }
350
351 char** FGAirport::searchNamesAndIdents(const std::string& aFilter)
352 {
353   // we delegate all the work to a horrible helper in FGPositioned, which can
354   // access the (private) index data.
355   return searchAirportNamesAndIdents(aFilter);
356 }
357
358 // find basic airport location info from airport database
359 const FGAirport *fgFindAirportID( const string& id)
360 {
361     if ( id.empty() ) {
362         return NULL;
363     }
364     
365     return FGAirport::findByIdent(id);
366 }
367
368 void FGAirport::loadRunways() const
369 {
370   if (mRunwaysLoaded) {
371     return; // already loaded, great
372   }
373   
374   mRunwaysLoaded = true;
375   loadSceneryDefinitions();
376 }
377
378 void FGAirport::loadTaxiways() const
379 {
380   if (mTaxiwaysLoaded) {
381     return; // already loaded, great
382   }
383 }
384
385 void FGAirport::loadProcedures() const
386 {
387   if (mProceduresLoaded) {
388     return;
389   }
390   
391   mProceduresLoaded = true;
392   SGPath path;
393   if (!XMLLoader::findAirportData(ident(), "procedures", path)) {
394     SG_LOG(SG_GENERAL, SG_INFO, "no procedures data available for " << ident());
395     return;
396   }
397   
398   SG_LOG(SG_GENERAL, SG_INFO, ident() << ": loading procedures from " << path.str());
399   Route::loadAirportProcedures(path, const_cast<FGAirport*>(this));
400 }
401
402 void FGAirport::loadSceneryDefinitions() const
403 {  
404   // allow users to disable the scenery data in the short-term
405   // longer term, this option can probably disappear
406   if (!fgGetBool("/sim/paths/use-custom-scenery-data")) {
407     return; 
408   }
409   
410   SGPath path;
411   SGPropertyNode_ptr rootNode = new SGPropertyNode;
412   if (XMLLoader::findAirportData(ident(), "threshold", path)) {
413     readProperties(path.str(), rootNode);
414     const_cast<FGAirport*>(this)->readThresholdData(rootNode);
415   }
416   
417   // repeat for the tower data
418   rootNode = new SGPropertyNode;
419   if (XMLLoader::findAirportData(ident(), "twr", path)) {
420     readProperties(path.str(), rootNode);
421     const_cast<FGAirport*>(this)->readTowerData(rootNode);
422   }
423 }
424
425 void FGAirport::readThresholdData(SGPropertyNode* aRoot)
426 {
427   SGPropertyNode* runway;
428   int runwayIndex = 0;
429   for (; (runway = aRoot->getChild("runway", runwayIndex)) != NULL; ++runwayIndex) {
430     SGPropertyNode* t0 = runway->getChild("threshold", 0),
431       *t1 = runway->getChild("threshold", 1);
432     assert(t0);
433     assert(t1); // too strict? mayeb we should finally allow single-ended runways
434     
435     processThreshold(t0);
436     processThreshold(t1);
437   } // of runways iteration
438 }
439
440 void FGAirport::processThreshold(SGPropertyNode* aThreshold)
441 {
442   // first, let's identify the current runway
443   string id(aThreshold->getStringValue("rwy"));
444   if (!hasRunwayWithIdent(id)) {
445     SG_LOG(SG_GENERAL, SG_WARN, "FGAirport::processThreshold: "
446       "found runway not defined in the global data:" << ident() << "/" << id);
447     return;
448   }
449   
450   FGRunway* rwy = getRunwayByIdent(id);
451   rwy->processThreshold(aThreshold);
452 }
453
454 void FGAirport::readTowerData(SGPropertyNode* aRoot)
455 {
456   SGPropertyNode* twrNode = aRoot->getChild("tower")->getChild("twr");
457   double lat = twrNode->getDoubleValue("lat"), 
458     lon = twrNode->getDoubleValue("lon"), 
459     elevM = twrNode->getDoubleValue("elev-m");  
460 // tower elevation is AGL, not AMSL. Since we don't want to depend on the
461 // scenery for a precise terrain elevation, we use the field elevation
462 // (this is also what the apt.dat code does)
463   double fieldElevationM = geod().getElevationM();
464   
465   _tower_location = SGGeod::fromDegM(lon, lat, fieldElevationM + elevM);
466 }
467
468 bool FGAirport::buildApproach(Waypt* aEnroute, STAR* aSTAR, FGRunway* aRwy, WayptVec& aRoute)
469 {
470   loadProcedures();
471
472   if ((aRwy && (aRwy->airport() != this))) {
473     throw sg_exception("invalid parameters", "FGAirport::buildApproach");
474   }
475   
476   if (aSTAR) {
477     bool ok = aSTAR->route(aRwy, aEnroute, aRoute);
478     if (!ok) {
479       SG_LOG(SG_GENERAL, SG_WARN, ident() << ": build approach, STAR " << aSTAR->ident() 
480          << " failed to route from transition " << aEnroute->ident());
481       return false;
482     }
483   } else if (aEnroute) {
484     // no a STAR specified, just use enroute point directly
485     aRoute.push_back(aEnroute);
486   }
487   
488   if (!aRwy) {
489     // no runway selected yet, but we loaded the STAR, so that's fine, we're done
490     return true;
491   }
492   
493 // build the approach (possibly including transition), and including the missed segment
494   vector<Approach*> aps;
495   for (unsigned int j=0; j<mApproaches.size();++j) {
496     if (mApproaches[j]->runway() == aRwy) {
497       aps.push_back(mApproaches[j]);
498     }
499   } // of approach filter by runway
500   
501   if (aps.empty()) {
502     SG_LOG(SG_GENERAL, SG_INFO, ident() << "; no approaches defined for runway " << aRwy->ident());
503     // could build a fallback approach here
504     return false;
505   }
506   
507   for (unsigned int k=0; k<aps.size(); ++k) {
508     if (aps[k]->route(aRoute.back(), aRoute)) {
509       return true;
510     }
511   } // of initial approach iteration
512   
513   SG_LOG(SG_GENERAL, SG_INFO, ident() << ": unable to find transition to runway "
514     << aRwy->ident() << ", assume vectors");
515   
516   WayptRef v(new ATCVectors(NULL, this));
517   aRoute.push_back(v);
518   return aps.front()->routeFromVectors(aRoute);
519 }
520
521 pair<flightgear::SID*, WayptRef>
522 FGAirport::selectSID(const SGGeod& aDest, FGRunway* aRwy)
523 {
524   loadProcedures();
525   
526   WayptRef enroute;
527   flightgear::SID* sid = NULL;
528   double d = 1e9;
529   
530   for (unsigned int i=0; i<mSIDs.size(); ++i) {
531     if (aRwy && !mSIDs[i]->isForRunway(aRwy)) {
532       continue;
533     }
534   
535     WayptRef e = mSIDs[i]->findBestTransition(aDest);
536     if (!e) {
537       continue; // strange, but let's not worry about it
538     }
539     
540     // assert(e->isFixedPosition());
541     double ed = SGGeodesy::distanceM(aDest, e->position());
542     if (ed < d) { // new best match
543       enroute = e;
544       d = ed;
545       sid = mSIDs[i];
546     }
547   } // of SID iteration
548   
549   if (!mSIDs.empty() && !sid) {
550     SG_LOG(SG_GENERAL, SG_INFO, ident() << "selectSID, no SID found (runway=" 
551       << (aRwy ? aRwy->ident() : "no runway preference"));
552   }
553   
554   return make_pair(sid, enroute);
555 }
556     
557 pair<STAR*, WayptRef>
558 FGAirport::selectSTAR(const SGGeod& aOrigin, FGRunway* aRwy)
559 {
560   loadProcedures();
561   
562   WayptRef enroute;
563   STAR* star = NULL;
564   double d = 1e9;
565   
566   for (unsigned int i=0; i<mSTARs.size(); ++i) {
567     if (!mSTARs[i]->isForRunway(aRwy)) {
568       continue;
569     }
570     
571     SG_LOG(SG_GENERAL, SG_INFO, "STAR " << mSTARs[i]->ident() << " is valid for runway");
572     WayptRef e = mSTARs[i]->findBestTransition(aOrigin);
573     if (!e) {
574       continue; // strange, but let's not worry about it
575     }
576     
577     // assert(e->isFixedPosition());
578     double ed = SGGeodesy::distanceM(aOrigin, e->position());
579     if (ed < d) { // new best match
580       enroute = e;
581       d = ed;
582       star = mSTARs[i];
583     }
584   } // of STAR iteration
585   
586   return make_pair(star, enroute);
587 }
588
589
590 void FGAirport::addSID(flightgear::SID* aSid)
591 {
592   mSIDs.push_back(aSid);
593 }
594
595 void FGAirport::addSTAR(STAR* aStar)
596 {
597   mSTARs.push_back(aStar);
598 }
599
600 void FGAirport::addApproach(Approach* aApp)
601 {
602   mApproaches.push_back(aApp);
603 }
604
605 unsigned int FGAirport::numSIDs() const
606 {
607   loadProcedures();
608   return mSIDs.size();
609 }
610
611 flightgear::SID* FGAirport::getSIDByIndex(unsigned int aIndex) const
612 {
613   loadProcedures();
614   return mSIDs[aIndex];
615 }
616
617 flightgear::SID* FGAirport::findSIDWithIdent(const std::string& aIdent) const
618 {
619   loadProcedures();
620   for (unsigned int i=0; i<mSIDs.size(); ++i) {
621     if (mSIDs[i]->ident() == aIdent) {
622       return mSIDs[i];
623     }
624   }
625   
626   return NULL;
627 }
628
629 unsigned int FGAirport::numSTARs() const
630 {
631   loadProcedures();
632   return mSTARs.size();
633 }
634
635 STAR* FGAirport::getSTARByIndex(unsigned int aIndex) const
636 {
637   loadProcedures();
638   return mSTARs[aIndex];
639 }
640
641 STAR* FGAirport::findSTARWithIdent(const std::string& aIdent) const
642 {
643   loadProcedures();
644   for (unsigned int i=0; i<mSTARs.size(); ++i) {
645     if (mSTARs[i]->ident() == aIdent) {
646       return mSTARs[i];
647     }
648   }
649   
650   return NULL;
651 }
652
653 unsigned int FGAirport::numApproaches() const
654 {
655   loadProcedures();
656   return mApproaches.size();
657 }
658
659 Approach* FGAirport::getApproachByIndex(unsigned int aIndex) const
660 {
661   loadProcedures();
662   return mApproaches[aIndex];
663 }
664
665 class AirportNodeListener : public SGPropertyChangeListener
666 {
667 public:
668     AirportNodeListener()
669     {
670         SGPropertyNode* airports = fgGetNode("/sim/airport");
671         airports->addChangeListener(this, false);
672     }
673
674     virtual void valueChanged(SGPropertyNode*)
675     {
676     }
677
678     virtual void childAdded(SGPropertyNode* pr, SGPropertyNode* child)
679     {
680        FGAirport* apt = FGAirport::findByIdent(child->getName());
681        if (!apt) {
682            return;
683        }
684        
685        flightgear::PositionedBinding::bind(apt, child);
686     }
687 };
688     
689 void FGAirport::installPropertyListener()
690 {
691     new AirportNodeListener;  
692 }
693
694 flightgear::PositionedBinding*
695 FGAirport::createBinding(SGPropertyNode* nd) const
696 {
697     return new flightgear::AirportBinding(this, nd);
698 }
699
700 void FGAirport::setCommStations(CommStationList& comms)
701 {
702     mCommStations.swap(comms);
703     for (unsigned int c=0; c<mCommStations.size(); ++c) {
704         mCommStations[c]->setAirport(this);
705     }
706 }
707
708 CommStationList
709 FGAirport::commStationsOfType(FGPositioned::Type aTy) const
710 {
711     CommStationList result;
712     for (unsigned int c=0; c<mCommStations.size(); ++c) {
713         if (mCommStations[c]->type() == aTy) {
714             result.push_back(mCommStations[c]);
715         }
716     }
717     return result;
718 }
719
720 // get airport elevation
721 double fgGetAirportElev( const string& id )
722 {
723     const FGAirport *a=fgFindAirportID( id);
724     if (a) {
725         return a->getElevation();
726     } else {
727         return -9999.0;
728     }
729 }
730
731
732 // get airport position
733 SGGeod fgGetAirportPos( const string& id )
734 {
735     const FGAirport *a = fgFindAirportID( id);
736
737     if (a) {
738         return SGGeod::fromDegM(a->getLongitude(), a->getLatitude(), a->getElevation());
739     } else {
740         return SGGeod::fromDegM(0.0, 0.0, -9999.0);
741     }
742 }