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/math/sg_geodesy.hxx>
34 #include <simgear/timing/timestamp.hxx>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/math/SGBox.hxx>
39 #include "positioned.hxx"
41 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
42 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
44 using std::lower_bound;
45 using std::upper_bound;
47 static NamedPositionedIndex global_identIndex;
48 static NamedPositionedIndex global_nameIndex;
50 //////////////////////////////////////////////////////////////////////////////
55 const double LEAF_SIZE = SG_NM_TO_METER * 8.0;
56 const double LEAF_SIZE_SQR = LEAF_SIZE * LEAF_SIZE;
58 typedef SGBox<double> SGBoxd;
60 template<typename T1, typename T2>
62 intersects(const SGVec3<T1>& v, const SGBox<T2>& box)
64 if (v[0] < box.getMin()[0])
66 if (box.getMax()[0] < v[0])
68 if (v[1] < box.getMin()[1])
70 if (box.getMax()[1] < v[1])
72 if (v[2] < box.getMin()[2])
74 if (box.getMax()[2] < v[2])
80 * Decorate an object with a double value, and use that value to order
81 * items, for the purpoises of the STL algorithms
87 Ordered(const T& v, double x) :
93 Ordered(const Ordered<T>& a) :
99 Ordered<T>& operator=(const Ordered<T>& a)
106 bool operator<(const Ordered<T>& other) const
108 return _order < other._order;
111 bool operator>(const Ordered<T>& other) const
113 return _order > other._order;
128 typedef Ordered<Node*> OrderedNode;
129 typedef std::greater<OrderedNode> FNPQCompare;
132 * the priority queue is fundamental to our search algorithm. When searching,
133 * we know the front of the queue is the nearest unexpanded node (to the search
134 * location). The default STL pqueue returns the 'largest' item from top(), so
135 * to get the smallest, we need to replace the default Compare functor (less<>)
138 typedef std::priority_queue<OrderedNode, std::vector<OrderedNode>, FNPQCompare> FindNearestPQueue;
140 typedef Ordered<FGPositioned*> OrderedPositioned;
141 typedef std::vector<OrderedPositioned> FindNearestResults;
143 Node* global_spatialOctree = NULL;
146 * Octree node base class, tracks its bounding box and provides various
147 * queries relating to it
152 bool contains(const SGVec3d& aPos) const
154 return intersects(aPos, _box);
157 double distSqrToNearest(const SGVec3d& aPos) const
159 return distSqr(aPos, getClosestPoint(aPos));
162 virtual void insert(FGPositioned* aP) = 0;
164 SGVec3d getClosestPoint(const SGVec3d& aPos) const
168 for (unsigned int i=0;i<3; ++i) {
169 if (aPos[i] < _box.getMin()[i]) {
170 r[i] = _box.getMin()[i];
171 } else if (aPos[i] > _box.getMax()[i]) {
172 r[i] = _box.getMax()[i];
176 } // of axis iteration
181 virtual void visit(const SGVec3d& aPos, double aCutoff,
182 FGPositioned::Filter* aFilter,
183 FindNearestResults& aResults, FindNearestPQueue&) = 0;
185 Node(const SGBoxd &aBox) :
193 class Leaf : public Node
196 Leaf(const SGBoxd& aBox) :
201 const FGPositioned::List& members() const
204 virtual void insert(FGPositioned* aP)
206 _members.push_back(aP);
209 virtual void visit(const SGVec3d& aPos, double aCutoff,
210 FGPositioned::Filter* aFilter,
211 FindNearestResults& aResults, FindNearestPQueue&)
213 int previousResultsSize = aResults.size();
216 for (unsigned int i=0; i<_members.size(); ++i) {
217 FGPositioned* p = _members[i];
218 double d2 = distSqr(aPos, p->cart());
224 if (aFilter->hasTypeRange() && !aFilter->passType(p->type())) {
228 if (!aFilter->pass(p)) {
231 } // of have a filter
234 aResults.push_back(OrderedPositioned(p, d2));
237 if (addedCount == 0) {
241 // keep aResults sorted
242 // sort the new items, usually just one or two items
243 std::sort(aResults.begin() + previousResultsSize, aResults.end());
245 // merge the two sorted ranges together - in linear time
246 std::inplace_merge(aResults.begin(),
247 aResults.begin() + previousResultsSize, aResults.end());
250 FGPositioned::List _members;
253 class Branch : public Node
256 Branch(const SGBoxd& aBox) :
259 memset(children, 0, sizeof(Node*) * 8);
262 virtual void insert(FGPositioned* aP)
264 SGVec3d cart(aP->cart());
265 assert(contains(cart));
268 SGVec3d center(_box.getCenter());
269 // tests must match indices in SGbox::getCorner
270 if (cart.x() < center.x()) {
274 if (cart.y() < center.y()) {
278 if (cart.z() < center.z()) {
282 Node* child = children[childIndex];
283 if (!child) { // lazy building of children
284 SGBoxd cb(boxForChild(childIndex));
285 double d2 = dot(cb.getSize(), cb.getSize());
286 if (d2 < LEAF_SIZE_SQR) {
287 child = new Leaf(cb);
289 child = new Branch(cb);
292 children[childIndex] = child;
298 virtual void visit(const SGVec3d& aPos, double aCutoff,
299 FGPositioned::Filter*,
300 FindNearestResults&, FindNearestPQueue& aQ)
302 for (unsigned int i=0; i<8; ++i) {
307 double d2 = children[i]->distSqrToNearest(aPos);
309 continue; // exceeded cutoff
312 aQ.push(Ordered<Node*>(children[i], d2));
313 } // of child iteration
319 * Return the box for a child touching the specified corner
321 SGBoxd boxForChild(unsigned int aCorner) const
323 SGBoxd r(_box.getCenter());
324 r.expandBy(_box.getCorner(aCorner));
331 void findNearestN(const SGVec3d& aPos, unsigned int aN, double aCutoffM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
334 FindNearestPQueue pq;
335 FindNearestResults results;
336 pq.push(Ordered<Node*>(global_spatialOctree, 0));
337 double cut = aCutoffM * aCutoffM;
339 while (!pq.empty()) {
340 if (!results.empty()) {
341 // terminate the search if we have sufficent results, and we are
342 // sure no node still on the queue contains a closer match
343 double furthestResultOrder = results.back().order();
344 if ((results.size() >= aN) && (furthestResultOrder < pq.top().order())) {
349 Node* nd = pq.top().get();
352 nd->visit(aPos, cut, aFilter, results, pq);
353 } // of queue iteration
355 // depending on leaf population, we may have (slighty) more results
357 unsigned int numResults = std::min((unsigned int) results.size(), aN);
359 aResults.resize(numResults);
360 for (unsigned int r=0; r<numResults; ++r) {
361 aResults[r] = results[r].get();
365 void findAllWithinRange(const SGVec3d& aPos, double aRangeM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
368 FindNearestPQueue pq;
369 FindNearestResults results;
370 pq.push(Ordered<Node*>(global_spatialOctree, 0));
371 double rng = aRangeM * aRangeM;
373 while (!pq.empty()) {
374 Node* nd = pq.top().get();
377 nd->visit(aPos, rng, aFilter, results, pq);
378 } // of queue iteration
380 unsigned int numResults = results.size();
382 aResults.resize(numResults);
383 for (unsigned int r=0; r<numResults; ++r) {
384 aResults[r] = results[r].get();
388 } // of namespace Octree
390 //////////////////////////////////////////////////////////////////////////////
393 addToIndices(FGPositioned* aPos)
396 if (!aPos->ident().empty()) {
397 global_identIndex.insert(global_identIndex.begin(),
398 std::make_pair(aPos->ident(), aPos));
401 if (!aPos->name().empty()) {
402 global_nameIndex.insert(global_nameIndex.begin(),
403 std::make_pair(aPos->name(), aPos));
406 if (!Octree::global_spatialOctree) {
407 double RADIUS_EARTH_M = 7000 * 1000.0; // 7000km is plenty
408 SGVec3d earthExtent(RADIUS_EARTH_M, RADIUS_EARTH_M, RADIUS_EARTH_M);
409 Octree::global_spatialOctree = new Octree::Branch(SGBox<double>(-earthExtent, earthExtent));
411 Octree::global_spatialOctree->insert(aPos);
415 removeFromIndices(FGPositioned* aPos)
419 if (!aPos->ident().empty()) {
420 NamedPositionedIndex::iterator it = global_identIndex.find(aPos->ident());
421 while (it != global_identIndex.end() && (it->first == aPos->ident())) {
422 if (it->second == aPos) {
423 global_identIndex.erase(it);
428 } // of multimap walk
431 if (!aPos->name().empty()) {
432 NamedPositionedIndex::iterator it = global_nameIndex.find(aPos->name());
433 while (it != global_nameIndex.end() && (it->first == aPos->name())) {
434 if (it->second == aPos) {
435 global_nameIndex.erase(it);
440 } // of multimap walk
444 class DistanceOrdering
447 DistanceOrdering(const SGGeod& aPos) :
448 mPos(SGVec3d::fromGeod(aPos))
451 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
454 throw sg_exception("empty reference passed to DistanceOrdering");
457 double dA = distSqr(a->cart(), mPos),
458 dB = distSqr(b->cart(), mPos);
467 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
469 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
472 static FGPositionedRef
473 namedFindClosest(const NamedPositionedIndex& aIndex, const std::string& aName,
474 const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
476 NamedIndexRange range = aIndex.equal_range(aName);
477 if (range.first == range.second) {
481 // common case, only one result. looks a bit ugly because these are
482 // sequential iterators, not random-access ones
483 NamedPositionedIndex::const_iterator check = range.first;
484 if (++check == range.second) {
485 // excellent, only one match in the range
486 FGPositioned* r = range.first->second;
488 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
492 if (!aFilter->pass(r)) {
495 } // of have a filter
498 } // of short-circuit logic for single-element range
500 // multiple matches, we need to actually check the distance to each one
501 double minDist = HUGE_VAL;
502 FGPositionedRef result;
503 NamedPositionedIndex::const_iterator it = range.first;
504 SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
506 for (; it != range.second; ++it) {
507 FGPositioned* r = it->second;
509 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
513 if (!aFilter->pass(r)) {
519 double d2 = distSqr(cartOrigin, r->cart());
529 //////////////////////////////////////////////////////////////////////////////
534 bool operator()(FGPositioned* a, FGPositioned* b) const
536 return a->name() < b->name();
541 * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
542 * implement the AirportList dialog. It's unfortunate that it needs to reside
543 * here, but for now it's least ugly solution.
545 char** searchAirportNamesAndIdents(const std::string& aFilter)
547 const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
548 std::string filter(aFilter);
549 bool hasFilter = !filter.empty();
551 ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
554 NamedPositionedIndex::const_iterator it = global_identIndex.begin();
555 NamedPositionedIndex::const_iterator end = global_identIndex.end();
557 // note this is a vector of raw pointers, not smart pointers, because it
558 // may get very large and smart-pointer-atomicity-locking then becomes a
559 // bottleneck for this case.
560 std::vector<FGPositioned*> matches;
563 for (; it != end; ++it) {
564 FGPositioned::Type ty = it->second->type();
565 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
569 if (hasFilter && (it->second->ident().find(aFilter) == std::string::npos)) {
570 upper = it->second->name(); // string copy, sadly
571 ct.toupper((char *)upper.data(), (char *)upper.data() + upper.size());
572 if (upper.find(aFilter) == std::string::npos) {
577 matches.push_back(it->second);
580 // sort alphabetically on name
581 std::sort(matches.begin(), matches.end(), OrderByName());
583 // convert results to format comptible with puaList
584 unsigned int numMatches = matches.size();
585 char** result = new char*[numMatches + 1];
586 result[numMatches] = NULL; // end-of-list marker
588 // nasty code to avoid excessive string copying and allocations.
589 // We format results as follows (note whitespace!):
590 // ' name-of-airport-chars (ident)'
591 // so the total length is:
592 // 1 + strlen(name) + 4 + 4 (for the ident) + 1 + 1 (for the null)
593 // which gives a grand total of 11 + the length of the name.
594 // note the ident is sometimes only three letters for non-ICAO small strips
595 for (unsigned int i=0; i<numMatches; ++i) {
596 int nameLength = matches[i]->name().size();
597 int icaoLength = matches[i]->ident().size();
598 char* entry = new char[nameLength + 11];
601 memcpy(dst, matches[i]->name().c_str(), nameLength);
607 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
617 ///////////////////////////////////////////////////////////////////////////////
620 FGPositioned::Filter::hasTypeRange() const
622 assert(minType() <= maxType());
623 return (minType() != INVALID) && (maxType() != INVALID);
627 FGPositioned::Filter::passType(Type aTy) const
629 assert(hasTypeRange());
630 return (minType() <= aTy) && (maxType() >= aTy);
633 static FGPositioned::List
634 findAllSortedByRange(const NamedPositionedIndex& aIndex,
635 const std::string& aName, const SGGeod& aPos, FGPositioned::Filter* aFilter)
637 FGPositioned::List result;
638 NamedIndexRange range = aIndex.equal_range(aName);
639 for (; range.first != range.second; ++range.first) {
640 FGPositioned* candidate = range.first->second;
642 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
646 if (!aFilter->pass(candidate)) {
651 result.push_back(range.first->second);
654 sortByDistance(aPos, result);
658 static FGPositionedRef
659 findWithPartial(const NamedPositionedIndex& aIndex, const std::string& aName,
660 FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
662 // see comment in findNextWithPartialId concerning upperBoundId
663 std::string upperBoundId = aName;
664 upperBoundId[upperBoundId.size()-1]++;
665 NamedPositionedIndex::const_iterator upperBound = aIndex.lower_bound(upperBoundId);
667 NamedIndexRange range = aIndex.equal_range(aName);
668 FGPositionedRef result;
670 while (range.first != upperBound) {
671 for (; range.first != range.second; ++range.first) {
672 FGPositionedRef candidate = range.first->second;
674 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
678 if (!aFilter->pass(candidate)) {
686 } else if (aOffset == 0) {
687 // okay, found our result. we need to go around once more to set aNext
690 --aOffset; // seen one more valid result, decrement the count
694 // Unable to match the filter with this range - try the next range.
695 range = aIndex.equal_range(range.second->first);
698 // if we fell out, we reached the end of the valid range. We might have a
699 // valid result, but we definitiely don't have a next result.
704 ///////////////////////////////////////////////////////////////////////////////
706 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
711 SGReferenced::get(this); // hold an owning ref, for the moment
714 assert(ty != TAXIWAY && ty != PAVEMENT);
719 FGPositioned::~FGPositioned()
721 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
722 removeFromIndices(this);
726 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
728 return new FGPositioned(WAYPOINT, aIdent, aPos, true);
732 FGPositioned::bucket() const
734 return SGBucket(mPosition);
738 FGPositioned::cart() const
740 return SGVec3d::fromGeod(mPosition);
743 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
745 if (aName.empty() || (aName == "")) {
754 const NameTypeEntry names[] = {
755 {"airport", AIRPORT},
763 {"waypoint", WAYPOINT},
772 std::string lowerName(boost::to_lower_copy(aName));
774 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
775 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
780 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
784 const char* FGPositioned::nameForType(Type aTy)
787 case RUNWAY: return "runway";
788 case TAXIWAY: return "taxiway";
789 case PAVEMENT: return "pavement";
790 case PARK_STAND: return "parking stand";
791 case FIX: return "fix";
792 case VOR: return "VOR";
793 case NDB: return "NDB";
794 case ILS: return "ILS";
795 case LOC: return "localiser";
796 case GS: return "glideslope";
797 case OM: return "outer-marker";
798 case MM: return "middle-marker";
799 case IM: return "inner-marker";
800 case AIRPORT: return "airport";
801 case HELIPORT: return "heliport";
802 case SEAPORT: return "seaport";
803 case WAYPOINT: return "waypoint";
804 case DME: return "dme";
805 case TACAN: return "tacan";
811 ///////////////////////////////////////////////////////////////////////////////
812 // search / query functions
815 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
817 return namedFindClosest(global_identIndex, aIdent, aPos, aFilter);
821 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
824 Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
825 aRangeNm * SG_NM_TO_METER, aFilter, result);
830 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
832 return findAllSortedByRange(global_identIndex, aIdent, aPos, aFilter);
836 FGPositioned::findAllWithNameSortedByRange(const std::string& aName, const SGGeod& aPos, Filter* aFilter)
838 return findAllSortedByRange(global_nameIndex, aName, aPos, aFilter);
842 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
844 List l(findClosestN(aPos, 1, aCutoffNm, aFilter));
849 assert(l.size() == 1);
854 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
857 Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result);
862 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
868 std::string id(boost::to_upper_copy(aId));
870 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
871 // Do this by generating a second ID with the final character incremented by 1.
872 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
873 std::string upperBoundId = id;
874 upperBoundId[upperBoundId.size()-1]++;
875 NamedPositionedIndex::const_iterator upperBound = global_identIndex.lower_bound(upperBoundId);
877 NamedIndexRange range = global_identIndex.equal_range(id);
878 while (range.first != upperBound) {
879 for (; range.first != range.second; ++range.first) {
880 FGPositionedRef candidate = range.first->second;
881 if (aCur == candidate) {
882 aCur = NULL; // found our start point, next match will pass
887 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
891 if (!aFilter->pass(candidate)) {
901 // Unable to match the filter with this range - try the next range.
902 range = global_identIndex.equal_range(range.second->first);
905 return NULL; // Reached the end of the valid sequence with no match.
909 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
911 return findWithPartial(global_identIndex, aId, aFilter, aOffset, aNext);
916 FGPositioned::findWithPartialName(const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
918 return findWithPartial(global_nameIndex, aName, aFilter, aOffset, aNext);
922 * Wrapper filter which proxies to an inner filter, but also ensures the
923 * ident starts with supplied partial ident.
925 class PartialIdentFilter : public FGPositioned::Filter
928 PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
931 _ident = boost::to_upper_copy(ident);
934 virtual bool pass(FGPositioned* aPos) const
936 if (!_inner->pass(aPos)) {
940 return (boost::algorithm::starts_with(aPos->ident(), _ident));
943 virtual FGPositioned::Type minType() const
944 { return _inner->minType(); }
946 virtual FGPositioned::Type maxType() const
947 { return _inner->maxType(); }
951 FGPositioned::Filter* _inner;
954 static FGPositionedRef
955 findClosestWithPartial(const SGGeod& aPos, FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
957 // why aOffset +2 ? at offset=3, we want the fourth search result, but also
958 // to know if the fifth result exists (to set aNext flag for iterative APIs)
959 FGPositioned::List matches;
960 Octree::findNearestN(SGVec3d::fromGeod(aPos), aOffset + 2, 1000 * SG_NM_TO_METER, aFilter, matches);
962 if ((int) matches.size() <= aOffset) {
963 SG_LOG(SG_GENERAL, SG_INFO, "findClosestWithPartial, couldn't match enough with prefix");
965 return NULL; // couldn't find a match within the cutoff distance
968 aNext = ((int) matches.size() >= (aOffset + 2));
969 return matches[aOffset];
974 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
976 PartialIdentFilter pf(aId, aFilter);
977 return findClosestWithPartial(aPos, &pf, aOffset, aNext);
981 * Wrapper filter which proxies to an inner filter, but also ensures the
982 * name starts with supplied partial name.
984 class PartialNameFilter : public FGPositioned::Filter
987 PartialNameFilter(const std::string& nm, FGPositioned::Filter* filter) :
993 virtual bool pass(FGPositioned* aPos) const
995 if (!_inner->pass(aPos)) {
999 return (boost::algorithm::istarts_with(aPos->name(), _name));
1002 virtual FGPositioned::Type minType() const
1003 { return _inner->minType(); }
1005 virtual FGPositioned::Type maxType() const
1006 { return _inner->maxType(); }
1010 FGPositioned::Filter* _inner;
1014 FGPositioned::findClosestWithPartialName(const SGGeod& aPos, const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
1016 PartialNameFilter pf(aName, aFilter);
1017 return findClosestWithPartial(aPos, &pf, aOffset, aNext);