QGIS API Documentation 3.41.0-Master (3440c17df1d)
Loading...
Searching...
No Matches
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( "Creates a polygon layer with the Delaunay triangulation corresponding to a points layer." );
53}
54
55QgsDelaunayTriangulationAlgorithm *QgsDelaunayTriangulationAlgorithm::createInstance() const
56{
57 return new QgsDelaunayTriangulationAlgorithm();
58}
59
60void QgsDelaunayTriangulationAlgorithm::initAlgorithm( const QVariantMap & )
61{
62 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList< int >() << static_cast< int >( Qgis::ProcessingSourceType::VectorPoint ) ) );
63 std::unique_ptr<QgsProcessingParameterNumber> toleranceParam = std::make_unique<QgsProcessingParameterNumber>( QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Double, 0, true, 0 );
64 toleranceParam->setHelp( QObject::tr( "Specifies an optional snapping tolerance which can be used to improve the robustness of the triangulation" ) );
65 addParameter( toleranceParam.release() );
66 addParameter( new QgsProcessingParameterBoolean( QStringLiteral( "ADD_ATTRIBUTES" ), QObject::tr( "Add point IDs to output" ), true ) );
67 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Delaunay triangulation" ), Qgis::ProcessingSourceType::VectorPolygon ) );
68}
69
70QVariantMap QgsDelaunayTriangulationAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
71{
72 std::unique_ptr< QgsProcessingFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
73 if ( !source )
74 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
75
76 if ( source->featureCount() < 3 )
77 throw QgsProcessingException( QObject::tr( "Input layer should contain at least 3 points." ) );
78
79 const double tolerance = parameterAsDouble( parameters, QStringLiteral( "TOLERANCE" ), context );
80 const bool addAttributes = parameterAsBool( parameters, QStringLiteral( "ADD_ATTRIBUTES" ), context );
81
82 QgsFields fields;
83 if ( addAttributes )
84 {
85 fields.append( QgsField( QStringLiteral( "POINTA" ), QMetaType::Type::LongLong ) );
86 fields.append( QgsField( QStringLiteral( "POINTB" ), QMetaType::Type::LongLong ) );
87 fields.append( QgsField( QStringLiteral( "POINTC" ), QMetaType::Type::LongLong ) );
88 }
89 else
90 {
91 fields.append( QgsField( QStringLiteral( "id" ), QMetaType::Type::LongLong ) );
92 }
93
94 QString dest;
95 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, Qgis::WkbType::Polygon, source->sourceCrs() ) );
96 if ( !sink )
97 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
98
100
101 QgsGeometry allPoints;
102
103 long long i = 0;
104 const double step = source->featureCount() > 0 ? 50.0 / source->featureCount() : 1;
105
106 const QgsSpatialIndex index( it, [&]( const QgsFeature & f )->bool
107 {
108 i++;
109 if ( feedback->isCanceled() )
110 return false;
111
112 feedback->setProgress( i * step );
113
114 if ( !f.hasGeometry() )
115 return true;
116
117 const QgsAbstractGeometry *geom = f.geometry().constGet();
118 if ( QgsWkbTypes::isMultiType( geom->wkbType() ) )
119 {
120 const QgsMultiPoint mp( *qgsgeometry_cast< const QgsMultiPoint * >( geom ) );
121 for ( auto pit = mp.const_parts_begin(); pit != mp.const_parts_end(); ++pit )
122 {
123 allPoints.addPartV2( qgsgeometry_cast< QgsPoint * >( *pit )->clone(), Qgis::WkbType::Point );
124 }
125 }
126 else
127 {
128 allPoints.addPartV2( qgsgeometry_cast< QgsPoint * >( geom )->clone(), Qgis::WkbType::Point );
129 }
130
131 return true;
133
134 const QgsGeometry triangulation = allPoints.delaunayTriangulation( tolerance );
135
136 if ( !triangulation.isEmpty() )
137 {
138 const QVector< QgsGeometry > collection = triangulation.asGeometryCollection();
139 for ( int i = 0; i < collection.length(); i++ )
140 {
141 if ( feedback->isCanceled() )
142 {
143 break;
144 }
145 QgsFeature f;
146 f.setFields( fields );
147 f.setGeometry( collection[ i ] );
148 if ( addAttributes )
149 {
150 const QList< QgsFeatureId > nearest = index.nearestNeighbor( collection[i], 3 );
151 QgsAttributes attrs;
152 for ( int j = 0; j < 3; j++ )
153 {
154 attrs << nearest.at( j );
155 }
156 f.setAttributes( attrs );
157 }
158 else
159 {
160 f.setAttributes( QgsAttributes() << i );
161 }
162
163 if ( !sink->addFeature( f, QgsFeatureSink::FastInsert ) )
164 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
165 feedback->setProgress( 50 + i * step );
166 }
167 }
168
169 sink->finalize();
170
171 QVariantMap outputs;
172 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
173 return outputs;
174}
175
@ 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.
This class 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.