QGIS API Documentation 3.41.0-Master (af5edcb665c)
Loading...
Searching...
No Matches
qgsgeometrysnapper.cpp
Go to the documentation of this file.
1/***************************************************************************
2 * qgsgeometrysnapper.cpp *
3 * ------------------- *
4 * copyright : (C) 2014 by Sandro Mani / Sourcepole AG *
5 * email : [email protected] *
6 ***************************************************************************/
7
8/***************************************************************************
9 * *
10 * This program is free software; you can redistribute it and/or modify *
11 * it under the terms of the GNU General Public License as published by *
12 * the Free Software Foundation; either version 2 of the License, or *
13 * (at your option) any later version. *
14 * *
15 ***************************************************************************/
16
17#include "qgsfeatureiterator.h"
18#include "qgsgeometry.h"
19#include "qgsvectorlayer.h"
20#include "qgsgeometrysnapper.h"
21#include "moc_qgsgeometrysnapper.cpp"
23#include "qgsgeometryutils.h"
24#include "qgssurface.h"
25#include "qgsmultisurface.h"
26#include "qgscurve.h"
27
28#include <QtConcurrentMap>
29#include <geos_c.h>
30
32
33QgsSnapIndex::PointSnapItem::PointSnapItem( const QgsSnapIndex::CoordIdx *_idx, bool isEndPoint )
34 : SnapItem( isEndPoint ? QgsSnapIndex::SnapEndPoint : QgsSnapIndex::SnapPoint )
35 , idx( _idx )
36{}
37
38QgsPoint QgsSnapIndex::PointSnapItem::getSnapPoint( const QgsPoint & /*p*/ ) const
39{
40 return idx->point();
41}
42
43QgsSnapIndex::SegmentSnapItem::SegmentSnapItem( const QgsSnapIndex::CoordIdx *_idxFrom, const QgsSnapIndex::CoordIdx *_idxTo )
44 : SnapItem( QgsSnapIndex::SnapSegment )
45 , idxFrom( _idxFrom )
46 , idxTo( _idxTo )
47{}
48
49QgsPoint QgsSnapIndex::SegmentSnapItem::getSnapPoint( const QgsPoint &p ) const
50{
51 return QgsGeometryUtils::projectPointOnSegment( p, idxFrom->point(), idxTo->point() );
52}
53
54bool QgsSnapIndex::SegmentSnapItem::getIntersection( const QgsPoint &p1, const QgsPoint &p2, QgsPoint &inter ) const
55{
56 const QgsPoint &q1 = idxFrom->point(), &q2 = idxTo->point();
57 QgsVector v( p2.x() - p1.x(), p2.y() - p1.y() );
58 QgsVector w( q2.x() - q1.x(), q2.y() - q1.y() );
59 const double vl = v.length();
60 const double wl = w.length();
61
62 if ( qgsDoubleNear( vl, 0, 0.000000000001 ) || qgsDoubleNear( wl, 0, 0.000000000001 ) )
63 {
64 return false;
65 }
66 v = v / vl;
67 w = w / wl;
68
69 const double d = v.y() * w.x() - v.x() * w.y();
70
71 if ( d == 0 )
72 return false;
73
74 const double dx = q1.x() - p1.x();
75 const double dy = q1.y() - p1.y();
76 const double k = ( dy * w.x() - dx * w.y() ) / d;
77
78 inter = QgsPoint( p1.x() + v.x() * k, p1.y() + v.y() * k );
79
80 const double lambdav = QgsVector( inter.x() - p1.x(), inter.y() - p1.y() ) * v;
81 if ( lambdav < 0. + 1E-8 || lambdav > vl - 1E-8 )
82 return false;
83
84 const double lambdaw = QgsVector( inter.x() - q1.x(), inter.y() - q1.y() ) * w;
85 return !( lambdaw < 0. + 1E-8 || lambdaw >= wl - 1E-8 );
86}
87
88bool QgsSnapIndex::SegmentSnapItem::getProjection( const QgsPoint &p, QgsPoint &pProj ) const
89{
90 const QgsPoint &s1 = idxFrom->point();
91 const QgsPoint &s2 = idxTo->point();
92 const double nx = s2.y() - s1.y();
93 const double ny = -( s2.x() - s1.x() );
94 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 );
95 if ( t < 0. || t > 1. )
96 {
97 return false;
98 }
99 pProj = QgsPoint( s1.x() + ( s2.x() - s1.x() ) * t, s1.y() + ( s2.y() - s1.y() ) * t );
100 return true;
101}
102
103bool QgsSnapIndex::SegmentSnapItem::withinSquaredDistance( const QgsPoint &p, const double squaredDistance )
104{
105 double minDistX, minDistY;
106 return QgsGeometryUtilsBase::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() ) <= squaredDistance;
107}
108
110
111QgsSnapIndex::QgsSnapIndex()
112{
113 mSTRTree = GEOSSTRtree_create_r( QgsGeosContext::get(), ( size_t ) 10 );
114}
115
116QgsSnapIndex::~QgsSnapIndex()
117{
118 qDeleteAll( mCoordIdxs );
119 qDeleteAll( mSnapItems );
120
121 GEOSSTRtree_destroy_r( QgsGeosContext::get(), mSTRTree );
122}
123
124void QgsSnapIndex::addPoint( const CoordIdx *idx, bool isEndPoint )
125{
126 const QgsPoint p = idx->point();
127
128 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
129 geos::unique_ptr point( GEOSGeom_createPointFromXY_r( geosctxt, p.x(), p.y() ) );
130
131 PointSnapItem *item = new PointSnapItem( idx, isEndPoint );
132 GEOSSTRtree_insert_r( geosctxt, mSTRTree, point.get(), item );
133 mSnapItems << item;
134}
135
136void QgsSnapIndex::addSegment( const CoordIdx *idxFrom, const CoordIdx *idxTo )
137{
138 const QgsPoint pointFrom = idxFrom->point();
139 const QgsPoint pointTo = idxTo->point();
140
141 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
142
143 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
144 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pointFrom.x(), pointFrom.y() );
145 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pointTo.x(), pointTo.y() );
146 geos::unique_ptr segment( GEOSGeom_createLineString_r( geosctxt, coord ) );
147
148 SegmentSnapItem *item = new SegmentSnapItem( idxFrom, idxTo );
149 GEOSSTRtree_insert_r( geosctxt, mSTRTree, segment.get(), item );
150 mSnapItems << item;
151}
152
153void QgsSnapIndex::addGeometry( const QgsAbstractGeometry *geom )
154{
155 for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart )
156 {
157 for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing )
158 {
159 int nVerts = geom->vertexCount( iPart, iRing );
160
161 if ( qgsgeometry_cast<const QgsSurface *>( geom ) )
162 nVerts--;
163 else if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( geom ) )
164 {
165 if ( curve->isClosed() )
166 nVerts--;
167 }
168
169 for ( int iVert = 0; iVert < nVerts; ++iVert )
170 {
171 CoordIdx *idx = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert ) );
172 CoordIdx *idx1 = new CoordIdx( geom, QgsVertexId( iPart, iRing, iVert + 1 ) );
173 mCoordIdxs.append( idx );
174 mCoordIdxs.append( idx1 );
175 addPoint( idx, iVert == 0 || iVert == nVerts - 1 );
176 if ( iVert < nVerts - 1 )
177 addSegment( idx, idx1 );
178 }
179 }
180 }
181}
182
184{
185 QList<QgsSnapIndex::SnapItem *> *list;
186};
187
188void _GEOSQueryCallback( void *item, void *userdata )
189{
190 reinterpret_cast<_GEOSQueryCallbackData *>( userdata )->list->append( static_cast<QgsSnapIndex::SnapItem *>( item ) );
191}
192
193QgsPoint QgsSnapIndex::getClosestSnapToPoint( const QgsPoint &startPoint, const QgsPoint &midPoint )
194{
195 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
196
197 // Look for intersections on segment from the target point to the point opposite to the point reference point
198 // p2 = p1 + 2 * (q - p1)
199 const QgsPoint endPoint( 2 * midPoint.x() - startPoint.x(), 2 * midPoint.y() - startPoint.y() );
200
201 QgsPoint minPoint = startPoint;
202 double minDistance = std::numeric_limits<double>::max();
203
204 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
205 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, startPoint.x(), startPoint.y() );
206 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, endPoint.x(), endPoint.y() );
207 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
208
209 QList<SnapItem *> items;
210 struct _GEOSQueryCallbackData callbackData;
211 callbackData.list = &items;
212 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(), _GEOSQueryCallback, &callbackData );
213 for ( const SnapItem *item : std::as_const( items ) )
214 {
215 if ( item->type == SnapSegment )
216 {
217 QgsPoint inter;
218 if ( static_cast<const SegmentSnapItem *>( item )->getIntersection( startPoint, endPoint, inter ) )
219 {
220 const double dist = QgsGeometryUtils::sqrDistance2D( midPoint, inter );
221 if ( dist < minDistance )
222 {
223 minDistance = dist;
224 minPoint = inter;
225 }
226 }
227 }
228 }
229
230 return minPoint;
231}
232
233QgsSnapIndex::SnapItem *QgsSnapIndex::getSnapItem( const QgsPoint &pos, const double tolerance, QgsSnapIndex::PointSnapItem **pSnapPoint, QgsSnapIndex::SegmentSnapItem **pSnapSegment, bool endPointOnly ) const
234{
235 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
236
237 GEOSCoordSequence *coord = GEOSCoordSeq_create_r( geosctxt, 2, 2 );
238 GEOSCoordSeq_setXY_r( geosctxt, coord, 0, pos.x() - tolerance, pos.y() - tolerance );
239 GEOSCoordSeq_setXY_r( geosctxt, coord, 1, pos.x() + tolerance, pos.y() + tolerance );
240
241 geos::unique_ptr searchDiagonal( GEOSGeom_createLineString_r( geosctxt, coord ) );
242
243 QList<SnapItem *> items;
244 struct _GEOSQueryCallbackData callbackData;
245 callbackData.list = &items;
246 GEOSSTRtree_query_r( geosctxt, mSTRTree, searchDiagonal.get(), _GEOSQueryCallback, &callbackData );
247
248 double minDistSegment = std::numeric_limits<double>::max();
249 double minDistPoint = std::numeric_limits<double>::max();
250 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
251 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
252
253 const double squaredTolerance = tolerance * tolerance;
254 const auto constItems = items;
255 for ( QgsSnapIndex::SnapItem *item : constItems )
256 {
257 if ( ( !endPointOnly && item->type == SnapPoint ) || item->type == SnapEndPoint )
258 {
259 const double dist = QgsGeometryUtils::sqrDistance2D( item->getSnapPoint( pos ), pos );
260 if ( dist < minDistPoint )
261 {
262 minDistPoint = dist;
263 snapPoint = static_cast<PointSnapItem *>( item );
264 }
265 }
266 else if ( item->type == SnapSegment && !endPointOnly )
267 {
268 if ( !static_cast<SegmentSnapItem *>( item )->withinSquaredDistance( pos, squaredTolerance ) )
269 continue;
270
271 QgsPoint pProj;
272 if ( !static_cast<SegmentSnapItem *>( item )->getProjection( pos, pProj ) )
273 continue;
274
275 const double dist = QgsGeometryUtils::sqrDistance2D( pProj, pos );
276 if ( dist < minDistSegment )
277 {
278 minDistSegment = dist;
279 snapSegment = static_cast<SegmentSnapItem *>( item );
280 }
281 }
282 }
283 snapPoint = minDistPoint < squaredTolerance ? snapPoint : nullptr;
284 snapSegment = minDistSegment < squaredTolerance ? snapSegment : nullptr;
285 if ( pSnapPoint )
286 *pSnapPoint = snapPoint;
287 if ( pSnapSegment )
288 *pSnapSegment = snapSegment;
289 return minDistPoint < minDistSegment ? static_cast<QgsSnapIndex::SnapItem *>( snapPoint ) : static_cast<QgsSnapIndex::SnapItem *>( snapSegment );
290}
291
293
294
295//
296// QgsGeometrySnapper
297//
298
300 : mReferenceSource( referenceSource )
301{
302 // Build spatial index
303 mIndex = QgsSpatialIndex( *mReferenceSource );
304}
305
306QgsFeatureList QgsGeometrySnapper::snapFeatures( const QgsFeatureList &features, double snapTolerance, SnapMode mode )
307{
308 QgsFeatureList list = features;
309 QtConcurrent::blockingMap( list, ProcessFeatureWrapper( this, snapTolerance, mode ) );
310 return list;
311}
312
313void QgsGeometrySnapper::processFeature( QgsFeature &feature, double snapTolerance, SnapMode mode )
314{
315 if ( !feature.geometry().isNull() )
316 feature.setGeometry( snapGeometry( feature.geometry(), snapTolerance, mode ) );
317 emit featureSnapped();
318}
319
320QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry &geometry, double snapTolerance, SnapMode mode ) const
321{
322 // Get potential reference features and construct snap index
323 QList<QgsGeometry> refGeometries;
324 mIndexMutex.lock();
325 QgsRectangle searchBounds = geometry.boundingBox();
326 searchBounds.grow( snapTolerance );
327 const QgsFeatureIds refFeatureIds = qgis::listToSet( mIndex.intersects( searchBounds ) );
328 mIndexMutex.unlock();
329
330 if ( refFeatureIds.isEmpty() )
331 return QgsGeometry( geometry );
332
333 refGeometries.reserve( refFeatureIds.size() );
334 QgsFeatureIds missingFeatureIds;
335 const QgsFeatureIds cachedIds = qgis::listToSet( mCachedReferenceGeometries.keys() );
336 for ( const QgsFeatureId id : refFeatureIds )
337 {
338 if ( cachedIds.contains( id ) )
339 {
340 refGeometries.append( mCachedReferenceGeometries[id] );
341 }
342 else
343 {
344 missingFeatureIds << id;
345 }
346 }
347
348 if ( missingFeatureIds.size() > 0 )
349 {
350 mReferenceLayerMutex.lock();
351 const QgsFeatureRequest refFeatureRequest = QgsFeatureRequest().setFilterFids( missingFeatureIds ).setNoAttributes();
352 QgsFeatureIterator refFeatureIt = mReferenceSource->getFeatures( refFeatureRequest );
353 QgsFeature refFeature;
354 while ( refFeatureIt.nextFeature( refFeature ) )
355 {
356 refGeometries.append( refFeature.geometry() );
357 }
358 mReferenceLayerMutex.unlock();
359 }
360
361 return snapGeometry( geometry, snapTolerance, refGeometries, mode );
362}
363
364QgsGeometry QgsGeometrySnapper::snapGeometry( const QgsGeometry &geometry, double snapTolerance, const QList<QgsGeometry> &referenceGeometries, QgsGeometrySnapper::SnapMode mode )
365{
367 return geometry;
368
369 const QgsPoint center = qgsgeometry_cast<const QgsPoint *>( geometry.constGet() ) ? *static_cast<const QgsPoint *>( geometry.constGet() ) : QgsPoint( geometry.constGet()->boundingBox().center() );
370
371 QgsSnapIndex refSnapIndex;
372 for ( const QgsGeometry &geom : referenceGeometries )
373 {
374 refSnapIndex.addGeometry( geom.constGet() );
375 }
376
377 // Snap geometries
378 QgsAbstractGeometry *subjGeom = geometry.constGet()->clone();
379 QList<QList<QList<PointFlag>>> subjPointFlags;
380
381 // Pass 1: snap vertices of subject geometry to reference vertices
382 for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart )
383 {
384 subjPointFlags.append( QList<QList<PointFlag>>() );
385
386 for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing )
387 {
388 subjPointFlags[iPart].append( QList<PointFlag>() );
389
390 for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
391 {
392 if ( ( mode == EndPointPreferClosest || mode == EndPointPreferNodes || mode == EndPointToEndPoint ) && QgsWkbTypes::geometryType( subjGeom->wkbType() ) == Qgis::GeometryType::Line && ( iVert > 0 && iVert < nVerts - 1 ) )
393 {
394 //endpoint mode and not at an endpoint, skip
395 subjPointFlags[iPart][iRing].append( Unsnapped );
396 continue;
397 }
398
399 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
400 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
401 const QgsVertexId vidx( iPart, iRing, iVert );
402 const QgsPoint p = subjGeom->vertexAt( vidx );
403 if ( !refSnapIndex.getSnapItem( p, snapTolerance, &snapPoint, &snapSegment, mode == EndPointToEndPoint ) )
404 {
405 subjPointFlags[iPart][iRing].append( Unsnapped );
406 }
407 else
408 {
409 switch ( mode )
410 {
411 case PreferNodes:
415 {
416 // Prefer snapping to point
417 if ( snapPoint )
418 {
419 subjGeom->moveVertex( vidx, snapPoint->getSnapPoint( p ) );
420 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
421 }
422 else if ( snapSegment )
423 {
424 subjGeom->moveVertex( vidx, snapSegment->getSnapPoint( p ) );
425 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
426 }
427 break;
428 }
429
430 case PreferClosest:
433 {
434 QgsPoint nodeSnap, segmentSnap;
435 double distanceNode = std::numeric_limits<double>::max();
436 double distanceSegment = std::numeric_limits<double>::max();
437 if ( snapPoint )
438 {
439 nodeSnap = snapPoint->getSnapPoint( p );
440 distanceNode = nodeSnap.distanceSquared( p );
441 }
442 if ( snapSegment )
443 {
444 segmentSnap = snapSegment->getSnapPoint( p );
445 distanceSegment = segmentSnap.distanceSquared( p );
446 }
447 if ( snapPoint && distanceNode < distanceSegment )
448 {
449 subjGeom->moveVertex( vidx, nodeSnap );
450 subjPointFlags[iPart][iRing].append( SnappedToRefNode );
451 }
452 else if ( snapSegment )
453 {
454 subjGeom->moveVertex( vidx, segmentSnap );
455 subjPointFlags[iPart][iRing].append( SnappedToRefSegment );
456 }
457 break;
458 }
459 }
460 }
461 }
462 }
463 }
464
465 // no extra vertices to add for point geometry
466 if ( qgsgeometry_cast<const QgsPoint *>( subjGeom ) )
467 return QgsGeometry( subjGeom );
468
469 // nor for no extra vertices modes and end point only snapping
471 {
472 QgsGeometry result( subjGeom );
473 result.removeDuplicateNodes();
474 return result;
475 }
476
477 std::unique_ptr<QgsSnapIndex> subjSnapIndex( new QgsSnapIndex() );
478 subjSnapIndex->addGeometry( subjGeom );
479
480 std::unique_ptr<QgsAbstractGeometry> origSubjGeom( subjGeom->clone() );
481 std::unique_ptr<QgsSnapIndex> origSubjSnapIndex( new QgsSnapIndex() );
482 origSubjSnapIndex->addGeometry( origSubjGeom.get() );
483
484 // Pass 2: add missing vertices to subject geometry
485 for ( const QgsGeometry &refGeom : referenceGeometries )
486 {
487 for ( int iPart = 0, nParts = refGeom.constGet()->partCount(); iPart < nParts; ++iPart )
488 {
489 for ( int iRing = 0, nRings = refGeom.constGet()->ringCount( iPart ); iRing < nRings; ++iRing )
490 {
491 for ( int iVert = 0, nVerts = polyLineSize( refGeom.constGet(), iPart, iRing ); iVert < nVerts; ++iVert )
492 {
493 QgsSnapIndex::PointSnapItem *snapPoint = nullptr;
494 QgsSnapIndex::SegmentSnapItem *snapSegment = nullptr;
495 const QgsPoint point = refGeom.constGet()->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
496 if ( subjSnapIndex->getSnapItem( point, snapTolerance, &snapPoint, &snapSegment ) )
497 {
498 // Snap to segment, unless a subject point was already snapped to the reference point
499 if ( snapPoint )
500 {
501 const QgsPoint snappedPoint = snapPoint->getSnapPoint( point );
502 if ( QgsGeometryUtils::sqrDistance2D( snappedPoint, point ) < 1E-16 )
503 continue;
504 }
505
506 if ( snapSegment )
507 {
508 // Look if there is a closer reference segment, if so, ignore this point
509 const QgsPoint pProj = snapSegment->getSnapPoint( point );
510 const QgsPoint closest = refSnapIndex.getClosestSnapToPoint( point, pProj );
511 if ( QgsGeometryUtils::sqrDistance2D( pProj, point ) > QgsGeometryUtils::sqrDistance2D( pProj, closest ) )
512 {
513 continue;
514 }
515
516 // If we are too far away from the original geometry, do nothing
517 if ( !origSubjSnapIndex->getSnapItem( point, snapTolerance ) )
518 {
519 continue;
520 }
521
522 const QgsSnapIndex::CoordIdx *idx = snapSegment->idxFrom;
523 subjGeom->insertVertex( QgsVertexId( idx->vidx.part, idx->vidx.ring, idx->vidx.vertex + 1 ), point );
524 subjPointFlags[idx->vidx.part][idx->vidx.ring].insert( idx->vidx.vertex + 1, SnappedToRefNode );
525 subjSnapIndex.reset( new QgsSnapIndex() );
526 subjSnapIndex->addGeometry( subjGeom );
527 }
528 }
529 }
530 }
531 }
532 }
533 subjSnapIndex.reset();
534 origSubjSnapIndex.reset();
535 origSubjGeom.reset();
536
537 // Pass 3: remove superfluous vertices: all vertices which are snapped to a segment and not preceded or succeeded by an unsnapped vertex
538 for ( int iPart = 0, nParts = subjGeom->partCount(); iPart < nParts; ++iPart )
539 {
540 for ( int iRing = 0, nRings = subjGeom->ringCount( iPart ); iRing < nRings; ++iRing )
541 {
542 const bool ringIsClosed = subjGeom->vertexAt( QgsVertexId( iPart, iRing, 0 ) ) == subjGeom->vertexAt( QgsVertexId( iPart, iRing, subjGeom->vertexCount( iPart, iRing ) - 1 ) );
543 for ( int iVert = 0, nVerts = polyLineSize( subjGeom, iPart, iRing ); iVert < nVerts; ++iVert )
544 {
545 const int iPrev = ( iVert - 1 + nVerts ) % nVerts;
546 const int iNext = ( iVert + 1 ) % nVerts;
547 const QgsPoint pMid = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
548 const QgsPoint pPrev = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iPrev ) );
549 const QgsPoint pNext = subjGeom->vertexAt( QgsVertexId( iPart, iRing, iNext ) );
550
551 if ( subjPointFlags[iPart][iRing][iVert] == SnappedToRefSegment && subjPointFlags[iPart][iRing][iPrev] != Unsnapped && subjPointFlags[iPart][iRing][iNext] != Unsnapped && QgsGeometryUtils::sqrDistance2D( QgsGeometryUtils::projectPointOnSegment( pMid, pPrev, pNext ), pMid ) < 1E-12 )
552 {
553 if ( ( ringIsClosed && nVerts > 3 ) || ( !ringIsClosed && nVerts > 2 ) )
554 {
555 subjGeom->deleteVertex( QgsVertexId( iPart, iRing, iVert ) );
556 subjPointFlags[iPart][iRing].removeAt( iVert );
557 iVert -= 1;
558 nVerts -= 1;
559 }
560 else
561 {
562 // Don't delete vertices if this would result in a degenerate geometry
563 break;
564 }
565 }
566 }
567 }
568 }
569
570 QgsGeometry result( subjGeom );
571 result.removeDuplicateNodes();
572 return result;
573}
574
575int QgsGeometrySnapper::polyLineSize( const QgsAbstractGeometry *geom, int iPart, int iRing )
576{
577 const int nVerts = geom->vertexCount( iPart, iRing );
578
579 if ( qgsgeometry_cast<const QgsSurface *>( geom ) || qgsgeometry_cast<const QgsMultiSurface *>( geom ) )
580 {
581 const QgsPoint front = geom->vertexAt( QgsVertexId( iPart, iRing, 0 ) );
582 const QgsPoint back = geom->vertexAt( QgsVertexId( iPart, iRing, nVerts - 1 ) );
583 if ( front == back )
584 return nVerts - 1;
585 }
586
587 return nVerts;
588}
589
590
591//
592// QgsInternalGeometrySnapper
593//
594
596 : mSnapTolerance( snapTolerance )
597 , mMode( mode )
598{}
599
601{
602 if ( !feature.hasGeometry() )
603 return QgsGeometry();
604
605 QgsFeature feat = feature;
606 QgsGeometry geometry = feat.geometry();
607 if ( !mFirstFeature )
608 {
609 // snap against processed geometries
610 // Get potential reference features and construct snap index
611 QgsRectangle searchBounds = geometry.boundingBox();
612 searchBounds.grow( mSnapTolerance );
613 const QgsFeatureIds refFeatureIds = qgis::listToSet( mProcessedIndex.intersects( searchBounds ) );
614 if ( !refFeatureIds.isEmpty() )
615 {
616 QList<QgsGeometry> refGeometries;
617 const auto constRefFeatureIds = refFeatureIds;
618 for ( const QgsFeatureId id : constRefFeatureIds )
619 {
620 refGeometries << mProcessedGeometries.value( id );
621 }
622
623 geometry = QgsGeometrySnapper::snapGeometry( geometry, mSnapTolerance, refGeometries, mMode );
624 }
625 }
626 mProcessedGeometries.insert( feat.id(), geometry );
627 mProcessedIndex.addFeature( feat );
628 mFirstFeature = false;
629 return geometry;
630}
@ Polygon
Polygons.
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
Returns the minimal bounding box for the geometry.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
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.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
Abstract base class for curved geometry type.
Definition qgscurve.h:35
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
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...
Definition qgsfeature.h:58
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
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.
SnapMode
Snapping modes.
@ 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 sqrDistToLine(double ptX, double ptY, double x1, double y1, double x2, double y2, double &minDistX, double &minDistY, double epsilon)
Returns the squared distance between a point and a line.
static QgsPoint projectPointOnSegment(const QgsPoint &p, const QgsPoint &s1, const QgsPoint &s2)
Project the point on a segment.
static Q_DECL_DEPRECATED double sqrDistance2D(double x1, double y1, double x2, double y2)
Returns the squared 2D distance between (x1, y1) and (x2, y2).
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
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.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
static GEOSContextHandle_t get()
Returns a thread local instance of a GEOS context, safe for use in the current thread.
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.
Definition qgspoint.h:49
QgsPoint vertexAt(QgsVertexId) const override
Returns the point corresponding to a specified vertex id.
Definition qgspoint.cpp:527
double x
Definition qgspoint.h:52
double distanceSquared(double x, double y) const
Returns the Cartesian 2D squared distance between this point a specified x, y coordinate.
Definition qgspoint.h:415
double y
Definition qgspoint.h:53
A rectangle specified with double values.
void grow(double delta)
Grows the rectangle in place by the specified amount.
QgsPointXY center
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.
Definition qgsvector.h:30
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:6066
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.
Definition qgsvertexid.h:30
QList< const QgsPointCloudLayerProfileResults::PointResult * > * list