]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/positioned.cxx
93204670b22dbb77e02af1a1c9cb0e1852997421
[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 #include <simgear/timing/timestamp.hxx>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/misc/strutils.hxx>
36
37 #include "positioned.hxx"
38
39 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
40 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
41
42 using std::lower_bound;
43 using std::upper_bound;
44
45 /**
46  * Order positioned elements by type, then pointer address. This allows us to
47  * use range searches (lower_ and upper_bound) to grab items of a particular
48  * type out of bucket efficently.
49  */
50 class OrderByType
51 {
52 public:
53   bool operator()(const FGPositioned* a, const FGPositioned* b) const
54   {
55     if (a->type() == b->type()) return a < b;
56     return a->type() < b->type();
57   }
58 };
59
60 class LowerLimitOfType
61 {
62 public:
63   bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
64   {
65     return a->type() < b;
66   }
67
68   bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
69   {
70     return a < b->type();
71   }
72
73   // The operator below is required by VS2005 in debug mode
74   bool operator()(const FGPositioned* a, const FGPositioned* b) const
75   {
76     return a->type() < b->type();
77   }
78 };
79
80
81 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
82 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
83
84 static NamedPositionedIndex global_namedIndex;
85 static SpatialPositionedIndex global_spatialIndex;
86
87 SpatialPositionedIndex::iterator
88 bucketEntryForPositioned(FGPositioned* aPos)
89 {
90   int bucketIndex = aPos->bucket().gen_index();
91   SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
92   if (it != global_spatialIndex.end()) {
93     return it;
94   }
95   
96   // create a new BucketEntry
97   return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
98 }
99
100 static void
101 addToIndices(FGPositioned* aPos)
102 {
103   assert(aPos);
104   if (!aPos->ident().empty()) {
105     global_namedIndex.insert(global_namedIndex.begin(), 
106       std::make_pair(aPos->ident(), aPos));
107   }
108     
109   SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
110   it->second.insert(aPos);
111 }
112
113 static void
114 removeFromIndices(FGPositioned* aPos)
115 {
116   assert(aPos);
117   
118   if (!aPos->ident().empty()) {
119     NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
120     while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
121       if (it->second == aPos) {
122         global_namedIndex.erase(it);
123         break;
124       }
125       
126       ++it;
127     } // of multimap walk
128   }
129   
130   SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
131   sit->second.erase(aPos);
132 }
133
134 static void
135 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
136 {
137   SpatialPositionedIndex::const_iterator it;
138   it = global_spatialIndex.find(aBucket.gen_index());
139   if (it == global_spatialIndex.end()) {
140     return;
141   }
142   
143   BucketEntry::const_iterator l = it->second.begin();
144   BucketEntry::const_iterator u = it->second.end();
145
146   if (!aFilter) { // pass everything
147     aResult.insert(aResult.end(), l, u);
148     return;
149   }
150
151   if (aFilter->hasTypeRange()) {
152     // avoid many calls to the filter hook
153     l = lower_bound(it->second.begin(), it->second.end(), aFilter->minType(), LowerLimitOfType());
154     u = upper_bound(l, it->second.end(), aFilter->maxType(), LowerLimitOfType());
155   }
156
157   for ( ; l != u; ++l) {
158     if ((*aFilter)(*l)) {
159       aResult.push_back(*l);
160     }
161   }
162 }
163
164 static void
165 spatialFind(const SGGeod& aPos, double aRange, 
166   FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
167 {
168   SGBucket buck(aPos);
169   double lat = aPos.getLatitudeDeg(),
170     lon = aPos.getLongitudeDeg();
171   
172   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
173   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
174     
175   // loop over bucket range 
176   for ( int i=-bx; i<=bx; i++) {
177     for ( int j=-by; j<=by; j++) {
178       spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
179     } // of j-iteration
180   } // of i-iteration  
181 }
182
183 /**
184  */
185 class RangePredictate
186 {
187 public:
188   RangePredictate(const SGGeod& aOrigin, double aRange) :
189     mOrigin(SGVec3d::fromGeod(aOrigin)),
190     mRangeSqr(aRange * aRange)
191   { ; }
192   
193   bool operator()(const FGPositionedRef& aPos)
194   {
195     double dSqr = distSqr(aPos->cart(), mOrigin);
196     return (dSqr > mRangeSqr);
197   }
198   
199 private:
200   SGVec3d mOrigin;
201   double mRangeSqr;
202 };
203
204 static void
205 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
206 {
207   RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
208   FGPositioned::List::iterator newEnd; 
209   newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
210   aResult.erase(newEnd, aResult.end());
211 }
212
213 class DistanceOrdering
214 {
215 public:
216   DistanceOrdering(const SGGeod& aPos) :
217     mPos(SGVec3d::fromGeod(aPos))
218   { }
219   
220   bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
221   {
222     double dA = distSqr(a->cart(), mPos),
223       dB = distSqr(b->cart(), mPos);
224     return dA < dB;
225   }
226
227 private:
228   SGVec3d mPos;
229 };
230
231 static void
232 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
233 {
234   std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
235 }
236
237 static FGPositionedRef
238 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
239 {
240   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
241   if (range.first == range.second) {
242     return NULL;
243   }
244   
245 // common case, only one result. looks a bit ugly because these are
246 // sequential iterators, not random-access ones
247   NamedPositionedIndex::const_iterator check = range.first;
248   if (++check == range.second) {
249     // excellent, only one match in the range
250     FGPositioned* r = range.first->second;
251     if (aFilter) {
252       if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
253         return NULL;
254       }
255       
256       if (!aFilter->pass(r)) {
257         return NULL;
258       }
259     } // of have a filter
260   
261     return r;
262   } // of short-circuit logic for single-element range
263   
264 // multiple matches, we need to actually check the distance to each one
265   double minDist = HUGE_VAL;
266   FGPositionedRef result;
267   NamedPositionedIndex::const_iterator it = range.first;
268   SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
269   
270   for (; it != range.second; ++it) {
271     FGPositioned* r = it->second;
272     if (aFilter) {
273       if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
274         continue;
275       }
276       
277       if (!aFilter->pass(r)) {
278         continue;
279       }
280     }
281     
282   // find distance
283     double d2 = distSqr(cartOrigin, r->cart());
284     if (d2 < minDist) {
285       minDist = d2;
286       result = r;
287     }
288   }
289   
290   return result;
291 }
292
293 static FGPositioned::List
294 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
295 {
296   FGPositioned::List result;
297   int radius = 1; // start at 1, radius 0 is handled explicitly
298   SGBucket buck;
299   double lat = aPos.getLatitudeDeg(),
300     lon = aPos.getLongitudeDeg();
301   // final cutoff is in metres, and scaled to account for testing the corners
302   // of the 'box' instead of the centre of each edge
303   double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
304   
305   // base case, simplifes loop to do it seperately here
306   spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
307
308   for (;result.size() < aN; ++radius) {
309     // cutoff check
310     double az1, az2, d1, d2;
311     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
312     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);  
313       
314     if ((d1 > cutoffM) && (d2 > cutoffM)) {
315       //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
316       break;
317     }
318     
319     FGPositioned::List hits;
320     for ( int i=-radius; i<=radius; i++) {
321       spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
322       spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
323       spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
324       spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
325     }
326
327     result.insert(result.end(), hits.begin(), hits.end()); // append
328   } // of outer loop
329   
330   sortByDistance(aPos, result);
331   if (result.size() > aN) {
332     result.resize(aN); // truncate at requested number of matches
333   }
334   
335   return result;
336 }
337
338 //////////////////////////////////////////////////////////////////////////////
339
340 class OrderByName
341 {
342 public:
343   bool operator()(FGPositioned* a, FGPositioned* b) const
344   {
345     return a->name() < b->name();
346   }
347 };
348
349 /**
350  * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
351  * implement the AirportList dialog. It's unfortunate that it needs to reside
352  * here, but for now it's least ugly solution.
353  */
354 char** searchAirportNamesAndIdents(const std::string& aFilter)
355 {
356   const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
357   std::string filter(aFilter);
358   bool hasFilter = !filter.empty();
359   if (hasFilter) {
360     ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
361   }
362   
363   NamedPositionedIndex::const_iterator it = global_namedIndex.begin();
364   NamedPositionedIndex::const_iterator end = global_namedIndex.end();
365   
366   // note this is a vector of raw pointers, not smart pointers, because it
367   // may get very large and smart-pointer-atomicity-locking then becomes a
368   // bottleneck for this case.
369   std::vector<FGPositioned*> matches;
370   std::string upper;
371   
372   for (; it != end; ++it) {
373     FGPositioned::Type ty = it->second->type();
374     if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
375       continue;
376     }
377     
378     if (hasFilter && (it->second->ident().find(aFilter) == std::string::npos)) {
379       upper = it->second->name(); // string copy, sadly
380       ct.toupper((char *)upper.data(), (char *)upper.data() + upper.size());
381       if (upper.find(aFilter) == std::string::npos) {
382         continue;
383       }
384     }
385     
386     matches.push_back(it->second);
387   }
388   
389   // sort alphabetically on name
390   std::sort(matches.begin(), matches.end(), OrderByName());
391   
392   // convert results to format comptible with puaList
393   unsigned int numMatches = matches.size();
394   char** result = new char*[numMatches + 1];
395   result[numMatches] = NULL; // end-of-list marker
396   
397   // nasty code to avoid excessive string copying and allocations.
398   // We format results as follows (note whitespace!):
399   //   ' name-of-airport-chars   (ident)'
400   // so the total length is:
401   //    1 + strlen(name) + 4 + 4 (for the ident) + 1 + 1 (for the null)
402   // which gives a grand total of 11 + the length of the name.
403   // note the ident is sometimes only three letters for non-ICAO small strips
404   for (unsigned int i=0; i<numMatches; ++i) {
405     int nameLength = matches[i]->name().size();
406     int icaoLength = matches[i]->ident().size();
407     char* entry = new char[nameLength + 11];
408     char* dst = entry;
409     *dst++ = ' ';
410     memcpy(dst, matches[i]->name().c_str(), nameLength);
411     dst += nameLength;
412     *dst++ = ' ';
413     *dst++ = ' ';
414     *dst++ = ' ';
415     *dst++ = '(';
416     memcpy(dst, matches[i]->ident().c_str(), icaoLength);
417     dst += icaoLength;
418     *dst++ = ')';
419     *dst++ = 0;
420     result[i] = entry;
421   }
422   
423   return result;
424 }
425
426 ///////////////////////////////////////////////////////////////////////////////
427
428 bool
429 FGPositioned::Filter::hasTypeRange() const
430 {
431   assert(minType() <= maxType());
432   return (minType() != INVALID) && (maxType() != INVALID);
433 }
434
435 bool
436 FGPositioned::Filter::passType(Type aTy) const
437 {
438   assert(hasTypeRange());
439   return (minType() <= aTy) && (maxType() >= aTy);
440 }
441
442 ///////////////////////////////////////////////////////////////////////////////
443
444 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
445   mType(ty),
446   mPosition(aPos),
447   mIdent(aIdent)
448 {  
449   SGReferenced::get(this); // hold an owning ref, for the moment
450   
451   if (aIndexed) {
452     assert(ty != TAXIWAY && ty != PAVEMENT);
453     addToIndices(this);
454   }
455 }
456
457 FGPositioned::~FGPositioned()
458 {
459   //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
460   removeFromIndices(this);
461 }
462
463 SGBucket
464 FGPositioned::bucket() const
465 {
466   return SGBucket(mPosition);
467 }
468
469 SGVec3d
470 FGPositioned::cart() const
471 {
472   return SGVec3d::fromGeod(mPosition);
473 }
474
475 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
476 {
477   if (aName.empty() || (aName == "")) {
478     return INVALID;
479   }
480
481   typedef struct {
482     const char* _name;
483     Type _ty;
484   } NameTypeEntry;
485   
486   const NameTypeEntry names[] = {
487     {"airport", AIRPORT},
488     {"vor", VOR},
489     {"ndb", NDB},
490     {"wpt", WAYPOINT},
491     {"fix", FIX},
492     {"tacan", TACAN},
493     {"dme", DME},
494   // aliases
495     {"waypoint", WAYPOINT},
496     {"apt", AIRPORT},
497     
498     {NULL, INVALID}
499   };
500   
501   std::string lowerName(simgear::strutils::convertToLowerCase(aName));
502   
503   for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
504     if (::strcmp(n->_name, lowerName.c_str()) == 0) {
505       return n->_ty;
506     }
507   }
508   
509   SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
510   return INVALID;
511 }
512
513 const char* FGPositioned::nameForType(Type aTy)
514 {
515  switch (aTy) {
516  case RUNWAY: return "runway";
517  case TAXIWAY: return "taxiway";
518  case PAVEMENT: return "pavement";
519  case PARK_STAND: return "parking stand";
520  case FIX: return "fix";
521  case VOR: return "VOR";
522  case NDB: return "NDB";
523  case ILS: return "ILS";
524  case LOC: return "localiser";
525  case GS: return "glideslope";
526  case OM: return "outer-marker";
527  case MM: return "middle-marker";
528  case IM: return "inner-marker";
529  case AIRPORT: return "airport";
530  case HELIPORT: return "heliport";
531  case SEAPORT: return "seaport";
532  case WAYPOINT: return "waypoint";
533  case DME: return "dme";
534  case TACAN: return "tacan";
535  default:
536   return "unknown";
537  }
538 }
539
540 ///////////////////////////////////////////////////////////////////////////////
541 // search / query functions
542
543 FGPositionedRef
544 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
545 {
546   return namedFindClosest(aIdent, aPos, aFilter);
547 }
548
549 FGPositioned::List
550 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
551 {
552   List result;
553   spatialFind(aPos, aRangeNm, aFilter, result);
554   filterListByRange(aPos, aRangeNm, result);
555   return result;
556 }
557
558 FGPositioned::List
559 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
560 {
561   List result;
562   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
563   for (; range.first != range.second; ++range.first) {
564     if (aFilter && !aFilter->pass(range.first->second)) {
565       continue;
566     }
567     
568     result.push_back(range.first->second);
569   }
570   
571   sortByDistance(aPos, result);
572   return result;
573 }
574
575 FGPositionedRef
576 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
577 {
578    FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
579    if (l.empty()) {
580       return NULL;
581    }
582    
583    assert(l.size() == 1);
584    return l.front();
585 }
586
587 FGPositioned::List
588 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
589 {
590   return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
591 }
592
593 FGPositionedRef
594 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
595 {
596   // It is essential to bound our search, to avoid iterating all the way to the end of the database.
597   // Do this by generating a second ID with the final character incremented by 1.
598   // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
599   std::string upperBoundId = aId;
600   upperBoundId[upperBoundId.size()-1]++;
601   NamedPositionedIndex::const_iterator upperBound = global_namedIndex.lower_bound(upperBoundId);
602
603   NamedIndexRange range = global_namedIndex.equal_range(aId);
604   while (range.first != upperBound) {
605     for (; range.first != range.second; ++range.first) {
606       FGPositionedRef candidate = range.first->second;
607       if (aCur == candidate) {
608         aCur = NULL; // found our start point, next match will pass
609         continue;
610       }
611
612       if (aFilter) {
613         if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
614           continue;
615         }
616
617         if (!aFilter->pass(candidate)) {
618           continue;
619         }
620       }
621
622       if (!aCur) {
623         return candidate;
624       }
625     }
626
627     // Unable to match the filter with this range - try the next range.
628     range = global_namedIndex.equal_range(range.second->first);
629   }
630
631   return NULL; // Reached the end of the valid sequence with no match.  
632 }
633   
634 FGPositionedRef
635 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset)
636 {
637   // see comment in findNextWithPartialId concerning upperBoundId
638   std::string upperBoundId = aId;
639   upperBoundId[upperBoundId.size()-1]++;
640   NamedPositionedIndex::const_iterator upperBound = global_namedIndex.lower_bound(upperBoundId);
641
642   NamedIndexRange range = global_namedIndex.equal_range(aId);
643   
644   while (range.first != upperBound) {
645     for (; range.first != range.second; ++range.first) {
646       FGPositionedRef candidate = range.first->second;
647       if (aFilter) {
648         if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
649           continue;
650         }
651
652         if (!aFilter->pass(candidate)) {
653           continue;
654         }
655       }
656
657       if (aOffset == 0) {
658         return candidate;
659       } else {
660         --aOffset; // seen one more valid result, decrement the count
661       }
662     }
663
664     // Unable to match the filter with this range - try the next range.
665     range = global_namedIndex.equal_range(range.second->first);
666   }
667
668   return NULL; // Reached the end of the valid sequence with no match.  
669 }
670
671 /**
672  * Wrapper filter which proxies to an inner filter, but also ensures the
673  * ident starts with supplied partial ident.
674  */
675 class PartialIdentFilter : public FGPositioned::Filter
676 {
677 public:
678   PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
679     _ident(ident),
680     _inner(filter)
681   { ; }
682   
683   virtual bool pass(FGPositioned* aPos) const
684   {
685     if (!_inner->pass(aPos)) {
686       return false;
687     }
688     
689     return (::strncmp(aPos->ident().c_str(), _ident.c_str(), _ident.size()) == 0);
690   }
691     
692   virtual FGPositioned::Type minType() const
693   { return _inner->minType(); }
694     
695   virtual FGPositioned::Type maxType() const
696   { return _inner->maxType(); }
697     
698 private:
699   std::string _ident;
700   FGPositioned::Filter* _inner;
701 };
702
703 FGPositionedRef
704 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset)
705 {
706   PartialIdentFilter pf(aId, aFilter);
707   List matches = spatialGetClosest(aPos, aOffset + 1, 1000.0, &pf);
708   
709   if ((int) matches.size() <= aOffset) {
710     SG_LOG(SG_GENERAL, SG_INFO, "FGPositioned::findClosestWithPartialId, couldn't match enough with prefix:" << aId);
711     return NULL; // couldn't find a match within the cutoff distance
712   }
713   
714   return matches[aOffset];
715 }
716