QGIS API Documentation 4.1.0-Master (5bf3c20f3c9)
Loading...
Searching...
No Matches
qgsalgorithmsplitwithlines.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmsplitwithlines.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson 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 "qgsgeometryengine.h"
21#include "qgsspatialindex.h"
22#include "qgsvectorlayer.h"
23
24#include <QString>
25
26using namespace Qt::StringLiterals;
27
29
30QString QgsSplitWithLinesAlgorithm::name() const
31{
32 return u"splitwithlines"_s;
33}
34
35QString QgsSplitWithLinesAlgorithm::displayName() const
36{
37 return QObject::tr( "Split with lines" );
38}
39
40QStringList QgsSplitWithLinesAlgorithm::tags() const
41{
42 return QObject::tr( "split,cut,lines" ).split( ',' );
43}
44
45QString QgsSplitWithLinesAlgorithm::group() const
46{
47 return QObject::tr( "Vector overlay" );
48}
49
50QString QgsSplitWithLinesAlgorithm::groupId() const
51{
52 return u"vectoroverlay"_s;
53}
54
55void QgsSplitWithLinesAlgorithm::initAlgorithm( const QVariantMap & )
56{
57 addParameter(
58 new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) )
59 );
60 addParameter(
61 new QgsProcessingParameterFeatureSource( u"LINES"_s, QObject::tr( "Split layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) )
62 );
63 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Split" ) ) );
64}
65
66QString QgsSplitWithLinesAlgorithm::shortHelpString() const
67{
68 return QObject::tr(
69 "This algorithm splits the lines or polygons in one layer using the lines or polygon rings in another layer to define the breaking points. "
70 "Intersection between geometries in both layers are considered as split points."
71 );
72}
73
74QString QgsSplitWithLinesAlgorithm::shortDescription() const
75{
76 return QObject::tr( "Splits the lines or polygons in one layer using the lines or polygon rings in another layer to define the breaking points." );
77}
78
79Qgis::ProcessingAlgorithmDocumentationFlags QgsSplitWithLinesAlgorithm::documentationFlags() const
80{
82}
83
84QgsSplitWithLinesAlgorithm *QgsSplitWithLinesAlgorithm::createInstance() const
85{
86 return new QgsSplitWithLinesAlgorithm();
87}
88
89Qgis::ProcessingAlgorithmFlags QgsSplitWithLinesAlgorithm::flags() const
90{
93 return f;
94}
95
96bool QgsSplitWithLinesAlgorithm::supportInPlaceEdit( const QgsMapLayer *l ) const
97{
98 const QgsVectorLayer *layer = qobject_cast<const QgsVectorLayer *>( l );
99 if ( !layer )
100 return false;
101
103 return false;
104
105 return true;
106}
107
108QVariantMap QgsSplitWithLinesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
109{
110 std::unique_ptr<QgsFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
111 if ( !source )
112 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
113
114 std::unique_ptr<QgsFeatureSource> linesSource( parameterAsSource( parameters, u"LINES"_s, context ) );
115 if ( !linesSource )
116 throw QgsProcessingException( invalidSourceError( parameters, u"LINES"_s ) );
117
118 bool sameLayer = parameters.value( u"INPUT"_s ) == parameters.value( u"LINES"_s );
119
120 QString dest;
121 std::unique_ptr<QgsFeatureSink> sink(
122 parameterAsSink( parameters, u"OUTPUT"_s, context, dest, source->fields(), QgsWkbTypes::multiType( source->wkbType() ), source->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey )
123 );
124 if ( !sink )
125 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
126
127 QgsFeatureRequest request;
128 request.setNoAttributes();
129 request.setDestinationCrs( source->sourceCrs(), context.transformContext() );
130
131 QgsFeatureIterator splitFeatures = linesSource->getFeatures( request );
132 QgsFeature aSplitFeature;
133
134 const QgsSpatialIndex splitFeaturesIndex( splitFeatures, feedback, QgsSpatialIndex::FlagStoreFeatureGeometries );
135
136 QgsFeature outFeat;
137 QgsFeatureIterator features = source->getFeatures();
138
139 double step = source->featureCount() > 0 ? 100.0 / source->featureCount() : 1;
140 int i = 0;
141 QgsFeature inFeatureA;
142 while ( features.nextFeature( inFeatureA ) )
143 {
144 i++;
145 if ( feedback->isCanceled() )
146 {
147 break;
148 }
149
150 if ( !inFeatureA.hasGeometry() )
151 {
152 if ( !sink->addFeature( inFeatureA, QgsFeatureSink::FastInsert ) )
153 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
154 continue;
155 }
156
157 const QgsGeometry originalGeometry = inFeatureA.geometry();
158 outFeat.setAttributes( inFeatureA.attributes() );
159
160 QVector<QgsGeometry> inGeoms = originalGeometry.asGeometryCollection();
161
162 const QgsFeatureIds splitFeatureCandidates = qgis::listToSet( splitFeaturesIndex.intersects( originalGeometry.boundingBox() ) );
163 if ( !splitFeatureCandidates.empty() ) // has intersection of bounding boxes
164 {
165 QVector<QgsGeometry> splittingLines;
166
167 // use prepared geometries for faster intersection tests
168 std::unique_ptr<QgsGeometryEngine> originalGeometryEngine;
169
170 for ( QgsFeatureId splitFeatureCandidateId : splitFeatureCandidates )
171 {
172 // check if trying to self-intersect
173 if ( sameLayer && inFeatureA.id() == splitFeatureCandidateId )
174 continue;
175
176 const QgsGeometry splitFeatureCandidate = splitFeaturesIndex.geometry( splitFeatureCandidateId );
177 if ( !originalGeometryEngine )
178 {
179 originalGeometryEngine.reset( QgsGeometry::createGeometryEngine( originalGeometry.constGet() ) );
180 originalGeometryEngine->prepareGeometry();
181 }
182
183 if ( originalGeometryEngine->intersects( splitFeatureCandidate.constGet() ) )
184 {
185 QVector<QgsGeometry> splitGeomParts = splitFeatureCandidate.convertToType( Qgis::GeometryType::Line, true ).asGeometryCollection();
186 splittingLines.append( splitGeomParts );
187 }
188 }
189
190 if ( !splittingLines.empty() )
191 {
192 for ( const QgsGeometry &splitGeom : std::as_const( splittingLines ) )
193 {
194 QgsPointSequence splitterPList;
195 QVector<QgsGeometry> outGeoms;
196
197 // use prepared geometries for faster intersection tests
198 std::unique_ptr<QgsGeometryEngine> splitGeomEngine( QgsGeometry::createGeometryEngine( splitGeom.constGet() ) );
199 splitGeomEngine->prepareGeometry();
200 while ( !inGeoms.empty() )
201 {
202 if ( feedback->isCanceled() )
203 {
204 break;
205 }
206
207 QgsGeometry inGeom = inGeoms.takeFirst();
208 if ( inGeom.isNull() )
209 continue;
210
211 if ( splitGeomEngine->intersects( inGeom.constGet() ) )
212 {
213 QgsGeometry before = inGeom;
214 if ( splitterPList.empty() )
215 {
216 const QgsCoordinateSequence sequence = splitGeom.constGet()->coordinateSequence();
217 for ( const QgsRingSequence &part : sequence )
218 {
219 for ( const QgsPointSequence &ring : part )
220 {
221 for ( const QgsPoint &pt : ring )
222 {
223 splitterPList << pt;
224 }
225 }
226 }
227 }
228
229 QVector<QgsGeometry> newGeometries;
230 QgsPointSequence topologyTestPoints;
231 Qgis::GeometryOperationResult result = inGeom.splitGeometry( splitterPList, newGeometries, false, topologyTestPoints, true );
232
233 // splitGeometry: If there are several intersections
234 // between geometry and splitLine, only the first one is considered.
236 {
237 // sometimes the resultant geometry has changed from the input, but only because of numerical precision issues.
238 // and is effectively indistinguishable from the input. By testing the Hausdorff distance is less than this threshold
239 // we are checking that the maximum "change" between the result and the input is actually significant enough to be meaningful...
240 if ( inGeom.hausdorffDistance( before ) < 1e-12 )
241 {
242 // effectively no change!!
243 outGeoms.append( inGeom );
244 }
245 else
246 {
247 outGeoms.append( inGeom );
248 outGeoms.append( newGeometries );
249 }
250 }
251 else
252 {
253 outGeoms.append( inGeom );
254 }
255 }
256 else
257 {
258 outGeoms.append( inGeom );
259 }
260 }
261 inGeoms = outGeoms;
262 }
263 }
264 }
265
266 QVector<QgsGeometry> parts;
267 for ( const QgsGeometry &aGeom : std::as_const( inGeoms ) )
268 {
269 if ( feedback->isCanceled() )
270 {
271 break;
272 }
273
274 bool passed = true;
275 if ( QgsWkbTypes::geometryType( aGeom.wkbType() ) == Qgis::GeometryType::Line )
276 {
277 int numPoints = aGeom.constGet()->nCoordinates();
278
279 if ( numPoints <= 2 )
280 {
281 if ( numPoints == 2 )
282 passed = !static_cast<const QgsCurve *>( aGeom.constGet() )->isClosed(); // tests if vertex 0 = vertex 1
283 else
284 passed = false; // sometimes splitting results in lines of zero length
285 }
286 }
287
288 if ( passed )
289 parts.append( aGeom );
290 }
291
292 for ( const QgsGeometry &g : parts )
293 {
294 outFeat.setGeometry( g );
295 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
296 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
297 }
298
299 feedback->setProgress( i * step );
300 }
301
302 sink->finalize();
303
304 QVariantMap outputs;
305 outputs.insert( u"OUTPUT"_s, dest );
306 return outputs;
307}
308
309
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3650
@ VectorLine
Vector line layers.
Definition qgis.h:3649
GeometryOperationResult
Success or failure of a geometry operation.
Definition qgis.h:2121
@ Success
Operation succeeded.
Definition qgis.h:2122
@ Line
Lines.
Definition qgis.h:381
@ Polygon
Polygons.
Definition qgis.h:382
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3734
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3724
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3745
@ SupportsInPlaceEdits
Algorithm supports in-place editing.
Definition qgis.h:3705
Abstract base class for curved geometry type.
Definition qgscurve.h:36
virtual bool isClosed() const
Returns true if the curve is closed.
Definition qgscurve.cpp:53
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.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
@ 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:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsFeatureId id
Definition qgsfeature.h:68
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 convertToType(Qgis::GeometryType destType, bool destMultipart=false) const
Try to convert the geometry to the requested type.
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.
double hausdorffDistance(const QgsGeometry &geom) const
Returns the Hausdorff distance between this geometry and geom.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Q_DECL_DEPRECATED Qgis::GeometryOperationResult splitGeometry(const QVector< QgsPointXY > &splitLine, QVector< QgsGeometry > &newGeometries, bool topological, QVector< QgsPointXY > &topologyTestPoints, bool splitFeature=true)
Splits this geometry according to a given line.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Base class for all map layer types.
Definition qgsmaplayer.h:83
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
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,...
Represents a vector layer which manages a vector based dataset.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.
QVector< QgsRingSequence > QgsCoordinateSequence
QVector< QgsPointSequence > QgsRingSequence
QVector< QgsPoint > QgsPointSequence
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features