QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
Loading...
Searching...
No Matches
qgsalgorithmconvertgeometrytype.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmconvertgeometrytype.cpp
3 ---------------------
4 begin : March 2025
5 copyright : (C) 2025 by Alexander Bruy
6 email : alexander dot bruy 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 <QString>
21
22using namespace Qt::StringLiterals;
23
25
26QString QgsConvertGeometryTypeAlgorithm::name() const
27{
28 return u"convertgeometrytype"_s;
29}
30
31QString QgsConvertGeometryTypeAlgorithm::displayName() const
32{
33 return QObject::tr( "Convert geometry type" );
34}
35
36QStringList QgsConvertGeometryTypeAlgorithm::tags() const
37{
38 return QObject::tr( "polygon,line,point,centroids,nodes,convert,type,geometry" ).split( ',' );
39}
40
41QString QgsConvertGeometryTypeAlgorithm::group() const
42{
43 return QObject::tr( "Vector geometry" );
44}
45
46QString QgsConvertGeometryTypeAlgorithm::groupId() const
47{
48 return u"vectorgeometry"_s;
49}
50
51QString QgsConvertGeometryTypeAlgorithm::shortHelpString() const
52{
53 return QObject::tr(
54 "This algorithm generates a new layer based on an existing one, with a different type of geometry.\n\n"
55 "Not all conversions are possible. For instance, a line layer can be converted to a "
56 "point layer, but a point layer cannot be converted to a line layer.\n\n"
57 "See the \"Polygonize\" or \"Lines to polygons\" algorithms for alternative options."
58 );
59}
60
61QString QgsConvertGeometryTypeAlgorithm::shortDescription() const
62{
63 return QObject::tr( "Converts the geometries from a vector layer to a different geometry type." );
64}
65
66QgsConvertGeometryTypeAlgorithm *QgsConvertGeometryTypeAlgorithm::createInstance() const
67{
68 return new QgsConvertGeometryTypeAlgorithm();
69}
70
71void QgsConvertGeometryTypeAlgorithm::initAlgorithm( const QVariantMap & )
72{
73 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
74
75 QStringList geometryTypes = QStringList() << QObject::tr( "Centroids" ) << QObject::tr( "Nodes" ) << QObject::tr( "Linestrings" ) << QObject::tr( "Multilinestrings" ) << QObject::tr( "Polygons" );
76
77 addParameter( new QgsProcessingParameterEnum( u"TYPE"_s, QObject::tr( "New geometry type" ), geometryTypes ) );
78 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Converted" ) ) );
79}
80
81QVariantMap QgsConvertGeometryTypeAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
82{
83 QGS_MARK_ALGORITHM_SOURCE
84
85 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
86 if ( !source )
87 {
88 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
89 }
90
91 const int typeIndex = parameterAsEnum( parameters, u"TYPE"_s, context );
93
94 if ( typeIndex == 0 ) // centroids
95 {
96 outputWkbType = Qgis::WkbType::Point;
97 }
98 else if ( typeIndex == 1 ) // nodes
99 {
100 outputWkbType = Qgis::WkbType::MultiPoint;
101 }
102 else if ( typeIndex == 2 ) // LineStrings
103 {
104 outputWkbType = Qgis::WkbType::LineString;
105 }
106 else if ( typeIndex == 3 ) // MultiLineStrings
107 {
108 outputWkbType = Qgis::WkbType::MultiLineString;
109 }
110 else if ( typeIndex == 4 ) // polygons
111 {
112 outputWkbType = Qgis::WkbType::Polygon;
113 }
114 else
115 {
116 throw QgsProcessingException( QObject::tr( "Invalid TYPE parameter value: %1" ).arg( typeIndex ) );
117 }
118
119 // preserve Z/M values
120 if ( QgsWkbTypes::hasM( source->wkbType() ) )
121 {
122 outputWkbType = QgsWkbTypes::addM( outputWkbType );
123 }
124 if ( QgsWkbTypes::hasZ( source->wkbType() ) )
125 {
126 outputWkbType = QgsWkbTypes::addZ( outputWkbType );
127 }
128
129 QString dest;
130 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, source->fields(), outputWkbType, source->sourceCrs() ) );
131 if ( !sink )
132 {
133 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
134 }
135
136 QgsFeatureIterator features = source->getFeatures();
137 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0;
138
139 QgsFeature f;
140 long long i = 0;
141 while ( features.nextFeature( f ) )
142 {
143 if ( feedback->isCanceled() )
144 break;
145
146 if ( !f.hasGeometry() )
147 {
148 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
149 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
150 else
151 feedback->featureAddedToSink( u"OUTPUT"_s );
152 }
153 else
154 {
155 const QVector< QgsGeometry > geometries = convertGeometry( f.geometry(), typeIndex, outputWkbType );
156 for ( const QgsGeometry &g : geometries )
157 {
158 QgsFeature feat;
159 feat.setGeometry( g );
160 feat.setAttributes( f.attributes() );
161 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
162 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
163 else
164 feedback->featureAddedToSink( u"OUTPUT"_s );
165 }
166 }
167
168 i++;
169 feedback->setProgress( i * step );
170 }
171
172 sink->finalize();
173 feedback->featureSinkFinalized( u"OUTPUT"_s );
174
175 QVariantMap results;
176 results.insert( u"OUTPUT"_s, dest );
177 return results;
178}
179
180const QVector< QgsGeometry > QgsConvertGeometryTypeAlgorithm::convertGeometry( const QgsGeometry &geom, const int typeIndex, const Qgis::WkbType outputWkbType )
181{
182 QVector< QgsGeometry > geometries;
183 if ( typeIndex == 0 )
184 {
185 geometries << geom.centroid();
186 }
187 else
188 {
189 geometries = geom.coerceToType( outputWkbType, 0, 0, false );
190 }
191
192 return geometries;
193}
194
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3749
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:294
@ Point
Point.
Definition qgis.h:296
@ LineString
LineString.
Definition qgis.h:297
@ MultiPoint
MultiPoint.
Definition qgis.h:300
@ Polygon
Polygon.
Definition qgis.h:298
@ MultiLineString
MultiLineString.
Definition qgis.h:301
@ Unknown
Unknown.
Definition qgis.h:295
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...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:64
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
A geometry is the spatial representation of a feature.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
QVector< QgsGeometry > coerceToType(Qgis::WkbType type, double defaultZ=0, double defaultM=0, bool avoidDuplicates=true) const
Attempts to coerce this geometry into the specified destination type.
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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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 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.