QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsalgorithmsnapgeometries.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmsnapgeometries.cpp
3 ---------------------
4 begin : May 2020
5 copyright : (C) 2020 by Alexander Bruy
6 email : alexander dot bruy at gmail dot com
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
19
20#include "qgsvectorlayer.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsSnapGeometriesAlgorithm::name() const
31{
32 return u"snapgeometries"_s;
33}
34
35QString QgsSnapGeometriesAlgorithm::displayName() const
36{
37 return QObject::tr( "Snap geometries to layer" );
38}
39
40QString QgsSnapGeometriesAlgorithm::shortHelpString() const
41{
42 return QObject::tr( "This algorithm snaps the geometries in a layer. Snapping can be done either to the geometries "
43 "from another layer, or to geometries within the same layer." )
44 + u"\n\n"_s
45 + QObject::tr( "A tolerance is specified in layer units to control how close vertices need "
46 "to be to the reference layer geometries before they are snapped." )
47 + u"\n\n"_s
48 + QObject::tr( "Snapping occurs to both nodes and edges. Depending on the snapping behavior, "
49 "either nodes or edges will be preferred." )
50 + u"\n\n"_s
51 + QObject::tr( "Vertices will be inserted or removed as required to make the geometries match "
52 "the reference geometries." );
53}
54
55QString QgsSnapGeometriesAlgorithm::shortDescription() const
56{
57 return QObject::tr( "Snaps the geometries to the geometries within the same layer or from another layer." );
58}
59
60QStringList QgsSnapGeometriesAlgorithm::tags() const
61{
62 return QObject::tr( "geometry,snap,tolerance" ).split( ',' );
63}
64
65QString QgsSnapGeometriesAlgorithm::group() const
66{
67 return QObject::tr( "Vector geometry" );
68}
69
70QString QgsSnapGeometriesAlgorithm::groupId() const
71{
72 return u"vectorgeometry"_s;
73}
74
75Qgis::ProcessingAlgorithmFlags QgsSnapGeometriesAlgorithm::flags() const
76{
79 return f;
80}
81
82bool QgsSnapGeometriesAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
83{
84 const QgsVectorLayer *layer = qobject_cast<const QgsVectorLayer *>( l );
85 if ( !layer )
86 return false;
87
88 return layer->isSpatial();
89}
90
91void QgsSnapGeometriesAlgorithm::initAlgorithm( const QVariantMap & )
92{
93 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
94 addParameter( new QgsProcessingParameterFeatureSource( u"REFERENCE_LAYER"_s, QObject::tr( "Reference layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
95
96 auto tolParam = std::make_unique<QgsProcessingParameterDistance>( u"TOLERANCE"_s, QObject::tr( "Tolerance" ), 10.0, u"INPUT"_s, false, 0.00000001 );
97 tolParam->setMetadata(
98 { QVariantMap( { { u"widget_wrapper"_s, QVariantMap( { { u"decimals"_s, 8 } } ) } } )
99 }
100 );
101 addParameter( tolParam.release() );
102
103 const QStringList options = QStringList()
104 << QObject::tr( "Prefer aligning nodes, insert extra vertices where required" )
105 << QObject::tr( "Prefer closest point, insert extra vertices where required" )
106 << QObject::tr( "Prefer aligning nodes, don't insert new vertices" )
107 << QObject::tr( "Prefer closest point, don't insert new vertices" )
108 << QObject::tr( "Move end points only, prefer aligning nodes" )
109 << QObject::tr( "Move end points only, prefer closest point" )
110 << QObject::tr( "Snap end points to end points only" )
111 << QObject::tr( "Snap to anchor nodes (single layer only)" );
112 addParameter( new QgsProcessingParameterEnum( u"BEHAVIOR"_s, QObject::tr( "Behavior" ), options, false, QVariantList() << 0 ) );
113 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Snapped geometry" ), Qgis::ProcessingSourceType::VectorAnyGeometry ) );
114}
115
116QgsSnapGeometriesAlgorithm *QgsSnapGeometriesAlgorithm::createInstance() const
117{
118 return new QgsSnapGeometriesAlgorithm();
119}
120
121QVariantMap QgsSnapGeometriesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
122{
123 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
124 if ( !source )
125 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
126
127 const std::unique_ptr<QgsProcessingFeatureSource> referenceSource( parameterAsSource( parameters, u"REFERENCE_LAYER"_s, context ) );
128 if ( !referenceSource )
129 throw QgsProcessingException( invalidSourceError( parameters, u"REFERENCE_LAYER"_s ) );
130
131 const double tolerance = parameterAsDouble( parameters, u"TOLERANCE"_s, context );
132 const QgsGeometrySnapper::SnapMode mode = static_cast<QgsGeometrySnapper::SnapMode>( parameterAsEnum( parameters, u"BEHAVIOR"_s, context ) );
133
134 QString dest;
135 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, source->fields(), source->wkbType(), source->sourceCrs() ) );
136 if ( !sink )
137 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
138
139 QgsFeatureIterator features = source->getFeatures();
140
141 if ( parameters.value( u"INPUT"_s ) != parameters.value( u"REFERENCE_LAYER"_s ) )
142 {
143 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
144 if ( mode == 7 )
145 throw QgsProcessingException( QObject::tr( "This mode applies when the input and reference layer are the same." ) );
146
147 const QgsGeometrySnapper snapper( referenceSource.get() );
148 long long processed = 0;
149 QgsFeature f;
150 while ( features.nextFeature( f ) )
151 {
152 if ( feedback->isCanceled() )
153 break;
154
155 if ( f.hasGeometry() )
156 {
157 QgsFeature outFeature( f );
158 outFeature.setGeometry( snapper.snapGeometry( f.geometry(), tolerance, mode ) );
159 if ( !sink->addFeature( outFeature, QgsFeatureSink::FastInsert ) )
160 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
161 }
162 else
163 {
164 if ( !sink->addFeature( f ) )
165 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
166 }
167 processed += 1;
168 feedback->setProgress( processed * step );
169 }
170 }
171 else if ( mode == 7 )
172 {
173 // input layer == reference layer
174 const int modified = QgsGeometrySnapperSingleSource::run( *source, *sink, tolerance, feedback );
175 feedback->pushInfo( QObject::tr( "Snapped %n geometries.", nullptr, modified ) );
176 }
177 else
178 {
179 // snapping internally
180 const double step = source->featureCount() > 0 ? 100.0 / ( source->featureCount() * 2 ) : 1;
181 long long processed = 0;
182
183 QgsInternalGeometrySnapper snapper( tolerance, mode );
184 QgsFeature f;
185 QList<QgsFeatureId> editedFeatureIds;
186 QMap<QgsFeatureId, QgsFeature> editedFeatures;
187 while ( features.nextFeature( f ) )
188 {
189 if ( feedback->isCanceled() )
190 break;
191
192 QgsFeature editedFeature( f );
193 if ( f.hasGeometry() )
194 {
195 editedFeature.setGeometry( snapper.snapFeature( f ) );
196 }
197 editedFeatureIds << editedFeature.id();
198 editedFeatures.insert( editedFeature.id(), editedFeature );
199 processed += 1;
200 }
201
202 // reversed order snapping round is required to insure geometries are snapped against all features
203 snapper = QgsInternalGeometrySnapper( tolerance, mode );
204 std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
205 for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
206 {
207 if ( feedback->isCanceled() )
208 break;
209
210 QgsFeature editedFeature( editedFeatures.value( fid ) );
211 if ( editedFeature.hasGeometry() )
212 {
213 editedFeature.setGeometry( snapper.snapFeature( editedFeature ) );
214 editedFeatures.insert( editedFeature.id(), editedFeature );
215 }
216 }
217 std::reverse( editedFeatureIds.begin(), editedFeatureIds.end() );
218 processed += 1;
219
220 if ( !feedback->isCanceled() )
221 {
222 for ( const QgsFeatureId &fid : std::as_const( editedFeatureIds ) )
223 {
224 QgsFeature outFeature( editedFeatures.value( fid ) );
225 if ( !sink->addFeature( outFeature ) )
226 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
227
228 feedback->setProgress( processed * step );
229 }
230 }
231 }
232
233 sink->finalize();
234
235 QVariantMap outputs;
236 outputs.insert( u"OUTPUT"_s, dest );
237 return outputs;
238}
239
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3604
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3607
@ VectorLine
Vector line layers.
Definition qgis.h:3606
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3680
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3661
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.
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
static int run(const QgsFeatureSource &source, QgsFeatureSink &sink, double thresh, QgsFeedback *feedback)
Run the algorithm on given source and output results to the sink, using threshold value in the source...
Allows a geometry to be snapped to the geometries within a different reference layer.
SnapMode
Snapping modes.
Allows a set of geometries to be snapped to each other.
Base class for all map layer types.
Definition qgsmaplayer.h:83
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
Represents a vector layer which manages a vector based dataset.
bool isSpatial() const final
Returns true if this is a geometry layer and false in case of NoGeometry (table only) or UnknownGeome...
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features