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