QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsalgorithmtransect.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmtransect.cpp
3 -------------------------
4 begin : October 2017
5 copyright : (C) 2017 by Loïc Bartoletti
6 email : lbartoletti at tuxfamily dot org
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 "qgsmultilinestring.h"
22
24
25QString QgsTransectAlgorithm::name() const
26{
27 return QStringLiteral( "transect" );
28}
29
30QString QgsTransectAlgorithm::displayName() const
31{
32 return QObject::tr( "Transect" );
33}
34
35QStringList QgsTransectAlgorithm::tags() const
36{
37 return QObject::tr( "transect,station,lines,extend," ).split( ',' );
38}
39
40QString QgsTransectAlgorithm::group() const
41{
42 return QObject::tr( "Vector geometry" );
43}
44
45QString QgsTransectAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeometry" );
48}
49
50void QgsTransectAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
53 auto length = std::make_unique<QgsProcessingParameterDistance>( QStringLiteral( "LENGTH" ), QObject::tr( "Length of the transect" ), 5.0, QStringLiteral( "INPUT" ), false, 0 );
54 length->setIsDynamic( true );
55 length->setDynamicPropertyDefinition( QgsPropertyDefinition( QStringLiteral( "LENGTH" ), QObject::tr( "Length of the transect" ), QgsPropertyDefinition::DoublePositive ) );
56 length->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
57 addParameter( length.release() );
58
59 auto angle = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "ANGLE" ), QObject::tr( "Angle in degrees from the original line at the vertices" ), Qgis::ProcessingNumberParameterType::Double, 90.0, false, 0, 360 );
60 angle->setIsDynamic( true );
61 angle->setDynamicPropertyDefinition( QgsPropertyDefinition( QStringLiteral( "ANGLE" ), QObject::tr( "Angle in degrees" ), QgsPropertyDefinition::Double ) );
62 angle->setDynamicLayerParameterName( QStringLiteral( "INPUT" ) );
63 addParameter( angle.release() );
64
65 addParameter( new QgsProcessingParameterEnum( QStringLiteral( "SIDE" ), QObject::tr( "Side to create the transects" ), QStringList() << QObject::tr( "Left" ) << QObject::tr( "Right" ) << QObject::tr( "Both" ), false ) );
66 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Transect" ), Qgis::ProcessingSourceType::VectorLine ) );
67}
68
69QString QgsTransectAlgorithm::shortHelpString() const
70{
71 return QObject::tr( "This algorithm creates transects on vertices for (multi)linestrings.\n" )
72 + QObject::tr( "A transect is a line oriented from an angle (by default perpendicular) to the input polylines (at vertices)." )
73 + QStringLiteral( "\n\n" )
74 + QObject::tr( "Field(s) from feature(s) are returned in the transect with these new fields:\n" )
75 + QObject::tr( "- TR_FID: ID of the original feature\n" )
76 + QObject::tr( "- TR_ID: ID of the transect. Each transect have an unique ID\n" )
77 + QObject::tr( "- TR_SEGMENT: ID of the segment of the linestring\n" )
78 + QObject::tr( "- TR_ANGLE: Angle in degrees from the original line at the vertex\n" )
79 + QObject::tr( "- TR_LENGTH: Total length of the transect returned\n" )
80 + QObject::tr( "- TR_ORIENT: Side of the transect (only on the left or right of the line, or both side)\n" );
81}
82
83QString QgsTransectAlgorithm::shortDescription() const
84{
85 return QObject::tr( "Creates transects on vertices for (multi)linestrings." );
86}
87
88Qgis::ProcessingAlgorithmDocumentationFlags QgsTransectAlgorithm::documentationFlags() const
89{
91}
92
93QgsTransectAlgorithm *QgsTransectAlgorithm::createInstance() const
94{
95 return new QgsTransectAlgorithm();
96}
97
98QVariantMap QgsTransectAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
99{
100 const Side orientation = static_cast<QgsTransectAlgorithm::Side>( parameterAsInt( parameters, QStringLiteral( "SIDE" ), context ) );
101 const double angle = fabs( parameterAsDouble( parameters, QStringLiteral( "ANGLE" ), context ) );
102 const bool dynamicAngle = QgsProcessingParameters::isDynamic( parameters, QStringLiteral( "ANGLE" ) );
103 QgsProperty angleProperty;
104 if ( dynamicAngle )
105 angleProperty = parameters.value( QStringLiteral( "ANGLE" ) ).value<QgsProperty>();
106
107 double length = parameterAsDouble( parameters, QStringLiteral( "LENGTH" ), context );
108 const bool dynamicLength = QgsProcessingParameters::isDynamic( parameters, QStringLiteral( "LENGTH" ) );
109 QgsProperty lengthProperty;
110 if ( dynamicLength )
111 lengthProperty = parameters.value( QStringLiteral( "LENGTH" ) ).value<QgsProperty>();
112
113 if ( orientation == QgsTransectAlgorithm::Both )
114 length /= 2.0;
115
116 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
117 if ( !source )
118 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
119
120 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, dynamic_cast<QgsProcessingFeatureSource *>( source.get() ) );
121
122 QgsFields newFields;
123 newFields.append( QgsField( QStringLiteral( "TR_FID" ), QMetaType::Type::Int, QString(), 20 ) );
124 newFields.append( QgsField( QStringLiteral( "TR_ID" ), QMetaType::Type::Int, QString(), 20 ) );
125 newFields.append( QgsField( QStringLiteral( "TR_SEGMENT" ), QMetaType::Type::Int, QString(), 20 ) );
126 newFields.append( QgsField( QStringLiteral( "TR_ANGLE" ), QMetaType::Type::Double, QString(), 5, 2 ) );
127 newFields.append( QgsField( QStringLiteral( "TR_LENGTH" ), QMetaType::Type::Double, QString(), 20, 6 ) );
128 newFields.append( QgsField( QStringLiteral( "TR_ORIENT" ), QMetaType::Type::Int, QString(), 1 ) );
129 QgsFields fields = QgsProcessingUtils::combineFields( source->fields(), newFields );
130
132 if ( QgsWkbTypes::hasZ( source->wkbType() ) )
133 outputWkb = QgsWkbTypes::addZ( outputWkb );
134 if ( QgsWkbTypes::hasM( source->wkbType() ) )
135 outputWkb = QgsWkbTypes::addM( outputWkb );
136
137 QString dest;
138 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, outputWkb, source->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
139 if ( !sink )
140 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
141
142 QgsFeatureIterator features = source->getFeatures();
143
144 int current = -1;
145 int number = 0;
146 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
147 QgsFeature feat;
148
149
150 while ( features.nextFeature( feat ) )
151 {
152 current++;
153 if ( feedback->isCanceled() )
154 {
155 break;
156 }
157
158 feedback->setProgress( current * step );
159 if ( !feat.hasGeometry() )
160 continue;
161
162 QgsGeometry inputGeometry = feat.geometry();
163
164 if ( dynamicLength || dynamicAngle )
165 {
166 expressionContext.setFeature( feat );
167 }
168
169 double evaluatedLength = length;
170 if ( dynamicLength )
171 evaluatedLength = lengthProperty.valueAsDouble( context.expressionContext(), length );
172 double evaluatedAngle = angle;
173 if ( dynamicAngle )
174 evaluatedAngle = angleProperty.valueAsDouble( context.expressionContext(), angle );
175
176 inputGeometry.convertToMultiType();
177 const QgsMultiLineString *multiLine = static_cast<const QgsMultiLineString *>( inputGeometry.constGet() );
178 for ( int id = 0; id < multiLine->numGeometries(); ++id )
179 {
180 const QgsLineString *line = multiLine->lineStringN( id );
182 while ( it != line->vertices_end() )
183 {
184 const QgsVertexId vertexId = it.vertexId();
185 const int i = vertexId.vertex;
186 QgsFeature outFeat;
187 QgsAttributes attrs = feat.attributes();
188 attrs << current << number << i + 1 << evaluatedAngle << ( ( orientation == QgsTransectAlgorithm::Both ) ? evaluatedLength * 2 : evaluatedLength ) << orientation;
189 outFeat.setAttributes( attrs );
190 const double angleAtVertex = line->vertexAngle( vertexId );
191 outFeat.setGeometry( calcTransect( *it, angleAtVertex, evaluatedLength, orientation, evaluatedAngle ) );
192 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
193 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
194 number++;
195 it++;
196 }
197 }
198 }
199
200 sink->finalize();
201
202 QVariantMap outputs;
203 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
204 return outputs;
205}
206
207
208QgsGeometry QgsTransectAlgorithm::calcTransect( const QgsPoint &point, const double angleAtVertex, const double length, const QgsTransectAlgorithm::Side orientation, const double angle )
209{
210 QgsPoint pLeft; // left point of the line
211 QgsPoint pRight; // right point of the line
212
213 QgsPolyline line;
214
215 if ( ( orientation == QgsTransectAlgorithm::Right ) || ( orientation == QgsTransectAlgorithm::Both ) )
216 {
217 pLeft = point.project( length, angle + 180.0 / M_PI * angleAtVertex );
218 if ( orientation != QgsTransectAlgorithm::Both )
219 pRight = point;
220 }
221
222 if ( ( orientation == QgsTransectAlgorithm::Left ) || ( orientation == QgsTransectAlgorithm::Both ) )
223 {
224 pRight = point.project( -length, angle + 180.0 / M_PI * angleAtVertex );
225 if ( orientation != QgsTransectAlgorithm::Both )
226 pLeft = point;
227 }
228
229 line.append( pLeft );
230 line.append( pRight );
231
232 return QgsGeometry::fromPolyline( line );
233}
234
@ VectorLine
Vector line layers.
Definition qgis.h:3535
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3619
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:277
@ LineString
LineString.
Definition qgis.h:280
@ Double
Double/float values.
Definition qgis.h:3804
The vertex_iterator class provides an STL-style iterator for vertices.
QgsVertexId vertexId() const
Returns vertex ID of the current item.
vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
vertex_iterator vertices_begin() const
Returns STL-style iterator pointing to the first vertex of the geometry.
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.
@ 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
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
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:73
int numGeometries() const
Returns the number of geometries within the collection.
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.
static QgsGeometry fromPolyline(const QgsPolyline &polyline)
Creates a new LineString geometry from a list of QgsPoint points.
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
Line string geometry type, with support for z-dimension and m-values.
double vertexAngle(QgsVertexId vertex) const override
Returns approximate angle at a vertex.
Multi line string geometry collection.
QgsLineString * lineStringN(int index)
Returns the line string with the specified index.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
QgsPoint project(double distance, double azimuth, double inclination=90.0) const
Returns a new point which corresponds to this point projected by a specified distance with specified ...
Definition qgspoint.cpp:707
Contains information about the context in which a processing algorithm is executed.
QgsExpressionContext & expressionContext()
Returns the expression context.
Custom exception class for processing related exceptions.
QgsFeatureSource subclass which proxies methods to an underlying QgsFeatureSource,...
Base class for providing feedback from a processing 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.
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...
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
Definition for a property.
Definition qgsproperty.h:45
@ Double
Double value (including negative values).
Definition qgsproperty.h:55
@ DoublePositive
Positive double value (including 0).
Definition qgsproperty.h:56
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.
static Qgis::WkbType addM(Qgis::WkbType type)
Adds the m dimension to a WKB type and returns the new type.
static Qgis::WkbType addZ(Qgis::WkbType type)
Adds the z dimension to a WKB type and returns the new type.
static Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static Q_INVOKABLE bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.
double ANALYSIS_EXPORT angle(QgsPoint *p1, QgsPoint *p2, QgsPoint *p3, QgsPoint *p4)
Calculates the angle between two segments (in 2 dimension, z-values are ignored).
QgsPointSequence QgsPolyline
Polyline as represented as a vector of points.
Definition qgsgeometry.h:70
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:30
int vertex
Vertex number.
Definition qgsvertexid.h:94