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 std::vector<Ordered<FGPositioned*> > results;
214 for (unsigned int i=0; i<_members.size(); ++i) {
215 FGPositioned* p = _members[i];
216 double d2 = distSqr(aPos, p->cart());
222 if (aFilter->hasTypeRange() && !aFilter->passType(p->type())) {
226 if (!aFilter->pass(p)) {
229 } // of have a filter
231 aResults.push_back(OrderedPositioned(p, d2));
235 FGPositioned::List _members;
238 class Branch : public Node
241 Branch(const SGBoxd& aBox) :
244 memset(children, 0, sizeof(Node*) * 8);
247 virtual void insert(FGPositioned* aP)
249 SGVec3d cart(aP->cart());
250 assert(contains(cart));
253 SGVec3d center(_box.getCenter());
254 // tests must match indices in SGbox::getCorner
255 if (cart.x() < center.x()) {
259 if (cart.y() < center.y()) {
263 if (cart.z() < center.z()) {
267 Node* child = children[childIndex];
268 if (!child) { // lazy building of children
269 SGBoxd cb(boxForChild(childIndex));
270 double d2 = dot(cb.getSize(), cb.getSize());
271 if (d2 < LEAF_SIZE_SQR) {
272 child = new Leaf(cb);
274 child = new Branch(cb);
277 children[childIndex] = child;
283 virtual void visit(const SGVec3d& aPos, double aCutoff,
284 FGPositioned::Filter*,
285 FindNearestResults&, FindNearestPQueue& aQ)
287 for (unsigned int i=0; i<8; ++i) {
292 double d2 = children[i]->distSqrToNearest(aPos);
294 continue; // exceeded cutoff
297 aQ.push(Ordered<Node*>(children[i], d2));
298 } // of child iteration
304 * Return the box for a child touching the specified corner
306 SGBoxd boxForChild(unsigned int aCorner) const
308 SGBoxd r(_box.getCenter());
309 r.expandBy(_box.getCorner(aCorner));
316 void findNearestN(const SGVec3d& aPos, unsigned int aN, double aCutoffM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
319 FindNearestPQueue pq;
320 FindNearestResults results;
321 pq.push(Ordered<Node*>(global_spatialOctree, 0));
322 double cut = aCutoffM * aCutoffM;
324 while (aResults.size() < aN) {
329 Node* nd = pq.top().get();
332 nd->visit(aPos, cut, aFilter, results, pq);
333 } // of queue iteration
336 std::sort(results.begin(), results.end());
337 // depending on leaf population, we may have (slighty) more results
339 unsigned int numResults = std::min((unsigned int) results.size(), aN);
342 aResults.resize(numResults);
343 for (unsigned int r=0; r<numResults; ++r) {
344 aResults[r] = results[r].get();
348 void findAllWithinRange(const SGVec3d& aPos, double aRangeM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
351 FindNearestPQueue pq;
352 FindNearestResults results;
353 pq.push(Ordered<Node*>(global_spatialOctree, 0));
354 double rng = aRangeM * aRangeM;
356 while (!pq.empty()) {
357 Node* nd = pq.top().get();
360 nd->visit(aPos, rng, aFilter, results, pq);
361 } // of queue iteration
364 std::sort(results.begin(), results.end());
365 unsigned int numResults = results.size();
368 aResults.resize(numResults);
369 for (unsigned int r=0; r<numResults; ++r) {
370 aResults[r] = results[r].get();
374 } // of namespace Octree
376 //////////////////////////////////////////////////////////////////////////////
379 addToIndices(FGPositioned* aPos)
382 if (!aPos->ident().empty()) {
383 global_identIndex.insert(global_identIndex.begin(),
384 std::make_pair(aPos->ident(), aPos));
387 if (!aPos->name().empty()) {
388 global_nameIndex.insert(global_nameIndex.begin(),
389 std::make_pair(aPos->name(), aPos));
392 if (!Octree::global_spatialOctree) {
393 double RADIUS_EARTH_M = 7000 * 1000.0; // 7000km is plenty
394 SGVec3d earthExtent(RADIUS_EARTH_M, RADIUS_EARTH_M, RADIUS_EARTH_M);
395 Octree::global_spatialOctree = new Octree::Branch(SGBox<double>(-earthExtent, earthExtent));
397 Octree::global_spatialOctree->insert(aPos);
401 removeFromIndices(FGPositioned* aPos)
405 if (!aPos->ident().empty()) {
406 NamedPositionedIndex::iterator it = global_identIndex.find(aPos->ident());
407 while (it != global_identIndex.end() && (it->first == aPos->ident())) {
408 if (it->second == aPos) {
409 global_identIndex.erase(it);
414 } // of multimap walk
417 if (!aPos->name().empty()) {
418 NamedPositionedIndex::iterator it = global_nameIndex.find(aPos->name());
419 while (it != global_nameIndex.end() && (it->first == aPos->name())) {
420 if (it->second == aPos) {
421 global_nameIndex.erase(it);
426 } // of multimap walk
430 class DistanceOrdering
433 DistanceOrdering(const SGGeod& aPos) :
434 mPos(SGVec3d::fromGeod(aPos))
437 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
440 throw sg_exception("empty reference passed to DistanceOrdering");
443 double dA = distSqr(a->cart(), mPos),
444 dB = distSqr(b->cart(), mPos);
453 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
455 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
458 static FGPositionedRef
459 namedFindClosest(const NamedPositionedIndex& aIndex, const std::string& aName,
460 const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
462 NamedIndexRange range = aIndex.equal_range(aName);
463 if (range.first == range.second) {
467 // common case, only one result. looks a bit ugly because these are
468 // sequential iterators, not random-access ones
469 NamedPositionedIndex::const_iterator check = range.first;
470 if (++check == range.second) {
471 // excellent, only one match in the range
472 FGPositioned* r = range.first->second;
474 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
478 if (!aFilter->pass(r)) {
481 } // of have a filter
484 } // of short-circuit logic for single-element range
486 // multiple matches, we need to actually check the distance to each one
487 double minDist = HUGE_VAL;
488 FGPositionedRef result;
489 NamedPositionedIndex::const_iterator it = range.first;
490 SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
492 for (; it != range.second; ++it) {
493 FGPositioned* r = it->second;
495 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
499 if (!aFilter->pass(r)) {
505 double d2 = distSqr(cartOrigin, r->cart());
515 //////////////////////////////////////////////////////////////////////////////
520 bool operator()(FGPositioned* a, FGPositioned* b) const
522 return a->name() < b->name();
527 * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
528 * implement the AirportList dialog. It's unfortunate that it needs to reside
529 * here, but for now it's least ugly solution.
531 char** searchAirportNamesAndIdents(const std::string& aFilter)
533 const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
534 std::string filter(aFilter);
535 bool hasFilter = !filter.empty();
537 ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
540 NamedPositionedIndex::const_iterator it = global_identIndex.begin();
541 NamedPositionedIndex::const_iterator end = global_identIndex.end();
543 // note this is a vector of raw pointers, not smart pointers, because it
544 // may get very large and smart-pointer-atomicity-locking then becomes a
545 // bottleneck for this case.
546 std::vector<FGPositioned*> matches;
549 for (; it != end; ++it) {
550 FGPositioned::Type ty = it->second->type();
551 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
555 if (hasFilter && (it->second->ident().find(aFilter) == std::string::npos)) {
556 upper = it->second->name(); // string copy, sadly
557 ct.toupper((char *)upper.data(), (char *)upper.data() + upper.size());
558 if (upper.find(aFilter) == std::string::npos) {
563 matches.push_back(it->second);
566 // sort alphabetically on name
567 std::sort(matches.begin(), matches.end(), OrderByName());
569 // convert results to format comptible with puaList
570 unsigned int numMatches = matches.size();
571 char** result = new char*[numMatches + 1];
572 result[numMatches] = NULL; // end-of-list marker
574 // nasty code to avoid excessive string copying and allocations.
575 // We format results as follows (note whitespace!):
576 // ' name-of-airport-chars (ident)'
577 // so the total length is:
578 // 1 + strlen(name) + 4 + 4 (for the ident) + 1 + 1 (for the null)
579 // which gives a grand total of 11 + the length of the name.
580 // note the ident is sometimes only three letters for non-ICAO small strips
581 for (unsigned int i=0; i<numMatches; ++i) {
582 int nameLength = matches[i]->name().size();
583 int icaoLength = matches[i]->ident().size();
584 char* entry = new char[nameLength + 11];
587 memcpy(dst, matches[i]->name().c_str(), nameLength);
593 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
603 ///////////////////////////////////////////////////////////////////////////////
606 FGPositioned::Filter::hasTypeRange() const
608 assert(minType() <= maxType());
609 return (minType() != INVALID) && (maxType() != INVALID);
613 FGPositioned::Filter::passType(Type aTy) const
615 assert(hasTypeRange());
616 return (minType() <= aTy) && (maxType() >= aTy);
619 static FGPositioned::List
620 findAllSortedByRange(const NamedPositionedIndex& aIndex,
621 const std::string& aName, const SGGeod& aPos, FGPositioned::Filter* aFilter)
623 FGPositioned::List result;
624 NamedIndexRange range = aIndex.equal_range(aName);
625 for (; range.first != range.second; ++range.first) {
626 FGPositioned* candidate = range.first->second;
628 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
632 if (!aFilter->pass(candidate)) {
637 result.push_back(range.first->second);
640 sortByDistance(aPos, result);
644 static FGPositionedRef
645 findWithPartial(const NamedPositionedIndex& aIndex, const std::string& aName,
646 FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
648 // see comment in findNextWithPartialId concerning upperBoundId
649 std::string upperBoundId = aName;
650 upperBoundId[upperBoundId.size()-1]++;
651 NamedPositionedIndex::const_iterator upperBound = aIndex.lower_bound(upperBoundId);
653 NamedIndexRange range = aIndex.equal_range(aName);
654 FGPositionedRef result;
656 while (range.first != upperBound) {
657 for (; range.first != range.second; ++range.first) {
658 FGPositionedRef candidate = range.first->second;
660 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
664 if (!aFilter->pass(candidate)) {
672 } else if (aOffset == 0) {
673 // okay, found our result. we need to go around once more to set aNext
676 --aOffset; // seen one more valid result, decrement the count
680 // Unable to match the filter with this range - try the next range.
681 range = aIndex.equal_range(range.second->first);
684 // if we fell out, we reached the end of the valid range. We might have a
685 // valid result, but we definitiely don't have a next result.
690 ///////////////////////////////////////////////////////////////////////////////
692 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
697 SGReferenced::get(this); // hold an owning ref, for the moment
700 assert(ty != TAXIWAY && ty != PAVEMENT);
705 FGPositioned::~FGPositioned()
707 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
708 removeFromIndices(this);
712 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
714 return new FGPositioned(WAYPOINT, aIdent, aPos, true);
718 FGPositioned::bucket() const
720 return SGBucket(mPosition);
724 FGPositioned::cart() const
726 return SGVec3d::fromGeod(mPosition);
729 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
731 if (aName.empty() || (aName == "")) {
740 const NameTypeEntry names[] = {
741 {"airport", AIRPORT},
749 {"waypoint", WAYPOINT},
758 std::string lowerName(boost::to_lower_copy(aName));
760 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
761 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
766 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
770 const char* FGPositioned::nameForType(Type aTy)
773 case RUNWAY: return "runway";
774 case TAXIWAY: return "taxiway";
775 case PAVEMENT: return "pavement";
776 case PARK_STAND: return "parking stand";
777 case FIX: return "fix";
778 case VOR: return "VOR";
779 case NDB: return "NDB";
780 case ILS: return "ILS";
781 case LOC: return "localiser";
782 case GS: return "glideslope";
783 case OM: return "outer-marker";
784 case MM: return "middle-marker";
785 case IM: return "inner-marker";
786 case AIRPORT: return "airport";
787 case HELIPORT: return "heliport";
788 case SEAPORT: return "seaport";
789 case WAYPOINT: return "waypoint";
790 case DME: return "dme";
791 case TACAN: return "tacan";
797 ///////////////////////////////////////////////////////////////////////////////
798 // search / query functions
801 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
803 return namedFindClosest(global_identIndex, aIdent, aPos, aFilter);
807 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
810 Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
811 aRangeNm * SG_NM_TO_METER, aFilter, result);
816 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
818 return findAllSortedByRange(global_identIndex, aIdent, aPos, aFilter);
822 FGPositioned::findAllWithNameSortedByRange(const std::string& aName, const SGGeod& aPos, Filter* aFilter)
824 return findAllSortedByRange(global_nameIndex, aName, aPos, aFilter);
828 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
830 List l(findClosestN(aPos, 1, aCutoffNm, aFilter));
835 assert(l.size() == 1);
840 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
843 Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result);
848 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
854 std::string id(boost::to_upper_copy(aId));
856 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
857 // Do this by generating a second ID with the final character incremented by 1.
858 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
859 std::string upperBoundId = id;
860 upperBoundId[upperBoundId.size()-1]++;
861 NamedPositionedIndex::const_iterator upperBound = global_identIndex.lower_bound(upperBoundId);
863 NamedIndexRange range = global_identIndex.equal_range(id);
864 while (range.first != upperBound) {
865 for (; range.first != range.second; ++range.first) {
866 FGPositionedRef candidate = range.first->second;
867 if (aCur == candidate) {
868 aCur = NULL; // found our start point, next match will pass
873 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
877 if (!aFilter->pass(candidate)) {
887 // Unable to match the filter with this range - try the next range.
888 range = global_identIndex.equal_range(range.second->first);
891 return NULL; // Reached the end of the valid sequence with no match.
895 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
897 return findWithPartial(global_identIndex, aId, aFilter, aOffset, aNext);
902 FGPositioned::findWithPartialName(const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
904 return findWithPartial(global_nameIndex, aName, aFilter, aOffset, aNext);
908 * Wrapper filter which proxies to an inner filter, but also ensures the
909 * ident starts with supplied partial ident.
911 class PartialIdentFilter : public FGPositioned::Filter
914 PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
917 _ident = boost::to_upper_copy(ident);
920 virtual bool pass(FGPositioned* aPos) const
922 if (!_inner->pass(aPos)) {
926 return (boost::algorithm::starts_with(aPos->ident(), _ident));
929 virtual FGPositioned::Type minType() const
930 { return _inner->minType(); }
932 virtual FGPositioned::Type maxType() const
933 { return _inner->maxType(); }
937 FGPositioned::Filter* _inner;
940 static FGPositionedRef
941 findClosestWithPartial(const SGGeod& aPos, FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
943 // why aOffset +2 ? at offset=3, we want the fourth search result, but also
944 // to know if the fifth result exists (to set aNext flag for iterative APIs)
945 FGPositioned::List matches;
946 Octree::findNearestN(SGVec3d::fromGeod(aPos), aOffset + 2, 1000 * SG_NM_TO_METER, aFilter, matches);
948 if ((int) matches.size() <= aOffset) {
949 SG_LOG(SG_GENERAL, SG_INFO, "findClosestWithPartial, couldn't match enough with prefix");
951 return NULL; // couldn't find a match within the cutoff distance
954 aNext = ((int) matches.size() >= (aOffset + 2));
955 return matches[aOffset];
960 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
962 PartialIdentFilter pf(aId, aFilter);
963 return findClosestWithPartial(aPos, &pf, aOffset, aNext);
967 * Wrapper filter which proxies to an inner filter, but also ensures the
968 * name starts with supplied partial name.
970 class PartialNameFilter : public FGPositioned::Filter
973 PartialNameFilter(const std::string& nm, FGPositioned::Filter* filter) :
979 virtual bool pass(FGPositioned* aPos) const
981 if (!_inner->pass(aPos)) {
985 return (boost::algorithm::istarts_with(aPos->name(), _name));
988 virtual FGPositioned::Type minType() const
989 { return _inner->minType(); }
991 virtual FGPositioned::Type maxType() const
992 { return _inner->maxType(); }
996 FGPositioned::Filter* _inner;
1000 FGPositioned::findClosestWithPartialName(const SGGeod& aPos, const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
1002 PartialNameFilter pf(aName, aFilter);
1003 return findClosestWithPartial(aPos, &pf, aOffset, aNext);