]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/positioned.cxx
e09f0da2c5c63800769885d415b2ccd65308a27d
[flightgear.git] / src / Navaids / positioned.cxx
1 // positioned.cxx - base class for objects which are positioned 
2 //
3 // Copyright (C) 2008 James Turner
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 // $Id$
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include <map>
26 #include <set>
27 #include <algorithm>
28
29 #include <simgear/math/sg_geodesy.hxx>
30
31 #include "positioned.hxx"
32
33 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
34 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
35
36 /**
37  * Order positioned elements by type, then pointer address. This allows us to
38  * use range searches (lower_ and upper_bound) to grab items of a particular
39  * type out of bucket efficently.
40  */
41 class OrderByType
42 {
43 public:
44   bool operator()(const FGPositioned* a, const FGPositioned* b) const
45   {
46     if (a->type() == b->type()) return a < b;
47     return a->type() < b->type();
48   }
49 };
50
51 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
52 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
53
54 static NamedPositionedIndex global_namedIndex;
55 static SpatialPositionedIndex global_spatialIndex;
56
57 SpatialPositionedIndex::iterator
58 bucketEntryForPositioned(FGPositioned* aPos)
59 {
60   int bucketIndex = aPos->bucket().gen_index();
61   SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
62   if (it != global_spatialIndex.end()) {
63     return it;
64   }
65   
66   // create a new BucketEntry
67   return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
68 }
69
70 static void
71 addToIndices(FGPositioned* aPos)
72 {
73   assert(aPos);
74   global_namedIndex.insert(global_namedIndex.begin(), 
75     std::make_pair(aPos->ident(), aPos));
76     
77   SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
78   it->second.insert(aPos);
79 }
80
81 static void
82 removeFromIndices(FGPositioned* aPos)
83 {
84   assert(aPos);
85   
86   NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
87   while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
88     if (it->second == aPos) {
89       global_namedIndex.erase(it);
90       break;
91     }
92     
93     ++it;
94   }
95   
96   SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
97   sit->second.erase(aPos);
98 }
99
100 static void
101 spatialFilterInBucket(const SGBucket& aBucket, const FGPositioned::Filter& aFilter, FGPositioned::List& aResult)
102 {
103   SpatialPositionedIndex::const_iterator it;
104   it = global_spatialIndex.find(aBucket.gen_index());
105   if (it == global_spatialIndex.end()) {
106     return;
107   }
108   
109   BucketEntry::const_iterator l = it->second.begin();
110   BucketEntry::const_iterator u = it->second.end();
111
112   for ( ; l != u; ++l) {
113     if (aFilter(*l)) {
114       aResult.push_back(*l);
115     }
116   }
117 }
118
119 static void
120 spatialFind(const SGGeod& aPos, double aRange, 
121   const FGPositioned::Filter& aFilter, FGPositioned::List& aResult)
122 {
123   SGBucket buck(aPos);
124   double lat = aPos.getLatitudeDeg(),
125     lon = aPos.getLongitudeDeg();
126   
127   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
128   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
129     
130   // loop over bucket range 
131   for ( int i=-bx; i<=bx; i++) {
132     for ( int j=-by; j<=by; j++) {
133       spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
134     } // of j-iteration
135   } // of i-iteration  
136 }
137
138 class LowerLimitOfType
139 {
140 public:
141   bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
142   {
143     return a->type() < b;
144   }
145   
146   bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
147   {
148     return a < b->type();
149   }
150 };
151
152 static void
153 spatialFindTyped(const SGGeod& aPos, double aRange, FGPositioned::Type aLower, FGPositioned::Type aUpper, FGPositioned::List& aResult)
154 {
155   SGBucket buck(aPos);
156   double lat = aPos.getLatitudeDeg(),
157     lon = aPos.getLongitudeDeg();
158   
159   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
160   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
161     
162   // loop over bucket range 
163   for ( int i=-bx; i<=bx; i++) {
164     for ( int j=-by; j<=by; j++) {
165       buck = sgBucketOffset(lon, lat, i, j);
166       
167       SpatialPositionedIndex::const_iterator it;
168       it = global_spatialIndex.find(buck.gen_index());
169       if (it == global_spatialIndex.end()) {
170         continue;
171       }
172       
173       BucketEntry::const_iterator l = std::lower_bound(it->second.begin(), it->second.end(), aLower, LowerLimitOfType());
174       BucketEntry::const_iterator u = std::upper_bound(l, it->second.end(), aUpper, LowerLimitOfType());
175       
176       for ( ; l != u; ++l) {
177         aResult.push_back(*l);
178       }
179       
180     } // of j-iteration
181   } // of i-iteration  
182 }
183
184 /**
185  */
186 class RangePredictate
187 {
188 public:
189   RangePredictate(const SGGeod& aOrigin, double aRange) :
190     mOrigin(aOrigin),
191     mRange(aRange)
192   { ; }
193   
194   bool operator()(const FGPositionedRef& aPos)
195   {
196     double d, az1, az2;
197     SGGeodesy::inverse(aPos->geod(), mOrigin, az1, az2, d);
198     return (d > mRange);
199   }
200   
201 private:
202   SGGeod mOrigin;
203   double mRange;
204 };
205
206 static void
207 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
208 {
209   RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
210   FGPositioned::List::iterator newEnd; 
211   newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
212   aResult.erase(newEnd, aResult.end());
213 }
214
215 class DistanceOrdering
216 {
217 public:
218   DistanceOrdering(const SGGeod& aPos) :
219     mPos(aPos)
220   { }
221   
222   bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
223   {
224     double dA, dB, az1, az2;
225     SGGeodesy::inverse(mPos, a->geod(), az1, az2, dA);
226     SGGeodesy::inverse(mPos, b->geod(), az1, az2, dB);
227     return dA < dB;
228   }
229
230 private:
231   SGGeod mPos;
232 };
233
234 static void
235 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
236 {
237   std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
238 }
239
240 static FGPositionedRef
241 namedFindClosestTyped(const std::string& aIdent, const SGGeod& aOrigin, 
242   FGPositioned::Type aLower, FGPositioned::Type aUpper)
243 {
244   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
245   if (range.first == range.second) {
246     return NULL;
247   }
248   
249 // common case, only one result. looks a bit ugly because these are
250 // sequential iterators, not random-access ones
251   NamedPositionedIndex::const_iterator check = range.first;
252   if (++check == range.second) {
253     // excellent, only one match in the range - all we care about is the type
254     FGPositioned::Type ty = range.first->second->type();
255     if ((ty < aLower) || (ty > aUpper)) {
256       return NULL; // type check failed
257     }
258     
259     return range.first->second;
260   } // of short-circuit logic for single-element range
261   
262 // multiple matches, we need to actually check the distance to each one
263   double minDist = HUGE_VAL;
264   FGPositionedRef result;
265   NamedPositionedIndex::const_iterator it = range.first;
266     
267   for (; it != range.second; ++it) {
268   // filter by type
269     FGPositioned::Type ty = it->second->type();
270     if ((ty < aLower) || (ty > aUpper)) {
271       continue;
272     }
273     
274   // find distance
275     double d, az1, az2;
276     SGGeodesy::inverse(aOrigin, it->second->geod(), az2, az2, d);
277     if (d < minDist) {
278       minDist = d;
279       result = it->second;
280     }
281   }
282   
283   return result;
284 }
285
286 static FGPositioned::List
287 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, const FGPositioned::Filter& aFilter)
288 {
289   FGPositioned::List result;
290   int radius = 1; // start at 1, radius 0 is handled explicitly
291   SGBucket buck;
292   double lat = aPos.getLatitudeDeg(),
293     lon = aPos.getLongitudeDeg();
294   // final cutoff is in metres, and scaled to account for testing the corners
295   // of the 'box' instead of the centre of each edge
296   double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
297   
298   // base case, simplifes loop to do it seperately here
299   spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
300
301   for (;result.size() < aN; ++radius) {
302     // cutoff check
303     double az1, az2, d1, d2;
304     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
305     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);  
306       
307     if ((d1 > cutoffM) && (d2 > cutoffM)) {
308       //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
309       break;
310     }
311     
312     FGPositioned::List hits;
313     for ( int i=-radius; i<=radius; i++) {
314       spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
315       spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
316       spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
317       spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
318     }
319
320     result.insert(result.end(), hits.begin(), hits.end()); // append
321   } // of outer loop
322   
323   if (result.size() > aN) {
324     result.resize(aN); // truncate at requested number of matches
325   }
326   
327   sortByDistance(aPos, result);
328   return result;
329 }
330
331 ///////////////////////////////////////////////////////////////////////////////
332
333 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, double aLat, double aLon, double aElev) :
334   mType(ty),
335   mPosition(SGGeod::fromDegFt(aLon, aLat, aElev)),
336   mIdent(aIdent)
337 {
338   addToIndices(this);
339   SGReferenced::get(this); // hold an owning ref, for the moment
340 }
341
342 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos) :
343   mType(ty),
344   mPosition(aPos),
345   mIdent(aIdent)
346 {
347   addToIndices(this);
348   SGReferenced::get(this); // hold an owning ref, for the moment
349 }
350
351 FGPositioned::~FGPositioned()
352 {
353   removeFromIndices(this);
354 }
355
356 SGBucket
357 FGPositioned::bucket() const
358 {
359   return SGBucket(mPosition);
360 }
361
362 const char* FGPositioned::nameForType(Type aTy)
363 {
364  switch (aTy) {
365  case FIX: return "fix";
366  case VOR: return "VOR";
367  case NDB: return "NDB";
368  case OM: return "outer-marker";
369  case MM: return "middle-marker";
370  case IM: return "inner-marker";
371  case AIRPORT: return "airport";
372  case HELIPORT: return "heliport";
373  case SEAPORT: return "seaport";
374  case WAYPOINT: return "waypoint";
375  default:
376   return "unknown";
377  }
378 }
379
380 ///////////////////////////////////////////////////////////////////////////////
381 // search / query functions
382
383 FGPositionedRef
384 FGPositioned::findClosestWithIdent(const std::string& aIdent, double aLat, double aLon)
385 {
386   return findClosestWithIdent(aIdent, SGGeod::fromDeg(aLon, aLat));
387 }
388
389 FGPositionedRef
390 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos)
391 {
392   return namedFindClosestTyped(aIdent, aPos, INVALID, LAST_TYPE);
393 }
394
395 FGPositioned::List
396 FGPositioned::findWithinRangeByType(const SGGeod& aPos, double aRangeNm, Type aTy)
397 {
398   List result;
399   spatialFindTyped(aPos, aRangeNm, aTy, aTy, result);
400   filterListByRange(aPos, aRangeNm, result);
401   return result;
402 }
403
404 FGPositioned::List
405 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, const Filter& aFilter)
406 {
407   List result;
408   spatialFind(aPos, aRangeNm, aFilter, result);
409   filterListByRange(aPos, aRangeNm, result);
410   return result;
411 }
412
413 FGPositioned::List
414 FGPositioned::findAllWithIdent(const std::string& aIdent)
415 {
416   List result;
417   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
418   for (; range.first != range.second; ++range.first) {
419     result.push_back(range.first->second);
420   }
421   
422   return result;
423 }
424
425 FGPositioned::List
426 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, const Filter& aFilter)
427 {
428   return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
429 }
430