27 #include <spatialindex/SpatialIndex.h> 29 #include <QLinkedListIterator> 35 static SpatialIndex::Point point2point(
const QgsPointXY &point )
37 double plow[2] = { point.
x(), point.
y() };
38 return Point( plow, 2 );
42 static SpatialIndex::Region rect2region(
const QgsRectangle &rect )
46 return SpatialIndex::Region( pLow, pHigh, 2 );
54 static const double POINT_LOC_EPSILON = 1e-12;
68 : mDataList( dataList )
72 IData *
getNext()
override {
return mIt.next(); }
73 bool hasNext()
override {
return mIt.hasNext(); }
75 uint32_t
size()
override { Q_ASSERT(
false &&
"not available" );
return 0; }
76 void rewind()
override { Q_ASSERT(
false &&
"not available" ); }
79 QLinkedList<RTree::Data *> mDataList;
80 QLinkedListIterator<RTree::Data *> mIt;
98 , mSrcPoint( srcPoint )
102 void visitNode(
const INode &n )
override { Q_UNUSED( n ); }
103 void visitData( std::vector<const IData *> &v )
override { Q_UNUSED( v ); }
109 int vertexIndex, beforeVertex, afterVertex;
118 if ( mFilter && !mFilter->acceptMatch( m ) )
121 if ( !mBest.isValid() || m.
distance() < mBest.distance() )
147 , mSrcPoint( srcPoint )
151 void visitNode(
const INode &n )
override { Q_UNUSED( n ); }
152 void visitData( std::vector<const IData *> &v )
override { Q_UNUSED( v ); }
165 edgePoints[0] = geom->
vertexAt( afterVertex - 1 );
166 edgePoints[1] = geom->
vertexAt( afterVertex );
169 if ( mFilter && !mFilter->acceptMatch( m ) )
172 if ( !mBest.isValid() || m.
distance() < mBest.distance() )
201 void visitNode(
const INode &n )
override { Q_UNUSED( n ); }
202 void visitData( std::vector<const IData *> &v )
override { Q_UNUSED( v ); }
228 static const int INSIDE = 0;
231 static const int BOTTOM = 4;
232 static const int TOP = 8;
238 OutCode code = INSIDE;
253 OutCode outcode0 = computeOutCode( x0, y0 );
254 OutCode outcode1 = computeOutCode( x1, y1 );
259 if ( !( outcode0 | outcode1 ) )
265 else if ( outcode0 & outcode1 )
277 OutCode outcodeOut = outcode0 ? outcode0 : outcode1;
281 if ( outcodeOut & TOP )
284 x = x0 + ( x1 - x0 ) * ( mRect.
yMaximum() - y0 ) / ( y1 - y0 );
287 else if ( outcodeOut & BOTTOM )
290 x = x0 + ( x1 - x0 ) * ( mRect.
yMinimum() - y0 ) / ( y1 - y0 );
293 else if ( outcodeOut & RIGHT )
296 y = y0 + ( y1 - y0 ) * ( mRect.
xMaximum() - x0 ) / ( x1 - x0 );
299 else if ( outcodeOut & LEFT )
302 y = y0 + ( y1 - y0 ) * ( mRect.
xMinimum() - x0 ) / ( x1 - x0 );
310 if ( outcodeOut == outcode0 )
314 outcode0 = computeOutCode( x0, y0 );
320 outcode1 = computeOutCode( x1, y1 );
355 if ( qgsgeometry_cast<QgsLineString *>( *part )->numPoints() < 2 )
361 while ( it != ( *part )->vertices_end() )
367 edgePoints[0] = prevPoint;
368 edgePoints[1] = thisPoint;
391 , mSrcRect( srcRect )
395 void visitNode(
const INode &n )
override { Q_UNUSED( n ); }
396 void visitData( std::vector<const IData *> &v )
override { Q_UNUSED( v ); }
403 Q_FOREACH (
const QgsPointLocator::Match &m, _geometrySegmentsInRect( geom, mSrcRect, mLocator->mLayer,
id ) )
406 if ( mFilter && !mFilter->acceptMatch( m ) )
435 , mSrcRect( srcRect )
439 void visitNode(
const INode &n )
override { Q_UNUSED( n ); }
440 void visitData( std::vector<const IData *> &v )
override { Q_UNUSED( v ); }
445 const QgsGeometry *geom = mLocator->mGeoms.value(
id );
449 if ( mSrcRect.contains( *it ) )
454 if ( mFilter && !mFilter->acceptMatch( m ) )
485 void getNextEntry(
const IEntry &entry, id_type &nextEntry,
bool &hasNext )
override 487 const INode *n =
dynamic_cast<const INode *
>( &entry );
491 QgsDebugMsgLevel( QStringLiteral(
"NODE: %1" ).arg( n->getIdentifier() ), 4 );
492 if ( n->getLevel() > 0 )
495 for ( uint32_t cChild = 0; cChild < n->getChildrenCount(); cChild++ )
497 QgsDebugMsgLevel( QStringLiteral(
"- CH: %1" ).arg( n->getChildIdentifier( cChild ) ), 4 );
498 ids.push( n->getChildIdentifier( cChild ) );
504 for ( uint32_t cChild = 0; cChild < n->getChildrenCount(); cChild++ )
506 QgsDebugMsgLevel( QStringLiteral(
"- L: %1" ).arg( n->getChildIdentifier( cChild ) ), 4 );
512 nextEntry = ids.back();
534 mStorage.reset( StorageManager::createNewMemoryStorageManager() );
556 mExtent.reset( extent ?
new QgsRectangle( *extent ) :
nullptr );
566 mContext.reset(
nullptr );
570 mContext = std::unique_ptr<QgsRenderContext>(
new QgsRenderContext( *context ) );
584 return mRTree || mIsEmptyLayer;
592 QLinkedList<RTree::Data *> dataList;
614 QgsDebugMsg( QStringLiteral(
"could not transform bounding box to map, skipping the snap filter (%1)" ).arg( e.
what() ) );
621 std::unique_ptr< QgsFeatureRenderer > renderer( mLayer->
renderer() ? mLayer->
renderer()->
clone() : nullptr );
626 ctx = mContext.get();
630 renderer->startRender( *ctx, mLayer->
fields() );
637 int indexedCount = 0;
644 if ( filter && ctx && renderer )
646 ctx->expressionContext().setFeature( f );
647 if ( !renderer->willRenderFeature( f, *ctx ) )
658 transformedGeometry.
transform( mTransform );
665 QgsDebugMsg( QStringLiteral(
"could not transform geometry to map, skipping the snap for it (%1)" ).arg( e.
what() ) );
673 SpatialIndex::Region r( rect2region( bbox ) );
674 dataList <<
new RTree::Data( 0,
nullptr, r, f.
id() );
676 if ( mGeoms.contains( f.
id() ) )
677 delete mGeoms.take( f.
id() );
682 if ( maxFeaturesToIndex != -1 && indexedCount > maxFeaturesToIndex )
684 qDeleteAll( dataList );
691 double fillFactor = 0.7;
692 unsigned long indexCapacity = 10;
693 unsigned long leafCapacity = 10;
694 unsigned long dimension = 2;
695 RTree::RTreeVariant variant = RTree::RV_RSTAR;
696 SpatialIndex::id_type indexId;
698 if ( dataList.isEmpty() )
700 mIsEmptyLayer =
true;
705 mRTree.reset( RTree::createAndBulkLoadNewRTree( RTree::BLM_STR, stream, *mStorage, fillFactor, indexCapacity,
706 leafCapacity, dimension, variant, indexId ) );
708 if ( ctx && renderer )
710 renderer->stopRender( *ctx );
720 mIsEmptyLayer =
false;
722 qDeleteAll( mGeoms );
727 void QgsPointLocator::onFeatureAdded(
QgsFeatureId fid )
744 std::unique_ptr< QgsFeatureRenderer > renderer( mLayer->
renderer() ? mLayer->
renderer()->
clone() : nullptr );
748 ctx = mContext.get();
749 if ( renderer && ctx )
752 renderer->startRender( *ctx, mLayer->
fields() );
754 ctx->expressionContext().setFeature( f );
755 if ( !renderer->willRenderFeature( f, *ctx ) )
760 renderer->stopRender( *ctx );
778 QgsDebugMsg( QStringLiteral(
"could not transform geometry to map, skipping the snap for it (%1)" ).arg( e.
what() ) );
786 SpatialIndex::Region r( rect2region( bbox ) );
787 mRTree->insertData( 0,
nullptr, r, f.
id() );
789 if ( mGeoms.contains( f.
id() ) )
790 delete mGeoms.take( f.
id() );
796 void QgsPointLocator::onFeatureDeleted(
QgsFeatureId fid )
801 if ( mGeoms.contains( fid ) )
803 mRTree->deleteData( rect2region( mGeoms[fid]->boundingBox() ), fid );
804 delete mGeoms.take( fid );
812 onFeatureDeleted( fid );
813 onFeatureAdded( fid );
816 void QgsPointLocator::onAttributeValueChanged(
QgsFeatureId fid,
int idx,
const QVariant &value )
822 onFeatureDeleted( fid );
823 onFeatureAdded( fid );
839 QgsRectangle rect( point.
x() - tolerance, point.
y() - tolerance, point.
x() + tolerance, point.
y() + tolerance );
840 mRTree->intersectsWithQuery( rect2region( rect ), visitor );
861 QgsRectangle rect( point.
x() - tolerance, point.
y() - tolerance, point.
x() + tolerance, point.
y() + tolerance );
862 mRTree->intersectsWithQuery( rect2region( rect ), visitor );
878 if ( mlist.count() && mlist.at( 0 ).isValid() )
880 return mlist.at( 0 );
883 if ( tolerance == 0 )
917 mRTree->intersectsWithQuery( rect2region( rect ), visitor );
924 QgsRectangle rect( point.
x() - tolerance, point.
y() - tolerance, point.
x() + tolerance, point.
y() + tolerance );
939 mRTree->intersectsWithQuery( rect2region( rect ), visitor );
946 QgsRectangle rect( point.
x() - tolerance, point.
y() - tolerance, point.
x() + tolerance, point.
y() + tolerance );
966 mRTree->intersectsWithQuery( point2point( point ), visitor );
The class defines interface for querying point location:
QgsPointLocator_Stream(const QLinkedList< RTree::Data * > &dataList)
Wrapper for iterator of features from vector data provider or vector layer.
A rectangle specified with double values.
QgsPointXY point() const
for vertex / edge match coords depending on what class returns it (geom.cache: layer coords...
QgsAbstractGeometry::vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry...
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false) SIP_THROW(QgsCsException)
Transforms this geometry as described by the coordinate transform ct.
void visitData(const IData &d) override
bool isFinite() const
Returns true if the rectangle has finite boundaries.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Features may be filtered, i.e. some features may not be rendered (categorized, rule based ...
QgsPointLocator_VisitorArea(QgsPointLocator *pl, const QgsPointXY &origPt, QgsPointLocator::MatchList &list)
constructor
A class to represent a 2D point.
Match nearestEdge(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr)
Find nearest edge to the specified point - up to distance specified by tolerance Optional filter may ...
void visitData(std::vector< const IData * > &v) override
QgsAbstractGeometry::vertex_iterator vertices_begin() const
Returns STL-style iterator pointing to the first vertex of the geometry.
int vertexNrFromVertexId(QgsVertexId id) const
Returns the vertex number corresponding to a vertex id.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsPointLocator_VisitorVerticesInRect(QgsPointLocator *pl, QgsPointLocator::MatchList &lst, const QgsRectangle &srcRect, QgsPointLocator::MatchFilter *filter=nullptr)
Constructs the visitor.
class QList< QgsPointLocator::Match > MatchList
Helper class used when traversing the index looking for edges - builds a list of matches.
A geometry is the spatial representation of a feature.
Match nearestArea(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr)
Find nearest area to the specified point - up to distance specified by tolerance Optional filter may ...
QgsFeatureId featureId() const
The id of the feature to which the snapped geometry belongs.
bool rebuildIndex(int maxFeaturesToIndex=-1)
void visitNode(const INode &n) override
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Interface that allows rejection of some matches in intersection queries (e.g.
void visitData(std::vector< const IData * > &v) override
void featureDeleted(QgsFeatureId fid)
Emitted when a feature has been deleted.
double closestSegmentWithContext(const QgsPointXY &point, QgsPointXY &minDistPoint, int &afterVertex, int *leftOf=nullptr, double epsilon=DEFAULT_SEGMENT_EPSILON) const
Searches for the closest segment of geometry to the given point.
void convertToStraightSegment(double tolerance=M_PI/180., QgsAbstractGeometry::SegmentationToleranceType toleranceType=QgsAbstractGeometry::MaximumAngle)
Converts the geometry to straight line segments, if it is a curved geometry type. ...
void styleChanged()
Signal emitted whenever a change affects the layer's style.
const QgsRectangle * extent() const
Gets extent of the area point locator covers - if null then it caches the whole layer.
~QgsPointLocator() override
QgsFields fields() const FINAL
Returns the list of fields of this layer.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double xMaximum() const
Returns the x maximum value (right side of rectangle).
#define QgsDebugMsgLevel(str, level)
QgsPointLocator_VisitorNearestVertex(QgsPointLocator *pl, QgsPointLocator::Match &m, const QgsPointXY &srcPoint, QgsPointLocator::MatchFilter *filter=nullptr)
OutCode computeOutCode(double x, double y)
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
void setRenderContext(const QgsRenderContext *context)
Configure render context - if not null, it will use to index only visible feature.
Snapped to a vertex. Can be a vertex of the geometry or an intersection.
Helper class to dump the R-index nodes and their content.
This class wraps a request for features to a vector layer (or directly its vector data provider)...
bool isSegmentInRect(double x0, double y0, double x1, double y1)
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
void geometryChanged(QgsFeatureId fid, const QgsGeometry &geometry)
Is emitted whenever a geometry change is done in the edit buffer.
void visitNode(const INode &n) override
void setExtent(const QgsRectangle *extent)
Configure extent - if not null, it will index only that area.
Helper class used when traversing the index with areas - builds a list of matches.
QgsFeatureRenderer * renderer()
Returns renderer.
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
void attributeValueChanged(QgsFeatureId fid, int idx, const QVariant &value)
Is emitted whenever an attribute value change is done in the edit buffer.
void featureAdded(QgsFeatureId fid)
Emitted when a new feature has been added to the layer.
bool intersects(const QgsRectangle &rectangle) const
Returns true if this geometry exactly intersects with a rectangle.
Contains information about the context in which a coordinate transform is executed.
The vertex_iterator class provides STL-style iterator for vertices.
double distance() const
for vertex / edge match units depending on what class returns it (geom.cache: layer units...
void visitData(const IData &d) override
Helper class used when traversing the index looking for vertices - builds a list of matches...
void visitNode(const INode &n) override
IData * getNext() override
GeometryType
The geometry types are used to group QgsWkbTypes::Type in a coarse way.
QgsPointLocator(QgsVectorLayer *layer, const QgsCoordinateReferenceSystem &destinationCrs=QgsCoordinateReferenceSystem(), const QgsCoordinateTransformContext &transformContext=QgsCoordinateTransformContext(), const QgsRectangle *extent=nullptr)
Construct point locator for a layer.
QgsVectorLayer * layer() const
The vector layer where the snap occurred.
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
Contains information about the context of a rendering operation.
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry...
MatchList verticesInRect(const QgsRectangle &rect, QgsPointLocator::MatchFilter *filter=nullptr)
Find vertices within a specified recangle Optional filter may discard unwanted matches.
QgsPointLocator_VisitorNearestEdge(QgsPointLocator *pl, QgsPointLocator::Match &m, const QgsPointXY &srcPoint, QgsPointLocator::MatchFilter *filter=nullptr)
Helper class for bulk loading of R-trees.
void visitData(const IData &d) override
MatchList pointInPolygon(const QgsPointXY &point)
find out if the point is in any polygons
void visitNode(const INode &n) override
bool init(int maxFeaturesToIndex=-1)
Prepare the index for queries.
QgsGeometry convertToType(QgsWkbTypes::GeometryType destType, bool destMultipart=false) const
Try to convert the geometry to the requested type.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
void visitData(std::vector< const IData * > &v) override
This class represents a coordinate reference system (CRS).
_CohenSutherland(const QgsRectangle &rect)
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void getNextEntry(const IEntry &entry, id_type &nextEntry, bool &hasNext) override
Match nearestVertex(const QgsPointXY &point, double tolerance, QgsPointLocator::MatchFilter *filter=nullptr)
Find nearest vertex to the specified point - up to distance specified by tolerance Optional filter ma...
void visitData(const IData &d) override
void dataChanged()
Data of layer changed.
Helper class used when traversing the index looking for vertices - builds a list of matches...
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Query the layer for features specified in request.
Helper class used when traversing the index looking for edges - builds a list of matches.
void visitNode(const INode &n) override
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsWkbTypes::GeometryType geometryType() const
Returns point, line or polygon.
MatchList edgesInRect(const QgsRectangle &rect, QgsPointLocator::MatchFilter *filter=nullptr)
Find edges within a specified recangle Optional filter may discard unwanted matches.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
bool nextFeature(QgsFeature &f)
bool hasIndex() const
Indicate whether the data have been already indexed.
Represents a vector layer which manages a vector based data sets.
QgsCoordinateReferenceSystem destinationCrs() const
Gets destination CRS - may be an invalid QgsCoordinateReferenceSystem if not doing OTF reprojection...
QgsWkbTypes::GeometryType type() const
Returns type of the geometry as a QgsWkbTypes::GeometryType.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Defines a QGIS exception class.
QgsPoint vertexAt(int atVertex) const
Returns coordinates of a vertex.
void visitData(const IData &d) override
void visitData(std::vector< const IData * > &v) override
void visitData(std::vector< const IData * > &v) override
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
QgsPointLocator_VisitorEdgesInRect(QgsPointLocator *pl, QgsPointLocator::MatchList &lst, const QgsRectangle &srcRect, QgsPointLocator::MatchFilter *filter=nullptr)
QgsCoordinateReferenceSystem crs
QgsPointXY closestVertex(const QgsPointXY &point, int &atVertex, int &beforeVertex, int &afterVertex, double &sqrDist) const
Returns the vertex closest to the given point, the corresponding vertex index, squared distance snap ...