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>
34 #include "positioned.hxx"
36 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
37 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
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.
47 bool operator()(const FGPositioned* a, const FGPositioned* b) const
49 if (a->type() == b->type()) return a < b;
50 return a->type() < b->type();
54 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
55 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
57 static NamedPositionedIndex global_namedIndex;
58 static SpatialPositionedIndex global_spatialIndex;
60 SpatialPositionedIndex::iterator
61 bucketEntryForPositioned(FGPositioned* aPos)
63 int bucketIndex = aPos->bucket().gen_index();
64 SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
65 if (it != global_spatialIndex.end()) {
69 // create a new BucketEntry
70 return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
74 addToIndices(FGPositioned* aPos)
77 if (!aPos->ident().empty()) {
78 global_namedIndex.insert(global_namedIndex.begin(),
79 std::make_pair(aPos->ident(), aPos));
82 SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
83 it->second.insert(aPos);
87 removeFromIndices(FGPositioned* aPos)
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);
100 } // of multimap walk
103 SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
104 sit->second.erase(aPos);
108 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
110 SpatialPositionedIndex::const_iterator it;
111 it = global_spatialIndex.find(aBucket.gen_index());
112 if (it == global_spatialIndex.end()) {
116 BucketEntry::const_iterator l = it->second.begin();
117 BucketEntry::const_iterator u = it->second.end();
119 if (!aFilter) { // pass everything
120 aResult.insert(aResult.end(), l, u);
124 for ( ; l != u; ++l) {
125 if ((*aFilter)(*l)) {
126 aResult.push_back(*l);
132 spatialFind(const SGGeod& aPos, double aRange,
133 FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
136 double lat = aPos.getLatitudeDeg(),
137 lon = aPos.getLongitudeDeg();
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 );
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);
151 class LowerLimitOfType
154 bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
156 return a->type() < b;
159 bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
161 return a < b->type();
167 spatialFindTyped(const SGGeod& aPos, double aRange, FGPositioned::Type aLower, FGPositioned::Type aUpper, FGPositioned::List& aResult)
170 double lat = aPos.getLatitudeDeg(),
171 lon = aPos.getLongitudeDeg();
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 );
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);
181 SpatialPositionedIndex::const_iterator it;
182 it = global_spatialIndex.find(buck.gen_index());
183 if (it == global_spatialIndex.end()) {
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());
190 for ( ; l != u; ++l) {
191 aResult.push_back(*l);
201 class RangePredictate
204 RangePredictate(const SGGeod& aOrigin, double aRange) :
205 mOrigin(SGVec3d::fromGeod(aOrigin)),
206 mRangeSqr(aRange * aRange)
209 bool operator()(const FGPositionedRef& aPos)
211 double dSqr = distSqr(aPos->cart(), mOrigin);
212 return (dSqr > mRangeSqr);
221 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
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());
229 class DistanceOrdering
232 DistanceOrdering(const SGGeod& aPos) :
233 mPos(SGVec3d::fromGeod(aPos))
236 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
238 double dA = distSqr(a->cart(), mPos),
239 dB = distSqr(b->cart(), mPos);
248 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
250 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
253 static FGPositionedRef
254 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
256 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
257 if (range.first == range.second) {
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
270 return range.first->second;
271 } // of short-circuit logic for single-element range
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));
279 for (; it != range.second; ++it) {
280 if (aFilter && !aFilter->pass(range.first->second)) {
285 double d2 = distSqr(cartOrigin, it->second->cart());
295 static FGPositioned::List
296 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
298 FGPositioned::List result;
299 int radius = 1; // start at 1, radius 0 is handled explicitly
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;
307 // base case, simplifes loop to do it seperately here
308 spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
310 for (;result.size() < aN; ++radius) {
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);
316 if ((d1 > cutoffM) && (d2 > cutoffM)) {
317 //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
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);
329 result.insert(result.end(), hits.begin(), hits.end()); // append
332 sortByDistance(aPos, result);
333 if (result.size() > aN) {
334 result.resize(aN); // truncate at requested number of matches
340 //////////////////////////////////////////////////////////////////////////////
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.
347 char** searchAirportNamesAndIdents(const std::string& aFilter)
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());
355 NamedPositionedIndex::const_iterator it = global_namedIndex.begin();
356 NamedPositionedIndex::const_iterator end = global_namedIndex.end();
358 FGPositioned::List matches;
359 if (aFilter.empty()) {
360 matches.reserve(2000);
363 for (; it != end; ++it) {
364 FGPositioned::Type ty = it->second->type();
365 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
369 if (aFilter.empty()) {
370 matches.push_back(it->second);
374 if ((it->second->name().find(aFilter) == std::string::npos) &&
375 (it->second->ident().find(aFilter) == std::string::npos)) {
379 matches.push_back(it->second);
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
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.
394 for (unsigned int i=0; i<numMatches; ++i) {
395 int nameLength = matches[i]->name().size();
396 char* entry = new char[nameLength + 11];
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;
412 ///////////////////////////////////////////////////////////////////////////////
414 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
419 SGReferenced::get(this); // hold an owning ref, for the moment
422 assert(ty != TAXIWAY);
427 FGPositioned::~FGPositioned()
429 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
430 removeFromIndices(this);
434 FGPositioned::bucket() const
436 return SGBucket(mPosition);
440 FGPositioned::cart() const
442 return SGVec3d::fromGeod(mPosition);
445 const char* FGPositioned::nameForType(Type 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";
471 ///////////////////////////////////////////////////////////////////////////////
472 // search / query functions
475 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
477 return namedFindClosest(aIdent, aPos, aFilter);
481 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
484 spatialFind(aPos, aRangeNm, aFilter, result);
485 filterListByRange(aPos, aRangeNm, result);
490 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
493 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
494 for (; range.first != range.second; ++range.first) {
495 if (aFilter && !aFilter->pass(range.first->second)) {
499 result.push_back(range.first->second);
502 sortByDistance(aPos, result);
507 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
509 FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
514 assert(l.size() == 1);
519 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
521 return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
525 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
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
535 if (aFilter && !aFilter->pass(candidate)) {
544 return NULL; // fell out, no match in range