QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
Loading...
Searching...
No Matches
qgsalgorithmclip.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmclip.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson 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
18#include "qgsalgorithmclip.h"
19
20#include "qgsgeometryengine.h"
21#include "qgsoverlayutils.h"
22#include "qgsvectorlayer.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsClipAlgorithm::name() const
31{
32 return u"clip"_s;
33}
34
35Qgis::ProcessingAlgorithmFlags QgsClipAlgorithm::flags() const
36{
39 return f;
40}
41
42QString QgsClipAlgorithm::displayName() const
43{
44 return QObject::tr( "Clip" );
45}
46
47QStringList QgsClipAlgorithm::tags() const
48{
49 return QObject::tr( "clip,intersect,intersection,mask" ).split( ',' );
50}
51
52QString QgsClipAlgorithm::group() const
53{
54 return QObject::tr( "Vector overlay" );
55}
56
57QString QgsClipAlgorithm::groupId() const
58{
59 return u"vectoroverlay"_s;
60}
61
62void QgsClipAlgorithm::initAlgorithm( const QVariantMap & )
63{
64 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ) ) );
65 addParameter( new QgsProcessingParameterFeatureSource( u"OVERLAY"_s, QObject::tr( "Overlay layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
66
67 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Clipped" ) ) );
68}
69
70QString QgsClipAlgorithm::shortHelpString() const
71{
72 return QObject::tr(
73 "This algorithm clips a vector layer using the features of an additional polygon layer. Only the parts of the features "
74 "in the Input layer that fall within the polygons of the Overlay layer will be added to the resulting layer."
75 )
76 + u"\n\n"_s
77 + QObject::tr(
78 "The attributes of the features are not modified, although properties such as area or length of the features will "
79 "be modified by the clipping operation. If such properties are stored as attributes, those attributes will have to "
80 "be manually updated."
81 );
82}
83
84QString QgsClipAlgorithm::shortDescription() const
85{
86 return QObject::tr( "Clips a vector layer using the features of an additional polygon layer." );
87}
88
89QgsClipAlgorithm *QgsClipAlgorithm::createInstance() const
90{
91 return new QgsClipAlgorithm();
92}
93
94bool QgsClipAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
95{
96 const QgsVectorLayer *layer = qobject_cast<const QgsVectorLayer *>( l );
97 if ( !layer )
98 return false;
99
100 return layer->isSpatial();
101}
102
103QVariantMap QgsClipAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
104{
105 QGS_MARK_ALGORITHM_SOURCE
106
107 std::unique_ptr<QgsFeatureSource> featureSource( parameterAsSource( parameters, u"INPUT"_s, context ) );
108 if ( !featureSource )
109 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
110
111 std::unique_ptr<QgsFeatureSource> maskSource( parameterAsSource( parameters, u"OVERLAY"_s, context ) );
112 if ( !maskSource )
113 throw QgsProcessingException( invalidSourceError( parameters, u"OVERLAY"_s ) );
114
115 if ( featureSource->hasSpatialIndex() == Qgis::SpatialIndexPresence::NotPresent )
116 feedback->pushWarning( QObject::tr( "No spatial index exists for input layer, performance will be severely degraded" ) );
117
118 QString dest;
119 const Qgis::GeometryType sinkType = QgsWkbTypes::geometryType( featureSource->wkbType() );
120 std::unique_ptr<QgsFeatureSink> sink(
121 parameterAsSink( parameters, u"OUTPUT"_s, context, dest, featureSource->fields(), QgsWkbTypes::promoteNonPointTypesToMulti( featureSource->wkbType() ), featureSource->sourceCrs() )
122 );
123
124 if ( !sink )
125 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
126
127 // first build up a list of clip geometries
128 QVector<QgsGeometry> clipGeoms;
129 QgsFeatureIterator it = maskSource->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QList<int>() ).setDestinationCrs( featureSource->sourceCrs(), context.transformContext() ) );
130 QgsFeature f;
131 while ( it.nextFeature( f ) )
132 {
133 if ( f.hasGeometry() )
134 clipGeoms << f.geometry();
135 }
136
137 QVariantMap outputs;
138 outputs.insert( u"OUTPUT"_s, dest );
139
140 if ( clipGeoms.isEmpty() )
141 return outputs;
142
143 // are we clipping against a single feature? if so, we can show finer progress reports
144 bool singleClipFeature = false;
145 QgsGeometry combinedClipGeom;
146 if ( clipGeoms.length() > 1 )
147 {
148 combinedClipGeom = QgsGeometry::unaryUnion( clipGeoms, QgsGeometryParameters(), feedback );
149 if ( combinedClipGeom.isEmpty() )
150 {
151 throw QgsProcessingException( QObject::tr( "Could not create the combined clip geometry: %1" ).arg( combinedClipGeom.lastError() ) );
152 }
153 singleClipFeature = false;
154 }
155 else
156 {
157 combinedClipGeom = clipGeoms.at( 0 );
158 singleClipFeature = true;
159 }
160
161 // use prepared geometries for faster intersection tests
162 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( combinedClipGeom.constGet() ) );
163 engine->prepareGeometry();
164
165 QgsFeatureIds testedFeatureIds;
166
167 int i = -1;
168 const auto constClipGeoms = clipGeoms;
169 for ( const QgsGeometry &clipGeom : constClipGeoms )
170 {
171 i++;
172 if ( feedback->isCanceled() )
173 {
174 break;
175 }
176 QgsFeatureIterator inputIt = featureSource->getFeatures( QgsFeatureRequest().setFilterRect( clipGeom.boundingBox() ) );
177 QgsFeatureList inputFeatures;
178 QgsFeature f;
179 while ( inputIt.nextFeature( f ) )
180 inputFeatures << f;
181
182 if ( inputFeatures.isEmpty() )
183 continue;
184
185 double step = 0;
186 if ( singleClipFeature )
187 step = 100.0 / inputFeatures.length();
188
189 const int current = 0;
190 const auto constInputFeatures = inputFeatures;
191 for ( const QgsFeature &inputFeature : constInputFeatures )
192 {
193 if ( feedback->isCanceled() )
194 {
195 break;
196 }
197
198 if ( !inputFeature.hasGeometry() )
199 continue;
200
201 if ( testedFeatureIds.contains( inputFeature.id() ) )
202 {
203 // don't retest a feature we have already checked
204 continue;
205 }
206 testedFeatureIds.insert( inputFeature.id() );
207
208 if ( !engine->intersects( inputFeature.geometry().constGet() ) )
209 continue;
210
211 QgsGeometry newGeometry;
212 if ( !engine->contains( inputFeature.geometry().constGet() ) )
213 {
214 const QgsGeometry currentGeometry = inputFeature.geometry();
215 newGeometry = combinedClipGeom.intersection( currentGeometry, QgsGeometryParameters(), feedback );
217 {
218 const QgsGeometry intCom = inputFeature.geometry().combine( newGeometry, QgsGeometryParameters(), feedback );
219 const QgsGeometry intSym = inputFeature.geometry().symDifference( newGeometry, QgsGeometryParameters(), feedback );
220 newGeometry = intCom.difference( intSym, QgsGeometryParameters(), feedback );
221 }
222 }
223 else
224 {
225 // clip geometry totally contains feature geometry, so no need to perform intersection
226 newGeometry = inputFeature.geometry();
227 }
228
229 if ( !QgsOverlayUtils::sanitizeIntersectionResult( newGeometry, sinkType, QgsOverlayUtils::SanitizeFlag::DontPromotePointGeometryToMultiPoint ) )
230 continue;
231
232 QgsFeature outputFeature;
233 outputFeature.setGeometry( newGeometry );
234 outputFeature.setAttributes( inputFeature.attributes() );
235 if ( !sink->addFeature( outputFeature, QgsFeatureSink::FastInsert ) )
236 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
237 else
238 feedback->featureAddedToSink( u"OUTPUT"_s );
239
240 if ( singleClipFeature )
241 feedback->setProgress( current * step );
242 }
243
244 if ( !singleClipFeature )
245 {
246 // coarse progress report for multiple clip geometries
247 feedback->setProgress( 100.0 * static_cast<double>( i ) / clipGeoms.length() );
248 }
249 }
250
251 sink->finalize();
252 feedback->featureSinkFinalized( u"OUTPUT"_s );
253
254 return outputs;
255}
256
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3752
@ NotPresent
No spatial index exists for the source.
Definition qgis.h:601
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:379
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3826
@ Unknown
Unknown.
Definition qgis.h:295
@ GeometryCollection
GeometryCollection.
Definition qgis.h:303
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3807
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.
Wraps a request for features to a vector layer (or directly its vector data provider).
@ 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
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:66
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
Encapsulates parameters under which a geometry operation is performed.
A geometry is the spatial representation of a feature.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points shared by this geometry and other.
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
QgsGeometry symDifference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points making up this geometry that do not make up other.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometry combine(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing all the points in this geometry and other (a union geometry operation...
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr)
Compute the unary union on a list of geometries.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
QgsGeometry difference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points making up this geometry that do not make up 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.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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...
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...
static Qgis::WkbType promoteNonPointTypesToMulti(Qgis::WkbType type)
Promotes a WKB geometry type to its multi-type equivalent, with the exception of point geometry types...
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
QList< QgsFeature > QgsFeatureList
QSet< QgsFeatureId > QgsFeatureIds