QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
Loading...
Searching...
No Matches
qgsalgorithmangletonearest.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmangletonearest.cpp
3 ---------------------
4 begin : July 2020
5 copyright : (C) 2020 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
19
20#include "qgslinestring.h"
21#include "qgsmarkersymbol.h"
22#include "qgsrenderer.h"
23#include "qgsspatialindex.h"
25#include "qgsvectorlayer.h"
26
27#include <QString>
28
29using namespace Qt::StringLiterals;
30
32
33class SetMarkerRotationVisitor : public QgsStyleEntityVisitorInterface
34{
35 public:
36 SetMarkerRotationVisitor( const QString &rotationField )
37 : mRotationField( rotationField )
38 {}
39
40 bool visit( const QgsStyleEntityVisitorInterface::StyleLeaf &entity ) override
41 {
42 if ( const QgsStyleSymbolEntity *symbolEntity = dynamic_cast<const QgsStyleSymbolEntity *>( entity.entity ) )
43 {
44 if ( QgsMarkerSymbol *marker = dynamic_cast<QgsMarkerSymbol *>( symbolEntity->symbol() ) )
45 {
46 marker->setDataDefinedAngle( QgsProperty::fromField( mRotationField ) );
47 }
48 }
49 return true;
50 }
51
52 private:
53 QString mRotationField;
54};
55
56class SetMarkerRotationPostProcessor : public QgsProcessingLayerPostProcessorInterface
57{
58 public:
59 SetMarkerRotationPostProcessor( std::unique_ptr<QgsFeatureRenderer> renderer, const QString &rotationField )
60 : mRenderer( std::move( renderer ) )
61 , mRotationField( rotationField )
62 {}
63
64 void postProcessLayer( QgsMapLayer *layer, QgsProcessingContext &, QgsProcessingFeedback * ) override
65 {
66 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
67 {
68 SetMarkerRotationVisitor visitor( mRotationField );
69 mRenderer->accept( &visitor );
70 vl->setRenderer( mRenderer.release() );
71 vl->triggerRepaint();
72 }
73 }
74
75 private:
76 std::unique_ptr<QgsFeatureRenderer> mRenderer;
77 QString mRotationField;
78};
79
80QString QgsAngleToNearestAlgorithm::name() const
81{
82 return u"angletonearest"_s;
83}
84
85QString QgsAngleToNearestAlgorithm::displayName() const
86{
87 return QObject::tr( "Align points to features" );
88}
89
90QStringList QgsAngleToNearestAlgorithm::tags() const
91{
92 return QObject::tr( "align,marker,stroke,fill,orient,points,lines,angles,rotation,rotate" ).split( ',' );
93}
94
95QString QgsAngleToNearestAlgorithm::group() const
96{
97 return QObject::tr( "Cartography" );
98}
99
100QString QgsAngleToNearestAlgorithm::groupId() const
101{
102 return u"cartography"_s;
103}
104
105QgsAngleToNearestAlgorithm::~QgsAngleToNearestAlgorithm() = default;
106
107void QgsAngleToNearestAlgorithm::initAlgorithm( const QVariantMap &configuration )
108{
109 mIsInPlace = configuration.value( u"IN_PLACE"_s ).toBool();
110
111 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
112 addParameter( new QgsProcessingParameterFeatureSource( u"REFERENCE_LAYER"_s, QObject::tr( "Reference layer" ) ) );
113
114 addParameter( new QgsProcessingParameterDistance( u"MAX_DISTANCE"_s, QObject::tr( "Maximum distance to consider" ), QVariant(), u"INPUT"_s, true, 0 ) );
115
116 if ( !mIsInPlace )
117 addParameter( new QgsProcessingParameterString( u"FIELD_NAME"_s, QObject::tr( "Angle field name" ), u"rotation"_s ) );
118 else
119 addParameter( new QgsProcessingParameterField( u"FIELD_NAME"_s, QObject::tr( "Angle field name" ), u"rotation"_s, u"INPUT"_s ) );
120
121 addParameter( new QgsProcessingParameterBoolean( u"APPLY_SYMBOLOGY"_s, QObject::tr( "Automatically apply symbology" ), true ) );
122
123 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Aligned layer" ), Qgis::ProcessingSourceType::VectorPoint ) );
124}
125
126Qgis::ProcessingAlgorithmFlags QgsAngleToNearestAlgorithm::flags() const
127{
130 return f;
131}
132
133QString QgsAngleToNearestAlgorithm::shortHelpString() const
134{
135 return QObject::tr(
136 "This algorithm calculates the rotation required to align point features with their nearest "
137 "feature from another reference layer. A new field is added to the output layer which is filled with the angle "
138 "(in degrees, clockwise) to the nearest reference feature.\n\n"
139 "Optionally, the output layer's symbology can be set to automatically use the calculated rotation "
140 "field to rotate marker symbols.\n\n"
141 "If desired, a maximum distance to use when aligning points can be set, to avoid aligning isolated points "
142 "to distant features."
143 );
144}
145
146QString QgsAngleToNearestAlgorithm::shortDescription() const
147{
148 return QObject::tr( "Rotates point features to align them to nearby features." );
149}
150
151QgsAngleToNearestAlgorithm *QgsAngleToNearestAlgorithm::createInstance() const
152{
153 return new QgsAngleToNearestAlgorithm();
154}
155
156bool QgsAngleToNearestAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const
157{
158 if ( const QgsVectorLayer *vl = qobject_cast<const QgsVectorLayer *>( layer ) )
159 {
160 return vl->geometryType() == Qgis::GeometryType::Point;
161 }
162 return false;
163}
164
165bool QgsAngleToNearestAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
166{
167 if ( !mIsInPlace )
168 {
169 if ( QgsVectorLayer *sourceLayer = parameterAsVectorLayer( parameters, u"INPUT"_s, context ) )
170 {
171 mSourceRenderer.reset( sourceLayer->renderer()->clone() );
172 }
173 }
174
175 return true;
176}
177
178QVariantMap QgsAngleToNearestAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
179{
180 QGS_MARK_ALGORITHM_SOURCE
181
182 const double maxDistance = parameters.value( u"MAX_DISTANCE"_s ).isValid() ? parameterAsDouble( parameters, u"MAX_DISTANCE"_s, context ) : std::numeric_limits<double>::quiet_NaN();
183 std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u"INPUT"_s, context ) );
184 if ( !input )
185 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
186
187 std::unique_ptr<QgsProcessingFeatureSource> referenceSource( parameterAsSource( parameters, u"REFERENCE_LAYER"_s, context ) );
188 if ( !referenceSource )
189 throw QgsProcessingException( invalidSourceError( parameters, u"REFERENCE_LAYER"_s ) );
190
191 const QString fieldName = parameterAsString( parameters, u"FIELD_NAME"_s, context );
192
193 QgsFields outFields = input->fields();
194 int fieldIndex = -1;
195 if ( mIsInPlace )
196 {
197 fieldIndex = outFields.lookupField( fieldName );
198 }
199 else
200 {
201 if ( outFields.lookupField( fieldName ) >= 0 )
202 {
203 throw QgsProcessingException( QObject::tr( "A field with the same name (%1) already exists" ).arg( fieldName ) );
204 }
205 outFields.append( QgsField( fieldName, QMetaType::Type::Double ) );
206 }
207
208 QString dest;
209 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, outFields, input->wkbType(), input->sourceCrs() ) );
210 if ( parameters.value( u"OUTPUT"_s ).isValid() && !sink )
211 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
212
213 // make spatial index
214 const QgsFeatureIterator f2 = referenceSource->getFeatures( QgsFeatureRequest().setDestinationCrs( input->sourceCrs(), context.transformContext() ).setNoAttributes() );
215 double step = referenceSource->featureCount() > 0 ? 50.0 / referenceSource->featureCount() : 1;
216 int i = 0;
217 const QgsSpatialIndex index(
218 f2,
219 [&]( const QgsFeature & ) -> bool {
220 i++;
221 if ( feedback->isCanceled() )
222 return false;
223
224 feedback->setProgress( i * step );
225
226 return true;
227 },
229 );
230
231 QgsFeature f;
232
233 // Create output vector layer with additional attributes
234 step = input->featureCount() > 0 ? 50.0 / input->featureCount() : 1;
235 QgsFeatureIterator features = input->getFeatures();
236 i = 0;
237 while ( features.nextFeature( f ) )
238 {
239 i++;
240 if ( feedback->isCanceled() )
241 {
242 break;
243 }
244
245 feedback->setProgress( 50 + i * step );
246
247 QgsAttributes attributes = f.attributes();
248
249 if ( !f.hasGeometry() )
250 {
251 if ( !mIsInPlace )
252 attributes.append( QVariant() );
253 else
254 attributes[fieldIndex] = QVariant();
255 f.setAttributes( attributes );
256 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
257 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
258 else
259 feedback->featureAddedToSink( u"OUTPUT"_s );
260 }
261 else
262 {
263 const QList<QgsFeatureId> nearest = index.nearestNeighbor( f.geometry(), 1, std::isnan( maxDistance ) ? 0 : maxDistance );
264 if ( nearest.empty() )
265 {
266 feedback->pushInfo( QObject::tr( "No matching features found within search distance" ) );
267 if ( !mIsInPlace )
268 attributes.append( QVariant() );
269 else
270 attributes[fieldIndex] = QVariant();
271 f.setAttributes( attributes );
272 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
273 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
274 else
275 feedback->featureAddedToSink( u"OUTPUT"_s );
276 }
277 else
278 {
279 if ( nearest.count() > 1 )
280 {
281 feedback->pushInfo( QObject::tr( "Multiple matching features found at same distance from search feature, found %n feature(s)", nullptr, nearest.count() ) );
282 }
283
284 const QgsGeometry joinLine = f.geometry().shortestLine( index.geometry( nearest.at( 0 ) ) );
285 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( joinLine.constGet() ) )
286 {
287 if ( !mIsInPlace )
288 attributes.append( line->startPoint().azimuth( line->endPoint() ) );
289 else
290 attributes[fieldIndex] = line->startPoint().azimuth( line->endPoint() );
291 }
292 else
293 {
294 if ( !mIsInPlace )
295 attributes.append( QVariant() );
296 else
297 attributes[fieldIndex] = QVariant();
298 }
299 f.setAttributes( attributes );
300 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
301 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
302 else
303 feedback->featureAddedToSink( u"OUTPUT"_s );
304 }
305 }
306 }
307
308 if ( sink )
309 {
310 sink->finalize();
311 feedback->featureSinkFinalized( u"OUTPUT"_s );
312 }
313
314 const bool applySymbology = parameterAsBool( parameters, u"APPLY_SYMBOLOGY"_s, context );
315 if ( applySymbology )
316 {
317 if ( mIsInPlace )
318 {
319 // get in place vector layer
320 // (possibly TODO - make this a reusable method!)
321 QVariantMap inPlaceParams = parameters;
322 inPlaceParams.insert( u"INPUT"_s, parameters.value( u"INPUT"_s ).value<QgsProcessingFeatureSourceDefinition>().source );
323 if ( QgsVectorLayer *sourceLayer = parameterAsVectorLayer( inPlaceParams, u"INPUT"_s, context ) )
324 {
325 std::unique_ptr<QgsFeatureRenderer> sourceRenderer( sourceLayer->renderer()->clone() );
326 SetMarkerRotationPostProcessor processor( std::move( sourceRenderer ), fieldName );
327 processor.postProcessLayer( sourceLayer, context, feedback );
328 }
329 }
330 else if ( mSourceRenderer && context.willLoadLayerOnCompletion( dest ) )
331 {
332 context.layerToLoadOnCompletionDetails( dest ).setPostProcessor( new SetMarkerRotationPostProcessor( std::move( mSourceRenderer ), fieldName ) );
333 }
334 }
335
336 QVariantMap outputs;
337 outputs.insert( u"OUTPUT"_s, dest );
338 return outputs;
339}
340
341
@ VectorPoint
Vector point layers.
Definition qgis.h:3750
@ Point
Points.
Definition qgis.h:380
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3826
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3807
A vector of attributes.
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).
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
@ 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
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
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
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.
QgsGeometry shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
Line string geometry type, with support for z-dimension and m-values.
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.
void setPostProcessor(QgsProcessingLayerPostProcessorInterface *processor)
Sets the layer post-processor.
Contains information about the context in which a processing algorithm is executed.
QgsProcessingContext::LayerDetails & layerToLoadOnCompletionDetails(const QString &layer)
Returns a reference to the details for a given layer which is loaded on completion of the algorithm o...
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
bool willLoadLayerOnCompletion(const QString &layer) const
Returns true if the given layer (by ID or datasource) will be loaded into the current project upon co...
Custom exception class for processing related exceptions.
Encapsulates settings relating to a feature source input to a processing algorithm.
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 pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
An interface for layer post-processing handlers for execution following a processing algorithm operat...
virtual void postProcessLayer(QgsMapLayer *layer, QgsProcessingContext &context, QgsProcessingFeedback *feedback)=0
Post-processes the specified layer, following successful execution of a processing algorithm.
A boolean parameter for processing algorithms.
A double numeric parameter for distance values.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A string parameter for processing algorithms.
static QgsProperty fromField(const QString &fieldName, bool isActive=true)
Returns a new FieldBasedProperty created from the specified field name.
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
An interface for classes which can visit style entity (e.g.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
Represents a vector layer which manages a vector based dataset.
T qgsgeometry_cast(QgsAbstractGeometry *geom)
const QgsStyleEntityInterface * entity
Reference to style entity being visited.