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