29#include <QtConcurrentMap>
34QgsSnapIndex::PointSnapItem::PointSnapItem(
const QgsSnapIndex::CoordIdx *_idx,
bool isEndPoint )
35 : SnapItem( isEndPoint ? QgsSnapIndex::SnapEndPoint : QgsSnapIndex::SnapPoint )
44QgsSnapIndex::SegmentSnapItem::SegmentSnapItem(
const QgsSnapIndex::CoordIdx *_idxFrom,
const QgsSnapIndex::CoordIdx *_idxTo )
45 : SnapItem( QgsSnapIndex::SnapSegment )
50QgsPoint QgsSnapIndex::SegmentSnapItem::getSnapPoint(
const QgsPoint &p )
const
57 const QgsPoint &q1 = idxFrom->point(), & q2 = idxTo->point();
60 const double vl = v.length();
61 const double wl = w.length();
70 const double d = v.y() * w.x() - v.x() * w.y();
75 const double dx = q1.
x() - p1.
x();
76 const double dy = q1.
y() - p1.
y();
77 const double k = ( dy * w.x() - dx * w.y() ) / d;
79 inter =
QgsPoint( p1.
x() + v.x() * k, p1.
y() + v.y() * k );
81 const double lambdav =
QgsVector( inter.
x() - p1.
x(), inter.
y() - p1.
y() ) * v;
82 if ( lambdav < 0. + 1E-8 || lambdav > vl - 1E-8 )
85 const double lambdaw =
QgsVector( inter.
x() - q1.
x(), inter.
y() - q1.
y() ) * w;
86 return !( lambdaw < 0. + 1E-8 || lambdaw >= wl - 1E-8 );
89bool QgsSnapIndex::SegmentSnapItem::getProjection(
const QgsPoint &p,
QgsPoint &pProj )
const
91 const QgsPoint &s1 = idxFrom->point();
93 const double nx = s2.
y() - s1.
y();
94 const double ny = -( s2.
x() - s1.
x() );
95 const double t = ( p.
x() * ny - p.
y() * nx - s1.
x() * ny + s1.
y() * nx ) / ( ( s2.
x() - s1.
x() ) * ny - ( s2.
y() - s1.
y() ) * nx );
96 if ( t < 0. || t > 1. )
100 pProj =
QgsPoint( s1.
x() + ( s2.
x() - s1.
x() ) * t, s1.
y() + ( s2.
y() - s1.
y() ) * t );
104bool QgsSnapIndex::SegmentSnapItem::withinDistance(
const QgsPoint &p,
const double tolerance )
106 double minDistX, minDistY;
107 const double distance =
QgsGeometryUtils::sqrDistToLine( p.
x(), p.
y(), idxFrom->point().x(), idxFrom->point().y(), idxTo->point().x(), idxTo->point().y(), minDistX, minDistY, 4 * std::numeric_limits<double>::epsilon() );
108 return distance <= tolerance;
113QgsSnapIndex::QgsSnapIndex()
118QgsSnapIndex::~QgsSnapIndex()
120 qDeleteAll( mCoordIdxs );
121 qDeleteAll( mSnapItems );
126void QgsSnapIndex::addPoint(
const CoordIdx *idx,
bool isEndPoint )
133 PointSnapItem *item =
new PointSnapItem( idx, isEndPoint );
134 GEOSSTRtree_insert_r( geosctxt, mSTRTree, point.get(), item );
138void QgsSnapIndex::addSegment(
const CoordIdx *idxFrom,
const CoordIdx *idxTo )
140 const QgsPoint pointFrom = idxFrom->point();
141 const QgsPoint pointTo = idxTo->point();
145 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
146 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pointFrom.
x(), pointFrom.
y() );
147 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pointTo.
x(), pointTo.
y() );
150 SegmentSnapItem *item =
new SegmentSnapItem( idxFrom, idxTo );
151 GEOSSTRtree_insert_r( geosctxt, mSTRTree,
segment.get(), item );
157 for (
int iPart = 0, nParts = geom->
partCount(); iPart < nParts; ++iPart )
159 for (
int iRing = 0, nRings = geom->
ringCount( iPart ); iRing < nRings; ++iRing )
163 if ( qgsgeometry_cast< const QgsSurface * >( geom ) )
165 else if (
const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( geom ) )
167 if ( curve->isClosed() )
171 for (
int iVert = 0; iVert < nVerts; ++iVert )
173 CoordIdx *idx =
new CoordIdx( geom,
QgsVertexId( iPart, iRing, iVert ) );
174 CoordIdx *idx1 =
new CoordIdx( geom,
QgsVertexId( iPart, iRing, iVert + 1 ) );
175 mCoordIdxs.append( idx );
176 mCoordIdxs.append( idx1 );
177 addPoint( idx, iVert == 0 || iVert == nVerts - 1 );
178 if ( iVert < nVerts - 1 )
179 addSegment( idx, idx1 );
187 QList< QgsSnapIndex::SnapItem * > *
list;
192 reinterpret_cast<_GEOSQueryCallbackData *
>( userdata )->list->append(
static_cast<QgsSnapIndex::SnapItem *
>( item ) );
201 const QgsPoint endPoint( 2 * midPoint.
x() - startPoint.
x(), 2 * midPoint.
y() - startPoint.
y() );
204 double minDistance = std::numeric_limits<double>::max();
206 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
207 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, startPoint.
x(), startPoint.
y() );
208 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, endPoint.x(), endPoint.y() );
209 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
211 QList<SnapItem *> items;
213 callbackData.
list = &items;
214 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(),
_GEOSQueryCallback, &callbackData );
215 for (
const SnapItem *item : std::as_const( items ) )
217 if ( item->type == SnapSegment )
220 if (
static_cast<const SegmentSnapItem *
>( item )->getIntersection( startPoint, endPoint, inter ) )
223 if ( dist < minDistance )
235QgsSnapIndex::SnapItem *QgsSnapIndex::getSnapItem(
const QgsPoint &pos,
const double tolerance, QgsSnapIndex::PointSnapItem **pSnapPoint, QgsSnapIndex::SegmentSnapItem **pSnapSegment,
bool endPointOnly )
const
239 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
240 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pos.
x() - tolerance, pos.
y() - tolerance );
241 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pos.
x() + tolerance, pos.
y() + tolerance );
243 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
245 QList<SnapItem *> items;
247 callbackData.
list = &items;
248 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(),
_GEOSQueryCallback, &callbackData );
250 double minDistSegment = std::numeric_limits<double>::max();
251 double minDistPoint = std::numeric_limits<double>::max();
252 QgsSnapIndex::SegmentSnapItem *snapSegment =
nullptr;
253 QgsSnapIndex::PointSnapItem *snapPoint =
nullptr;
255 const auto constItems = items;
256 for ( QgsSnapIndex::SnapItem *item : constItems )
258 if ( ( ! endPointOnly && item->type == SnapPoint ) || item->type == SnapEndPoint )
261 if ( dist < minDistPoint )
264 snapPoint =
static_cast<PointSnapItem *
>( item );
267 else if ( item->type == SnapSegment && !endPointOnly )
269 if ( !
static_cast<SegmentSnapItem *
>( item )->withinDistance( pos, tolerance ) )
273 if ( !
static_cast<SegmentSnapItem *
>( item )->getProjection( pos, pProj ) )
277 if ( dist < minDistSegment )
279 minDistSegment = dist;
280 snapSegment =
static_cast<SegmentSnapItem *
>( item );
284 snapPoint = minDistPoint < tolerance * tolerance ? snapPoint :
nullptr;
285 snapSegment = minDistSegment < tolerance * tolerance ? snapSegment :
nullptr;
286 if ( pSnapPoint ) *pSnapPoint = snapPoint;
287 if ( pSnapSegment ) *pSnapSegment = snapSegment;
288 return minDistPoint < minDistSegment ? static_cast<QgsSnapIndex::SnapItem *>( snapPoint ) : static_cast<QgsSnapIndex::SnapItem *>( snapSegment );
299 : mReferenceSource( referenceSource )
308 QtConcurrent::blockingMap(
list, ProcessFeatureWrapper(
this, snapTolerance, mode ) );
312void QgsGeometrySnapper::processFeature(
QgsFeature &feature,
double snapTolerance, SnapMode mode )
322 QList<QgsGeometry> refGeometries;
325 searchBounds.
grow( snapTolerance );
327 mIndexMutex.unlock();
329 if ( refFeatureIds.isEmpty() )
332 refGeometries.reserve( refFeatureIds.size() );
334 const QgsFeatureIds cachedIds = qgis::listToSet( mCachedReferenceGeometries.keys() );
337 if ( cachedIds.contains(
id ) )
339 refGeometries.append( mCachedReferenceGeometries[
id] );
343 missingFeatureIds << id;
347 if ( missingFeatureIds.size() > 0 )
350 mReferenceLayerMutex.lock();
356 refGeometries.append( refFeature.
geometry() );
358 mReferenceLayerMutex.unlock();
361 return snapGeometry( geometry, snapTolerance, refGeometries, mode );
373 QgsSnapIndex refSnapIndex;
374 for (
const QgsGeometry &geom : referenceGeometries )
376 refSnapIndex.addGeometry( geom.constGet() );
381 QList < QList< QList<PointFlag> > > subjPointFlags;
384 for (
int iPart = 0, nParts = subjGeom->
partCount(); iPart < nParts; ++iPart )
386 subjPointFlags.append( QList< QList<PointFlag> >() );
388 for (
int iRing = 0, nRings = subjGeom->
ringCount( iPart ); iRing < nRings; ++iRing )
390 subjPointFlags[iPart].append( QList<PointFlag>() );
392 for (
int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
398 subjPointFlags[iPart][iRing].append( Unsnapped );
402 QgsSnapIndex::PointSnapItem *snapPoint =
nullptr;
403 QgsSnapIndex::SegmentSnapItem *snapSegment =
nullptr;
406 if ( !refSnapIndex.getSnapItem( p, snapTolerance, &snapPoint, &snapSegment, mode ==
EndPointToEndPoint ) )
408 subjPointFlags[iPart][iRing].append( Unsnapped );
422 subjGeom->
moveVertex( vidx, snapPoint->getSnapPoint( p ) );
423 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
425 else if ( snapSegment )
427 subjGeom->
moveVertex( vidx, snapSegment->getSnapPoint( p ) );
428 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
438 double distanceNode = std::numeric_limits<double>::max();
439 double distanceSegment = std::numeric_limits<double>::max();
442 nodeSnap = snapPoint->getSnapPoint( p );
447 segmentSnap = snapSegment->getSnapPoint( p );
450 if ( snapPoint && distanceNode < distanceSegment )
453 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
455 else if ( snapSegment )
458 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
469 if ( qgsgeometry_cast< const QgsPoint * >( subjGeom ) )
480 std::unique_ptr< QgsSnapIndex > subjSnapIndex(
new QgsSnapIndex() );
481 subjSnapIndex->addGeometry( subjGeom );
483 std::unique_ptr< QgsAbstractGeometry > origSubjGeom( subjGeom->
clone() );
484 std::unique_ptr< QgsSnapIndex > origSubjSnapIndex(
new QgsSnapIndex() );
485 origSubjSnapIndex->addGeometry( origSubjGeom.get() );
488 for (
const QgsGeometry &refGeom : referenceGeometries )
490 for (
int iPart = 0, nParts = refGeom.constGet()->partCount(); iPart < nParts; ++iPart )
492 for (
int iRing = 0, nRings = refGeom.constGet()->ringCount( iPart ); iRing < nRings; ++iRing )
494 for (
int iVert = 0, nVerts = polyLineSize( refGeom.constGet(), iPart, iRing ); iVert < nVerts; ++iVert )
496 QgsSnapIndex::PointSnapItem *snapPoint =
nullptr;
497 QgsSnapIndex::SegmentSnapItem *snapSegment =
nullptr;
499 if ( subjSnapIndex->getSnapItem( point, snapTolerance, &snapPoint, &snapSegment ) )
504 const QgsPoint snappedPoint = snapPoint->getSnapPoint( point );
512 const QgsPoint pProj = snapSegment->getSnapPoint( point );
513 const QgsPoint closest = refSnapIndex.getClosestSnapToPoint( point, pProj );
520 if ( !origSubjSnapIndex->getSnapItem( point, snapTolerance ) )
525 const QgsSnapIndex::CoordIdx *idx = snapSegment->idxFrom;
527 subjPointFlags[idx->vidx.part][idx->vidx.ring].insert( idx->vidx.vertex + 1, SnappedToRefNode );
528 subjSnapIndex.reset(
new QgsSnapIndex() );
529 subjSnapIndex->addGeometry( subjGeom );
536 subjSnapIndex.reset();
537 origSubjSnapIndex.reset();
538 origSubjGeom.reset();
541 for (
int iPart = 0, nParts = subjGeom->
partCount(); iPart < nParts; ++iPart )
543 for (
int iRing = 0, nRings = subjGeom->
ringCount( iPart ); iRing < nRings; ++iRing )
546 for (
int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
548 const int iPrev = ( iVert - 1 + nVerts ) % nVerts;
549 const int iNext = ( iVert + 1 ) % nVerts;
554 if ( subjPointFlags[iPart][iRing][iVert] == SnappedToRefSegment &&
555 subjPointFlags[iPart][iRing][iPrev] != Unsnapped &&
556 subjPointFlags[iPart][iRing][iNext] != Unsnapped &&
559 if ( ( ringIsClosed && nVerts > 3 ) || ( !ringIsClosed && nVerts > 2 ) )
562 subjPointFlags[iPart][iRing].removeAt( iVert );
581int QgsGeometrySnapper::polyLineSize(
const QgsAbstractGeometry *geom,
int iPart,
int iRing )
583 const int nVerts = geom->
vertexCount( iPart, iRing );
585 if ( qgsgeometry_cast< const QgsSurface * >( geom ) || qgsgeometry_cast< const QgsMultiSurface * >( geom ) )
605 : mSnapTolerance( snapTolerance )
616 if ( !mFirstFeature )
621 searchBounds.
grow( mSnapTolerance );
623 if ( !refFeatureIds.isEmpty() )
625 QList< QgsGeometry > refGeometries;
626 const auto constRefFeatureIds = refFeatureIds;
629 refGeometries << mProcessedGeometries.value(
id );
635 mProcessedGeometries.insert( feat.
id(), geometry );
637 mFirstFeature =
false;
Abstract base class for all geometries.
virtual int ringCount(int part=0) const =0
Returns the number of rings of which this geometry is built.
virtual bool moveVertex(QgsVertexId position, const QgsPoint &newPos)=0
Moves a vertex within the geometry.
virtual int vertexCount(int part=0, int ring=0) const =0
Returns the number of vertices of which this geometry is built.
virtual QgsRectangle boundingBox() const =0
Returns the minimal bounding box for the geometry.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
virtual bool insertVertex(QgsVertexId position, const QgsPoint &vertex)=0
Inserts a vertex into the geometry.
virtual int partCount() const =0
Returns count of parts contained in the geometry.
virtual bool deleteVertex(QgsVertexId position)=0
Deletes a vertex within the geometry.
QgsWkbTypes::Type wkbType() const SIP_HOLDGIL
Returns the WKB type of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
Abstract base class for curved geometry type.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
An interface for objects which provide features via a getFeatures method.
virtual QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const =0
Returns an iterator for the features in the source.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
void featureSnapped()
Emitted each time a feature has been processed when calling snapFeatures()
QgsFeatureList snapFeatures(const QgsFeatureList &features, double snapTolerance, SnapMode mode=PreferNodes)
Snaps a set of features to the reference layer and returns the result.
QgsGeometry snapGeometry(const QgsGeometry &geometry, double snapTolerance, SnapMode mode=PreferNodes) const
Snaps a geometry to the reference layer and returns the result.
@ EndPointPreferClosest
Only snap start/end points of lines (point features will also be snapped, polygon features will not b...
@ PreferClosestNoExtraVertices
Snap to closest point, regardless of it is a node or a segment. No new nodes will be inserted.
@ EndPointPreferNodes
Only snap start/end points of lines (point features will also be snapped, polygon features will not b...
@ PreferNodes
Prefer to snap to nodes, even when a segment may be closer than a node. New nodes will be inserted to...
@ PreferClosest
Snap to closest point, regardless of it is a node or a segment. New nodes will be inserted to make ge...
@ EndPointToEndPoint
Only snap the start/end points of lines to other start/end points of lines.
@ PreferNodesNoExtraVertices
Prefer to snap to nodes, even when a segment may be closer than a node. No new nodes will be inserted...
QgsGeometrySnapper(QgsFeatureSource *referenceSource)
Constructor for QgsGeometrySnapper.
static double sqrDistance2D(const QgsPoint &pt1, const QgsPoint &pt2) SIP_HOLDGIL
Returns the squared 2D distance between two points.
static QgsPoint projectPointOnSegment(const QgsPoint &p, const QgsPoint &s1, const QgsPoint &s2) SIP_HOLDGIL
Project the point on a segment.
static double sqrDistToLine(double ptX, double ptY, double x1, double y1, double x2, double y2, double &minDistX, double &minDistY, double epsilon) SIP_HOLDGIL
Returns the squared distance between a point and a line.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsWkbTypes::Type wkbType() const SIP_HOLDGIL
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
bool removeDuplicateNodes(double epsilon=4 *std::numeric_limits< double >::epsilon(), bool useZValues=false)
Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerat...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static GEOSContextHandle_t getGEOSHandler()
QgsInternalGeometrySnapper(double snapTolerance, QgsGeometrySnapper::SnapMode mode=QgsGeometrySnapper::PreferNodes)
Constructor for QgsInternalGeometrySnapper.
QgsGeometry snapFeature(const QgsFeature &feature)
Snaps a single feature's geometry against all feature geometries already processed by calls to snapFe...
Point geometry type, with support for z-dimension and m-values.
QgsPoint vertexAt(QgsVertexId) const override
Returns the point corresponding to a specified vertex id.
double distanceSquared(double x, double y) const SIP_HOLDGIL
Returns the Cartesian 2D squared distance between this point a specified x, y coordinate.
A rectangle specified with double values.
void grow(double delta)
Grows the rectangle in place by the specified amount.
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
A spatial index for QgsFeature objects.
QList< QgsFeatureId > intersects(const QgsRectangle &rectangle) const
Returns a list of features with a bounding box which intersects the specified rectangle.
bool addFeature(QgsFeature &feature, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a feature to the index.
A class to represent a vector.
static GeometryType geometryType(Type type) SIP_HOLDGIL
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
QList< QgsFeature > QgsFeatureList
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
void _GEOSQueryCallback(void *item, void *userdata)
QLineF segment(int index, QRectF rect, double radius)
Utility class for identifying a unique vertex within a geometry.
QList< const QgsPointCloudLayerProfileResults::PointResult * > * list