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 + strlen(icao) + 1 + 1 (for the null)
554 // which gives a grand total of 7 + name-length + icao-length.
555 // note the ident can be three letters (non-ICAO local strip), four
556 // (default ICAO) or more (extended format ICAO)
557 for (unsigned int i=0; i<numMatches; ++i) {
558 int nameLength = matches[i]->name().size();
559 int icaoLength = matches[i]->ident().size();
560 char* entry = new char[7 + nameLength + icaoLength];
563 memcpy(dst, matches[i]->name().c_str(), nameLength);
569 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
579 ///////////////////////////////////////////////////////////////////////////////
582 FGPositioned::Filter::hasTypeRange() const
584 assert(minType() <= maxType());
585 return (minType() != INVALID) && (maxType() != INVALID);
589 FGPositioned::Filter::passType(Type aTy) const
591 assert(hasTypeRange());
592 return (minType() <= aTy) && (maxType() >= aTy);
595 static FGPositioned::List
596 findAllSortedByRange(const NamedPositionedIndex& aIndex,
597 const std::string& aName, const SGGeod& aPos, FGPositioned::Filter* aFilter)
599 FGPositioned::List result;
600 NamedIndexRange range = aIndex.equal_range(aName);
601 for (; range.first != range.second; ++range.first) {
602 FGPositioned* candidate = range.first->second;
604 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
608 if (!aFilter->pass(candidate)) {
613 result.push_back(range.first->second);
616 sortByDistance(aPos, result);
620 static FGPositionedRef
621 findWithPartial(const NamedPositionedIndex& aIndex, const std::string& aName,
622 FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
624 // see comment in findNextWithPartialId concerning upperBoundId
625 std::string upperBoundId = aName;
626 upperBoundId[upperBoundId.size()-1]++;
627 NamedPositionedIndex::const_iterator upperBound = aIndex.lower_bound(upperBoundId);
629 NamedIndexRange range = aIndex.equal_range(aName);
630 FGPositionedRef result;
632 while (range.first != upperBound) {
633 for (; range.first != range.second; ++range.first) {
634 FGPositionedRef candidate = range.first->second;
636 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
640 if (!aFilter->pass(candidate)) {
648 } else if (aOffset == 0) {
649 // okay, found our result. we need to go around once more to set aNext
652 --aOffset; // seen one more valid result, decrement the count
656 // Unable to match the filter with this range - try the next range.
657 range = aIndex.equal_range(range.second->first);
660 // if we fell out, we reached the end of the valid range. We might have a
661 // valid result, but we definitiely don't have a next result.
666 ///////////////////////////////////////////////////////////////////////////////
668 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
673 SGReferenced::get(this); // hold an owning ref, for the moment
676 assert(ty != TAXIWAY && ty != PAVEMENT);
681 FGPositioned::~FGPositioned()
683 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
684 removeFromIndices(this);
688 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
690 return new FGPositioned(WAYPOINT, aIdent, aPos, true);
694 FGPositioned::cart() const
696 return SGVec3d::fromGeod(mPosition);
699 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
701 if (aName.empty() || (aName == "")) {
710 const NameTypeEntry names[] = {
711 {"airport", AIRPORT},
719 {"waypoint", WAYPOINT},
728 std::string lowerName(boost::to_lower_copy(aName));
730 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
731 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
736 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
740 const char* FGPositioned::nameForType(Type aTy)
743 case RUNWAY: return "runway";
744 case TAXIWAY: return "taxiway";
745 case PAVEMENT: return "pavement";
746 case PARK_STAND: return "parking stand";
747 case FIX: return "fix";
748 case VOR: return "VOR";
749 case NDB: return "NDB";
750 case ILS: return "ILS";
751 case LOC: return "localiser";
752 case GS: return "glideslope";
753 case OM: return "outer-marker";
754 case MM: return "middle-marker";
755 case IM: return "inner-marker";
756 case AIRPORT: return "airport";
757 case HELIPORT: return "heliport";
758 case SEAPORT: return "seaport";
759 case WAYPOINT: return "waypoint";
760 case DME: return "dme";
761 case TACAN: return "tacan";
767 ///////////////////////////////////////////////////////////////////////////////
768 // search / query functions
771 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
773 return namedFindClosest(global_identIndex, aIdent, aPos, aFilter);
777 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
780 Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
781 aRangeNm * SG_NM_TO_METER, aFilter, result);
786 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
788 return findAllSortedByRange(global_identIndex, aIdent, aPos, aFilter);
792 FGPositioned::findAllWithNameSortedByRange(const std::string& aName, const SGGeod& aPos, Filter* aFilter)
794 return findAllSortedByRange(global_nameIndex, aName, aPos, aFilter);
798 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
800 List l(findClosestN(aPos, 1, aCutoffNm, aFilter));
805 assert(l.size() == 1);
810 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
813 Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result);
818 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
824 std::string id(boost::to_upper_copy(aId));
826 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
827 // Do this by generating a second ID with the final character incremented by 1.
828 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
829 std::string upperBoundId = id;
830 upperBoundId[upperBoundId.size()-1]++;
831 NamedPositionedIndex::const_iterator upperBound = global_identIndex.lower_bound(upperBoundId);
833 NamedIndexRange range = global_identIndex.equal_range(id);
834 while (range.first != upperBound) {
835 for (; range.first != range.second; ++range.first) {
836 FGPositionedRef candidate = range.first->second;
837 if (aCur == candidate) {
838 aCur = NULL; // found our start point, next match will pass
843 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
847 if (!aFilter->pass(candidate)) {
857 // Unable to match the filter with this range - try the next range.
858 range = global_identIndex.equal_range(range.second->first);
861 return NULL; // Reached the end of the valid sequence with no match.
865 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
867 return findWithPartial(global_identIndex, aId, aFilter, aOffset, aNext);
872 FGPositioned::findWithPartialName(const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
874 return findWithPartial(global_nameIndex, aName, aFilter, aOffset, aNext);
878 * Wrapper filter which proxies to an inner filter, but also ensures the
879 * ident starts with supplied partial ident.
881 class PartialIdentFilter : public FGPositioned::Filter
884 PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
887 _ident = boost::to_upper_copy(ident);
890 virtual bool pass(FGPositioned* aPos) const
892 if (!_inner->pass(aPos)) {
896 return (boost::algorithm::starts_with(aPos->ident(), _ident));
899 virtual FGPositioned::Type minType() const
900 { return _inner->minType(); }
902 virtual FGPositioned::Type maxType() const
903 { return _inner->maxType(); }
907 FGPositioned::Filter* _inner;
910 static FGPositionedRef
911 findClosestWithPartial(const SGGeod& aPos, FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
913 // why aOffset +2 ? at offset=3, we want the fourth search result, but also
914 // to know if the fifth result exists (to set aNext flag for iterative APIs)
915 FGPositioned::List matches;
916 Octree::findNearestN(SGVec3d::fromGeod(aPos), aOffset + 2, 1000 * SG_NM_TO_METER, aFilter, matches);
918 if ((int) matches.size() <= aOffset) {
919 SG_LOG(SG_GENERAL, SG_INFO, "findClosestWithPartial, couldn't match enough with prefix");
921 return NULL; // couldn't find a match within the cutoff distance
924 aNext = ((int) matches.size() >= (aOffset + 2));
925 return matches[aOffset];
930 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
932 PartialIdentFilter pf(aId, aFilter);
933 return findClosestWithPartial(aPos, &pf, aOffset, aNext);
937 * Wrapper filter which proxies to an inner filter, but also ensures the
938 * name starts with supplied partial name.
940 class PartialNameFilter : public FGPositioned::Filter
943 PartialNameFilter(const std::string& nm, FGPositioned::Filter* filter) :
949 virtual bool pass(FGPositioned* aPos) const
951 if (!_inner->pass(aPos)) {
955 return (boost::algorithm::istarts_with(aPos->name(), _name));
958 virtual FGPositioned::Type minType() const
959 { return _inner->minType(); }
961 virtual FGPositioned::Type maxType() const
962 { return _inner->maxType(); }
966 FGPositioned::Filter* _inner;
970 FGPositioned::findClosestWithPartialName(const SGGeod& aPos, const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
972 PartialNameFilter pf(aName, aFilter);
973 return findClosestWithPartial(aPos, &pf, aOffset, aNext);