QGIS API Documentation 3.99.0-Master (26c88405ac0)
Loading...
Searching...
No Matches
qgsalgorithmbuffer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmbuffer.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 "qgsalgorithmbuffer.h"
19
20#include "qgsmessagelog.h"
21#include "qgsvectorlayer.h"
22
24
25QString QgsBufferAlgorithm::name() const
26{
27 return QStringLiteral( "buffer" );
28}
29
30QString QgsBufferAlgorithm::displayName() const
31{
32 return QObject::tr( "Buffer" );
33}
34
35QStringList QgsBufferAlgorithm::tags() const
36{
37 return QObject::tr( "buffer,grow,fixed,variable,distance" ).split( ',' );
38}
39
40QString QgsBufferAlgorithm::group() const
41{
42 return QObject::tr( "Vector geometry" );
43}
44
45QString QgsBufferAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeometry" );
48}
49
50void QgsBufferAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
53
54 auto bufferParam = std::make_unique<QgsProcessingParameterDistance>( QStringLiteral( "DISTANCE" ), QObject::tr( "Distance" ), 10, QStringLiteral( "INPUT" ) );
55 bufferParam->setIsDynamic( true );
56 bufferParam->setDynamicPropertyDefinition( QgsPropertyDefinition( QStringLiteral( "Distance" ), QObject::tr( "Buffer distance" ), QgsPropertyDefinition::Double ) );
57 bufferParam->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
58 addParameter( bufferParam.release() );
59 auto segmentParam = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "SEGMENTS" ), QObject::tr( "Segments" ), Qgis::ProcessingNumberParameterType::Integer, 5, false, 1 );
60 segmentParam->setHelp( QObject::tr( "The segments parameter controls the number of line segments to use to approximate a quarter circle when creating rounded offsets." ) );
61 addParameter( segmentParam.release() );
62 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "END_CAP_STYLE" ), QObject::tr( "End cap style" ), QStringList() << QObject::tr( "Round" ) << QObject::tr( "Flat" ) << QObject::tr( "Square" ), false, 0 ) );
63 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "JOIN_STYLE" ), QObject::tr( "Join style" ), QStringList() << QObject::tr( "Round" ) << QObject::tr( "Miter" ) << QObject::tr( "Bevel" ), false, 0 ) );
64 addParameter( new QgsProcessingParameterNumber( QStringLiteral( "MITER_LIMIT" ), QObject::tr( "Miter limit" ), Qgis::ProcessingNumberParameterType::Double, 2, false, 1 ) );
65
66 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "DISSOLVE" ), QObject::tr( "Dissolve result" ), false ) );
67
68 auto keepDisjointParam = std::make_unique<QgsProcessingParameterBoolean>( QStringLiteral( "SEPARATE_DISJOINT" ), QObject::tr( "Keep disjoint results separate" ), false );
69 keepDisjointParam->setFlags( keepDisjointParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
70 keepDisjointParam->setHelp( QObject::tr( "If checked, then any disjoint parts in the buffer results will be output as separate single-part features." ) );
71 addParameter( keepDisjointParam.release() );
72
73 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Buffered" ), Qgis::ProcessingSourceType::VectorPolygon, QVariant(), false, true, true ) );
74}
75
76QString QgsBufferAlgorithm::shortHelpString() const
77{
78 return QObject::tr( "This algorithm computes a buffer area for all the features in an input layer, using a fixed or dynamic distance.\n\n"
79 "The segments parameter controls the number of line segments to use to approximate a quarter circle when creating rounded offsets.\n\n"
80 "The end cap style parameter controls how line endings are handled in the buffer.\n\n"
81 "The join style parameter specifies whether round, miter or beveled joins should be used when offsetting corners in a line.\n\n"
82 "The miter limit parameter is only applicable for miter join styles, and controls the maximum distance from the offset curve to use when creating a mitered join." );
83}
84
85QString QgsBufferAlgorithm::shortDescription() const
86{
87 return QObject::tr( "Computes a buffer area for all the features in an input layer, using a fixed or dynamic distance." );
88}
89
90Qgis::ProcessingAlgorithmDocumentationFlags QgsBufferAlgorithm::documentationFlags() const
91{
93}
94
95QgsBufferAlgorithm *QgsBufferAlgorithm::createInstance() const
96{
97 return new QgsBufferAlgorithm();
98}
99
100QVariantMap QgsBufferAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
101{
102 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
103 if ( !source )
104 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
105
106 // fixed parameters
107 const bool dissolve = parameterAsBoolean( parameters, QStringLiteral( "DISSOLVE" ), context );
108 const bool keepDisjointSeparate = parameterAsBoolean( parameters, QStringLiteral( "SEPARATE_DISJOINT" ), context );
109 const int segments = parameterAsInt( parameters, QStringLiteral( "SEGMENTS" ), context );
110 const Qgis::EndCapStyle endCapStyle = static_cast<Qgis::EndCapStyle>( 1 + parameterAsInt( parameters, QStringLiteral( "END_CAP_STYLE" ), context ) );
111 const Qgis::JoinStyle joinStyle = static_cast<Qgis::JoinStyle>( 1 + parameterAsInt( parameters, QStringLiteral( "JOIN_STYLE" ), context ) );
112 const double miterLimit = parameterAsDouble( parameters, QStringLiteral( "MITER_LIMIT" ), context );
113 const double bufferDistance = parameterAsDouble( parameters, QStringLiteral( "DISTANCE" ), context );
114 const bool dynamicBuffer = QgsProcessingParameters::isDynamic( parameters, QStringLiteral( "DISTANCE" ) );
115
116 QString dest;
117 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(), Qgis::WkbType::MultiPolygon, source->sourceCrs(), keepDisjointSeparate ? QgsFeatureSink::RegeneratePrimaryKey : QgsFeatureSink::SinkFlags() ) );
118 if ( !sink )
119 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
120
121 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, source.get() );
122 QgsProperty bufferProperty;
123 if ( dynamicBuffer )
124 {
125 bufferProperty = parameters.value( QStringLiteral( "DISTANCE" ) ).value<QgsProperty>();
126 }
127
128 const long count = source->featureCount();
129
130 QgsFeature f;
131 // buffer doesn't care about invalid features, and buffering can be used to repair geometries
133
134 const double step = count > 0 ? 100.0 / count : 1;
135 int current = 0;
136
137 QVector<QgsGeometry> bufferedGeometriesForDissolve;
138 QgsAttributes dissolveAttrs;
139
140 while ( it.nextFeature( f ) )
141 {
142 if ( feedback->isCanceled() )
143 {
144 break;
145 }
146 if ( dissolveAttrs.isEmpty() )
147 dissolveAttrs = f.attributes();
148
149 QgsFeature out = f;
150 if ( out.hasGeometry() )
151 {
152 double distance = bufferDistance;
153 if ( dynamicBuffer )
154 {
155 expressionContext.setFeature( f );
156 distance = bufferProperty.valueAsDouble( expressionContext, bufferDistance );
157 }
158
159 QgsGeometry outputGeometry = f.geometry().buffer( distance, segments, endCapStyle, joinStyle, miterLimit );
160 if ( outputGeometry.isNull() )
161 {
162 QgsMessageLog::logMessage( QObject::tr( "Error calculating buffer for feature %1" ).arg( f.id() ), QObject::tr( "Processing" ), Qgis::MessageLevel::Warning );
163 }
164 if ( dissolve )
165 {
166 bufferedGeometriesForDissolve << outputGeometry;
167 }
168 else
169 {
170 outputGeometry.convertToMultiType();
171
172 if ( !keepDisjointSeparate )
173 {
174 out.setGeometry( outputGeometry );
175
176 if ( !sink->addFeature( out, QgsFeatureSink::FastInsert ) )
177 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
178 }
179 else
180 {
181 for ( auto partIt = outputGeometry.const_parts_begin(); partIt != outputGeometry.const_parts_end(); ++partIt )
182 {
183 if ( const QgsAbstractGeometry *part = *partIt )
184 {
185 out.setGeometry( QgsGeometry( part->clone() ) );
186 if ( !sink->addFeature( out, QgsFeatureSink::FastInsert ) )
187 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
188 }
189 }
190 }
191 }
192 }
193 else if ( !dissolve )
194 {
195 if ( !sink->addFeature( out, QgsFeatureSink::FastInsert ) )
196 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
197 }
198
199 feedback->setProgress( current * step );
200 current++;
201 }
202
203 if ( dissolve && !bufferedGeometriesForDissolve.isEmpty() )
204 {
205 QgsGeometry finalGeometry = QgsGeometry::unaryUnion( bufferedGeometriesForDissolve );
206 finalGeometry.convertToMultiType();
207 QgsFeature f;
208 f.setAttributes( dissolveAttrs );
209
210 if ( !keepDisjointSeparate )
211 {
212 f.setGeometry( finalGeometry );
213 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
214 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
215 }
216 else
217 {
218 for ( auto partIt = finalGeometry.const_parts_begin(); partIt != finalGeometry.const_parts_end(); ++partIt )
219 {
220 if ( const QgsAbstractGeometry *part = *partIt )
221 {
222 f.setGeometry( QgsGeometry( part->clone() ) );
223 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
224 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
225 }
226 }
227 }
228 }
229
230 sink->finalize();
231
232 QVariantMap outputs;
233 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
234 return outputs;
235}
236
237Qgis::ProcessingAlgorithmFlags QgsBufferAlgorithm::flags() const
238{
241 return f;
242}
243
244QgsProcessingAlgorithm::VectorProperties QgsBufferAlgorithm::sinkProperties( const QString &sink, const QVariantMap &parameters, QgsProcessingContext &context, const QMap<QString, QgsProcessingAlgorithm::VectorProperties> &sourceProperties ) const
245{
246 const bool keepDisjointSeparate = parameterAsBoolean( parameters, QStringLiteral( "SEPARATE_DISJOINT" ), context );
247
249 if ( sink == QLatin1String( "OUTPUT" ) )
250 {
251 if ( sourceProperties.value( QStringLiteral( "INPUT" ) ).availability == Qgis::ProcessingPropertyAvailability::Available )
252 {
253 const VectorProperties inputProps = sourceProperties.value( QStringLiteral( "INPUT" ) );
254 result.fields = inputProps.fields;
255 result.crs = inputProps.crs;
256 result.wkbType = keepDisjointSeparate ? Qgis::WkbType::Polygon : Qgis::WkbType::MultiPolygon;
258 return result;
259 }
260 else
261 {
262 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
263 if ( source )
264 {
265 result.fields = source->fields();
266 result.crs = source->sourceCrs();
267 result.wkbType = keepDisjointSeparate ? Qgis::WkbType::Polygon : Qgis::WkbType::MultiPolygon;
269 return result;
270 }
271 }
272 }
273 return result;
274}
275
276bool QgsBufferAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
277{
278 const QgsVectorLayer *vlayer = qobject_cast<const QgsVectorLayer *>( layer );
279 if ( !vlayer )
280 return false;
281 //Only Polygons
282 return vlayer->wkbType() == Qgis::WkbType::Polygon || vlayer->wkbType() == Qgis::WkbType::MultiPolygon;
283}
284
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3536
@ Warning
Warning message.
Definition qgis.h:158
@ Available
Properties are available.
Definition qgis.h:3644
JoinStyle
Join styles for buffers.
Definition qgis.h:2121
@ RegeneratesPrimaryKeyInSomeScenarios
Algorithm may drop the existing primary keys or FID values in some scenarios, depending on algorithm ...
Definition qgis.h:3620
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3609
EndCapStyle
End cap styles for buffers.
Definition qgis.h:2108
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3711
@ Polygon
Polygon.
Definition qgis.h:281
@ MultiPolygon
MultiPolygon.
Definition qgis.h:285
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3590
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
@ Double
Double/float values.
Definition qgis.h:3804
Abstract base class for all geometries.
A vector of attributes.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
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).
QFlags< SinkFlag > SinkFlags
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsAttributes attributes
Definition qgsfeature.h:67
QgsFeatureId id
Definition qgsfeature.h:66
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.
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
QgsGeometry buffer(double distance, int segments) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
Base class for all map layer types.
Definition qgsmaplayer.h:80
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
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.
A boolean parameter for processing algorithms.
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.
A numeric parameter for processing algorithms.
static bool isDynamic(const QVariantMap &parameters, const QString &name)
Returns true if the parameter with matching name is a dynamic parameter, and must be evaluated once f...
Definition for a property.
Definition qgsproperty.h:45
@ Double
Double value (including negative values).
Definition qgsproperty.h:55
A store for object properties.
QVariant value(const QgsExpressionContext &context, const QVariant &defaultValue=QVariant(), bool *ok=nullptr) const
Calculates the current value of the property, including any transforms which are set for the property...
double valueAsDouble(const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property and interprets it as a double.
Represents a vector layer which manages a vector based dataset.
Q_INVOKABLE Qgis::WkbType wkbType() const final
Returns the WKBType or WKBUnknown in case of error.
Properties of a vector source or sink used in an algorithm.
Qgis::WkbType wkbType
Geometry (WKB) type.
QgsCoordinateReferenceSystem crs
Coordinate Reference System.
Qgis::ProcessingPropertyAvailability availability
Availability of the properties. By default properties are not available.