]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/positioned.cxx
37445073976cb4b0c7576d709ff13e169b492668
[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> // for sort
28 #include <locale> // for char-traits toupper
29
30 #include <iostream>
31
32 #include <simgear/math/sg_geodesy.hxx>
33
34 #include "positioned.hxx"
35
36 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
37 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
38
39 /**
40  * Order positioned elements by type, then pointer address. This allows us to
41  * use range searches (lower_ and upper_bound) to grab items of a particular
42  * type out of bucket efficently.
43  */
44 class OrderByType
45 {
46 public:
47   bool operator()(const FGPositioned* a, const FGPositioned* b) const
48   {
49     if (a->type() == b->type()) return a < b;
50     return a->type() < b->type();
51   }
52 };
53
54 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
55 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
56
57 static NamedPositionedIndex global_namedIndex;
58 static SpatialPositionedIndex global_spatialIndex;
59
60 SpatialPositionedIndex::iterator
61 bucketEntryForPositioned(FGPositioned* aPos)
62 {
63   int bucketIndex = aPos->bucket().gen_index();
64   SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
65   if (it != global_spatialIndex.end()) {
66     return it;
67   }
68   
69   // create a new BucketEntry
70   return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
71 }
72
73 static void
74 addToIndices(FGPositioned* aPos)
75 {
76   assert(aPos);
77   if (!aPos->ident().empty()) {
78     global_namedIndex.insert(global_namedIndex.begin(), 
79       std::make_pair(aPos->ident(), aPos));
80   }
81     
82   SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
83   it->second.insert(aPos);
84 }
85
86 static void
87 removeFromIndices(FGPositioned* aPos)
88 {
89   assert(aPos);
90   
91   if (!aPos->ident().empty()) {
92     NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
93     while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
94       if (it->second == aPos) {
95         global_namedIndex.erase(it);
96         break;
97       }
98       
99       ++it;
100     } // of multimap walk
101   }
102   
103   SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
104   sit->second.erase(aPos);
105 }
106
107 static void
108 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
109 {
110   SpatialPositionedIndex::const_iterator it;
111   it = global_spatialIndex.find(aBucket.gen_index());
112   if (it == global_spatialIndex.end()) {
113     return;
114   }
115   
116   BucketEntry::const_iterator l = it->second.begin();
117   BucketEntry::const_iterator u = it->second.end();
118
119   if (!aFilter) { // pass everything
120     aResult.insert(aResult.end(), l, u);
121     return;
122   }
123
124   for ( ; l != u; ++l) {
125     if ((*aFilter)(*l)) {
126       aResult.push_back(*l);
127     }
128   }
129 }
130
131 static void
132 spatialFind(const SGGeod& aPos, double aRange, 
133   FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
134 {
135   SGBucket buck(aPos);
136   double lat = aPos.getLatitudeDeg(),
137     lon = aPos.getLongitudeDeg();
138   
139   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
140   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
141     
142   // loop over bucket range 
143   for ( int i=-bx; i<=bx; i++) {
144     for ( int j=-by; j<=by; j++) {
145       spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
146     } // of j-iteration
147   } // of i-iteration  
148 }
149
150 /*
151 class LowerLimitOfType
152 {
153 public:
154   bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
155   {
156     return a->type() < b;
157   }
158   
159   bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
160   {
161     return a < b->type();
162   }
163 };
164
165
166 static void
167 spatialFindTyped(const SGGeod& aPos, double aRange, FGPositioned::Type aLower, FGPositioned::Type aUpper, FGPositioned::List& aResult)
168 {
169   SGBucket buck(aPos);
170   double lat = aPos.getLatitudeDeg(),
171     lon = aPos.getLongitudeDeg();
172   
173   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
174   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
175     
176   // loop over bucket range 
177   for ( int i=-bx; i<=bx; i++) {
178     for ( int j=-by; j<=by; j++) {
179       buck = sgBucketOffset(lon, lat, i, j);
180       
181       SpatialPositionedIndex::const_iterator it;
182       it = global_spatialIndex.find(buck.gen_index());
183       if (it == global_spatialIndex.end()) {
184         continue;
185       }
186       
187       BucketEntry::const_iterator l = std::lower_bound(it->second.begin(), it->second.end(), aLower, LowerLimitOfType());
188       BucketEntry::const_iterator u = std::upper_bound(l, it->second.end(), aUpper, LowerLimitOfType());
189       
190       for ( ; l != u; ++l) {
191         aResult.push_back(*l);
192       }
193       
194     } // of j-iteration
195   } // of i-iteration  
196 }
197 */
198
199 /**
200  */
201 class RangePredictate
202 {
203 public:
204   RangePredictate(const SGGeod& aOrigin, double aRange) :
205     mOrigin(SGVec3d::fromGeod(aOrigin)),
206     mRangeSqr(aRange * aRange)
207   { ; }
208   
209   bool operator()(const FGPositionedRef& aPos)
210   {
211     double dSqr = distSqr(aPos->cart(), mOrigin);
212     return (dSqr > mRangeSqr);
213   }
214   
215 private:
216   SGVec3d mOrigin;
217   double mRangeSqr;
218 };
219
220 static void
221 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
222 {
223   RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
224   FGPositioned::List::iterator newEnd; 
225   newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
226   aResult.erase(newEnd, aResult.end());
227 }
228
229 class DistanceOrdering
230 {
231 public:
232   DistanceOrdering(const SGGeod& aPos) :
233     mPos(SGVec3d::fromGeod(aPos))
234   { }
235   
236   bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
237   {
238     double dA = distSqr(a->cart(), mPos),
239       dB = distSqr(b->cart(), mPos);
240     return dA < dB;
241   }
242
243 private:
244   SGVec3d mPos;
245 };
246
247 static void
248 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
249 {
250   std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
251 }
252
253 static FGPositionedRef
254 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
255 {
256   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
257   if (range.first == range.second) {
258     return NULL;
259   }
260   
261 // common case, only one result. looks a bit ugly because these are
262 // sequential iterators, not random-access ones
263   NamedPositionedIndex::const_iterator check = range.first;
264   if (++check == range.second) {
265     // excellent, only one match in the range - all we care about is the type
266     if (aFilter && !aFilter->pass(range.first->second)) {
267       return NULL; // type check failed
268     }
269     
270     return range.first->second;
271   } // of short-circuit logic for single-element range
272   
273 // multiple matches, we need to actually check the distance to each one
274   double minDist = HUGE_VAL;
275   FGPositionedRef result;
276   NamedPositionedIndex::const_iterator it = range.first;
277   SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
278   
279   for (; it != range.second; ++it) {
280     if (aFilter && !aFilter->pass(range.first->second)) {
281       continue;
282     }
283     
284   // find distance
285     double d2 = distSqr(cartOrigin, it->second->cart());
286     if (d2 < minDist) {
287       minDist = d2;
288       result = it->second;
289     }
290   }
291   
292   return result;
293 }
294
295 static FGPositioned::List
296 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
297 {
298   FGPositioned::List result;
299   int radius = 1; // start at 1, radius 0 is handled explicitly
300   SGBucket buck;
301   double lat = aPos.getLatitudeDeg(),
302     lon = aPos.getLongitudeDeg();
303   // final cutoff is in metres, and scaled to account for testing the corners
304   // of the 'box' instead of the centre of each edge
305   double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
306   
307   // base case, simplifes loop to do it seperately here
308   spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
309
310   for (;result.size() < aN; ++radius) {
311     // cutoff check
312     double az1, az2, d1, d2;
313     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
314     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);  
315       
316     if ((d1 > cutoffM) && (d2 > cutoffM)) {
317       //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
318       break;
319     }
320     
321     FGPositioned::List hits;
322     for ( int i=-radius; i<=radius; i++) {
323       spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
324       spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
325       spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
326       spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
327     }
328
329     result.insert(result.end(), hits.begin(), hits.end()); // append
330   } // of outer loop
331   
332   sortByDistance(aPos, result);
333   if (result.size() > aN) {
334     result.resize(aN); // truncate at requested number of matches
335   }
336   
337   return result;
338 }
339
340 //////////////////////////////////////////////////////////////////////////////
341
342 /**
343  * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
344  * implement the AirportList dialog. It's unfortunate that it needs to reside
345  * here, but for now it's least ugly solution.
346  */
347 char** searchAirportNamesAndIdents(const std::string& aFilter)
348 {
349   const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
350   std::string filter(aFilter);
351   if (!filter.empty()) {
352     ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
353   }
354   
355   NamedPositionedIndex::const_iterator it = global_namedIndex.begin();
356   NamedPositionedIndex::const_iterator end = global_namedIndex.end();
357   
358   FGPositioned::List matches;
359   if (aFilter.empty()) {
360     matches.reserve(2000);
361   }
362   
363   for (; it != end; ++it) {
364     FGPositioned::Type ty = it->second->type();
365     if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
366       continue;
367     }
368     
369     if (aFilter.empty()) {
370       matches.push_back(it->second);
371       continue;
372     }
373     
374     if ((it->second->name().find(aFilter) == std::string::npos) &&
375         (it->second->ident().find(aFilter) == std::string::npos)) {
376       continue;
377     }
378     
379     matches.push_back(it->second);
380   }
381   
382   // convert results to format comptible with puaList
383   unsigned int numMatches = matches.size();
384   char** result = new char*[numMatches + 1];
385   result[numMatches] = NULL; // end-of-list marker
386   
387   // nasty code to avoid excessive string copying and allocations.
388   // We format results as follows (note whitespace!):
389   //   ' name-of-airport-chars   (icao)'
390   // so the total length is:
391   //    1 + strlen(name) + 4 + 4 (for the ICAO) + 1 + 1 (for the null)
392   // which gives a grand total of 11 + the length of the name.
393   
394   for (unsigned int i=0; i<numMatches; ++i) {
395     int nameLength = matches[i]->name().size();
396     char* entry = new char[nameLength + 11];
397     entry[0] = ' ';
398     memcpy(entry + 1, matches[i]->name().c_str(), nameLength);
399     entry[nameLength + 1] = ' ';
400     entry[nameLength + 2] = ' ';
401     entry[nameLength + 3] = ' ';
402     entry[nameLength + 4] = '(';
403     memcpy(entry + nameLength + 5, matches[i]->ident().c_str(), 4);
404     entry[nameLength + 9] = ')';
405     entry[nameLength + 10] = 0;
406     result[i] = entry;
407   }
408   
409   return result;
410 }
411
412 ///////////////////////////////////////////////////////////////////////////////
413
414 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
415   mType(ty),
416   mPosition(aPos),
417   mIdent(aIdent)
418 {  
419   SGReferenced::get(this); // hold an owning ref, for the moment
420   
421   if (aIndexed) {
422     assert(ty != TAXIWAY);
423     addToIndices(this);
424   }
425 }
426
427 FGPositioned::~FGPositioned()
428 {
429   //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
430   removeFromIndices(this);
431 }
432
433 SGBucket
434 FGPositioned::bucket() const
435 {
436   return SGBucket(mPosition);
437 }
438
439 SGVec3d
440 FGPositioned::cart() const
441 {
442   return SGVec3d::fromGeod(mPosition);
443 }
444
445 const char* FGPositioned::nameForType(Type aTy)
446 {
447  switch (aTy) {
448  case RUNWAY: return "runway";
449  case TAXIWAY: return "taxiway";
450  case PARK_STAND: return "parking stand";
451  case FIX: return "fix";
452  case VOR: return "VOR";
453  case NDB: return "NDB";
454  case ILS: return "ILS";
455  case LOC: return "localiser";
456  case GS: return "glideslope";
457  case OM: return "outer-marker";
458  case MM: return "middle-marker";
459  case IM: return "inner-marker";
460  case AIRPORT: return "airport";
461  case HELIPORT: return "heliport";
462  case SEAPORT: return "seaport";
463  case WAYPOINT: return "waypoint";
464  case DME: return "dme";
465  case TACAN: return "tacan";
466  default:
467   return "unknown";
468  }
469 }
470
471 ///////////////////////////////////////////////////////////////////////////////
472 // search / query functions
473
474 FGPositionedRef
475 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
476 {
477   return namedFindClosest(aIdent, aPos, aFilter);
478 }
479
480 FGPositioned::List
481 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
482 {
483   List result;
484   spatialFind(aPos, aRangeNm, aFilter, result);
485   filterListByRange(aPos, aRangeNm, result);
486   return result;
487 }
488
489 FGPositioned::List
490 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
491 {
492   List result;
493   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
494   for (; range.first != range.second; ++range.first) {
495     if (aFilter && !aFilter->pass(range.first->second)) {
496       continue;
497     }
498     
499     result.push_back(range.first->second);
500   }
501   
502   sortByDistance(aPos, result);
503   return result;
504 }
505
506 FGPositionedRef
507 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
508 {
509    FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
510    if (l.empty()) {
511       return NULL;
512    }
513    
514    assert(l.size() == 1);
515    return l.front();
516 }
517
518 FGPositioned::List
519 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
520 {
521   return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
522 }
523
524 FGPositionedRef
525 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
526 {
527   NamedIndexRange range = global_namedIndex.equal_range(aId);
528   for (; range.first != range.second; ++range.first) {
529     FGPositionedRef candidate = range.first->second;
530     if (aCur == candidate) {
531       aCur = NULL; // found our start point, next match will pass
532       continue;
533     }
534     
535     if (aFilter && !aFilter->pass(candidate)) {
536       continue;
537     }
538   
539     if (!aCur) {
540       return candidate;
541     }
542   }
543   
544   return NULL; // fell out, no match in range
545 }
546