QGIS API Documentation  2.99.0-Master (01468d0)
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 
21 QgsGeometryValidator::QgsGeometryValidator( const QgsGeometry &geometry, QList<QgsGeometry::Error> *errors, QgsGeometry::ValidationMethod method )
22  : QThread()
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 QgsPolyline &ring0,
44  int p1, int i1, const QgsPolyline &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, QgsPolyline 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 QgsPolygon &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  char *r = nullptr;
221  GEOSGeometry *g0 = mGeometry.exportToGeos();
222  GEOSContextHandle_t handle = QgsGeometry::getGEOSHandler();
223  if ( !g0 )
224  {
225  emit errorFound( QgsGeometry::Error( QObject::tr( "GEOS error:could not produce geometry for GEOS (check log window)" ) ) );
226  }
227  else
228  {
229  GEOSGeometry *g1 = nullptr;
230  char res = GEOSisValidDetail_r( handle, g0, GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE, &r, &g1 );
231  GEOSGeom_destroy_r( handle, g0 );
232  if ( res != 1 )
233  {
234  if ( g1 )
235  {
236  const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( handle, g1 );
237 
238  unsigned int n;
239  if ( GEOSCoordSeq_getSize_r( handle, cs, &n ) && n == 1 )
240  {
241  double x, y;
242  GEOSCoordSeq_getX_r( handle, cs, 0, &x );
243  GEOSCoordSeq_getY_r( handle, cs, 0, &y );
244  emit errorFound( QgsGeometry::Error( QObject::tr( "GEOS error:%1" ).arg( r ), QgsPointXY( x, y ) ) );
245  mErrorCount++;
246  }
247 
248  GEOSGeom_destroy_r( handle, g1 );
249  }
250  else
251  {
252  emit errorFound( QgsGeometry::Error( QObject::tr( "GEOS error:%1" ).arg( r ) ) );
253  mErrorCount++;
254  }
255 
256  GEOSFree_r( handle, r );
257  }
258  }
259 
260  break;
261  }
262 
264  {
265  QgsDebugMsg( "validation thread started." );
266 
267  QgsWkbTypes::Type flatType = QgsWkbTypes::flatType( mGeometry.wkbType() );
268  //if ( flatType == QgsWkbTypes::Point || flatType == QgsWkbTypes::MultiPoint )
269  // break;
270  if ( flatType == QgsWkbTypes::LineString )
271  {
272  validatePolyline( 0, mGeometry.asPolyline() );
273  }
274  else if ( flatType == QgsWkbTypes::MultiLineString )
275  {
276  QgsMultiPolyline mp = mGeometry.asMultiPolyline();
277  for ( int i = 0; !mStop && i < mp.size(); i++ )
278  validatePolyline( i, mp[i] );
279  }
280  else if ( flatType == QgsWkbTypes::Polygon )
281  {
282  validatePolygon( 0, mGeometry.asPolygon() );
283  }
284  else if ( flatType == QgsWkbTypes::MultiPolygon )
285  {
286  QgsMultiPolygon mp = mGeometry.asMultiPolygon();
287  for ( int i = 0; !mStop && i < mp.size(); i++ )
288  {
289  validatePolygon( i, mp[i] );
290  }
291 
292  for ( int i = 0; !mStop && i < mp.size(); i++ )
293  {
294  if ( mp[i].isEmpty() )
295  {
296  emit errorFound( QgsGeometry::Error( QObject::tr( "polygon %1 has no rings" ).arg( i ) ) );
297  mErrorCount++;
298  continue;
299  }
300 
301  for ( int j = i + 1; !mStop && j < mp.size(); j++ )
302  {
303  if ( mp[j].isEmpty() )
304  continue;
305 
306  if ( ringInRing( mp[i][0], mp[j][0] ) )
307  {
308  emit errorFound( QgsGeometry::Error( QObject::tr( "polygon %1 inside polygon %2" ).arg( i ).arg( j ) ) );
309  mErrorCount++;
310  }
311  else if ( ringInRing( mp[j][0], mp[i][0] ) )
312  {
313  emit errorFound( QgsGeometry::Error( QObject::tr( "polygon %1 inside polygon %2" ).arg( j ).arg( i ) ) );
314  mErrorCount++;
315  }
316  else
317  {
318  checkRingIntersections( i, 0, mp[i][0], j, 0, mp[j][0] );
319  }
320  }
321  }
322  }
323 
324  else if ( flatType == QgsWkbTypes::Unknown )
325  {
326  QgsDebugMsg( QObject::tr( "Unknown geometry type" ) );
327  emit errorFound( QgsGeometry::Error( QObject::tr( "Unknown geometry type %1" ).arg( mGeometry.wkbType() ) ) );
328  mErrorCount++;
329  }
330 
331  QgsDebugMsg( "validation finished." );
332 
333  if ( mStop )
334  {
335  emit errorFound( QgsGeometry::Error( QObject::tr( "Geometry validation was aborted." ) ) );
336  }
337  else if ( mErrorCount > 0 )
338  {
339  emit errorFound( QgsGeometry::Error( QObject::tr( "Geometry has %1 errors." ).arg( mErrorCount ) ) );
340  }
341 #if 0
342  else
343  {
344  emit errorFound( QgsGeometry::Error( QObject::tr( "Geometry is valid." ) ) );
345  }
346 #endif
347  break;
348  }
349  }
350 }
351 
353 {
354  if ( mErrors )
355  *mErrors << e;
356 }
357 
358 void QgsGeometryValidator::validateGeometry( const QgsGeometry &geometry, QList<QgsGeometry::Error> &errors, QgsGeometry::ValidationMethod method )
359 {
360  QgsGeometryValidator *gv = new QgsGeometryValidator( geometry, &errors, method );
362  gv->run();
363  gv->wait();
364 }
365 
366 //
367 // distance of point q from line through p in direction v
368 // return >0 => q lies left of the line
369 // <0 => q lies right of the line
370 //
371 double QgsGeometryValidator::distLine2Point( const QgsPointXY &p, QgsVector v, const QgsPointXY &q )
372 {
373  if ( qgsDoubleNear( v.length(), 0 ) )
374  {
375  throw QgsException( QObject::tr( "invalid line" ) );
376  }
377 
378  return ( v.x() * ( q.y() - p.y() ) - v.y() * ( q.x() - p.x() ) ) / v.length();
379 }
380 
381 bool QgsGeometryValidator::intersectLines( const QgsPointXY &p, QgsVector v, const QgsPointXY &q, QgsVector w, QgsPointXY &s )
382 {
383  double d = v.y() * w.x() - v.x() * w.y();
384 
385  if ( qgsDoubleNear( d, 0 ) )
386  return false;
387 
388  double dx = q.x() - p.x();
389  double dy = q.y() - p.y();
390  double k = ( dy * w.x() - dx * w.y() ) / d;
391 
392  s = p + v * k;
393 
394  return true;
395 }
396 
397 bool QgsGeometryValidator::pointInRing( const QgsPolyline &ring, const QgsPointXY &p )
398 {
399  bool inside = false;
400  int j = ring.size() - 1;
401 
402  for ( int i = 0; !mStop && i < ring.size(); i++ )
403  {
404  if ( qgsDoubleNear( ring[i].x(), p.x() ) && qgsDoubleNear( ring[i].y(), p.y() ) )
405  return true;
406 
407  if ( ( ring[i].y() < p.y() && ring[j].y() >= p.y() ) ||
408  ( ring[j].y() < p.y() && ring[i].y() >= p.y() ) )
409  {
410  if ( ring[i].x() + ( p.y() - ring[i].y() ) / ( ring[j].y() - ring[i].y() ) * ( ring[j].x() - ring[i].x() ) <= p.x() )
411  inside = !inside;
412  }
413 
414  j = i;
415  }
416 
417  return inside;
418 }
419 
420 bool QgsGeometryValidator::ringInRing( const QgsPolyline &inside, const QgsPolyline &outside )
421 {
422  for ( int i = 0; !mStop && i < inside.size(); i++ )
423  {
424  if ( !pointInRing( outside, inside[i] ) )
425  return false;
426  }
427 
428  return true;
429 }
QgsPolygon asPolygon() const
Returns contents of the geometry as a polygon if wkbType is WKBPolygon, otherwise an empty list...
QgsMultiPolyline asMultiPolyline() const
Returns contents of the geometry as a multi linestring if wkbType is WKBMultiLineString, otherwise an empty list.
Use GEOS validation methods.
Definition: qgsgeometry.h:1176
#define QgsDebugMsg(str)
Definition: qgslogger.h:37
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:47
A class to represent a 2D point.
Definition: qgspointxy.h:42
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:92
bool qgsDoubleNear(double a, double b, double epsilon=4 *DBL_EPSILON)
Compare two doubles (but allow some difference)
Definition: qgis.h:210
QgsPolyline asPolyline() const
Returns contents of the geometry as a polyline if wkbType is WKBLineString, otherwise an empty list...
QVector< QgsPointXY > QgsPolyline
Polyline is represented as a vector of points.
Definition: qgsgeometry.h:48
QString what() const
Definition: qgsexception.h:48
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:66
Use internal QgsGeometryValidator method.
Definition: qgsgeometry.h:1175
QVector< QgsPolygon > QgsMultiPolygon
A collection of QgsPolygons that share a common collection of attributes.
Definition: qgsgeometry.h:72
QVector< QgsPolyline > QgsPolygon
Polygon: first item of the list is outer ring, inner rings (if any) start from second item...
Definition: qgsgeometry.h:55
void errorFound(const QgsGeometry::Error &)
double length() const
Returns the length of the vector.
Definition: qgsvector.cpp:77
double x
Definition: qgspointxy.h:46
A class to represent a vector.
Definition: qgsvector.h:26
QVector< QgsPolyline > QgsMultiPolyline
A collection of QgsPolylines that share a common collection of attributes.
Definition: qgsgeometry.h:65
QgsVector perpVector() const
Returns the perpendicular vector to this vector (rotated 90 degrees counter-clockwise) ...
Definition: qgsvector.cpp:92
QString toString() const
String representation of the point (x,y)
Definition: qgspointxy.cpp:45
static void validateGeometry(const QgsGeometry &geometry, QList< QgsGeometry::Error > &errors, QgsGeometry::ValidationMethod method=QgsGeometry::ValidatorQgisInternal)
Validate geometry and produce a list of geometry errors.
static GEOSContextHandle_t getGEOSHandler()
Return GEOS context handle.
QgsGeometryValidator(const QgsGeometry &geoemtry, QList< QgsGeometry::Error > *errors=nullptr, QgsGeometry::ValidationMethod method=QgsGeometry::ValidatorQgisInternal)
Constructor for QgsGeometryValidator.
GEOSGeometry * exportToGeos(double precision=0) const
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
QgsMultiPolygon asMultiPolygon() const
Returns contents of the geometry as a multi polygon if wkbType is WKBMultiPolygon, otherwise an empty list.
ValidationMethod
Available methods for validating geometries.
Definition: qgsgeometry.h:1173
double x() const
Returns the vector&#39;s x-component.
Definition: qgsvector.cpp:82
static Type flatType(Type type)
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:423
double y() const
Returns the vector&#39;s y-component.
Definition: qgsvector.cpp:87
Defines a QGIS exception class.
Definition: qgsexception.h:33