QGIS API Documentation  2.99.0-Master (c558d51)
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 #include <QSettings>
22 
23 QgsGeometryValidator::QgsGeometryValidator( const QgsGeometry *g, QList<QgsGeometry::Error> *errors )
24  : QThread()
25  , mErrors( errors )
26  , mStop( false )
27  , mErrorCount( 0 )
28 {
29  Q_ASSERT( g );
30  if ( g )
31  mG = *g;
32 }
33 
35 {
36  stop();
37  wait();
38 }
39 
41 {
42  mStop = true;
43 }
44 
45 void QgsGeometryValidator::checkRingIntersections(
46  int p0, int i0, const QgsPolyline &ring0,
47  int p1, int i1, const QgsPolyline &ring1 )
48 {
49  for ( int i = 0; !mStop && i < ring0.size() - 1; i++ )
50  {
51  QgsVector v = ring0[i+1] - ring0[i];
52 
53  for ( int j = 0; !mStop && j < ring1.size() - 1; j++ )
54  {
55  QgsVector w = ring1[j+1] - ring1[j];
56 
57  QgsPoint s;
58  if ( intersectLines( ring0[i], v, ring1[j], w, s ) )
59  {
60  double d = -distLine2Point( ring0[i], v.perpVector(), s );
61 
62  if ( d >= 0 && d <= v.length() )
63  {
64  d = -distLine2Point( ring1[j], w.perpVector(), s );
65  if ( d > 0 && d < w.length() &&
66  ring0[i+1] != ring1[j+1] && ring0[i+1] != ring1[j] &&
67  ring0[i+0] != ring1[j+1] && ring0[i+0] != ring1[j] )
68  {
69  QString msg = QObject::tr( "segment %1 of ring %2 of polygon %3 intersects segment %4 of ring %5 of polygon %6 at %7" )
70  .arg( i0 ).arg( i ).arg( p0 )
71  .arg( i1 ).arg( j ).arg( p1 )
72  .arg( s.toString() );
73  QgsDebugMsg( msg );
74  emit errorFound( QgsGeometry::Error( msg, s ) );
75  mErrorCount++;
76  }
77  }
78  }
79  }
80  }
81 }
82 
83 void QgsGeometryValidator::validatePolyline( int i, QgsPolyline line, bool ring )
84 {
85  if ( ring )
86  {
87  if ( line.size() < 4 )
88  {
89  QString msg = QObject::tr( "ring %1 with less than four points" ).arg( i );
90  QgsDebugMsg( msg );
91  emit errorFound( QgsGeometry::Error( msg ) );
92  mErrorCount++;
93  return;
94  }
95 
96  if ( line[0] != line[ line.size()-1 ] )
97  {
98  QString msg = QObject::tr( "ring %1 not closed" ).arg( i );
99  QgsDebugMsg( msg );
100  emit errorFound( QgsGeometry::Error( msg ) );
101  mErrorCount++;
102  return;
103  }
104  }
105  else if ( line.size() < 2 )
106  {
107  QString msg = QObject::tr( "line %1 with less than two points" ).arg( i );
108  QgsDebugMsg( msg );
109  emit errorFound( QgsGeometry::Error( msg ) );
110  mErrorCount++;
111  return;
112  }
113 
114  int j = 0;
115  while ( j < line.size() - 1 )
116  {
117  int n = 0;
118  while ( j < line.size() - 1 && line[j] == line[j+1] )
119  {
120  line.remove( j );
121  n++;
122  }
123 
124  if ( n > 0 )
125  {
126  QString msg = QObject::tr( "line %1 contains %n duplicate node(s) at %2", "number of duplicate nodes", n ).arg( i ).arg( j );
127  QgsDebugMsg( msg );
128  emit errorFound( QgsGeometry::Error( msg, line[j] ) );
129  mErrorCount++;
130  }
131 
132  j++;
133  }
134 
135  for ( j = 0; !mStop && j < line.size() - 3; j++ )
136  {
137  QgsVector v = line[j+1] - line[j];
138  double vl = v.length();
139 
140  int n = ( j == 0 && ring ) ? line.size() - 2 : line.size() - 1;
141 
142  for ( int k = j + 2; !mStop && k < n; k++ )
143  {
144  QgsVector w = line[k+1] - line[k];
145 
146  QgsPoint s;
147  if ( !intersectLines( line[j], v, line[k], w, s ) )
148  continue;
149 
150  double d = 0.0;
151  try
152  {
153  d = -distLine2Point( line[j], v.perpVector(), s );
154  }
155  catch ( QgsException & e )
156  {
157  Q_UNUSED( e );
158  QgsDebugMsg( "Error validating: " + e.what() );
159  continue;
160  }
161  if ( d < 0 || d > vl )
162  continue;
163 
164  try
165  {
166  d = -distLine2Point( line[k], w.perpVector(), s );
167  }
168  catch ( QgsException & e )
169  {
170  Q_UNUSED( e );
171  QgsDebugMsg( "Error validating: " + e.what() );
172  continue;
173  }
174 
175  if ( d <= 0 || d >= w.length() )
176  continue;
177 
178  QString msg = QObject::tr( "segments %1 and %2 of line %3 intersect at %4" ).arg( j ).arg( k ).arg( i ).arg( s.toString() );
179  QgsDebugMsg( msg );
180  emit errorFound( QgsGeometry::Error( msg, s ) );
181  mErrorCount++;
182  }
183  }
184 }
185 
186 void QgsGeometryValidator::validatePolygon( int idx, const QgsPolygon &polygon )
187 {
188  // check if holes are inside polygon
189  for ( int i = 1; !mStop && i < polygon.size(); i++ )
190  {
191  if ( !ringInRing( polygon[i], polygon[0] ) )
192  {
193  QString msg = QObject::tr( "ring %1 of polygon %2 not in exterior ring" ).arg( i ).arg( idx );
194  QgsDebugMsg( msg );
195  emit errorFound( QgsGeometry::Error( msg ) );
196  mErrorCount++;
197  }
198  }
199 
200  // check holes for intersections
201  for ( int i = 1; !mStop && i < polygon.size(); i++ )
202  {
203  for ( int j = i + 1; !mStop && j < polygon.size(); j++ )
204  {
205  checkRingIntersections( idx, i, polygon[i], idx, j, polygon[j] );
206  }
207  }
208 
209  // check if rings are self-intersecting
210  for ( int i = 0; !mStop && i < polygon.size(); i++ )
211  {
212  validatePolyline( i, polygon[i], true );
213  }
214 }
215 
217 {
218  mErrorCount = 0;
219  QSettings settings;
220  if ( settings.value( QStringLiteral( "/qgis/digitizing/validate_geometries" ), 1 ).toInt() == 2 )
221  {
222  char *r = nullptr;
223  GEOSGeometry *g0 = mG.exportToGeos();
224  GEOSContextHandle_t handle = QgsGeometry::getGEOSHandler();
225  if ( !g0 )
226  {
227  emit errorFound( QgsGeometry::Error( QObject::tr( "GEOS error:could not produce geometry for GEOS (check log window)" ) ) );
228  }
229  else
230  {
231  GEOSGeometry *g1 = nullptr;
232  char res = GEOSisValidDetail_r( handle, g0, GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE, &r, &g1 );
233  GEOSGeom_destroy_r( handle, g0 );
234  if ( res != 1 )
235  {
236  if ( g1 )
237  {
238  const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( handle, g1 );
239 
240  unsigned int n;
241  if ( GEOSCoordSeq_getSize_r( handle, cs, &n ) && n == 1 )
242  {
243  double x, y;
244  GEOSCoordSeq_getX_r( handle, cs, 0, &x );
245  GEOSCoordSeq_getY_r( handle, cs, 0, &y );
246  emit errorFound( QgsGeometry::Error( QObject::tr( "GEOS error:%1" ).arg( r ), QgsPoint( x, y ) ) );
247  mErrorCount++;
248  }
249 
250  GEOSGeom_destroy_r( handle, g1 );
251  }
252  else
253  {
254  emit errorFound( QgsGeometry::Error( QObject::tr( "GEOS error:%1" ).arg( r ) ) );
255  mErrorCount++;
256  }
257 
258  GEOSFree_r( handle, r );
259  }
260  }
261 
262  return;
263  }
264 
265  QgsDebugMsg( "validation thread started." );
266 
268  //if ( flatType == QgsWkbTypes::Point || flatType == QgsWkbTypes::MultiPoint )
269  // break;
270  if ( flatType == QgsWkbTypes::LineString )
271  {
272  validatePolyline( 0, mG.asPolyline() );
273  }
274  else if ( flatType == QgsWkbTypes::MultiLineString )
275  {
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, mG.asPolygon() );
283  }
284  else if ( flatType == QgsWkbTypes::MultiPolygon )
285  {
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( mG.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 }
348 
350 {
351  if ( mErrors )
352  *mErrors << e;
353 }
354 
355 void QgsGeometryValidator::validateGeometry( const QgsGeometry *g, QList<QgsGeometry::Error> &errors )
356 {
357  QgsGeometryValidator *gv = new QgsGeometryValidator( g, &errors );
358  connect( gv, SIGNAL( errorFound( QgsGeometry::Error ) ), gv, SLOT( addError( QgsGeometry::Error ) ) );
359  gv->run();
360  gv->wait();
361 }
362 
363 //
364 // distance of point q from line through p in direction v
365 // return >0 => q lies left of the line
366 // <0 => q lies right of the line
367 //
368 double QgsGeometryValidator::distLine2Point( const QgsPoint& p, QgsVector v, const QgsPoint& q )
369 {
370  if ( qgsDoubleNear( v.length(), 0 ) )
371  {
372  throw QgsException( QObject::tr( "invalid line" ) );
373  }
374 
375  return ( v.x()*( q.y() - p.y() ) - v.y()*( q.x() - p.x() ) ) / v.length();
376 }
377 
378 bool QgsGeometryValidator::intersectLines( const QgsPoint& p, QgsVector v, const QgsPoint& q, QgsVector w, QgsPoint &s )
379 {
380  double d = v.y() * w.x() - v.x() * w.y();
381 
382  if ( qgsDoubleNear( d, 0 ) )
383  return false;
384 
385  double dx = q.x() - p.x();
386  double dy = q.y() - p.y();
387  double k = ( dy * w.x() - dx * w.y() ) / d;
388 
389  s = p + v * k;
390 
391  return true;
392 }
393 
394 bool QgsGeometryValidator::pointInRing( const QgsPolyline &ring, const QgsPoint &p )
395 {
396  bool inside = false;
397  int j = ring.size() - 1;
398 
399  for ( int i = 0; !mStop && i < ring.size(); i++ )
400  {
401  if ( qgsDoubleNear( ring[i].x(), p.x() ) && qgsDoubleNear( ring[i].y(), p.y() ) )
402  return true;
403 
404  if (( ring[i].y() < p.y() && ring[j].y() >= p.y() ) ||
405  ( ring[j].y() < p.y() && ring[i].y() >= p.y() ) )
406  {
407  if ( ring[i].x() + ( p.y() - ring[i].y() ) / ( ring[j].y() - ring[i].y() )*( ring[j].x() - ring[i].x() ) <= p.x() )
408  inside = !inside;
409  }
410 
411  j = i;
412  }
413 
414  return inside;
415 }
416 
417 bool QgsGeometryValidator::ringInRing( const QgsPolyline &inside, const QgsPolyline &outside )
418 {
419  for ( int i = 0; !mStop && i < inside.size(); i++ )
420  {
421  if ( !pointInRing( outside, inside[i] ) )
422  return false;
423  }
424 
425  return true;
426 }
double y
Definition: qgspoint.h:116
#define QgsDebugMsg(str)
Definition: qgslogger.h:33
void addError(const QgsGeometry::Error &)
QgsMultiPolyline asMultiPolyline() const
Return contents of the geometry as a multi linestring if wkbType is WKBMultiLineString, otherwise an empty list.
QVector< QgsPoint > QgsPolyline
Polyline is represented as a vector of points.
Definition: qgsgeometry.h:46
QgsPolygon asPolygon() const
Return contents of the geometry as a polygon if wkbType is WKBPolygon, otherwise an empty list...
double y() const
Returns the vector&#39;s y-component.
Definition: qgspoint.cpp:73
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:78
bool qgsDoubleNear(double a, double b, double epsilon=4 *DBL_EPSILON)
Compare two doubles (but allow some difference)
Definition: qgis.h:196
QgsMultiPolygon asMultiPolygon() const
Return contents of the geometry as a multi polygon if wkbType is WKBMultiPolygon, otherwise an empty ...
GEOSGeometry * exportToGeos(double precision=0) const
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
QgsVector perpVector() const
Returns the perpendicular vector to this vector (rotated 90 degrees counter-clockwise) ...
Definition: qgspoint.cpp:78
QVector< QgsPolygon > QgsMultiPolygon
A collection of QgsPolygons that share a common collection of attributes.
Definition: qgsgeometry.h:61
QString toString() const
String representation of the point (x,y)
Definition: qgspoint.cpp:129
QVector< QgsPolyline > QgsPolygon
Polygon: first item of the list is outer ring, inner rings (if any) start from second item...
Definition: qgsgeometry.h:52
void errorFound(const QgsGeometry::Error &)
A class to represent a point.
Definition: qgspoint.h:111
A class to represent a vector.
Definition: qgspoint.h:32
double length() const
Returns the length of the vector.
Definition: qgspoint.cpp:63
static void validateGeometry(const QgsGeometry *g, QList< QgsGeometry::Error > &errors)
Validate geometry and produce a list of geometry errors.
QVector< QgsPolyline > QgsMultiPolyline
A collection of QgsPolylines that share a common collection of attributes.
Definition: qgsgeometry.h:58
QgsPolyline asPolyline() const
Return contents of the geometry as a polyline if wkbType is WKBLineString, otherwise an empty list...
QString what() const
Definition: qgsexception.h:36
static GEOSContextHandle_t getGEOSHandler()
Return GEOS context handle.
double x() const
Returns the vector&#39;s x-component.
Definition: qgspoint.cpp:68
static Type flatType(Type type)
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:366
QgsGeometryValidator(const QgsGeometry *g, QList< QgsGeometry::Error > *errors=nullptr)
Constructor.
QgsWkbTypes::Type wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.)
Defines a qgis exception class.
Definition: qgsexception.h:25
double x
Definition: qgspoint.h:115