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
30 #include <boost/algorithm/string/case_conv.hpp>
31 #include <boost/algorithm/string/predicate.hpp>
33 #include <simgear/timing/timestamp.hxx>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/structure/exception.hxx>
36 #include <simgear/math/SGGeometry.hxx>
38 #include "positioned.hxx"
40 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
41 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
43 using std::lower_bound;
44 using std::upper_bound;
46 static NamedPositionedIndex global_identIndex;
47 static NamedPositionedIndex global_nameIndex;
49 //////////////////////////////////////////////////////////////////////////////
54 const double LEAF_SIZE = SG_NM_TO_METER * 8.0;
55 const double LEAF_SIZE_SQR = LEAF_SIZE * LEAF_SIZE;
58 * Decorate an object with a double value, and use that value to order
59 * items, for the purpoises of the STL algorithms
65 Ordered(const T& v, double x) :
71 Ordered(const Ordered<T>& a) :
77 Ordered<T>& operator=(const Ordered<T>& a)
84 bool operator<(const Ordered<T>& other) const
86 return _order < other._order;
89 bool operator>(const Ordered<T>& other) const
91 return _order > other._order;
106 typedef Ordered<Node*> OrderedNode;
107 typedef std::greater<OrderedNode> FNPQCompare;
110 * the priority queue is fundamental to our search algorithm. When searching,
111 * we know the front of the queue is the nearest unexpanded node (to the search
112 * location). The default STL pqueue returns the 'largest' item from top(), so
113 * to get the smallest, we need to replace the default Compare functor (less<>)
116 typedef std::priority_queue<OrderedNode, std::vector<OrderedNode>, FNPQCompare> FindNearestPQueue;
118 typedef Ordered<FGPositioned*> OrderedPositioned;
119 typedef std::vector<OrderedPositioned> FindNearestResults;
121 Node* global_spatialOctree = NULL;
124 * Octree node base class, tracks its bounding box and provides various
125 * queries relating to it
130 bool contains(const SGVec3d& aPos) const
132 return intersects(aPos, _box);
135 double distSqrToNearest(const SGVec3d& aPos) const
137 return distSqr(aPos, _box.getClosestPoint(aPos));
140 virtual void insert(FGPositioned* aP) = 0;
142 virtual void visit(const SGVec3d& aPos, double aCutoff,
143 FGPositioned::Filter* aFilter,
144 FindNearestResults& aResults, FindNearestPQueue&) = 0;
146 Node(const SGBoxd &aBox) :
154 class Leaf : public Node
157 Leaf(const SGBoxd& aBox) :
162 const FGPositioned::List& members() const
165 virtual void insert(FGPositioned* aP)
167 _members.push_back(aP);
170 virtual void visit(const SGVec3d& aPos, double aCutoff,
171 FGPositioned::Filter* aFilter,
172 FindNearestResults& aResults, FindNearestPQueue&)
174 int previousResultsSize = aResults.size();
177 for (unsigned int i=0; i<_members.size(); ++i) {
178 FGPositioned* p = _members[i];
179 double d2 = distSqr(aPos, p->cart());
185 if (aFilter->hasTypeRange() && !aFilter->passType(p->type())) {
189 if (!aFilter->pass(p)) {
192 } // of have a filter
195 aResults.push_back(OrderedPositioned(p, d2));
198 if (addedCount == 0) {
202 // keep aResults sorted
203 // sort the new items, usually just one or two items
204 std::sort(aResults.begin() + previousResultsSize, aResults.end());
206 // merge the two sorted ranges together - in linear time
207 std::inplace_merge(aResults.begin(),
208 aResults.begin() + previousResultsSize, aResults.end());
211 FGPositioned::List _members;
214 class Branch : public Node
217 Branch(const SGBoxd& aBox) :
220 memset(children, 0, sizeof(Node*) * 8);
223 virtual void insert(FGPositioned* aP)
225 SGVec3d cart(aP->cart());
226 assert(contains(cart));
229 SGVec3d center(_box.getCenter());
230 // tests must match indices in SGbox::getCorner
231 if (cart.x() < center.x()) {
235 if (cart.y() < center.y()) {
239 if (cart.z() < center.z()) {
243 Node* child = children[childIndex];
244 if (!child) { // lazy building of children
245 SGBoxd cb(boxForChild(childIndex));
246 double d2 = dot(cb.getSize(), cb.getSize());
247 if (d2 < LEAF_SIZE_SQR) {
248 child = new Leaf(cb);
250 child = new Branch(cb);
253 children[childIndex] = child;
259 virtual void visit(const SGVec3d& aPos, double aCutoff,
260 FGPositioned::Filter*,
261 FindNearestResults&, FindNearestPQueue& aQ)
263 for (unsigned int i=0; i<8; ++i) {
268 double d2 = children[i]->distSqrToNearest(aPos);
270 continue; // exceeded cutoff
273 aQ.push(Ordered<Node*>(children[i], d2));
274 } // of child iteration
280 * Return the box for a child touching the specified corner
282 SGBoxd boxForChild(unsigned int aCorner) const
284 SGBoxd r(_box.getCenter());
285 r.expandBy(_box.getCorner(aCorner));
292 void findNearestN(const SGVec3d& aPos, unsigned int aN, double aCutoffM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
295 FindNearestPQueue pq;
296 FindNearestResults results;
297 pq.push(Ordered<Node*>(global_spatialOctree, 0));
298 double cut = aCutoffM * aCutoffM;
300 while (!pq.empty()) {
301 if (!results.empty()) {
302 // terminate the search if we have sufficent results, and we are
303 // sure no node still on the queue contains a closer match
304 double furthestResultOrder = results.back().order();
305 if ((results.size() >= aN) && (furthestResultOrder < pq.top().order())) {
310 Node* nd = pq.top().get();
313 nd->visit(aPos, cut, aFilter, results, pq);
314 } // of queue iteration
316 // depending on leaf population, we may have (slighty) more results
318 unsigned int numResults = std::min((unsigned int) results.size(), aN);
320 aResults.resize(numResults);
321 for (unsigned int r=0; r<numResults; ++r) {
322 aResults[r] = results[r].get();
326 void findAllWithinRange(const SGVec3d& aPos, double aRangeM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
329 FindNearestPQueue pq;
330 FindNearestResults results;
331 pq.push(Ordered<Node*>(global_spatialOctree, 0));
332 double rng = aRangeM * aRangeM;
334 while (!pq.empty()) {
335 Node* nd = pq.top().get();
338 nd->visit(aPos, rng, aFilter, results, pq);
339 } // of queue iteration
341 unsigned int numResults = results.size();
343 aResults.resize(numResults);
344 for (unsigned int r=0; r<numResults; ++r) {
345 aResults[r] = results[r].get();
349 } // of namespace Octree
351 //////////////////////////////////////////////////////////////////////////////
354 addToIndices(FGPositioned* aPos)
357 if (!aPos->ident().empty()) {
358 global_identIndex.insert(global_identIndex.begin(),
359 std::make_pair(aPos->ident(), aPos));
362 if (!aPos->name().empty()) {
363 global_nameIndex.insert(global_nameIndex.begin(),
364 std::make_pair(aPos->name(), aPos));
367 if (!Octree::global_spatialOctree) {
368 double RADIUS_EARTH_M = 7000 * 1000.0; // 7000km is plenty
369 SGVec3d earthExtent(RADIUS_EARTH_M, RADIUS_EARTH_M, RADIUS_EARTH_M);
370 Octree::global_spatialOctree = new Octree::Branch(SGBox<double>(-earthExtent, earthExtent));
372 Octree::global_spatialOctree->insert(aPos);
376 removeFromIndices(FGPositioned* aPos)
380 if (!aPos->ident().empty()) {
381 NamedPositionedIndex::iterator it = global_identIndex.find(aPos->ident());
382 while (it != global_identIndex.end() && (it->first == aPos->ident())) {
383 if (it->second == aPos) {
384 global_identIndex.erase(it);
389 } // of multimap walk
392 if (!aPos->name().empty()) {
393 NamedPositionedIndex::iterator it = global_nameIndex.find(aPos->name());
394 while (it != global_nameIndex.end() && (it->first == aPos->name())) {
395 if (it->second == aPos) {
396 global_nameIndex.erase(it);
401 } // of multimap walk
405 class DistanceOrdering
408 DistanceOrdering(const SGGeod& aPos) :
409 mPos(SGVec3d::fromGeod(aPos))
412 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
415 throw sg_exception("empty reference passed to DistanceOrdering");
418 double dA = distSqr(a->cart(), mPos),
419 dB = distSqr(b->cart(), mPos);
428 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
430 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
433 static FGPositionedRef
434 namedFindClosest(const NamedPositionedIndex& aIndex, const std::string& aName,
435 const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
437 NamedIndexRange range = aIndex.equal_range(aName);
438 if (range.first == range.second) {
442 // common case, only one result. looks a bit ugly because these are
443 // sequential iterators, not random-access ones
444 NamedPositionedIndex::const_iterator check = range.first;
445 if (++check == range.second) {
446 // excellent, only one match in the range
447 FGPositioned* r = range.first->second;
449 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
453 if (!aFilter->pass(r)) {
456 } // of have a filter
459 } // of short-circuit logic for single-element range
461 // multiple matches, we need to actually check the distance to each one
462 double minDist = HUGE_VAL;
463 FGPositionedRef result;
464 NamedPositionedIndex::const_iterator it = range.first;
465 SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
467 for (; it != range.second; ++it) {
468 FGPositioned* r = it->second;
470 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
474 if (!aFilter->pass(r)) {
480 double d2 = distSqr(cartOrigin, r->cart());
490 //////////////////////////////////////////////////////////////////////////////
495 bool operator()(FGPositioned* a, FGPositioned* b) const
497 return a->name() < b->name();
502 * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
503 * implement the AirportList dialog. It's unfortunate that it needs to reside
504 * here, but for now it's least ugly solution.
506 char** searchAirportNamesAndIdents(const std::string& aFilter)
508 const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
509 std::string filter(aFilter);
510 bool hasFilter = !filter.empty();
512 ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
515 NamedPositionedIndex::const_iterator it = global_identIndex.begin();
516 NamedPositionedIndex::const_iterator end = global_identIndex.end();
518 // note this is a vector of raw pointers, not smart pointers, because it
519 // may get very large and smart-pointer-atomicity-locking then becomes a
520 // bottleneck for this case.
521 std::vector<FGPositioned*> matches;
524 for (; it != end; ++it) {
525 FGPositioned::Type ty = it->second->type();
526 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
530 if (hasFilter && (it->second->ident().find(aFilter) == std::string::npos)) {
531 upper = it->second->name(); // string copy, sadly
532 ct.toupper((char *)upper.data(), (char *)upper.data() + upper.size());
533 if (upper.find(aFilter) == std::string::npos) {
538 matches.push_back(it->second);
541 // sort alphabetically on name
542 std::sort(matches.begin(), matches.end(), OrderByName());
544 // convert results to format comptible with puaList
545 unsigned int numMatches = matches.size();
546 char** result = new char*[numMatches + 1];
547 result[numMatches] = NULL; // end-of-list marker
549 // nasty code to avoid excessive string copying and allocations.
550 // We format results as follows (note whitespace!):
551 // ' name-of-airport-chars (ident)'
552 // so the total length is:
553 // 1 + strlen(name) + 4 + 4 (for the ident) + 1 + 1 (for the null)
554 // which gives a grand total of 11 + the length of the name.
555 // note the ident is sometimes only three letters for non-ICAO small strips
556 for (unsigned int i=0; i<numMatches; ++i) {
557 int nameLength = matches[i]->name().size();
558 int icaoLength = matches[i]->ident().size();
559 char* entry = new char[nameLength + 11];
562 memcpy(dst, matches[i]->name().c_str(), nameLength);
568 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
578 ///////////////////////////////////////////////////////////////////////////////
581 FGPositioned::Filter::hasTypeRange() const
583 assert(minType() <= maxType());
584 return (minType() != INVALID) && (maxType() != INVALID);
588 FGPositioned::Filter::passType(Type aTy) const
590 assert(hasTypeRange());
591 return (minType() <= aTy) && (maxType() >= aTy);
594 static FGPositioned::List
595 findAllSortedByRange(const NamedPositionedIndex& aIndex,
596 const std::string& aName, const SGGeod& aPos, FGPositioned::Filter* aFilter)
598 FGPositioned::List result;
599 NamedIndexRange range = aIndex.equal_range(aName);
600 for (; range.first != range.second; ++range.first) {
601 FGPositioned* candidate = range.first->second;
603 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
607 if (!aFilter->pass(candidate)) {
612 result.push_back(range.first->second);
615 sortByDistance(aPos, result);
619 static FGPositionedRef
620 findWithPartial(const NamedPositionedIndex& aIndex, const std::string& aName,
621 FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
623 // see comment in findNextWithPartialId concerning upperBoundId
624 std::string upperBoundId = aName;
625 upperBoundId[upperBoundId.size()-1]++;
626 NamedPositionedIndex::const_iterator upperBound = aIndex.lower_bound(upperBoundId);
628 NamedIndexRange range = aIndex.equal_range(aName);
629 FGPositionedRef result;
631 while (range.first != upperBound) {
632 for (; range.first != range.second; ++range.first) {
633 FGPositionedRef candidate = range.first->second;
635 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
639 if (!aFilter->pass(candidate)) {
647 } else if (aOffset == 0) {
648 // okay, found our result. we need to go around once more to set aNext
651 --aOffset; // seen one more valid result, decrement the count
655 // Unable to match the filter with this range - try the next range.
656 range = aIndex.equal_range(range.second->first);
659 // if we fell out, we reached the end of the valid range. We might have a
660 // valid result, but we definitiely don't have a next result.
665 ///////////////////////////////////////////////////////////////////////////////
667 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
672 SGReferenced::get(this); // hold an owning ref, for the moment
675 assert(ty != TAXIWAY && ty != PAVEMENT);
680 FGPositioned::~FGPositioned()
682 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
683 removeFromIndices(this);
687 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
689 return new FGPositioned(WAYPOINT, aIdent, aPos, true);
693 FGPositioned::cart() const
695 return SGVec3d::fromGeod(mPosition);
698 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
700 if (aName.empty() || (aName == "")) {
709 const NameTypeEntry names[] = {
710 {"airport", AIRPORT},
718 {"waypoint", WAYPOINT},
727 std::string lowerName(boost::to_lower_copy(aName));
729 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
730 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
735 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
739 const char* FGPositioned::nameForType(Type aTy)
742 case RUNWAY: return "runway";
743 case TAXIWAY: return "taxiway";
744 case PAVEMENT: return "pavement";
745 case PARK_STAND: return "parking stand";
746 case FIX: return "fix";
747 case VOR: return "VOR";
748 case NDB: return "NDB";
749 case ILS: return "ILS";
750 case LOC: return "localiser";
751 case GS: return "glideslope";
752 case OM: return "outer-marker";
753 case MM: return "middle-marker";
754 case IM: return "inner-marker";
755 case AIRPORT: return "airport";
756 case HELIPORT: return "heliport";
757 case SEAPORT: return "seaport";
758 case WAYPOINT: return "waypoint";
759 case DME: return "dme";
760 case TACAN: return "tacan";
766 ///////////////////////////////////////////////////////////////////////////////
767 // search / query functions
770 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
772 return namedFindClosest(global_identIndex, aIdent, aPos, aFilter);
776 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
779 Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
780 aRangeNm * SG_NM_TO_METER, aFilter, result);
785 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
787 return findAllSortedByRange(global_identIndex, aIdent, aPos, aFilter);
791 FGPositioned::findAllWithNameSortedByRange(const std::string& aName, const SGGeod& aPos, Filter* aFilter)
793 return findAllSortedByRange(global_nameIndex, aName, aPos, aFilter);
797 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
799 List l(findClosestN(aPos, 1, aCutoffNm, aFilter));
804 assert(l.size() == 1);
809 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
812 Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result);
817 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
823 std::string id(boost::to_upper_copy(aId));
825 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
826 // Do this by generating a second ID with the final character incremented by 1.
827 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
828 std::string upperBoundId = id;
829 upperBoundId[upperBoundId.size()-1]++;
830 NamedPositionedIndex::const_iterator upperBound = global_identIndex.lower_bound(upperBoundId);
832 NamedIndexRange range = global_identIndex.equal_range(id);
833 while (range.first != upperBound) {
834 for (; range.first != range.second; ++range.first) {
835 FGPositionedRef candidate = range.first->second;
836 if (aCur == candidate) {
837 aCur = NULL; // found our start point, next match will pass
842 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
846 if (!aFilter->pass(candidate)) {
856 // Unable to match the filter with this range - try the next range.
857 range = global_identIndex.equal_range(range.second->first);
860 return NULL; // Reached the end of the valid sequence with no match.
864 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
866 return findWithPartial(global_identIndex, aId, aFilter, aOffset, aNext);
871 FGPositioned::findWithPartialName(const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
873 return findWithPartial(global_nameIndex, aName, aFilter, aOffset, aNext);
877 * Wrapper filter which proxies to an inner filter, but also ensures the
878 * ident starts with supplied partial ident.
880 class PartialIdentFilter : public FGPositioned::Filter
883 PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
886 _ident = boost::to_upper_copy(ident);
889 virtual bool pass(FGPositioned* aPos) const
891 if (!_inner->pass(aPos)) {
895 return (boost::algorithm::starts_with(aPos->ident(), _ident));
898 virtual FGPositioned::Type minType() const
899 { return _inner->minType(); }
901 virtual FGPositioned::Type maxType() const
902 { return _inner->maxType(); }
906 FGPositioned::Filter* _inner;
909 static FGPositionedRef
910 findClosestWithPartial(const SGGeod& aPos, FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
912 // why aOffset +2 ? at offset=3, we want the fourth search result, but also
913 // to know if the fifth result exists (to set aNext flag for iterative APIs)
914 FGPositioned::List matches;
915 Octree::findNearestN(SGVec3d::fromGeod(aPos), aOffset + 2, 1000 * SG_NM_TO_METER, aFilter, matches);
917 if ((int) matches.size() <= aOffset) {
918 SG_LOG(SG_GENERAL, SG_INFO, "findClosestWithPartial, couldn't match enough with prefix");
920 return NULL; // couldn't find a match within the cutoff distance
923 aNext = ((int) matches.size() >= (aOffset + 2));
924 return matches[aOffset];
929 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
931 PartialIdentFilter pf(aId, aFilter);
932 return findClosestWithPartial(aPos, &pf, aOffset, aNext);
936 * Wrapper filter which proxies to an inner filter, but also ensures the
937 * name starts with supplied partial name.
939 class PartialNameFilter : public FGPositioned::Filter
942 PartialNameFilter(const std::string& nm, FGPositioned::Filter* filter) :
948 virtual bool pass(FGPositioned* aPos) const
950 if (!_inner->pass(aPos)) {
954 return (boost::algorithm::istarts_with(aPos->name(), _name));
957 virtual FGPositioned::Type minType() const
958 { return _inner->minType(); }
960 virtual FGPositioned::Type maxType() const
961 { return _inner->maxType(); }
965 FGPositioned::Filter* _inner;
969 FGPositioned::findClosestWithPartialName(const SGGeod& aPos, const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
971 PartialNameFilter pf(aName, aFilter);
972 return findClosestWithPartial(aPos, &pf, aOffset, aNext);