QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
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 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
84 if ( !source )
85 {
86 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
87 }
88
89 const int typeIndex = parameterAsEnum( parameters, u"TYPE"_s, context );
91
92 if ( typeIndex == 0 ) // centroids
93 {
94 outputWkbType = Qgis::WkbType::Point;
95 }
96 else if ( typeIndex == 1 ) // nodes
97 {
98 outputWkbType = Qgis::WkbType::MultiPoint;
99 }
100 else if ( typeIndex == 2 ) // LineStrings
101 {
102 outputWkbType = Qgis::WkbType::LineString;
103 }
104 else if ( typeIndex == 3 ) // MultiLineStrings
105 {
106 outputWkbType = Qgis::WkbType::MultiLineString;
107 }
108 else if ( typeIndex == 4 ) // polygons
109 {
110 outputWkbType = Qgis::WkbType::Polygon;
111 }
112 else
113 {
114 throw QgsProcessingException( QObject::tr( "Invalid TYPE parameter value: %1" ).arg( typeIndex ) );
115 }
116
117 // preserve Z/M values
118 if ( QgsWkbTypes::hasM( source->wkbType() ) )
119 {
120 outputWkbType = QgsWkbTypes::addM( outputWkbType );
121 }
122 if ( QgsWkbTypes::hasZ( source->wkbType() ) )
123 {
124 outputWkbType = QgsWkbTypes::addZ( outputWkbType );
125 }
126
127 QString dest;
128 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, source->fields(), outputWkbType, source->sourceCrs() ) );
129 if ( !sink )
130 {
131 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
132 }
133
134 QgsFeatureIterator features = source->getFeatures();
135 const double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 0;
136
137 QgsFeature f;
138 long long i = 0;
139 while ( features.nextFeature( f ) )
140 {
141 if ( feedback->isCanceled() )
142 break;
143
144 if ( !f.hasGeometry() )
145 {
146 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
147 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
148 }
149 else
150 {
151 const QVector< QgsGeometry > geometries = convertGeometry( f.geometry(), typeIndex, outputWkbType );
152 for ( const QgsGeometry &g : geometries )
153 {
154 QgsFeature feat;
155 feat.setGeometry( g );
156 feat.setAttributes( f.attributes() );
157 if ( !sink->addFeature( feat, QgsFeatureSink::FastInsert ) )
158 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
159 }
160 }
161
162 i++;
163 feedback->setProgress( i * step );
164 }
165
166 sink->finalize();
167
168 QVariantMap results;
169 results.insert( u"OUTPUT"_s, dest );
170 return results;
171}
172
173const QVector< QgsGeometry > QgsConvertGeometryTypeAlgorithm::convertGeometry( const QgsGeometry &geom, const int typeIndex, const Qgis::WkbType outputWkbType )
174{
175 QVector< QgsGeometry > geometries;
176 if ( typeIndex == 0 )
177 {
178 geometries << geom.centroid();
179 }
180 else
181 {
182 geometries = geom.coerceToType( outputWkbType, 0, 0, false );
183 }
184
185 return geometries;
186}
187
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3647
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:69
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
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.
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.