QGIS API Documentation 3.43.0-Master (ac9f54ad1f7)
qgsalgorithmdelaunaytriangulation.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmdelaunaytriangulation.cpp
3 ---------------------
4 begin : July 2023
5 copyright : (C) 2023 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#include "qgsspatialindex.h"
20#include "qgsmultipoint.h"
21#include "qgsattributes.h"
22
24
25QString QgsDelaunayTriangulationAlgorithm::name() const
26{
27 return QStringLiteral( "delaunaytriangulation" );
28}
29
30QString QgsDelaunayTriangulationAlgorithm::displayName() const
31{
32 return QObject::tr( "Delaunay triangulation" );
33}
34
35QStringList QgsDelaunayTriangulationAlgorithm::tags() const
36{
37 return QObject::tr( "delaunay,triangulation,polygons,voronoi" ).split( ',' );
38}
39
40QString QgsDelaunayTriangulationAlgorithm::group() const
41{
42 return QObject::tr( "Vector geometry" );
43}
44
45QString QgsDelaunayTriangulationAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectorgeometry" );
48}
49
50QString QgsDelaunayTriangulationAlgorithm::shortHelpString() const
51{
52 return QObject::tr( "This algorithm creates a polygon layer with the Delaunay triangulation corresponding to a points layer." );
53}
54
55QString QgsDelaunayTriangulationAlgorithm::shortDescription() const
56{
57 return QObject::tr( "Creates a polygon layer with the Delaunay triangulation corresponding to a points layer." );
58}
59
60QgsDelaunayTriangulationAlgorithm *QgsDelaunayTriangulationAlgorithm::createInstance() const
61{
62 return new QgsDelaunayTriangulationAlgorithm();
63}
64
65void QgsDelaunayTriangulationAlgorithm::initAlgorithm( const QVariantMap & )
66{
67 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
68 auto toleranceParam = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Double, 0, true, 0 );
69 toleranceParam->setHelp( QObject::tr( "Specifies an optional snapping tolerance which can be used to improve the robustness of the triangulation" ) );
70 addParameter( toleranceParam.release() );
71 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "ADD_ATTRIBUTES" ), QObject::tr( "Add point IDs to output" ), true ) );
72 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Delaunay triangulation" ), Qgis::ProcessingSourceType::VectorPolygon ) );
73}
74
75QVariantMap QgsDelaunayTriangulationAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
76{
77 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
78 if ( !source )
79 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
80
81 if ( source->featureCount() < 3 )
82 throw QgsProcessingException( QObject::tr( "Input layer should contain at least 3 points." ) );
83
84 const double tolerance = parameterAsDouble( parameters, QStringLiteral( "TOLERANCE" ), context );
85 const bool addAttributes = parameterAsBool( parameters, QStringLiteral( "ADD_ATTRIBUTES" ), context );
86
87 QgsFields fields;
88 if ( addAttributes )
89 {
90 fields.append( QgsField( QStringLiteral( "POINTA" ), QMetaType::Type::LongLong ) );
91 fields.append( QgsField( QStringLiteral( "POINTB" ), QMetaType::Type::LongLong ) );
92 fields.append( QgsField( QStringLiteral( "POINTC" ), QMetaType::Type::LongLong ) );
93 }
94 else
95 {
96 fields.append( QgsField( QStringLiteral( "id" ), QMetaType::Type::LongLong ) );
97 }
98
99 QString dest;
100 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Polygon, source->sourceCrs() ) );
101 if ( !sink )
102 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
103
105
106 QgsGeometry allPoints;
107
108 long long i = 0;
109 const double step = source->featureCount() > 0 ? 50.0 / source->featureCount() : 1;
110
111 const QgsSpatialIndex index( it, [&]( const QgsFeature &f ) -> bool {
112 i++;
113 if ( feedback->isCanceled() )
114 return false;
115
116 feedback->setProgress( i * step );
117
118 if ( !f.hasGeometry() )
119 return true;
120
121 const QgsAbstractGeometry *geom = f.geometry().constGet();
122 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
123 {
124 const QgsMultiPoint mp( *qgsgeometry_cast< const QgsMultiPoint * >( geom ) );
125 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
126 {
127 allPoints.addPartV2( qgsgeometry_cast< const QgsPoint * >( *pit )->clone(), Qgis::WkbType::Point );
128 }
129 }
130 else
131 {
132 allPoints.addPartV2( qgsgeometry_cast< const QgsPoint * >( geom )->clone(), Qgis::WkbType::Point );
133 }
134
136
137 const QgsGeometry triangulation = allPoints.delaunayTriangulation( tolerance );
138
139 if ( !triangulation.isEmpty() )
140 {
141 const QVector<QgsGeometry> collection = triangulation.asGeometryCollection();
142 for ( int i = 0; i < collection.length(); i++ )
143 {
144 if ( feedback->isCanceled() )
145 {
146 break;
147 }
148 QgsFeature f;
149 f.setFields( fields );
150 f.setGeometry( collection[i] );
151 if ( addAttributes )
152 {
153 const QList<QgsFeatureId> nearest = index.nearestNeighbor( collection[i], 3 );
154 QgsAttributes attrs;
155 for ( int j = 0; j < 3; j++ )
156 {
157 attrs << nearest.at( j );
158 }
159 f.setAttributes( attrs );
160 }
161 else
162 {
163 f.setAttributes( QgsAttributes() << i );
164 }
165
166 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
167 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
168 feedback->setProgress( 50 + i * step );
169 }
170 }
171
172 sink->finalize();
173
174 QVariantMap outputs;
175 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
176 return outputs;
177}
178
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
@ Polygon
Polygon.
Abstract base class for all geometries.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
A vector of attributes.
Wrapper for iterator of features from vector data provider or vector layer.
Wraps a request for features to a vector layer (or directly its vector data provider).
@ 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:58
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
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:53
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:70
A geometry is the spatial representation of a feature.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::GeometryOperationResult addPartV2(const QVector< QgsPointXY > &points, Qgis::WkbType wkbType=Qgis::WkbType::Unknown)
Adds a new part to a the geometry.
QgsGeometry delaunayTriangulation(double tolerance=0.0, bool edgesOnly=false) const
Returns the Delaunay triangulation for the vertices of the geometry.
Multi point geometry collection.
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.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
static bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.