# include "config.h"
#endif
+#include "positioned.hxx"
+
#include <map>
#include <set>
-#include <algorithm>
+#include <algorithm> // for sort
+#include <queue>
+#include <memory>
-#include <simgear/math/sg_geodesy.hxx>
+#include <boost/algorithm/string/case_conv.hpp>
+#include <boost/algorithm/string/predicate.hpp>
-#include "positioned.hxx"
+#include <simgear/timing/timestamp.hxx>
+#include <simgear/debug/logstream.hxx>
+#include <simgear/structure/exception.hxx>
+#include <simgear/math/SGGeometry.hxx>
+#include <simgear/sg_inlines.h>
-typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
-typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
+#include "Navaids/PositionedOctree.hxx"
-/**
- * Order positioned elements by type, then pointer address. This allows us to
- * use range searches (lower_ and upper_bound) to grab items of a particular
- * type out of bucket efficently.
- */
-class OrderByType
-{
-public:
- bool operator()(const FGPositioned* a, const FGPositioned* b) const
- {
- if (a->type() == b->type()) return a < b;
- return a->type() < b->type();
- }
-};
-
-typedef std::set<FGPositioned*, OrderByType> BucketEntry;
-typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
+using std::string;
+using namespace flightgear;
-static NamedPositionedIndex global_namedIndex;
-static SpatialPositionedIndex global_spatialIndex;
-
-SpatialPositionedIndex::iterator
-bucketEntryForPositioned(FGPositioned* aPos)
+static void validateSGGeod(const SGGeod& geod)
{
- int bucketIndex = aPos->bucket().gen_index();
- SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
- if (it != global_spatialIndex.end()) {
- return it;
+ if (SGMisc<double>::isNaN(geod.getLatitudeDeg()) ||
+ SGMisc<double>::isNaN(geod.getLongitudeDeg()))
+ {
+ throw sg_range_exception("position is invalid, NaNs");
}
-
- // create a new BucketEntry
- return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
-}
-
-static void
-addToIndices(FGPositioned* aPos)
-{
- assert(aPos);
- global_namedIndex.insert(global_namedIndex.begin(),
- std::make_pair(aPos->ident(), aPos));
-
- SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
- it->second.insert(aPos);
}
-static void
-removeFromIndices(FGPositioned* aPos)
-{
- assert(aPos);
-
- NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
- while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
- if (it->second == aPos) {
- global_namedIndex.erase(it);
- break;
- }
-
- ++it;
- }
-
- SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
- sit->second.erase(aPos);
-}
-static void
-spatialFilterInBucket(const SGBucket& aBucket, const FGPositioned::Filter& aFilter, FGPositioned::List& aResult)
-{
- SpatialPositionedIndex::const_iterator it;
- it = global_spatialIndex.find(aBucket.gen_index());
- if (it == global_spatialIndex.end()) {
- return;
- }
-
- BucketEntry::const_iterator l = it->second.begin();
- BucketEntry::const_iterator u = it->second.end();
+///////////////////////////////////////////////////////////////////////////////
- for ( ; l != u; ++l) {
- if (aFilter(*l)) {
- aResult.push_back(*l);
- }
- }
+FGPositioned::FGPositioned(PositionedID aGuid, Type ty, const std::string& aIdent, const SGGeod& aPos) :
+ mGuid(aGuid),
+ mPosition(aPos),
+ mCart(SGVec3d::fromGeod(mPosition)),
+ mType(ty),
+ mIdent(aIdent)
+{
}
-static void
-spatialFind(const SGGeod& aPos, double aRange,
- const FGPositioned::Filter& aFilter, FGPositioned::List& aResult)
+FGPositioned::~FGPositioned()
{
- SGBucket buck(aPos);
- double lat = aPos.getLatitudeDeg(),
- lon = aPos.getLongitudeDeg();
-
- int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
- int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
-
- // loop over bucket range
- for ( int i=-bx; i<=bx; i++) {
- for ( int j=-by; j<=by; j++) {
- spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
- } // of j-iteration
- } // of i-iteration
+// std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
}
-class LowerLimitOfType
+FGPositioned*
+FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
{
-public:
- bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
- {
- return a->type() < b;
+ NavDataCache* cache = NavDataCache::instance();
+ TypeFilter filter(WAYPOINT);
+ FGPositioned::List existing = cache->findAllWithIdent(aIdent, &filter, true);
+ if (!existing.empty()) {
+ SG_LOG(SG_NAVAID, SG_WARN, "attempt to insert duplicate WAYPOINT:" << aIdent);
+ return existing.front().ptr();
}
- bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
- {
- return a < b->type();
- }
-};
+ PositionedID id = cache->createPOI(WAYPOINT, aIdent, aPos);
+ return cache->loadById(id);
+}
-static void
-spatialFindTyped(const SGGeod& aPos, double aRange, FGPositioned::Type aLower, FGPositioned::Type aUpper, FGPositioned::List& aResult)
+void FGPositioned::deleteUserWaypoint(const std::string& aIdent)
{
- SGBucket buck(aPos);
- double lat = aPos.getLatitudeDeg(),
- lon = aPos.getLongitudeDeg();
-
- int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
- int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
-
- // loop over bucket range
- for ( int i=-bx; i<=bx; i++) {
- for ( int j=-by; j<=by; j++) {
- buck = sgBucketOffset(lon, lat, i, j);
-
- SpatialPositionedIndex::const_iterator it;
- it = global_spatialIndex.find(buck.gen_index());
- if (it == global_spatialIndex.end()) {
- continue;
- }
-
- BucketEntry::const_iterator l = std::lower_bound(it->second.begin(), it->second.end(), aLower, LowerLimitOfType());
- BucketEntry::const_iterator u = std::upper_bound(l, it->second.end(), aUpper, LowerLimitOfType());
-
- for ( ; l != u; ++l) {
- aResult.push_back(*l);
- }
-
- } // of j-iteration
- } // of i-iteration
+ NavDataCache* cache = NavDataCache::instance();
+ cache->removePOI(WAYPOINT, aIdent);
}
-/**
- * Cartesian range predicate. Note that for really long ranges, might need to
- * to use geodetic / geocentric distance instead
- */
-class RangePredictate
-{
-public:
- RangePredictate(const Point3D& aOrigin, double aRange) :
- mOrigin(aOrigin),
- mRangeSquared(aRange * aRange)
- { ; }
-
- bool operator()(const FGPositionedRef& aPos)
- {
- Point3D p(Point3D::fromSGGeod(aPos->geod()));
- bool ok = (mOrigin.distance3Dsquared(p) > mRangeSquared);
- if (ok) {
- double x = sqrt(mOrigin.distance3Dsquared(p) - mRangeSquared);
- x *= SG_METER_TO_NM;
- //std::cout << "pos:" << aPos->ident() << " failed range check by " << x << std::endl;
- }
- return ok;
- }
-
-private:
- Point3D mOrigin;
- double mRangeSquared;
-};
-static void
-filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
+const SGVec3d&
+FGPositioned::cart() const
{
- RangePredictate pred(Point3D::fromSGGeod(aPos), aRange * SG_NM_TO_METER);
- FGPositioned::List::iterator newEnd;
- newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
- aResult.erase(newEnd, aResult.end());
+ return mCart;
}
-class DistanceOrdering
+FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
{
-public:
- DistanceOrdering(const SGGeod& aPos) :
- mPos(Point3D::fromSGGeod(aPos))
- { }
-
- bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
- {
- return mPos.distance3Dsquared(Point3D::fromSGGeod(a->geod())) <
- mPos.distance3Dsquared(Point3D::fromSGGeod(b->geod()));
+ if (aName.empty() || (aName == "")) {
+ return INVALID;
}
-private:
- Point3D mPos;
-};
-
-static void
-sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
-{
- std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
-}
-
-static FGPositionedRef
-namedFindClosestTyped(const std::string& aIdent, const SGGeod& aOrigin,
- FGPositioned::Type aLower, FGPositioned::Type aUpper)
-{
- NamedIndexRange range = global_namedIndex.equal_range(aIdent);
- if (range.first == range.second) return NULL;
+ typedef struct {
+ const char* _name;
+ Type _ty;
+ } NameTypeEntry;
-// common case, only one result. looks a bit ugly because these are
-// sequential iterators, not random-access ones
- NamedPositionedIndex::const_iterator check = range.first;
- if (++check == range.second) {
- // excellent, only one match in the range - all we care about is the type
- FGPositioned::Type ty = range.first->second->type();
- if ((ty < aLower) || (ty > aUpper)) {
- return NULL; // type check failed
- }
+ const NameTypeEntry names[] = {
+ {"airport", AIRPORT},
+ {"vor", VOR},
+ {"loc", LOC},
+ {"ils", ILS},
+ {"gs", GS},
+ {"ndb", NDB},
+ {"wpt", WAYPOINT},
+ {"fix", FIX},
+ {"tacan", TACAN},
+ {"dme", DME},
+ {"atis", FREQ_ATIS},
+ {"awos", FREQ_AWOS},
+ {"tower", FREQ_TOWER},
+ {"ground", FREQ_GROUND},
+ {"approach", FREQ_APP_DEP},
+ {"departure", FREQ_APP_DEP},
+ {"runway", RUNWAY},
+ {"helipad", HELIPAD},
+ {"country", COUNTRY},
+ {"city", CITY},
+ {"town", TOWN},
+ {"village", VILLAGE},
+
+ // aliases
+ {"gnd", FREQ_GROUND},
+ {"twr", FREQ_TOWER},
+ {"waypoint", WAYPOINT},
+ {"apt", AIRPORT},
+ {"arpt", AIRPORT},
+ {"rwy", RUNWAY},
+ {"any", INVALID},
+ {"all", INVALID},
- return range.first->second;
- } // of short-circuit logic for single-element range
+ {NULL, INVALID}
+ };
-// multiple matches, we need to actually check the distance to each one
- double minDist = HUGE_VAL;
- FGPositionedRef result;
- Point3D origin(Point3D::fromSGGeod(aOrigin));
+ std::string lowerName(boost::to_lower_copy(aName));
- for (; range.first != range.second; ++range.first) {
- // filter by type
- FGPositioned::Type ty = range.first->second->type();
- if ((ty < aLower) || (ty > aUpper)) {
- continue;
- }
-
- // find distance
- Point3D p(Point3D::fromSGGeod(range.first->second->geod()));
- double ds = origin.distance3Dsquared(p);
- if (ds < minDist) {
- minDist = ds;
- result = range.first->second;
+ for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
+ if (::strcmp(n->_name, lowerName.c_str()) == 0) {
+ return n->_ty;
}
}
- return result;
-}
-
-static FGPositioned::List
-spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, const FGPositioned::Filter& aFilter)
-{
- FGPositioned::List result;
- int radius = 1; // start at 1, radius 0 is handled explicitly
- SGBucket buck;
- double lat = aPos.getLatitudeDeg(),
- lon = aPos.getLongitudeDeg();
- // final cutoff is in metres, and scaled to account for testing the corners
- // of the 'box' instead of the centre of each edge
- double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
-
- // base case, simplifes loop to do it seperately here
- spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
-
- for (;result.size() < aN; ++radius) {
- // cutoff check
- double az1, az2, d1, d2;
- SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
- SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);
-
- if ((d1 > cutoffM) && (d2 > cutoffM)) {
- //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
- break;
- }
-
- FGPositioned::List hits;
- for ( int i=-radius; i<=radius; i++) {
- spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
- spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
- spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
- spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
- }
-
- result.insert(result.end(), hits.begin(), hits.end()); // append
- } // of outer loop
-
- if (result.size() > aN) {
- result.resize(aN); // truncate at requested number of matches
- }
-
- sortByDistance(aPos, result);
- return result;
-}
-
-///////////////////////////////////////////////////////////////////////////////
-
-FGPositioned::FGPositioned() :
- mType(INVALID)
-{
-}
-
-FGPositioned::FGPositioned(Type ty, const std::string& aIdent, double aLat, double aLon, double aElev) :
- mType(ty),
- mIdent(aIdent),
- mPosition(SGGeod::fromDegFt(aLon, aLat, aElev))
-{
- //addToIndices(this);
- //SGReferenced::get(this); // hold an owning ref, for the moment
-}
-
-FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos) :
- mType(ty),
- mIdent(aIdent),
- mPosition(aPos)
-{
- //addToIndices(this);
- //SGReferenced::get(this); // hold an owning ref, for the moment
-}
-
-FGPositioned::~FGPositioned()
-{
- //std::cout << "~FGPositioned:" << mIdent << std::endl;
- //removeFromIndices(this);
-}
-
-SGBucket
-FGPositioned::bucket() const
-{
- return SGBucket(mPosition);
+ SG_LOG(SG_NAVAID, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
+ return INVALID;
}
const char* FGPositioned::nameForType(Type aTy)
{
switch (aTy) {
+ case RUNWAY: return "runway";
+ case HELIPAD: return "helipad";
+ case TAXIWAY: return "taxiway";
+ case PAVEMENT: return "pavement";
+ case PARKING: return "parking stand";
case FIX: return "fix";
case VOR: return "VOR";
case NDB: return "NDB";
+ case ILS: return "ILS";
+ case LOC: return "localiser";
+ case GS: return "glideslope";
case OM: return "outer-marker";
case MM: return "middle-marker";
case IM: return "inner-marker";
case HELIPORT: return "heliport";
case SEAPORT: return "seaport";
case WAYPOINT: return "waypoint";
+ case DME: return "dme";
+ case TACAN: return "tacan";
+ case FREQ_TOWER: return "tower";
+ case FREQ_ATIS: return "atis";
+ case FREQ_AWOS: return "awos";
+ case FREQ_GROUND: return "ground";
+ case FREQ_CLEARANCE: return "clearance";
+ case FREQ_UNICOM: return "unicom";
+ case FREQ_APP_DEP: return "approach-departure";
+ case TAXI_NODE: return "taxi-node";
+ case COUNTRY: return "country";
+ case CITY: return "city";
+ case TOWN: return "town";
+ case VILLAGE: return "village";
default:
return "unknown";
}
// search / query functions
FGPositionedRef
-FGPositioned::findClosestWithIdent(const std::string& aIdent, double aLat, double aLon)
+FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
{
- return findClosestWithIdent(aIdent, SGGeod::fromDeg(aLon, aLat));
+ validateSGGeod(aPos);
+ return NavDataCache::instance()->findClosestWithIdent(aIdent, aPos, aFilter);
}
FGPositionedRef
-FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos)
+FGPositioned::findFirstWithIdent(const std::string& aIdent, Filter* aFilter)
{
- return namedFindClosestTyped(aIdent, aPos, INVALID, LAST_TYPE);
+ if (aIdent.empty()) {
+ return NULL;
+ }
+
+ List r = NavDataCache::instance()->findAllWithIdent(aIdent, aFilter, true);
+ if (r.empty()) {
+ return NULL;
+ }
+
+ return r.front();
}
FGPositioned::List
-FGPositioned::findWithinRangeByType(const SGGeod& aPos, double aRangeNm, Type aTy)
+FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
{
+ validateSGGeod(aPos);
+
List result;
- spatialFindTyped(aPos, aRangeNm, aTy, aTy, result);
- filterListByRange(aPos, aRangeNm, result);
+ Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
+ aRangeNm * SG_NM_TO_METER, aFilter, result, 0xffffff);
return result;
}
FGPositioned::List
-FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, const Filter& aFilter)
+FGPositioned::findWithinRangePartial(const SGGeod& aPos, double aRangeNm, Filter* aFilter, bool& aPartial)
{
+ validateSGGeod(aPos);
+
+ int limitMsec = 32;
List result;
- spatialFind(aPos, aRangeNm, aFilter, result);
- filterListByRange(aPos, aRangeNm, result);
+ aPartial = Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
+ aRangeNm * SG_NM_TO_METER, aFilter, result,
+ limitMsec);
return result;
}
FGPositioned::List
-FGPositioned::findAllWithIdent(const std::string& aIdent)
+FGPositioned::findAllWithIdent(const std::string& aIdent, Filter* aFilter, bool aExact)
{
- List result;
- NamedIndexRange range = global_namedIndex.equal_range(aIdent);
- for (; range.first != range.second; ++range.first) {
- result.push_back(range.first->second);
+ return NavDataCache::instance()->findAllWithIdent(aIdent, aFilter, aExact);
+}
+
+FGPositioned::List
+FGPositioned::findAllWithName(const std::string& aName, Filter* aFilter, bool aExact)
+{
+ return NavDataCache::instance()->findAllWithName(aName, aFilter, aExact);
+}
+
+FGPositionedRef
+FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
+{
+ validateSGGeod(aPos);
+
+ List l(findClosestN(aPos, 1, aCutoffNm, aFilter));
+ if (l.empty()) {
+ return NULL;
}
+
+ assert(l.size() == 1);
+ return l.front();
+}
+
+FGPositioned::List
+FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
+{
+ validateSGGeod(aPos);
+ List result;
+ int limitMsec = 0xffff;
+ Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result, limitMsec);
return result;
}
FGPositioned::List
-FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, const Filter& aFilter)
+FGPositioned::findClosestNPartial(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter, bool &aPartial)
+{
+ validateSGGeod(aPos);
+
+ List result;
+ int limitMsec = 32;
+ aPartial = Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result,
+ limitMsec);
+ return result;
+}
+
+void
+FGPositioned::sortByRange(List& aResult, const SGGeod& aPos)
{
- return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
+ validateSGGeod(aPos);
+
+ SGVec3d cartPos(SGVec3d::fromGeod(aPos));
+// computer ordering values
+ Octree::FindNearestResults r;
+ List::iterator it = aResult.begin(), lend = aResult.end();
+ for (; it != lend; ++it) {
+ double d2 = distSqr((*it)->cart(), cartPos);
+ r.push_back(Octree::OrderedPositioned(*it, d2));
+ }
+
+// sort
+ std::sort(r.begin(), r.end());
+
+// convert to a plain list
+ unsigned int count = aResult.size();
+ for (unsigned int i=0; i<count; ++i) {
+ aResult[i] = r[i].get();
+ }
+}
+
+void FGPositioned::modifyPosition(const SGGeod& newPos)
+{
+ const_cast<SGGeod&>(mPosition) = newPos;
+ const_cast<SGVec3d&>(mCart) = SGVec3d::fromGeod(newPos);
+}
+
+FGPositioned::TypeFilter::TypeFilter(Type aTy) :
+ mMinType(aTy),
+ mMaxType(aTy)
+{
+ addType(aTy);
+}
+
+void FGPositioned::TypeFilter::addType(Type aTy)
+{
+ if (aTy == INVALID) {
+ return;
+ }
+
+ types.push_back(aTy);
+ mMinType = std::min(mMinType, aTy);
+ mMaxType = std::max(mMaxType, aTy);
+}
+
+bool
+FGPositioned::TypeFilter::pass(FGPositioned* aPos) const
+{
+ if (types.empty()) {
+ return true;
+ }
+
+ std::vector<Type>::const_iterator it = types.begin(),
+ end = types.end();
+ for (; it != end; ++it) {
+ return aPos->type() == *it;
+ }
+
+ return false;
}