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