]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/airways.cxx
Whoops, work-around for #926 correctly.
[flightgear.git] / src / Navaids / airways.cxx
1 // airways.cxx - storage of airways network, and routing between nodes
2 // Written by James Turner, started 2009.
3 //
4 // Copyright (C) 2009  Curtis L. Olson
5 //
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19
20 #ifndef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 #include "airways.hxx"
25
26 #include <algorithm>
27 #include <set>
28
29 #include <simgear/sg_inlines.h>
30 #include <simgear/structure/exception.hxx>
31 #include <simgear/misc/sgstream.hxx>
32 #include <simgear/misc/sg_path.hxx>
33
34 #include <boost/foreach.hpp>
35 #include <boost/tuple/tuple.hpp>
36
37 #include <Main/globals.hxx>
38 #include <Navaids/positioned.hxx>
39 #include <Navaids/waypoint.hxx>
40 #include <Navaids/NavDataCache.hxx>
41
42 using std::make_pair;
43 using std::string;
44 using std::set;
45 using std::vector;
46
47 //#define DEBUG_AWY_SEARCH 1
48
49 namespace flightgear
50 {
51
52 //////////////////////////////////////////////////////////////////////////////
53
54 class AStarOpenNode : public SGReferenced
55 {
56 public:
57   AStarOpenNode(FGPositionedRef aNode, double aLegDist, 
58     int aAirway,
59     FGPositionedRef aDest, AStarOpenNode* aPrev) :
60     node(aNode),
61     airway(aAirway),
62     previous(aPrev)
63   { 
64     distanceFromStart = aLegDist;
65     if (previous) {
66       distanceFromStart +=  previous->distanceFromStart;
67     }
68     
69                 directDistanceToDestination = SGGeodesy::distanceM(node->geod(), aDest->geod());
70   }
71   
72   virtual ~AStarOpenNode()
73   {
74   }
75   
76   FGPositionedRef node;
77   int airway;
78   SGSharedPtr<AStarOpenNode> previous;
79   double distanceFromStart; // aka 'g(x)'
80   double directDistanceToDestination; // aka 'h(x)'
81   
82   /**
83          * aka 'f(x)'
84          */
85         double totalCost() const {
86                 return distanceFromStart + directDistanceToDestination;
87         }
88 };
89
90 typedef SGSharedPtr<AStarOpenNode> AStarOpenNodeRef;
91
92 ////////////////////////////////////////////////////////////////////////////
93
94 Airway::Network* Airway::lowLevel()
95 {
96   static Network* static_lowLevel = NULL;
97   
98   if (!static_lowLevel) {
99     static_lowLevel = new Network;
100     static_lowLevel->_networkID = 1;
101   }
102   
103   return static_lowLevel;
104 }
105
106 Airway::Network* Airway::highLevel()
107 {
108   static Network* static_highLevel = NULL;
109   if (!static_highLevel) {
110     static_highLevel = new Network;
111     static_highLevel->_networkID = 2;
112   }
113   
114   return static_highLevel;
115 }
116
117 Airway::Airway(const std::string& aIdent, double aTop, double aBottom) :
118   _ident(aIdent),
119   _topAltitudeFt(aTop),
120   _bottomAltitudeFt(aBottom)
121 {
122 }
123
124 void Airway::load(const SGPath& path)
125 {
126   std::string identStart, identEnd, name;
127   double latStart, lonStart, latEnd, lonEnd;
128   int type, base, top;
129   //int airwayIndex = 0;
130   //FGNode *n;
131
132   sg_gzifstream in( path.str() );
133   if ( !in.is_open() ) {
134     SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path.str() );
135     throw sg_io_exception("Could not open airways data", sg_location(path.str()));
136   }
137 // toss the first two lines of the file
138   in >> skipeol;
139   in >> skipeol;
140
141 // read in each remaining line of the file
142   while (!in.eof()) {
143     in >> identStart;
144
145     if (identStart == "99") {
146       break;
147     }
148     
149     in >> latStart >> lonStart >> identEnd >> latEnd >> lonEnd >> type >> base >> top >> name;
150     in >> skipeol;
151
152     // type = 1; low-altitude
153     // type = 2; high-altitude
154     Network* net = (type == 1) ? lowLevel() : highLevel();
155   
156     SGGeod startPos(SGGeod::fromDeg(lonStart, latStart)),
157       endPos(SGGeod::fromDeg(lonEnd, latEnd));
158     
159     int awy = net->findAirway(name, top, base);
160     net->addEdge(awy, startPos, identStart, endPos, identEnd);
161   } // of file line iteration
162 }
163
164 int Airway::Network::findAirway(const std::string& aName, double aTop, double aBase)
165 {
166   return NavDataCache::instance()->findAirway(_networkID, aName);
167 }
168
169 void Airway::Network::addEdge(int aWay, const SGGeod& aStartPos,
170   const std::string& aStartIdent, 
171   const SGGeod& aEndPos, const std::string& aEndIdent)
172 {
173   FGPositionedRef start = FGPositioned::findClosestWithIdent(aStartIdent, aStartPos);
174   FGPositionedRef end = FGPositioned::findClosestWithIdent(aEndIdent, aEndPos);
175     
176   if (!start) {
177     SG_LOG(SG_NAVAID, SG_DEBUG, "unknown airways start pt: '" << aStartIdent << "'");
178     start = FGPositioned::createUserWaypoint(aStartIdent, aStartPos);
179     return;
180   }
181   
182   if (!end) {
183     SG_LOG(SG_NAVAID, SG_DEBUG, "unknown airways end pt: '" << aEndIdent << "'");
184     end = FGPositioned::createUserWaypoint(aEndIdent, aEndPos);
185     return;
186   }
187   
188   NavDataCache::instance()->insertEdge(_networkID, aWay, start->guid(), end->guid());
189 }
190
191 //////////////////////////////////////////////////////////////////////////////
192
193 bool Airway::Network::inNetwork(PositionedID posID) const
194 {
195   NetworkMembershipDict::iterator it = _inNetworkCache.find(posID);
196   if (it != _inNetworkCache.end()) {
197     return it->second; // cached, easy
198   }
199   
200   bool r =  NavDataCache::instance()->isInAirwayNetwork(_networkID, posID);
201   _inNetworkCache.insert(it, std::make_pair(posID, r));
202   return r;
203 }
204
205 bool Airway::Network::route(WayptRef aFrom, WayptRef aTo, 
206   WayptVec& aPath)
207 {
208   if (!aFrom || !aTo) {
209     throw sg_exception("invalid waypoints to route between");
210   }
211   
212 // find closest nodes on the graph to from/to
213 // if argument waypoints are directly on the graph (which is frequently the
214 // case), note this so we don't duplicate them in the output.
215
216   FGPositionedRef from, to;
217   bool exactTo, exactFrom;
218   boost::tie(from, exactFrom) = findClosestNode(aFrom);
219   boost::tie(to, exactTo) = findClosestNode(aTo);
220   
221 #ifdef DEBUG_AWY_SEARCH
222   SG_LOG(SG_NAVAID, SG_INFO, "from:" << from->ident() << "/" << from->name());
223   SG_LOG(SG_NAVAID, SG_INFO, "to:" << to->ident() << "/" << to->name());
224 #endif
225
226   bool ok = search2(from, to, aPath);
227   if (!ok) {
228     return false;
229   }
230   
231   if (exactTo) {
232     aPath.pop_back();
233   }
234   
235   if (exactFrom) {
236     // edge case - if from and to are equal, which can happen, don't
237     // crash here. This happens routing EGPH -> EGCC; 'DCS' is common
238     // to the EGPH departure and EGCC STAR.
239     if (!aPath.empty()) {
240       aPath.erase(aPath.begin());
241     }
242   }
243   
244   return true;
245 }
246
247 std::pair<FGPositionedRef, bool> 
248 Airway::Network::findClosestNode(WayptRef aRef)
249 {
250   return findClosestNode(aRef->position());
251 }
252
253 class InAirwayFilter : public FGPositioned::Filter
254 {
255 public:
256   InAirwayFilter(Airway::Network* aNet) :
257     _net(aNet)
258   { ; }
259   
260   virtual bool pass(FGPositioned* aPos) const
261   {
262     return _net->inNetwork(aPos->guid());
263   }
264   
265   virtual FGPositioned::Type minType() const
266   { return FGPositioned::WAYPOINT; }
267   
268   virtual FGPositioned::Type maxType() const
269   { return FGPositioned::NDB; }
270   
271 private:
272   Airway::Network* _net;
273 };
274
275 std::pair<FGPositionedRef, bool> 
276 Airway::Network::findClosestNode(const SGGeod& aGeod)
277 {
278   InAirwayFilter f(this);
279   FGPositionedRef r = FGPositioned::findClosest(aGeod, 800.0, &f);
280   bool exact = false;
281   
282   if (r && (SGGeodesy::distanceM(aGeod, r->geod()) < 100.0)) {
283     exact = true; // within 100 metres, let's call that exact
284   }
285   
286   return make_pair(r, exact);
287 }
288
289 /////////////////////////////////////////////////////////////////////////////
290
291 typedef vector<AStarOpenNodeRef> OpenNodeHeap;
292
293 static void buildWaypoints(AStarOpenNodeRef aNode, WayptVec& aRoute)
294 {
295 // count the route length, and hence pre-size aRoute
296   int count = 0;
297   AStarOpenNodeRef n = aNode;
298   for (; n != NULL; ++count, n = n->previous) {;}
299   aRoute.resize(count);
300   
301 // run over the route, creating waypoints
302   for (n = aNode; n; n=n->previous) {
303     aRoute[--count] = new NavaidWaypoint(n->node, NULL);
304   }
305 }
306
307 /**
308  * Inefficent (linear) helper to find an open node in the heap
309  */
310 static AStarOpenNodeRef
311 findInOpen(const OpenNodeHeap& aHeap, FGPositioned* aPos)
312 {
313   for (unsigned int i=0; i<aHeap.size(); ++i) {
314     if (aHeap[i]->node == aPos) {
315       return aHeap[i];
316     }
317   }
318   
319   return NULL;
320 }
321
322 class HeapOrder
323 {
324 public:
325   bool operator()(AStarOpenNode* a, AStarOpenNode* b)
326   {
327     return a->totalCost() > b->totalCost();
328   }
329 };
330
331 bool Airway::Network::search2(FGPositionedRef aStart, FGPositionedRef aDest,
332   WayptVec& aRoute)
333 {  
334   typedef set<PositionedID> ClosedNodeSet;
335   
336   OpenNodeHeap openNodes;
337   ClosedNodeSet closedNodes;
338   HeapOrder ordering;
339   
340   openNodes.push_back(new AStarOpenNode(aStart, 0.0, 0, aDest, NULL));
341   
342 // A* open node iteration
343   while (!openNodes.empty()) {
344     std::pop_heap(openNodes.begin(), openNodes.end(), ordering);
345     AStarOpenNodeRef x = openNodes.back();
346     FGPositioned* xp = x->node;    
347     openNodes.pop_back();
348     closedNodes.insert(xp->guid());
349   
350 #ifdef DEBUG_AWY_SEARCH
351     SG_LOG(SG_NAVAID, SG_INFO, "x:" << xp->ident() << ", f(x)=" << x->totalCost());
352 #endif
353     
354   // check if xp is the goal; if so we're done, since there cannot be an open
355   // node with lower f(x) value.
356     if (xp == aDest) {
357       buildWaypoints(x, aRoute);
358       return true;
359     }
360     
361   // adjacent (neighbour) iteration
362     NavDataCache* cache = NavDataCache::instance();
363     BOOST_FOREACH(AirwayEdge other, cache->airwayEdgesFrom(_networkID, xp->guid())) {
364       if (closedNodes.count(other.second)) {
365         continue; // closed, ignore
366       }
367
368       FGPositioned* yp = cache->loadById(other.second);
369       double edgeDistanceM = SGGeodesy::distanceM(xp->geod(), yp->geod());
370       AStarOpenNodeRef y = findInOpen(openNodes, yp);
371       if (y) { // already open
372         double g = x->distanceFromStart + edgeDistanceM;
373         if (g > y->distanceFromStart) {
374           // worse path, ignore
375 #ifdef DEBUG_AWY_SEARCH
376           SG_LOG(SG_NAVAID, SG_INFO, "\tabandoning " << yp->ident() <<
377            " path is worse: g(y)" << y->distanceFromStart << ", g'=" << g);
378 #endif
379           continue;
380         }
381         
382       // we need to update y. Unfortunately this means rebuilding the heap,
383       // since y's score can change arbitrarily
384 #ifdef DEBUG_AWY_SEARCH
385         SG_LOG(SG_NAVAID, SG_INFO, "\tfixing up previous for new path to " << yp->ident() << ", d =" << g);
386 #endif
387         y->previous = x;
388         y->distanceFromStart = g;
389         y->airway = other.first;
390         std::make_heap(openNodes.begin(), openNodes.end(), ordering);
391       } else { // not open, insert a new node for y into the heap
392         y = new AStarOpenNode(yp, edgeDistanceM, other.first, aDest, x);
393 #ifdef DEBUG_AWY_SEARCH
394         SG_LOG(SG_NAVAID, SG_INFO, "\ty=" << yp->ident() << ", f(y)=" << y->totalCost());
395 #endif
396         openNodes.push_back(y);
397         std::push_heap(openNodes.begin(), openNodes.end(), ordering);
398       }
399     } // of neighbour iteration
400   } // of open node iteration
401   
402   SG_LOG(SG_NAVAID, SG_INFO, "A* failed to find route");
403   return false;
404 }
405
406 } // of namespace flightgear