QGIS API Documentation 4.1.0-Master (60fea48833c)
Loading...
Searching...
No Matches
qgscurve.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgscurve.cpp
3 --------------
4 begin : November 2014
5 copyright : (C) 2014 by Marco Hugentobler
6 email : marco at sourcepole dot ch
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
18#include "qgscurve.h"
19
20#include <memory>
21
22#include "qgsgeos.h"
23#include "qgslinestring.h"
24#include "qgsmultipoint.h"
25#include "qgspoint.h"
26#include "qgsvertexid.h"
27
28bool QgsCurve::operator==( const QgsAbstractGeometry &other ) const
29{
30 const QgsCurve *otherCurve = qgsgeometry_cast< const QgsCurve * >( &other );
31 if ( !otherCurve )
32 return false;
33
34 return equals( *otherCurve );
35}
36
37bool QgsCurve::operator!=( const QgsAbstractGeometry &other ) const
38{
39 return !operator==( other );
40}
41
43{
44 if ( numPoints() == 0 )
45 return false;
46
47 //don't consider M-coordinates when testing closedness
48 const QgsPoint start = startPoint();
49 const QgsPoint end = endPoint();
50
51 return qgsDoubleNear( start.x(), end.x() ) && qgsDoubleNear( start.y(), end.y() );
52}
54{
55 bool closed = isClosed2D();
56 if ( is3D() && closed )
57 {
58 const QgsPoint start = startPoint();
59 const QgsPoint end = endPoint();
60 closed &= qgsDoubleNear( start.z(), end.z() ) || ( std::isnan( start.z() ) && std::isnan( end.z() ) );
61 }
62 return closed;
63}
64
65bool QgsCurve::isRing() const
66{
67 return ( isClosed() && numPoints() >= 4 );
68}
69
70QPainterPath QgsCurve::asQPainterPath() const
71{
72 QPainterPath p;
74 return p;
75}
76
78{
79 QgsCoordinateSequence sequence;
80 sequence.append( QgsRingSequence() );
81 sequence.back().append( QgsPointSequence() );
82 points( sequence.back().back() );
83
84 return sequence;
85}
86
87bool QgsCurve::nextVertex( QgsVertexId &id, QgsPoint &vertex ) const
88{
89 if ( id.vertex < 0 )
90 {
91 id.vertex = 0;
92 if ( id.part < 0 )
93 {
94 id.part = 0;
95 }
96 if ( id.ring < 0 )
97 {
98 id.ring = 0;
99 }
100 }
101 else
102 {
103 if ( id.vertex + 1 >= numPoints() )
104 {
105 return false;
106 }
107 ++id.vertex;
108 }
109 return pointAt( id.vertex, vertex, id.type );
110}
111
113{
114 const int n = numPoints();
115 if ( vertex.vertex < 0 || vertex.vertex >= n )
116 {
117 previousVertex = QgsVertexId();
119 return;
120 }
121
122 if ( vertex.vertex == 0 )
123 {
124 previousVertex = QgsVertexId();
125 }
126 else
127 {
128 previousVertex = QgsVertexId( vertex.part, vertex.ring, vertex.vertex - 1 );
129 }
130 if ( vertex.vertex == n - 1 )
131 {
133 }
134 else
135 {
136 nextVertex = QgsVertexId( vertex.part, vertex.ring, vertex.vertex + 1 );
137 }
138}
139
141{
142 if ( id.part != 0 || id.ring != 0 )
143 return -1;
144 if ( id.vertex < 0 || id.vertex >= numPoints() )
145 return -1;
146 return id.vertex;
147}
148
150{
151 if ( isEmpty() )
152 return nullptr;
153
154 if ( isClosed() )
155 return nullptr;
156
157 QgsMultiPoint *multiPoint = new QgsMultiPoint();
158 multiPoint->reserve( 2 );
159 multiPoint->addGeometry( new QgsPoint( startPoint() ) );
160 multiPoint->addGeometry( new QgsPoint( endPoint() ) );
161 return multiPoint;
162}
163
164QString QgsCurve::asKml( int precision ) const
165{
166 std::unique_ptr<QgsLineString> lineString( curveToLine() );
167 if ( !lineString )
168 {
169 return QString();
170 }
171 QString kml = lineString->asKml( precision );
172 return kml;
173}
174
175QgsCurve *QgsCurve::segmentize( double tolerance, SegmentationToleranceType toleranceType ) const
176{
177 return curveToLine( tolerance, toleranceType );
178}
179
180int QgsCurve::vertexCount( int part, int ring ) const
181{
182 Q_UNUSED( part )
183 Q_UNUSED( ring )
184 return numPoints();
185}
186
187int QgsCurve::ringCount( int part ) const
188{
189 Q_UNUSED( part )
190 return numPoints() > 0 ? 1 : 0;
191}
192
194{
195 return numPoints() > 0 ? 1 : 0;
196}
197
199{
200 QgsPoint v;
201 Qgis::VertexType type;
202 pointAt( id.vertex, v, type );
203 return v;
204}
205
207{
208 return clone();
209}
210
212{
213 if ( isEmpty() )
214 return;
215
216 if ( !isClosed() )
217 {
218 return;
219 }
220
221 int minCoordinateIndex = 0;
222 QgsPoint minCoord;
223 int i = 0;
224 for ( auto it = vertices_begin(); it != vertices_end(); ++it )
225 {
226 const QgsPoint vertex = *it;
227 if ( minCoord.isEmpty() || minCoord.compareTo( &vertex ) > 0 )
228 {
229 minCoord = vertex;
230 minCoordinateIndex = i;
231 }
232 i++;
233 }
234
235 scroll( minCoordinateIndex );
236}
237
239{
240 if ( mBoundingBox.isNull() )
241 {
243 }
244 return mBoundingBox;
245}
246
247bool QgsCurve::isValid( QString &error, Qgis::GeometryValidityFlags flags ) const
248{
249 if ( flags == 0 && mHasCachedValidity )
250 {
251 // use cached validity results
252 error = mValidityFailureReason;
253 return error.isEmpty();
254 }
255
256 const QgsGeos geos( this, 0, Qgis::GeosCreationFlags() );
257 const bool res = geos.isValid( &error, flags & Qgis::GeometryValidityFlag::AllowSelfTouchingHoles, nullptr );
258 if ( flags == 0 )
259 {
260 mValidityFailureReason = !res ? error : QString();
261 mHasCachedValidity = true;
262 }
263 return res;
264}
265
266QPolygonF QgsCurve::asQPolygonF() const
267{
268 std::unique_ptr< QgsLineString > segmentized( curveToLine() );
269 return segmentized->asQPolygonF();
270}
271
273{
274 return startPoint().distance( endPoint() );
275}
276
278{
279 const double d = straightDistance2d();
280 if ( qgsDoubleNear( d, 0.0 ) )
281 return std::numeric_limits<double>::quiet_NaN();
282
283 return length() / d;
284}
285
292
294{
296 mHasCachedValidity = false;
297 mValidityFailureReason.clear();
301}
302
304{
305 return numPoints();
306}
307
309{
310 QgsPoint point;
311 Qgis::VertexType type;
312 const bool res = pointAt( index, point, type );
313 Q_ASSERT( res );
314 Q_UNUSED( res )
315 return point;
316}
317
319 double hSpacing,
320 double vSpacing,
321 double dSpacing,
322 double mSpacing,
323 const QVector<double> &srcX,
324 const QVector<double> &srcY,
325 const QVector<double> &srcZ,
326 const QVector<double> &srcM,
327 QVector<double> &outX,
328 QVector<double> &outY,
329 QVector<double> &outZ,
330 QVector<double> &outM,
331 bool removeRedundantPoints
332) const
333{
334 const int length = numPoints();
335 if ( length < 2 )
336 return false;
337
338 const bool hasZ = is3D();
339 const bool hasM = isMeasure();
340
341 outX.reserve( length );
342 outY.reserve( length );
343 if ( hasZ )
344 outZ.reserve( length );
345 if ( hasM )
346 outM.reserve( length );
347
348 const double *xIn = srcX.constData();
349 const double *yIn = srcY.constData();
350 const double *zIn = hasZ ? srcZ.constData() : nullptr;
351 const double *mIn = hasM ? srcM.constData() : nullptr;
352
353 double previousX = 0;
354 double previousY = 0;
355 double previousZ = 0;
356 double previousM = 0;
357 int outSize = 0;
358 for ( int i = 0; i < length; ++i )
359 {
360 const double currentX = *xIn++;
361 const double currentY = *yIn++;
362 const double currentZ = zIn ? *zIn++ : 0;
363 const double currentM = mIn ? *mIn++ : 0;
364
365 const double roundedX = hSpacing > 0 ? ( std::round( currentX / hSpacing ) * hSpacing ) : currentX;
366 const double roundedY = vSpacing > 0 ? ( std::round( currentY / vSpacing ) * vSpacing ) : currentY;
367 const double roundedZ = hasZ && dSpacing > 0 ? ( std::round( currentZ / dSpacing ) * dSpacing ) : currentZ;
368 const double roundedM = hasM && mSpacing > 0 ? ( std::round( currentM / mSpacing ) * mSpacing ) : currentM;
369
370 if ( i == 0 )
371 {
372 outX.append( roundedX );
373 outY.append( roundedY );
374 if ( hasZ )
375 outZ.append( roundedZ );
376 if ( hasM )
377 outM.append( roundedM );
378 outSize++;
379 }
380 else
381 {
382 const bool isPointEqual = qgsDoubleNear( roundedX, previousX )
383 && qgsDoubleNear( roundedY, previousY )
384 && ( !hasZ || dSpacing <= 0 || qgsDoubleNear( roundedZ, previousZ ) )
385 && ( !hasM || mSpacing <= 0 || qgsDoubleNear( roundedM, previousM ) );
386 if ( isPointEqual )
387 continue;
388
389 // maybe previous point is redundant and is just a midpoint on a straight line -- let's check
390 bool previousPointRedundant = false;
391 if ( removeRedundantPoints && outSize > 1 && !hasZ && !hasM )
392 {
393 previousPointRedundant = QgsGeometryUtilsBase::leftOfLine( outX.at( outSize - 1 ), outY.at( outSize - 1 ), outX.at( outSize - 2 ), outY.at( outSize - 2 ), roundedX, roundedY ) == 0;
394 }
395 if ( previousPointRedundant )
396 {
397 outX[outSize - 1] = roundedX;
398 outY[outSize - 1] = roundedY;
399 }
400 else
401 {
402 outX.append( roundedX );
403 outY.append( roundedY );
404 if ( hasZ )
405 outZ.append( roundedZ );
406 if ( hasM )
407 outM.append( roundedM );
408 outSize++;
409 }
410 }
411
412 previousX = roundedX;
413 previousY = roundedY;
414 previousZ = roundedZ;
415 previousM = roundedM;
416 }
417
418 if ( removeRedundantPoints && isClosed() && outSize > 4 && !hasZ && !hasM )
419 {
420 // maybe first/last vertex is redundant, let's try to remove that too
421 const bool firstVertexIsRedundant = QgsGeometryUtilsBase::leftOfLine( outX.at( 0 ), outY.at( 0 ), outX.at( outSize - 2 ), outY.at( outSize - 2 ), outX.at( 1 ), outY.at( 1 ) ) == 0;
422 if ( firstVertexIsRedundant )
423 {
424 outX.removeAt( 0 );
425 outY.removeAt( 0 );
426 outX[outSize - 2] = outX.at( 0 );
427 outY[outSize - 2] = outY.at( 0 );
428 }
429 }
430
431 // we previously reserved size based on a worst case scenario, let's free
432 // unnecessary memory reservation now
433 outX.squeeze();
434 outY.squeeze();
435 if ( hasZ )
436 outZ.squeeze();
437 if ( hasM )
438 outM.squeeze();
439
440 return outSize >= 4 || ( !isClosed() && outSize >= 2 );
441}
@ AllowSelfTouchingHoles
Indicates that self-touching holes are permitted. OGC validity states that self-touching holes are NO...
Definition qgis.h:2151
AngularDirection
Angular directions.
Definition qgis.h:3546
@ CounterClockwise
Counter-clockwise direction.
Definition qgis.h:3548
@ Clockwise
Clockwise direction.
Definition qgis.h:3547
QFlags< GeometryValidityFlag > GeometryValidityFlags
Geometry validity flags.
Definition qgis.h:2155
VertexType
Types of vertex.
Definition qgis.h:3179
QFlags< GeosCreationFlag > GeosCreationFlags
Geos geometry creation behavior flags.
Definition qgis.h:2238
SegmentationToleranceType
Segmentation tolerance as maximum angle or maximum difference between approximation and circle.
vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
virtual QgsBox3D calculateBoundingBox3D() const
Calculates the minimal 3D bounding box for the geometry.
bool isMeasure() const
Returns true if the geometry contains m values.
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
virtual void clearCache() const
Clears any cached parameters associated with the geometry, e.g., bounding boxes.
virtual double length() const
Returns the planar, 2-dimensional length of the geometry.
virtual bool isEmpty() const
Returns true if the geometry is empty.
vertex_iterator vertices_begin() const
Returns STL-style iterator pointing to the first vertex of the geometry.
virtual int compareTo(const QgsAbstractGeometry *other) const
Comparator for sorting of geometry.
QgsAbstractGeometry()=default
A 3-dimensional box composed of x, y, z coordinates.
Definition qgsbox3d.h:45
virtual bool equals(const QgsCurve &other) const =0
Checks whether this curve exactly equals another curve.
Qgis::AngularDirection orientation() const
Returns the curve's orientation, e.g.
Definition qgscurve.cpp:286
QgsCoordinateSequence coordinateSequence() const override
Retrieves the sequence of geometries, rings and nodes.
Definition qgscurve.cpp:77
virtual int numPoints() const =0
Returns the number of points in the curve.
void clearCache() const override
Clears any cached parameters associated with the geometry, e.g., bounding boxes.
Definition qgscurve.cpp:293
double sinuosity() const
Returns the curve sinuosity, which is the ratio of the curve length() to curve straightDistance2d().
Definition qgscurve.cpp:277
bool mHasCachedSummedUpArea
Definition qgscurve.h:404
void normalize() final
Reorganizes the geometry into a normalized form (or "canonical" form).
Definition qgscurve.cpp:211
QPainterPath asQPainterPath() const override
Returns the geometry represented as a QPainterPath.
Definition qgscurve.cpp:70
QgsPoint childPoint(int index) const override
Returns point at index (for geometries without child geometries - i.e.
Definition qgscurve.cpp:308
int vertexNumberFromVertexId(QgsVertexId id) const override
Returns the vertex number corresponding to a vertex id.
Definition qgscurve.cpp:140
virtual void scroll(int firstVertexIndex)=0
Scrolls the curve vertices so that they start with the vertex at the given index.
int partCount() const override
Returns count of parts contained in the geometry.
Definition qgscurve.cpp:193
QgsCurve * segmentize(double tolerance=M_PI_2/90, SegmentationToleranceType toleranceType=MaximumAngle) const override
Returns a geometry without curves.
Definition qgscurve.cpp:175
virtual bool isRing() const
Returns true if the curve is a ring.
Definition qgscurve.cpp:65
virtual bool pointAt(int node, QgsPoint &point, Qgis::VertexType &type) const =0
Returns the point and vertex id of a point within the curve.
int childCount() const override
Returns number of child geometries (for geometries with child geometries) or child points (for geomet...
Definition qgscurve.cpp:303
QgsBox3D boundingBox3D() const override
Returns the 3D bounding box for the geometry.
Definition qgscurve.cpp:238
bool mHasCachedSummedUpArea3D
Definition qgscurve.h:406
virtual bool isClosed() const
Returns true if the curve is closed.
Definition qgscurve.cpp:53
bool isValid(QString &error, Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const override
Checks validity of the geometry, and returns true if the geometry is valid.
Definition qgscurve.cpp:247
virtual bool isClosed2D() const
Returns true if the curve is closed.
Definition qgscurve.cpp:42
int vertexCount(int part=0, int ring=0) const override
Returns the number of vertices of which this geometry is built.
Definition qgscurve.cpp:180
QgsPoint vertexAt(QgsVertexId id) const override
Returns the point corresponding to a specified vertex id.
Definition qgscurve.cpp:198
QgsAbstractGeometry * boundary() const override
Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the...
Definition qgscurve.cpp:149
virtual QPolygonF asQPolygonF() const
Returns a QPolygonF representing the points.
Definition qgscurve.cpp:266
void adjacentVertices(QgsVertexId vertex, QgsVertexId &previousVertex, QgsVertexId &nextVertex) const override
Returns the vertices adjacent to a specified vertex within a geometry.
Definition qgscurve.cpp:112
virtual void addToPainterPath(QPainterPath &path) const =0
Adds a curve to a painter path.
QgsCurve * toCurveType() const override
Returns the geometry converted to the more generic curve type.
Definition qgscurve.cpp:206
virtual void sumUpArea(double &sum) const =0
Sums up the area of the curve by iterating over the vertices (shoelace formula).
bool operator==(const QgsAbstractGeometry &other) const override
Definition qgscurve.cpp:28
bool snapToGridPrivate(double hSpacing, double vSpacing, double dSpacing, double mSpacing, const QVector< double > &srcX, const QVector< double > &srcY, const QVector< double > &srcZ, const QVector< double > &srcM, QVector< double > &outX, QVector< double > &outY, QVector< double > &outZ, QVector< double > &outM, bool removeRedundantPoints) const
Helper function for QgsCurve subclasses to snap to grids.
Definition qgscurve.cpp:318
QString asKml(int precision=17) const override
Returns a KML representation of the geometry.
Definition qgscurve.cpp:164
QgsBox3D mBoundingBox
Cached bounding box.
Definition qgscurve.h:402
QgsCurve * clone() const override=0
Clones the geometry by performing a deep copy.
int ringCount(int part=0) const override
Returns the number of rings of which this geometry is built.
Definition qgscurve.cpp:187
virtual QgsPoint startPoint() const =0
Returns the starting point of the curve.
bool operator!=(const QgsAbstractGeometry &other) const override
Definition qgscurve.cpp:37
double straightDistance2d() const
Returns the straight distance of the curve, i.e.
Definition qgscurve.cpp:272
bool nextVertex(QgsVertexId &id, QgsPoint &vertex) const override
Returns next vertex id and coordinates.
Definition qgscurve.cpp:87
virtual QgsPoint endPoint() const =0
Returns the end point of the curve.
virtual void points(QgsPointSequence &pt) const =0
Returns a list of points within the curve.
virtual QgsLineString * curveToLine(double tolerance=M_PI_2/90, SegmentationToleranceType toleranceType=MaximumAngle) const =0
Returns a new line string geometry corresponding to a segmentized approximation of the curve.
QgsCurve()=default
void reserve(int size)
Attempts to allocate memory for at least size geometries.
static int leftOfLine(const double x, const double y, const double x1, const double y1, const double x2, const double y2)
Returns a value < 0 if the point (x, y) is left of the line from (x1, y1) -> (x2, y2).
Does vector analysis using the GEOS library and handles import, export, and exception handling.
Definition qgsgeos.h:139
Multi point geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
double z
Definition qgspoint.h:58
double x
Definition qgspoint.h:56
bool isEmpty() const override
Returns true if the geometry is empty.
Definition qgspoint.cpp:766
double distance(double x, double y) const
Returns the Cartesian 2D distance between this point and a specified x, y coordinate.
Definition qgspoint.h:466
double y
Definition qgspoint.h:57
Contains geos related utilities and functions.
Definition qgsgeos.h:76
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6975
T qgsgeometry_cast(QgsAbstractGeometry *geom)
QVector< QgsRingSequence > QgsCoordinateSequence
QVector< QgsPointSequence > QgsRingSequence
QVector< QgsPoint > QgsPointSequence
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:34
int vertex
Vertex number.
Definition qgsvertexid.h:99
int part
Part number.
Definition qgsvertexid.h:93
int ring
Ring number.
Definition qgsvertexid.h:96