1 // positioned.cxx - base class for objects which are positioned
3 // Copyright (C) 2008 James Turner
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.
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.
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.
27 #include <algorithm> // for sort
28 #include <locale> // for char-traits toupper
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>
37 #include "positioned.hxx"
39 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
40 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
42 using std::lower_bound;
43 using std::upper_bound;
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.
53 bool operator()(const FGPositioned* a, const FGPositioned* b) const
55 if (a->type() == b->type()) return a < b;
56 return a->type() < b->type();
60 class LowerLimitOfType
63 bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
68 bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
73 // The operator below is required by VS2005 in debug mode
74 bool operator()(const FGPositioned* a, const FGPositioned* b) const
76 return a->type() < b->type();
81 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
82 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
84 static NamedPositionedIndex global_namedIndex;
85 static SpatialPositionedIndex global_spatialIndex;
87 SpatialPositionedIndex::iterator
88 bucketEntryForPositioned(FGPositioned* aPos)
90 int bucketIndex = aPos->bucket().gen_index();
91 SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
92 if (it != global_spatialIndex.end()) {
96 // create a new BucketEntry
97 return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
101 addToIndices(FGPositioned* aPos)
104 if (!aPos->ident().empty()) {
105 global_namedIndex.insert(global_namedIndex.begin(),
106 std::make_pair(aPos->ident(), aPos));
109 SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
110 it->second.insert(aPos);
114 removeFromIndices(FGPositioned* aPos)
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);
127 } // of multimap walk
130 SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
131 sit->second.erase(aPos);
135 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
137 SpatialPositionedIndex::const_iterator it;
138 it = global_spatialIndex.find(aBucket.gen_index());
139 if (it == global_spatialIndex.end()) {
143 BucketEntry::const_iterator l = it->second.begin();
144 BucketEntry::const_iterator u = it->second.end();
146 if (!aFilter) { // pass everything
147 aResult.insert(aResult.end(), l, u);
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());
157 for ( ; l != u; ++l) {
158 if ((*aFilter)(*l)) {
159 aResult.push_back(*l);
165 spatialFind(const SGGeod& aPos, double aRange,
166 FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
169 double lat = aPos.getLatitudeDeg(),
170 lon = aPos.getLongitudeDeg();
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 );
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);
185 class RangePredictate
188 RangePredictate(const SGGeod& aOrigin, double aRange) :
189 mOrigin(SGVec3d::fromGeod(aOrigin)),
190 mRangeSqr(aRange * aRange)
193 bool operator()(const FGPositionedRef& aPos)
195 double dSqr = distSqr(aPos->cart(), mOrigin);
196 return (dSqr > mRangeSqr);
205 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
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());
213 class DistanceOrdering
216 DistanceOrdering(const SGGeod& aPos) :
217 mPos(SGVec3d::fromGeod(aPos))
220 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
222 double dA = distSqr(a->cart(), mPos),
223 dB = distSqr(b->cart(), mPos);
232 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
234 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
237 static FGPositionedRef
238 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
240 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
241 if (range.first == range.second) {
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;
252 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
256 if (!aFilter->pass(r)) {
259 } // of have a filter
262 } // of short-circuit logic for single-element range
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));
270 for (; it != range.second; ++it) {
271 FGPositioned* r = it->second;
273 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
277 if (!aFilter->pass(r)) {
283 double d2 = distSqr(cartOrigin, r->cart());
293 static FGPositioned::List
294 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
296 FGPositioned::List result;
297 int radius = 1; // start at 1, radius 0 is handled explicitly
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;
305 // base case, simplifes loop to do it seperately here
306 spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
308 for (;result.size() < aN; ++radius) {
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);
314 if ((d1 > cutoffM) && (d2 > cutoffM)) {
315 //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
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);
327 result.insert(result.end(), hits.begin(), hits.end()); // append
330 sortByDistance(aPos, result);
331 if (result.size() > aN) {
332 result.resize(aN); // truncate at requested number of matches
338 //////////////////////////////////////////////////////////////////////////////
343 bool operator()(FGPositioned* a, FGPositioned* b) const
345 return a->name() < b->name();
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.
354 char** searchAirportNamesAndIdents(const std::string& aFilter)
356 const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
357 std::string filter(aFilter);
358 bool hasFilter = !filter.empty();
360 ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
363 NamedPositionedIndex::const_iterator it = global_namedIndex.begin();
364 NamedPositionedIndex::const_iterator end = global_namedIndex.end();
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;
372 for (; it != end; ++it) {
373 FGPositioned::Type ty = it->second->type();
374 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
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) {
386 matches.push_back(it->second);
389 // sort alphabetically on name
390 std::sort(matches.begin(), matches.end(), OrderByName());
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
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];
410 memcpy(dst, matches[i]->name().c_str(), nameLength);
416 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
426 ///////////////////////////////////////////////////////////////////////////////
429 FGPositioned::Filter::hasTypeRange() const
431 assert(minType() <= maxType());
432 return (minType() != INVALID) && (maxType() != INVALID);
436 FGPositioned::Filter::passType(Type aTy) const
438 assert(hasTypeRange());
439 return (minType() <= aTy) && (maxType() >= aTy);
442 ///////////////////////////////////////////////////////////////////////////////
444 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
449 SGReferenced::get(this); // hold an owning ref, for the moment
452 assert(ty != TAXIWAY && ty != PAVEMENT);
457 FGPositioned::~FGPositioned()
459 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
460 removeFromIndices(this);
464 FGPositioned::bucket() const
466 return SGBucket(mPosition);
470 FGPositioned::cart() const
472 return SGVec3d::fromGeod(mPosition);
475 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
477 if (aName.empty() || (aName == "")) {
486 const NameTypeEntry names[] = {
487 {"airport", AIRPORT},
495 {"waypoint", WAYPOINT},
501 std::string lowerName(simgear::strutils::convertToLowerCase(aName));
503 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
504 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
509 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
513 const char* FGPositioned::nameForType(Type 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";
540 ///////////////////////////////////////////////////////////////////////////////
541 // search / query functions
544 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
546 return namedFindClosest(aIdent, aPos, aFilter);
550 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
553 spatialFind(aPos, aRangeNm, aFilter, result);
554 filterListByRange(aPos, aRangeNm, result);
559 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
562 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
563 for (; range.first != range.second; ++range.first) {
564 if (aFilter && !aFilter->pass(range.first->second)) {
568 result.push_back(range.first->second);
571 sortByDistance(aPos, result);
576 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
578 FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
583 assert(l.size() == 1);
588 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
590 return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
594 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
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);
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
613 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
617 if (!aFilter->pass(candidate)) {
627 // Unable to match the filter with this range - try the next range.
628 range = global_namedIndex.equal_range(range.second->first);
631 return NULL; // Reached the end of the valid sequence with no match.
635 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset)
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);
642 NamedIndexRange range = global_namedIndex.equal_range(aId);
644 while (range.first != upperBound) {
645 for (; range.first != range.second; ++range.first) {
646 FGPositionedRef candidate = range.first->second;
648 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
652 if (!aFilter->pass(candidate)) {
660 --aOffset; // seen one more valid result, decrement the count
664 // Unable to match the filter with this range - try the next range.
665 range = global_namedIndex.equal_range(range.second->first);
668 return NULL; // Reached the end of the valid sequence with no match.
672 * Wrapper filter which proxies to an inner filter, but also ensures the
673 * ident starts with supplied partial ident.
675 class PartialIdentFilter : public FGPositioned::Filter
678 PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
683 virtual bool pass(FGPositioned* aPos) const
685 if (!_inner->pass(aPos)) {
689 return (::strncmp(aPos->ident().c_str(), _ident.c_str(), _ident.size()) == 0);
692 virtual FGPositioned::Type minType() const
693 { return _inner->minType(); }
695 virtual FGPositioned::Type maxType() const
696 { return _inner->maxType(); }
700 FGPositioned::Filter* _inner;
704 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset)
706 PartialIdentFilter pf(aId, aFilter);
707 List matches = spatialGetClosest(aPos, aOffset + 1, 1000.0, &pf);
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
714 return matches[aOffset];