QGIS API Documentation  3.8.0-Zanzibar (11aff65)
qgsgeometryvalidator.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsgeometryvalidator.cpp - geometry validation thread
3  -------------------------------------------------------------------
4 Date : 03.01.2012
5 Copyright : (C) 2012 by Juergen E. Fischer
6 email : jef at norbit dot de
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include "qgis.h"
17 #include "qgsgeometryvalidator.h"
18 #include "qgsgeometry.h"
19 #include "qgslogger.h"
20 #include "qgsgeos.h"
21 
22 QgsGeometryValidator::QgsGeometryValidator( const QgsGeometry &geometry, QVector<QgsGeometry::Error> *errors, QgsGeometry::ValidationMethod method )
23  : mGeometry( geometry )
24  , mErrors( errors )
25  , mStop( false )
26  , mErrorCount( 0 )
27  , mMethod( method )
28 {
29 }
30 
32 {
33  stop();
34  wait();
35 }
36 
38 {
39  mStop = true;
40 }
41 
42 void QgsGeometryValidator::checkRingIntersections(
43  int p0, int i0, const QgsPolylineXY &ring0,
44  int p1, int i1, const QgsPolylineXY &ring1 )
45 {
46  for ( int i = 0; !mStop && i < ring0.size() - 1; i++ )
47  {
48  QgsVector v = ring0[i + 1] - ring0[i];
49 
50  for ( int j = 0; !mStop && j < ring1.size() - 1; j++ )
51  {
52  QgsVector w = ring1[j + 1] - ring1[j];
53 
54  QgsPointXY s;
55  if ( intersectLines( ring0[i], v, ring1[j], w, s ) )
56  {
57  double d = -distLine2Point( ring0[i], v.perpVector(), s );
58 
59  if ( d >= 0 && d <= v.length() )
60  {
61  d = -distLine2Point( ring1[j], w.perpVector(), s );
62  if ( d > 0 && d < w.length() &&
63  ring0[i + 1] != ring1[j + 1] && ring0[i + 1] != ring1[j] &&
64  ring0[i + 0] != ring1[j + 1] && ring0[i + 0] != ring1[j] )
65  {
66  QString msg = QObject::tr( "segment %1 of ring %2 of polygon %3 intersects segment %4 of ring %5 of polygon %6 at %7" )
67  .arg( i0 ).arg( i ).arg( p0 )
68  .arg( i1 ).arg( j ).arg( p1 )
69  .arg( s.toString() );
70  QgsDebugMsg( msg );
71  emit errorFound( QgsGeometry::Error( msg, s ) );
72  mErrorCount++;
73  }
74  }
75  }
76  }
77  }
78 }
79 
80 void QgsGeometryValidator::validatePolyline( int i, QgsPolylineXY line, bool ring )
81 {
82  if ( ring )
83  {
84  if ( line.size() < 4 )
85  {
86  QString msg = QObject::tr( "ring %1 with less than four points" ).arg( i );
87  QgsDebugMsg( msg );
88  emit errorFound( QgsGeometry::Error( msg ) );
89  mErrorCount++;
90  return;
91  }
92 
93  if ( line[0] != line[ line.size() - 1 ] )
94  {
95  QString msg = QObject::tr( "ring %1 not closed" ).arg( i );
96  QgsDebugMsg( msg );
97  emit errorFound( QgsGeometry::Error( msg ) );
98  mErrorCount++;
99  return;
100  }
101  }
102  else if ( line.size() < 2 )
103  {
104  QString msg = QObject::tr( "line %1 with less than two points" ).arg( i );
105  QgsDebugMsg( msg );
106  emit errorFound( QgsGeometry::Error( msg ) );
107  mErrorCount++;
108  return;
109  }
110 
111  int j = 0;
112  while ( j < line.size() - 1 )
113  {
114  int n = 0;
115  while ( j < line.size() - 1 && line[j] == line[j + 1] )
116  {
117  line.remove( j );
118  n++;
119  }
120 
121  if ( n > 0 )
122  {
123  QString msg = QObject::tr( "line %1 contains %n duplicate node(s) at %2", "number of duplicate nodes", n ).arg( i ).arg( j );
124  QgsDebugMsg( msg );
125  emit errorFound( QgsGeometry::Error( msg, line[j] ) );
126  mErrorCount++;
127  }
128 
129  j++;
130  }
131 
132  for ( j = 0; !mStop && j < line.size() - 3; j++ )
133  {
134  QgsVector v = line[j + 1] - line[j];
135  double vl = v.length();
136 
137  int n = ( j == 0 && ring ) ? line.size() - 2 : line.size() - 1;
138 
139  for ( int k = j + 2; !mStop && k < n; k++ )
140  {
141  QgsVector w = line[k + 1] - line[k];
142 
143  QgsPointXY s;
144  if ( !intersectLines( line[j], v, line[k], w, s ) )
145  continue;
146 
147  double d = 0.0;
148  try
149  {
150  d = -distLine2Point( line[j], v.perpVector(), s );
151  }
152  catch ( QgsException &e )
153  {
154  Q_UNUSED( e )
155  QgsDebugMsg( "Error validating: " + e.what() );
156  continue;
157  }
158  if ( d < 0 || d > vl )
159  continue;
160 
161  try
162  {
163  d = -distLine2Point( line[k], w.perpVector(), s );
164  }
165  catch ( QgsException &e )
166  {
167  Q_UNUSED( e )
168  QgsDebugMsg( "Error validating: " + e.what() );
169  continue;
170  }
171 
172  if ( d <= 0 || d >= w.length() )
173  continue;
174 
175  QString msg = QObject::tr( "segments %1 and %2 of line %3 intersect at %4" ).arg( j ).arg( k ).arg( i ).arg( s.toString() );
176  QgsDebugMsg( msg );
177  emit errorFound( QgsGeometry::Error( msg, s ) );
178  mErrorCount++;
179  }
180  }
181 }
182 
183 void QgsGeometryValidator::validatePolygon( int idx, const QgsPolygonXY &polygon )
184 {
185  // check if holes are inside polygon
186  for ( int i = 1; !mStop && i < polygon.size(); i++ )
187  {
188  if ( !ringInRing( polygon[i], polygon[0] ) )
189  {
190  QString msg = QObject::tr( "Ring %1 of polygon %2 not in exterior ring" ).arg( i ).arg( idx );
191  QgsDebugMsg( msg );
192  emit errorFound( QgsGeometry::Error( msg ) );
193  mErrorCount++;
194  }
195  }
196 
197  // check holes for intersections
198  for ( int i = 1; !mStop && i < polygon.size(); i++ )
199  {
200  for ( int j = i + 1; !mStop && j < polygon.size(); j++ )
201  {
202  checkRingIntersections( idx, i, polygon[i], idx, j, polygon[j] );
203  }
204  }
205 
206  // check if rings are self-intersecting
207  for ( int i = 0; !mStop && i < polygon.size(); i++ )
208  {
209  validatePolyline( i, polygon[i], true );
210  }
211 }
212 
214 {
215  mErrorCount = 0;
216  switch ( mMethod )
217  {
219  {
220  if ( mGeometry.isNull() )
221  {
222  return;
223  }
224 
225  // avoid calling geos for trivial point geometries
227  {
228  return;
229  }
230 
231  QgsGeos geos( mGeometry.constGet() );
232  QString error;
233  QgsGeometry errorLoc;
234  if ( !geos.isValid( &error, true, &errorLoc ) )
235  {
236  if ( errorLoc.isNull() )
237  {
238  emit errorFound( QgsGeometry::Error( error ) );
239  mErrorCount++;
240  }
241  else
242  {
243  const QgsPointXY point = errorLoc.asPoint();
244  emit errorFound( QgsGeometry::Error( error, point ) );
245  mErrorCount++;
246  }
247  }
248 
249  break;
250  }
251 
253  {
254  QgsWkbTypes::Type flatType = QgsWkbTypes::flatType( mGeometry.wkbType() );
255  //if ( flatType == QgsWkbTypes::Point || flatType == QgsWkbTypes::MultiPoint )
256  // break;
257  if ( flatType == QgsWkbTypes::LineString )
258  {
259  validatePolyline( 0, mGeometry.asPolyline() );
260  }
261  else if ( flatType == QgsWkbTypes::MultiLineString )
262  {
263  QgsMultiPolylineXY mp = mGeometry.asMultiPolyline();
264  for ( int i = 0; !mStop && i < mp.size(); i++ )
265  validatePolyline( i, mp[i] );
266  }
267  else if ( flatType == QgsWkbTypes::Polygon )
268  {
269  validatePolygon( 0, mGeometry.asPolygon() );
270  }
271  else if ( flatType == QgsWkbTypes::MultiPolygon )
272  {
273  QgsMultiPolygonXY mp = mGeometry.asMultiPolygon();
274  for ( int i = 0; !mStop && i < mp.size(); i++ )
275  {
276  validatePolygon( i, mp[i] );
277  }
278 
279  for ( int i = 0; !mStop && i < mp.size(); i++ )
280  {
281  if ( mp[i].isEmpty() )
282  {
283  emit errorFound( QgsGeometry::Error( QObject::tr( "Polygon %1 has no rings" ).arg( i ) ) );
284  mErrorCount++;
285  continue;
286  }
287 
288  for ( int j = i + 1; !mStop && j < mp.size(); j++ )
289  {
290  if ( mp[j].isEmpty() )
291  continue;
292 
293  if ( ringInRing( mp[i][0], mp[j][0] ) )
294  {
295  emit errorFound( QgsGeometry::Error( QObject::tr( "Polygon %1 lies inside polygon %2" ).arg( i ).arg( j ) ) );
296  mErrorCount++;
297  }
298  else if ( ringInRing( mp[j][0], mp[i][0] ) )
299  {
300  emit errorFound( QgsGeometry::Error( QObject::tr( "Polygon %1 lies inside polygon %2" ).arg( j ).arg( i ) ) );
301  mErrorCount++;
302  }
303  else
304  {
305  checkRingIntersections( i, 0, mp[i][0], j, 0, mp[j][0] );
306  }
307  }
308  }
309  }
310 
311  else if ( flatType == QgsWkbTypes::Unknown )
312  {
313  emit errorFound( QgsGeometry::Error( QObject::tr( "Unknown geometry type %1" ).arg( mGeometry.wkbType() ) ) );
314  mErrorCount++;
315  }
316 
317  if ( mStop )
318  {
319  emit validationFinished( QObject::tr( "Geometry validation was aborted." ) );
320  }
321  else if ( mErrorCount > 0 )
322  {
323  emit validationFinished( QObject::tr( "Geometry has %1 errors." ).arg( mErrorCount ) );
324  }
325  else
326  {
327  emit validationFinished( QObject::tr( "Geometry is valid." ) );
328  }
329  break;
330  }
331  }
332 }
333 
335 {
336  if ( mErrors )
337  *mErrors << e;
338 }
339 
340 void QgsGeometryValidator::validateGeometry( const QgsGeometry &geometry, QVector<QgsGeometry::Error> &errors, QgsGeometry::ValidationMethod method )
341 {
342  QgsGeometryValidator *gv = new QgsGeometryValidator( geometry, &errors, method );
344  gv->run();
345  gv->wait();
346 }
347 
348 //
349 // distance of point q from line through p in direction v
350 // return >0 => q lies left of the line
351 // <0 => q lies right of the line
352 //
353 double QgsGeometryValidator::distLine2Point( const QgsPointXY &p, QgsVector v, const QgsPointXY &q )
354 {
355  if ( qgsDoubleNear( v.length(), 0 ) )
356  {
357  throw QgsException( QObject::tr( "invalid line" ) );
358  }
359 
360  return ( v.x() * ( q.y() - p.y() ) - v.y() * ( q.x() - p.x() ) ) / v.length();
361 }
362 
363 bool QgsGeometryValidator::intersectLines( const QgsPointXY &p, QgsVector v, const QgsPointXY &q, QgsVector w, QgsPointXY &s )
364 {
365  double d = v.y() * w.x() - v.x() * w.y();
366 
367  if ( qgsDoubleNear( d, 0 ) )
368  return false;
369 
370  double dx = q.x() - p.x();
371  double dy = q.y() - p.y();
372  double k = ( dy * w.x() - dx * w.y() ) / d;
373 
374  s = p + v * k;
375 
376  return true;
377 }
378 
379 bool QgsGeometryValidator::pointInRing( const QgsPolylineXY &ring, const QgsPointXY &p )
380 {
381  bool inside = false;
382  int j = ring.size() - 1;
383 
384  for ( int i = 0; !mStop && i < ring.size(); i++ )
385  {
386  if ( qgsDoubleNear( ring[i].x(), p.x() ) && qgsDoubleNear( ring[i].y(), p.y() ) )
387  return true;
388 
389  if ( ( ring[i].y() < p.y() && ring[j].y() >= p.y() ) ||
390  ( ring[j].y() < p.y() && ring[i].y() >= p.y() ) )
391  {
392  if ( ring[i].x() + ( p.y() - ring[i].y() ) / ( ring[j].y() - ring[i].y() ) * ( ring[j].x() - ring[i].x() ) <= p.x() )
393  inside = !inside;
394  }
395 
396  j = i;
397  }
398 
399  return inside;
400 }
401 
402 bool QgsGeometryValidator::ringInRing( const QgsPolylineXY &inside, const QgsPolylineXY &outside )
403 {
404  for ( int i = 0; !mStop && i < inside.size(); i++ )
405  {
406  if ( !pointInRing( outside, inside[i] ) )
407  return false;
408  }
409 
410  return true;
411 }
static void validateGeometry(const QgsGeometry &geometry, QVector< QgsGeometry::Error > &errors, QgsGeometry::ValidationMethod method=QgsGeometry::ValidatorQgisInternal)
Validate geometry and produce a list of geometry errors.
void validationFinished(const QString &summary)
Sent when the validation is finished.
Use GEOS validation methods.
Definition: qgsgeometry.h:1884
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
void addError(const QgsGeometry::Error &)
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
double y
Definition: qgspointxy.h:48
A class to represent a 2D point.
Definition: qgspointxy.h:43
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:265
QVector< QgsPolylineXY > QgsPolygonXY
Polygon: first item of the list is outer ring, inner rings (if any) start from second item...
Definition: qgsgeometry.h:73
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:111
QString toString(int precision=-1) const
Returns a string representation of the point (x, y) with a preset precision.
Definition: qgspointxy.cpp:40
QVector< QgsPolygonXY > QgsMultiPolygonXY
A collection of QgsPolygons that share a common collection of attributes.
Definition: qgsgeometry.h:90
QString what() const
Definition: qgsexception.h:48
QVector< QgsPolylineXY > QgsMultiPolylineXY
A collection of QgsPolylines that share a common collection of attributes.
Definition: qgsgeometry.h:83
QgsMultiPolylineXY asMultiPolyline() const
Returns the contents of the geometry as a multi-linestring.
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:68
QgsPolygonXY asPolygon() const
Returns the contents of the geometry as a polygon.
static GeometryType geometryType(Type type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
Definition: qgswkbtypes.h:666
Use internal QgsGeometryValidator method.
Definition: qgsgeometry.h:1883
Does vector analysis using the geos library and handles import, export, exception handling*...
Definition: qgsgeos.h:103
double length() const
Returns the length of the vector.
Definition: qgsvector.cpp:71
double x
Definition: qgspointxy.h:47
A class to represent a vector.
Definition: qgsvector.h:29
Contains geos related utilities and functions.
Definition: qgsgeos.h:41
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsGeometryValidator(const QgsGeometry &geometry, QVector< QgsGeometry::Error > *errors=nullptr, QgsGeometry::ValidationMethod method=QgsGeometry::ValidatorQgisInternal)
Constructor for QgsGeometryValidator.
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.
Definition: qgsgeometry.h:49
QgsVector perpVector() const
Returns the perpendicular vector to this vector (rotated 90 degrees counter-clockwise) ...
Definition: qgsvector.cpp:86
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
ValidationMethod
Available methods for validating geometries.
Definition: qgsgeometry.h:1881
QgsPolylineXY asPolyline() const
Returns the contents of the geometry as a polyline.
double x() const
Returns the vector&#39;s x-component.
Definition: qgsvector.cpp:76
static Type flatType(Type type)
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:430
QgsMultiPolygonXY asMultiPolygon() const
Returns the contents of the geometry as a multi-polygon.
double y() const
Returns the vector&#39;s y-component.
Definition: qgsvector.cpp:81
Defines a QGIS exception class.
Definition: qgsexception.h:34
void errorFound(const QgsGeometry::Error &error)
Sent when an error has been found during the validation process.