QGIS API Documentation  3.2.0-Bonn (bc43194)
qgsgeos.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsgeos.cpp
3  -------------------------------------------------------------------
4 Date : 22 Sept 2014
5 Copyright : (C) 2014 by Marco Hugentobler
6 email : marco.hugentobler at sourcepole dot com
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 "qgsgeos.h"
17 #include "qgsabstractgeometry.h"
18 #include "qgsgeometrycollection.h"
19 #include "qgsgeometryfactory.h"
20 #include "qgslinestring.h"
21 #include "qgsmulticurve.h"
22 #include "qgsmultilinestring.h"
23 #include "qgsmultipoint.h"
24 #include "qgsmultipolygon.h"
25 #include "qgslogger.h"
26 #include "qgspolygon.h"
27 #include "qgsgeometryeditutils.h"
28 #include <limits>
29 #include <cstdio>
30 
31 #define DEFAULT_QUADRANT_SEGMENTS 8
32 
33 #define CATCH_GEOS(r) \
34  catch (GEOSException &) \
35  { \
36  return r; \
37  }
38 
39 #define CATCH_GEOS_WITH_ERRMSG(r) \
40  catch (GEOSException &e) \
41  { \
42  if ( errorMsg ) \
43  { \
44  *errorMsg = e.what(); \
45  } \
46  return r; \
47  }
48 
50 
51 static void throwGEOSException( const char *fmt, ... )
52 {
53  va_list ap;
54  char buffer[1024];
55 
56  va_start( ap, fmt );
57  vsnprintf( buffer, sizeof buffer, fmt, ap );
58  va_end( ap );
59 
60  qWarning( "GEOS exception: %s", buffer );
61  QString message = QString::fromUtf8( buffer );
62 
63 #ifdef _MSC_VER
64  // stupid stupid MSVC, *SOMETIMES* raises it's own exception if we throw GEOSException, resulting in a crash!
65  // see https://issues.qgis.org/issues/14752
66  // if you want to test alternative fixes for this, run the testqgsexpression.cpp test suite - that will crash
67  // and burn on the "line_interpolate_point point" test if a GEOSException is thrown.
68  // TODO - find a real fix for the underlying issue
69  try
70  {
71  throw GEOSException( message );
72  }
73  catch ( ... )
74  {
75  // oops, msvc threw an exception when we tried to throw the exception!
76  // just throw nothing instead (except your mouse at your monitor)
77  }
78 #else
79  throw GEOSException( message );
80 #endif
81 }
82 
83 
84 static void printGEOSNotice( const char *fmt, ... )
85 {
86 #if defined(QGISDEBUG)
87  va_list ap;
88  char buffer[1024];
89 
90  va_start( ap, fmt );
91  vsnprintf( buffer, sizeof buffer, fmt, ap );
92  va_end( ap );
93 
94  QgsDebugMsg( QString( "GEOS notice: %1" ).arg( QString::fromUtf8( buffer ) ) );
95 #else
96  Q_UNUSED( fmt );
97 #endif
98 }
99 
100 class GEOSInit
101 {
102  public:
103  GEOSContextHandle_t ctxt;
104 
105  GEOSInit()
106  {
107  ctxt = initGEOS_r( printGEOSNotice, throwGEOSException );
108  }
109 
110  ~GEOSInit()
111  {
112  finishGEOS_r( ctxt );
113  }
114 
115  GEOSInit( const GEOSInit &rh ) = delete;
116  GEOSInit &operator=( const GEOSInit &rh ) = delete;
117 };
118 
119 static GEOSInit geosinit;
120 
121 void geos::GeosDeleter::operator()( GEOSGeometry *geom )
122 {
123  GEOSGeom_destroy_r( geosinit.ctxt, geom );
124 }
125 
126 void geos::GeosDeleter::operator()( const GEOSPreparedGeometry *geom )
127 {
128  GEOSPreparedGeom_destroy_r( geosinit.ctxt, geom );
129 }
130 
131 void geos::GeosDeleter::operator()( GEOSBufferParams *params )
132 {
133  GEOSBufferParams_destroy_r( geosinit.ctxt, params );
134 }
135 
136 void geos::GeosDeleter::operator()( GEOSCoordSequence *sequence )
137 {
138  GEOSCoordSeq_destroy_r( geosinit.ctxt, sequence );
139 }
140 
141 
143 
144 
145 QgsGeos::QgsGeos( const QgsAbstractGeometry *geometry, double precision )
146  : QgsGeometryEngine( geometry )
147  , mGeos( nullptr )
148  , mPrecision( precision )
149 {
150  cacheGeos();
151 }
152 
154 {
155  QgsGeometry g( QgsGeos::fromGeos( geos ) );
156  GEOSGeom_destroy_r( QgsGeos::getGEOSHandler(), geos );
157  return g;
158 }
159 
161 {
162  QgsGeometry g( QgsGeos::fromGeos( geos.get() ) );
163  return g;
164 }
165 
166 geos::unique_ptr QgsGeos::asGeos( const QgsGeometry &geometry, double precision )
167 {
168  if ( geometry.isNull() )
169  {
170  return nullptr;
171  }
172 
173  return asGeos( geometry.constGet(), precision );
174 }
175 
176 QgsGeometry::OperationResult QgsGeos::addPart( QgsGeometry &geometry, GEOSGeometry *newPart )
177 {
178  if ( geometry.isNull() )
179  {
181  }
182  if ( !newPart )
183  {
185  }
186 
187  std::unique_ptr< QgsAbstractGeometry > geom = fromGeos( newPart );
188  return QgsGeometryEditUtils::addPart( geometry.get(), std::move( geom ) );
189 }
190 
192 {
193  mGeos.reset();
194  mGeosPrepared.reset();
195  cacheGeos();
196 }
197 
199 {
200  mGeosPrepared.reset();
201  if ( mGeos )
202  {
203  mGeosPrepared.reset( GEOSPrepare_r( geosinit.ctxt, mGeos.get() ) );
204  }
205 }
206 
207 void QgsGeos::cacheGeos() const
208 {
209  if ( !mGeometry )
210  {
211  return;
212  }
213 
214  mGeos = asGeos( mGeometry, mPrecision );
215 }
216 
217 QgsAbstractGeometry *QgsGeos::intersection( const QgsAbstractGeometry *geom, QString *errorMsg ) const
218 {
219  return overlay( geom, OverlayIntersection, errorMsg ).release();
220 }
221 
222 QgsAbstractGeometry *QgsGeos::difference( const QgsAbstractGeometry *geom, QString *errorMsg ) const
223 {
224  return overlay( geom, OverlayDifference, errorMsg ).release();
225 }
226 
227 std::unique_ptr<QgsAbstractGeometry> QgsGeos::clip( const QgsRectangle &rect, QString *errorMsg ) const
228 {
229  if ( !mGeos || rect.isNull() || rect.isEmpty() )
230  {
231  return nullptr;
232  }
233 
234  try
235  {
236  geos::unique_ptr opGeom( GEOSClipByRect_r( geosinit.ctxt, mGeos.get(), rect.xMinimum(), rect.yMinimum(), rect.xMaximum(), rect.yMaximum() ) );
237  return fromGeos( opGeom.get() );
238  }
239  catch ( GEOSException &e )
240  {
241  if ( errorMsg )
242  {
243  *errorMsg = e.what();
244  }
245  return nullptr;
246  }
247 }
248 
249 
250 
251 
252 void QgsGeos::subdivideRecursive( const GEOSGeometry *currentPart, int maxNodes, int depth, QgsGeometryCollection *parts, const QgsRectangle &clipRect ) const
253 {
254  int partType = GEOSGeomTypeId_r( geosinit.ctxt, currentPart );
255  if ( qgsDoubleNear( clipRect.width(), 0.0 ) && qgsDoubleNear( clipRect.height(), 0.0 ) )
256  {
257  if ( partType == GEOS_POINT )
258  {
259  parts->addGeometry( fromGeos( currentPart ).release() );
260  return;
261  }
262  else
263  {
264  return;
265  }
266  }
267 
268  if ( partType == GEOS_MULTILINESTRING || partType == GEOS_MULTIPOLYGON || partType == GEOS_GEOMETRYCOLLECTION )
269  {
270  int partCount = GEOSGetNumGeometries_r( geosinit.ctxt, currentPart );
271  for ( int i = 0; i < partCount; ++i )
272  {
273  subdivideRecursive( GEOSGetGeometryN_r( geosinit.ctxt, currentPart, i ), maxNodes, depth, parts, clipRect );
274  }
275  return;
276  }
277 
278  if ( depth > 50 )
279  {
280  parts->addGeometry( fromGeos( currentPart ).release() );
281  return;
282  }
283 
284  int vertexCount = GEOSGetNumCoordinates_r( geosinit.ctxt, currentPart );
285  if ( vertexCount == 0 )
286  {
287  return;
288  }
289  else if ( vertexCount < maxNodes )
290  {
291  parts->addGeometry( fromGeos( currentPart ).release() );
292  return;
293  }
294 
295  // chop clipping rect in half by longest side
296  double width = clipRect.width();
297  double height = clipRect.height();
298  QgsRectangle halfClipRect1 = clipRect;
299  QgsRectangle halfClipRect2 = clipRect;
300  if ( width > height )
301  {
302  halfClipRect1.setXMaximum( clipRect.xMinimum() + width / 2.0 );
303  halfClipRect2.setXMinimum( halfClipRect1.xMaximum() );
304  }
305  else
306  {
307  halfClipRect1.setYMaximum( clipRect.yMinimum() + height / 2.0 );
308  halfClipRect2.setYMinimum( halfClipRect1.yMaximum() );
309  }
310 
311  if ( height <= 0 )
312  {
313  halfClipRect1.setYMinimum( halfClipRect1.yMinimum() - std::numeric_limits<double>::epsilon() );
314  halfClipRect2.setYMinimum( halfClipRect2.yMinimum() - std::numeric_limits<double>::epsilon() );
315  halfClipRect1.setYMaximum( halfClipRect1.yMaximum() + std::numeric_limits<double>::epsilon() );
316  halfClipRect2.setYMaximum( halfClipRect2.yMaximum() + std::numeric_limits<double>::epsilon() );
317  }
318  if ( width <= 0 )
319  {
320  halfClipRect1.setXMinimum( halfClipRect1.xMinimum() - std::numeric_limits<double>::epsilon() );
321  halfClipRect2.setXMinimum( halfClipRect2.xMinimum() - std::numeric_limits<double>::epsilon() );
322  halfClipRect1.setXMaximum( halfClipRect1.xMaximum() + std::numeric_limits<double>::epsilon() );
323  halfClipRect2.setXMaximum( halfClipRect2.xMaximum() + std::numeric_limits<double>::epsilon() );
324  }
325 
326  geos::unique_ptr clipPart1( GEOSClipByRect_r( geosinit.ctxt, currentPart, halfClipRect1.xMinimum(), halfClipRect1.yMinimum(), halfClipRect1.xMaximum(), halfClipRect1.yMaximum() ) );
327  geos::unique_ptr clipPart2( GEOSClipByRect_r( geosinit.ctxt, currentPart, halfClipRect2.xMinimum(), halfClipRect2.yMinimum(), halfClipRect2.xMaximum(), halfClipRect2.yMaximum() ) );
328 
329  ++depth;
330 
331  if ( clipPart1 )
332  {
333  subdivideRecursive( clipPart1.get(), maxNodes, depth, parts, halfClipRect1 );
334  }
335  if ( clipPart2 )
336  {
337  subdivideRecursive( clipPart2.get(), maxNodes, depth, parts, halfClipRect2 );
338  }
339 }
340 
341 std::unique_ptr<QgsAbstractGeometry> QgsGeos::subdivide( int maxNodes, QString *errorMsg ) const
342 {
343  if ( !mGeos )
344  {
345  return nullptr;
346  }
347 
348  // minimum allowed max is 8
349  maxNodes = std::max( maxNodes, 8 );
350 
351  std::unique_ptr< QgsGeometryCollection > parts = QgsGeometryFactory::createCollectionOfType( mGeometry->wkbType() );
352  try
353  {
354  subdivideRecursive( mGeos.get(), maxNodes, 0, parts.get(), mGeometry->boundingBox() );
355  }
356  CATCH_GEOS_WITH_ERRMSG( nullptr )
357 
358  return std::move( parts );
359 }
360 
361 QgsAbstractGeometry *QgsGeos::combine( const QgsAbstractGeometry *geom, QString *errorMsg ) const
362 {
363  return overlay( geom, OverlayUnion, errorMsg ).release();
364 }
365 
366 QgsAbstractGeometry *QgsGeos::combine( const QVector<QgsAbstractGeometry *> &geomList, QString *errorMsg ) const
367 {
368  QVector< GEOSGeometry * > geosGeometries;
369  geosGeometries.reserve( geomList.size() );
370  for ( const QgsAbstractGeometry *g : geomList )
371  {
372  if ( !g )
373  continue;
374 
375  geosGeometries << asGeos( g, mPrecision ).release();
376  }
377 
378  geos::unique_ptr geomUnion;
379  try
380  {
381  geos::unique_ptr geomCollection = createGeosCollection( GEOS_GEOMETRYCOLLECTION, geosGeometries );
382  geomUnion.reset( GEOSUnaryUnion_r( geosinit.ctxt, geomCollection.get() ) );
383  }
384  CATCH_GEOS_WITH_ERRMSG( nullptr )
385 
386  std::unique_ptr< QgsAbstractGeometry > result = fromGeos( geomUnion.get() );
387  return result.release();
388 }
389 
390 QgsAbstractGeometry *QgsGeos::combine( const QVector<QgsGeometry> &geomList, QString *errorMsg ) const
391 {
392  QVector< GEOSGeometry * > geosGeometries;
393  geosGeometries.reserve( geomList.size() );
394  for ( const QgsGeometry &g : geomList )
395  {
396  if ( !g )
397  continue;
398 
399  geosGeometries << asGeos( g.constGet(), mPrecision ).release();
400  }
401 
402  geos::unique_ptr geomUnion;
403  try
404  {
405  geos::unique_ptr geomCollection = createGeosCollection( GEOS_GEOMETRYCOLLECTION, geosGeometries );
406  geomUnion.reset( GEOSUnaryUnion_r( geosinit.ctxt, geomCollection.get() ) );
407  }
408  CATCH_GEOS_WITH_ERRMSG( nullptr )
409 
410  std::unique_ptr< QgsAbstractGeometry > result = fromGeos( geomUnion.get() );
411  return result.release();
412 }
413 
414 QgsAbstractGeometry *QgsGeos::symDifference( const QgsAbstractGeometry *geom, QString *errorMsg ) const
415 {
416  return overlay( geom, OverlaySymDifference, errorMsg ).release();
417 }
418 
419 double QgsGeos::distance( const QgsAbstractGeometry *geom, QString *errorMsg ) const
420 {
421  double distance = -1.0;
422  if ( !mGeos )
423  {
424  return distance;
425  }
426 
427  geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
428  if ( !otherGeosGeom )
429  {
430  return distance;
431  }
432 
433  try
434  {
435  GEOSDistance_r( geosinit.ctxt, mGeos.get(), otherGeosGeom.get(), &distance );
436  }
437  CATCH_GEOS_WITH_ERRMSG( -1.0 )
438 
439  return distance;
440 }
441 
442 double QgsGeos::hausdorffDistance( const QgsAbstractGeometry *geom, QString *errorMsg ) const
443 {
444  double distance = -1.0;
445  if ( !mGeos )
446  {
447  return distance;
448  }
449 
450  geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
451  if ( !otherGeosGeom )
452  {
453  return distance;
454  }
455 
456  try
457  {
458  GEOSHausdorffDistance_r( geosinit.ctxt, mGeos.get(), otherGeosGeom.get(), &distance );
459  }
460  CATCH_GEOS_WITH_ERRMSG( -1.0 )
461 
462  return distance;
463 }
464 
465 double QgsGeos::hausdorffDistanceDensify( const QgsAbstractGeometry *geom, double densifyFraction, QString *errorMsg ) const
466 {
467  double distance = -1.0;
468  if ( !mGeos )
469  {
470  return distance;
471  }
472 
473  geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
474  if ( !otherGeosGeom )
475  {
476  return distance;
477  }
478 
479  try
480  {
481  GEOSHausdorffDistanceDensify_r( geosinit.ctxt, mGeos.get(), otherGeosGeom.get(), densifyFraction, &distance );
482  }
483  CATCH_GEOS_WITH_ERRMSG( -1.0 )
484 
485  return distance;
486 }
487 
488 bool QgsGeos::intersects( const QgsAbstractGeometry *geom, QString *errorMsg ) const
489 {
490  return relation( geom, RelationIntersects, errorMsg );
491 }
492 
493 bool QgsGeos::touches( const QgsAbstractGeometry *geom, QString *errorMsg ) const
494 {
495  return relation( geom, RelationTouches, errorMsg );
496 }
497 
498 bool QgsGeos::crosses( const QgsAbstractGeometry *geom, QString *errorMsg ) const
499 {
500  return relation( geom, RelationCrosses, errorMsg );
501 }
502 
503 bool QgsGeos::within( const QgsAbstractGeometry *geom, QString *errorMsg ) const
504 {
505  return relation( geom, RelationWithin, errorMsg );
506 }
507 
508 bool QgsGeos::overlaps( const QgsAbstractGeometry *geom, QString *errorMsg ) const
509 {
510  return relation( geom, RelationOverlaps, errorMsg );
511 }
512 
513 bool QgsGeos::contains( const QgsAbstractGeometry *geom, QString *errorMsg ) const
514 {
515  return relation( geom, RelationContains, errorMsg );
516 }
517 
518 bool QgsGeos::disjoint( const QgsAbstractGeometry *geom, QString *errorMsg ) const
519 {
520  return relation( geom, RelationDisjoint, errorMsg );
521 }
522 
523 QString QgsGeos::relate( const QgsAbstractGeometry *geom, QString *errorMsg ) const
524 {
525  if ( !mGeos )
526  {
527  return QString();
528  }
529 
530  geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
531  if ( !geosGeom )
532  {
533  return QString();
534  }
535 
536  QString result;
537  try
538  {
539  char *r = GEOSRelate_r( geosinit.ctxt, mGeos.get(), geosGeom.get() );
540  if ( r )
541  {
542  result = QString( r );
543  GEOSFree_r( geosinit.ctxt, r );
544  }
545  }
546  catch ( GEOSException &e )
547  {
548  if ( errorMsg )
549  {
550  *errorMsg = e.what();
551  }
552  }
553 
554  return result;
555 }
556 
557 bool QgsGeos::relatePattern( const QgsAbstractGeometry *geom, const QString &pattern, QString *errorMsg ) const
558 {
559  if ( !mGeos || !geom )
560  {
561  return false;
562  }
563 
564  geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
565  if ( !geosGeom )
566  {
567  return false;
568  }
569 
570  bool result = false;
571  try
572  {
573  result = ( GEOSRelatePattern_r( geosinit.ctxt, mGeos.get(), geosGeom.get(), pattern.toLocal8Bit().constData() ) == 1 );
574  }
575  catch ( GEOSException &e )
576  {
577  if ( errorMsg )
578  {
579  *errorMsg = e.what();
580  }
581  }
582 
583  return result;
584 }
585 
586 double QgsGeos::area( QString *errorMsg ) const
587 {
588  double area = -1.0;
589  if ( !mGeos )
590  {
591  return area;
592  }
593 
594  try
595  {
596  if ( GEOSArea_r( geosinit.ctxt, mGeos.get(), &area ) != 1 )
597  return -1.0;
598  }
599  CATCH_GEOS_WITH_ERRMSG( -1.0 );
600  return area;
601 }
602 
603 double QgsGeos::length( QString *errorMsg ) const
604 {
605  double length = -1.0;
606  if ( !mGeos )
607  {
608  return length;
609  }
610  try
611  {
612  if ( GEOSLength_r( geosinit.ctxt, mGeos.get(), &length ) != 1 )
613  return -1.0;
614  }
615  CATCH_GEOS_WITH_ERRMSG( -1.0 )
616  return length;
617 }
618 
620  QVector<QgsGeometry> &newGeometries,
621  bool topological,
622  QgsPointSequence &topologyTestPoints,
623  QString *errorMsg ) const
624 {
625 
626  EngineOperationResult returnCode = Success;
627  if ( !mGeos || !mGeometry )
628  {
629  return InvalidBaseGeometry;
630  }
631 
632  //return if this type is point/multipoint
633  if ( mGeometry->dimension() == 0 )
634  {
635  return SplitCannotSplitPoint; //cannot split points
636  }
637 
638  if ( !GEOSisValid_r( geosinit.ctxt, mGeos.get() ) )
639  return InvalidBaseGeometry;
640 
641  //make sure splitLine is valid
642  if ( ( mGeometry->dimension() == 1 && splitLine.numPoints() < 1 ) ||
643  ( mGeometry->dimension() == 2 && splitLine.numPoints() < 2 ) )
644  return InvalidInput;
645 
646  newGeometries.clear();
647  geos::unique_ptr splitLineGeos;
648 
649  try
650  {
651  if ( splitLine.numPoints() > 1 )
652  {
653  splitLineGeos = createGeosLinestring( &splitLine, mPrecision );
654  }
655  else if ( splitLine.numPoints() == 1 )
656  {
657  splitLineGeos = createGeosPointXY( splitLine.xAt( 0 ), splitLine.yAt( 0 ), false, 0, false, 0, 2, mPrecision );
658  }
659  else
660  {
661  return InvalidInput;
662  }
663 
664  if ( !GEOSisValid_r( geosinit.ctxt, splitLineGeos.get() ) || !GEOSisSimple_r( geosinit.ctxt, splitLineGeos.get() ) )
665  {
666  return InvalidInput;
667  }
668 
669  if ( topological )
670  {
671  //find out candidate points for topological corrections
672  if ( !topologicalTestPointsSplit( splitLineGeos.get(), topologyTestPoints ) )
673  {
674  return InvalidInput; // TODO: is it really an invalid input?
675  }
676  }
677 
678  //call split function depending on geometry type
679  if ( mGeometry->dimension() == 1 )
680  {
681  returnCode = splitLinearGeometry( splitLineGeos.get(), newGeometries );
682  }
683  else if ( mGeometry->dimension() == 2 )
684  {
685  returnCode = splitPolygonGeometry( splitLineGeos.get(), newGeometries );
686  }
687  else
688  {
689  return InvalidInput;
690  }
691  }
693 
694  return returnCode;
695 }
696 
697 
698 
699 bool QgsGeos::topologicalTestPointsSplit( const GEOSGeometry *splitLine, QgsPointSequence &testPoints, QString *errorMsg ) const
700 {
701  //Find out the intersection points between splitLineGeos and this geometry.
702  //These points need to be tested for topological correctness by the calling function
703  //if topological editing is enabled
704 
705  if ( !mGeos )
706  {
707  return false;
708  }
709 
710  try
711  {
712  testPoints.clear();
713  geos::unique_ptr intersectionGeom( GEOSIntersection_r( geosinit.ctxt, mGeos.get(), splitLine ) );
714  if ( !intersectionGeom )
715  return false;
716 
717  bool simple = false;
718  int nIntersectGeoms = 1;
719  if ( GEOSGeomTypeId_r( geosinit.ctxt, intersectionGeom.get() ) == GEOS_LINESTRING
720  || GEOSGeomTypeId_r( geosinit.ctxt, intersectionGeom.get() ) == GEOS_POINT )
721  simple = true;
722 
723  if ( !simple )
724  nIntersectGeoms = GEOSGetNumGeometries_r( geosinit.ctxt, intersectionGeom.get() );
725 
726  for ( int i = 0; i < nIntersectGeoms; ++i )
727  {
728  const GEOSGeometry *currentIntersectGeom = nullptr;
729  if ( simple )
730  currentIntersectGeom = intersectionGeom.get();
731  else
732  currentIntersectGeom = GEOSGetGeometryN_r( geosinit.ctxt, intersectionGeom.get(), i );
733 
734  const GEOSCoordSequence *lineSequence = GEOSGeom_getCoordSeq_r( geosinit.ctxt, currentIntersectGeom );
735  unsigned int sequenceSize = 0;
736  double x, y;
737  if ( GEOSCoordSeq_getSize_r( geosinit.ctxt, lineSequence, &sequenceSize ) != 0 )
738  {
739  for ( unsigned int i = 0; i < sequenceSize; ++i )
740  {
741  if ( GEOSCoordSeq_getX_r( geosinit.ctxt, lineSequence, i, &x ) != 0 )
742  {
743  if ( GEOSCoordSeq_getY_r( geosinit.ctxt, lineSequence, i, &y ) != 0 )
744  {
745  testPoints.push_back( QgsPoint( x, y ) );
746  }
747  }
748  }
749  }
750  }
751  }
752  CATCH_GEOS_WITH_ERRMSG( true )
753 
754  return true;
755 }
756 
757 geos::unique_ptr QgsGeos::linePointDifference( GEOSGeometry *GEOSsplitPoint ) const
758 {
759  int type = GEOSGeomTypeId_r( geosinit.ctxt, mGeos.get() );
760 
761  std::unique_ptr< QgsMultiCurve > multiCurve;
762  if ( type == GEOS_MULTILINESTRING )
763  {
764  multiCurve.reset( qgsgeometry_cast<QgsMultiCurve *>( mGeometry->clone() ) );
765  }
766  else if ( type == GEOS_LINESTRING )
767  {
768  multiCurve.reset( new QgsMultiCurve() );
769  multiCurve->addGeometry( mGeometry->clone() );
770  }
771  else
772  {
773  return nullptr;
774  }
775 
776  if ( !multiCurve )
777  {
778  return nullptr;
779  }
780 
781 
782  std::unique_ptr< QgsAbstractGeometry > splitGeom( fromGeos( GEOSsplitPoint ) );
783  QgsPoint *splitPoint = qgsgeometry_cast<QgsPoint *>( splitGeom.get() );
784  if ( !splitPoint )
785  {
786  return nullptr;
787  }
788 
789  QgsMultiCurve lines;
790 
791  //For each part
792  for ( int i = 0; i < multiCurve->numGeometries(); ++i )
793  {
794  const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( multiCurve->geometryN( i ) );
795  if ( line )
796  {
797  //For each segment
798  QgsLineString newLine;
799  newLine.addVertex( line->pointN( 0 ) );
800  int nVertices = line->numPoints();
801  for ( int j = 1; j < ( nVertices - 1 ); ++j )
802  {
803  QgsPoint currentPoint = line->pointN( j );
804  newLine.addVertex( currentPoint );
805  if ( currentPoint == *splitPoint )
806  {
807  lines.addGeometry( newLine.clone() );
808  newLine = QgsLineString();
809  newLine.addVertex( currentPoint );
810  }
811  }
812  newLine.addVertex( line->pointN( nVertices - 1 ) );
813  lines.addGeometry( newLine.clone() );
814  }
815  }
816 
817  return asGeos( &lines, mPrecision );
818 }
819 
820 QgsGeometryEngine::EngineOperationResult QgsGeos::splitLinearGeometry( GEOSGeometry *splitLine, QVector<QgsGeometry> &newGeometries ) const
821 {
822  if ( !splitLine )
823  return InvalidInput;
824 
825  if ( !mGeos )
826  return InvalidBaseGeometry;
827 
828  //first test if linestring intersects geometry. If not, return straight away
829  if ( !GEOSIntersects_r( geosinit.ctxt, splitLine, mGeos.get() ) )
830  return NothingHappened;
831 
832  //check that split line has no linear intersection
833  int linearIntersect = GEOSRelatePattern_r( geosinit.ctxt, mGeos.get(), splitLine, "1********" );
834  if ( linearIntersect > 0 )
835  return InvalidInput;
836 
837  int splitGeomType = GEOSGeomTypeId_r( geosinit.ctxt, splitLine );
838 
839  geos::unique_ptr splitGeom;
840  if ( splitGeomType == GEOS_POINT )
841  {
842  splitGeom = linePointDifference( splitLine );
843  }
844  else
845  {
846  splitGeom.reset( GEOSDifference_r( geosinit.ctxt, mGeos.get(), splitLine ) );
847  }
848  QVector<GEOSGeometry *> lineGeoms;
849 
850  int splitType = GEOSGeomTypeId_r( geosinit.ctxt, splitGeom.get() );
851  if ( splitType == GEOS_MULTILINESTRING )
852  {
853  int nGeoms = GEOSGetNumGeometries_r( geosinit.ctxt, splitGeom.get() );
854  lineGeoms.reserve( nGeoms );
855  for ( int i = 0; i < nGeoms; ++i )
856  lineGeoms << GEOSGeom_clone_r( geosinit.ctxt, GEOSGetGeometryN_r( geosinit.ctxt, splitGeom.get(), i ) );
857 
858  }
859  else
860  {
861  lineGeoms << GEOSGeom_clone_r( geosinit.ctxt, splitGeom.get() );
862  }
863 
864  mergeGeometriesMultiTypeSplit( lineGeoms );
865 
866  for ( int i = 0; i < lineGeoms.size(); ++i )
867  {
868  newGeometries << QgsGeometry( fromGeos( lineGeoms[i] ) );
869  GEOSGeom_destroy_r( geosinit.ctxt, lineGeoms[i] );
870  }
871 
872  return Success;
873 }
874 
875 QgsGeometryEngine::EngineOperationResult QgsGeos::splitPolygonGeometry( GEOSGeometry *splitLine, QVector<QgsGeometry> &newGeometries ) const
876 {
877  if ( !splitLine )
878  return InvalidInput;
879 
880  if ( !mGeos )
881  return InvalidBaseGeometry;
882 
883  //first test if linestring intersects geometry. If not, return straight away
884  if ( !GEOSIntersects_r( geosinit.ctxt, splitLine, mGeos.get() ) )
885  return NothingHappened;
886 
887  //first union all the polygon rings together (to get them noded, see JTS developer guide)
888  geos::unique_ptr nodedGeometry = nodeGeometries( splitLine, mGeos.get() );
889  if ( !nodedGeometry )
890  return NodedGeometryError; //an error occurred during noding
891 
892  const GEOSGeometry *noded = nodedGeometry.get();
893  geos::unique_ptr polygons( GEOSPolygonize_r( geosinit.ctxt, &noded, 1 ) );
894  if ( !polygons || numberOfGeometries( polygons.get() ) == 0 )
895  {
896  return InvalidBaseGeometry;
897  }
898 
899  //test every polygon if contained in original geometry
900  //include in result if yes
901  QVector<GEOSGeometry *> testedGeometries;
902  geos::unique_ptr intersectGeometry;
903 
904  //ratio intersect geometry / geometry. This should be close to 1
905  //if the polygon belongs to the input geometry
906 
907  for ( int i = 0; i < numberOfGeometries( polygons.get() ); i++ )
908  {
909  const GEOSGeometry *polygon = GEOSGetGeometryN_r( geosinit.ctxt, polygons.get(), i );
910  intersectGeometry.reset( GEOSIntersection_r( geosinit.ctxt, mGeos.get(), polygon ) );
911  if ( !intersectGeometry )
912  {
913  QgsDebugMsg( "intersectGeometry is nullptr" );
914  continue;
915  }
916 
917  double intersectionArea;
918  GEOSArea_r( geosinit.ctxt, intersectGeometry.get(), &intersectionArea );
919 
920  double polygonArea;
921  GEOSArea_r( geosinit.ctxt, polygon, &polygonArea );
922 
923  const double areaRatio = intersectionArea / polygonArea;
924  if ( areaRatio > 0.99 && areaRatio < 1.01 )
925  testedGeometries << GEOSGeom_clone_r( geosinit.ctxt, polygon );
926  }
927 
928  int nGeometriesThis = numberOfGeometries( mGeos.get() ); //original number of geometries
929  if ( testedGeometries.empty() || testedGeometries.size() == nGeometriesThis )
930  {
931  //no split done, preserve original geometry
932  for ( int i = 0; i < testedGeometries.size(); ++i )
933  {
934  GEOSGeom_destroy_r( geosinit.ctxt, testedGeometries[i] );
935  }
936  return NothingHappened;
937  }
938 
939  mergeGeometriesMultiTypeSplit( testedGeometries );
940 
941  int i;
942  for ( i = 0; i < testedGeometries.size() && GEOSisValid_r( geosinit.ctxt, testedGeometries[i] ); ++i )
943  ;
944 
945  if ( i < testedGeometries.size() )
946  {
947  for ( i = 0; i < testedGeometries.size(); ++i )
948  GEOSGeom_destroy_r( geosinit.ctxt, testedGeometries[i] );
949 
950  return InvalidBaseGeometry;
951  }
952 
953  for ( i = 0; i < testedGeometries.size(); ++i )
954  {
955  newGeometries << QgsGeometry( fromGeos( testedGeometries[i] ) );
956  GEOSGeom_destroy_r( geosinit.ctxt, testedGeometries[i] );
957  }
958 
959  return Success;
960 }
961 
962 geos::unique_ptr QgsGeos::nodeGeometries( const GEOSGeometry *splitLine, const GEOSGeometry *geom )
963 {
964  if ( !splitLine || !geom )
965  return nullptr;
966 
967  geos::unique_ptr geometryBoundary;
968  if ( GEOSGeomTypeId_r( geosinit.ctxt, geom ) == GEOS_POLYGON || GEOSGeomTypeId_r( geosinit.ctxt, geom ) == GEOS_MULTIPOLYGON )
969  geometryBoundary.reset( GEOSBoundary_r( geosinit.ctxt, geom ) );
970  else
971  geometryBoundary.reset( GEOSGeom_clone_r( geosinit.ctxt, geom ) );
972 
973  geos::unique_ptr splitLineClone( GEOSGeom_clone_r( geosinit.ctxt, splitLine ) );
974  geos::unique_ptr unionGeometry( GEOSUnion_r( geosinit.ctxt, splitLineClone.get(), geometryBoundary.get() ) );
975 
976  return unionGeometry;
977 }
978 
979 int QgsGeos::mergeGeometriesMultiTypeSplit( QVector<GEOSGeometry *> &splitResult ) const
980 {
981  if ( !mGeos )
982  return 1;
983 
984  //convert mGeos to geometry collection
985  int type = GEOSGeomTypeId_r( geosinit.ctxt, mGeos.get() );
986  if ( type != GEOS_GEOMETRYCOLLECTION &&
987  type != GEOS_MULTILINESTRING &&
988  type != GEOS_MULTIPOLYGON &&
989  type != GEOS_MULTIPOINT )
990  return 0;
991 
992  QVector<GEOSGeometry *> copyList = splitResult;
993  splitResult.clear();
994 
995  //collect all the geometries that belong to the initial multifeature
996  QVector<GEOSGeometry *> unionGeom;
997 
998  for ( int i = 0; i < copyList.size(); ++i )
999  {
1000  //is this geometry a part of the original multitype?
1001  bool isPart = false;
1002  for ( int j = 0; j < GEOSGetNumGeometries_r( geosinit.ctxt, mGeos.get() ); j++ )
1003  {
1004  if ( GEOSEquals_r( geosinit.ctxt, copyList[i], GEOSGetGeometryN_r( geosinit.ctxt, mGeos.get(), j ) ) )
1005  {
1006  isPart = true;
1007  break;
1008  }
1009  }
1010 
1011  if ( isPart )
1012  {
1013  unionGeom << copyList[i];
1014  }
1015  else
1016  {
1017  QVector<GEOSGeometry *> geomVector;
1018  geomVector << copyList[i];
1019 
1020  if ( type == GEOS_MULTILINESTRING )
1021  splitResult << createGeosCollection( GEOS_MULTILINESTRING, geomVector ).release();
1022  else if ( type == GEOS_MULTIPOLYGON )
1023  splitResult << createGeosCollection( GEOS_MULTIPOLYGON, geomVector ).release();
1024  else
1025  GEOSGeom_destroy_r( geosinit.ctxt, copyList[i] );
1026  }
1027  }
1028 
1029  //make multifeature out of unionGeom
1030  if ( !unionGeom.isEmpty() )
1031  {
1032  if ( type == GEOS_MULTILINESTRING )
1033  splitResult << createGeosCollection( GEOS_MULTILINESTRING, unionGeom ).release();
1034  else if ( type == GEOS_MULTIPOLYGON )
1035  splitResult << createGeosCollection( GEOS_MULTIPOLYGON, unionGeom ).release();
1036  }
1037  else
1038  {
1039  unionGeom.clear();
1040  }
1041 
1042  return 0;
1043 }
1044 
1045 geos::unique_ptr QgsGeos::createGeosCollection( int typeId, const QVector<GEOSGeometry *> &geoms )
1046 {
1047  int nNullGeoms = geoms.count( nullptr );
1048  int nNotNullGeoms = geoms.size() - nNullGeoms;
1049 
1050  GEOSGeometry **geomarr = new GEOSGeometry*[ nNotNullGeoms ];
1051  if ( !geomarr )
1052  {
1053  return nullptr;
1054  }
1055 
1056  int i = 0;
1057  QVector<GEOSGeometry *>::const_iterator geomIt = geoms.constBegin();
1058  for ( ; geomIt != geoms.constEnd(); ++geomIt )
1059  {
1060  if ( *geomIt )
1061  {
1062  geomarr[i] = *geomIt;
1063  ++i;
1064  }
1065  }
1066  geos::unique_ptr geom;
1067 
1068  try
1069  {
1070  geom.reset( GEOSGeom_createCollection_r( geosinit.ctxt, typeId, geomarr, nNotNullGeoms ) );
1071  }
1072  catch ( GEOSException & )
1073  {
1074  }
1075 
1076  delete [] geomarr;
1077 
1078  return geom;
1079 }
1080 
1081 std::unique_ptr<QgsAbstractGeometry> QgsGeos::fromGeos( const GEOSGeometry *geos )
1082 {
1083  if ( !geos )
1084  {
1085  return nullptr;
1086  }
1087 
1088  int nCoordDims = GEOSGeom_getCoordinateDimension_r( geosinit.ctxt, geos );
1089  int nDims = GEOSGeom_getDimensions_r( geosinit.ctxt, geos );
1090  bool hasZ = ( nCoordDims == 3 );
1091  bool hasM = ( ( nDims - nCoordDims ) == 1 );
1092 
1093  switch ( GEOSGeomTypeId_r( geosinit.ctxt, geos ) )
1094  {
1095  case GEOS_POINT: // a point
1096  {
1097  const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, geos );
1098  return std::unique_ptr<QgsAbstractGeometry>( coordSeqPoint( cs, 0, hasZ, hasM ).clone() );
1099  }
1100  case GEOS_LINESTRING:
1101  {
1102  return sequenceToLinestring( geos, hasZ, hasM );
1103  }
1104  case GEOS_POLYGON:
1105  {
1106  return fromGeosPolygon( geos );
1107  }
1108  case GEOS_MULTIPOINT:
1109  {
1110  std::unique_ptr< QgsMultiPoint > multiPoint( new QgsMultiPoint() );
1111  int nParts = GEOSGetNumGeometries_r( geosinit.ctxt, geos );
1112  for ( int i = 0; i < nParts; ++i )
1113  {
1114  const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, GEOSGetGeometryN_r( geosinit.ctxt, geos, i ) );
1115  if ( cs )
1116  {
1117  multiPoint->addGeometry( coordSeqPoint( cs, 0, hasZ, hasM ).clone() );
1118  }
1119  }
1120  return std::move( multiPoint );
1121  }
1122  case GEOS_MULTILINESTRING:
1123  {
1124  std::unique_ptr< QgsMultiLineString > multiLineString( new QgsMultiLineString() );
1125  int nParts = GEOSGetNumGeometries_r( geosinit.ctxt, geos );
1126  for ( int i = 0; i < nParts; ++i )
1127  {
1128  std::unique_ptr< QgsLineString >line( sequenceToLinestring( GEOSGetGeometryN_r( geosinit.ctxt, geos, i ), hasZ, hasM ) );
1129  if ( line )
1130  {
1131  multiLineString->addGeometry( line.release() );
1132  }
1133  }
1134  return std::move( multiLineString );
1135  }
1136  case GEOS_MULTIPOLYGON:
1137  {
1138  std::unique_ptr< QgsMultiPolygon > multiPolygon( new QgsMultiPolygon() );
1139 
1140  int nParts = GEOSGetNumGeometries_r( geosinit.ctxt, geos );
1141  for ( int i = 0; i < nParts; ++i )
1142  {
1143  std::unique_ptr< QgsPolygon > poly = fromGeosPolygon( GEOSGetGeometryN_r( geosinit.ctxt, geos, i ) );
1144  if ( poly )
1145  {
1146  multiPolygon->addGeometry( poly.release() );
1147  }
1148  }
1149  return std::move( multiPolygon );
1150  }
1151  case GEOS_GEOMETRYCOLLECTION:
1152  {
1153  std::unique_ptr< QgsGeometryCollection > geomCollection( new QgsGeometryCollection() );
1154  int nParts = GEOSGetNumGeometries_r( geosinit.ctxt, geos );
1155  for ( int i = 0; i < nParts; ++i )
1156  {
1157  std::unique_ptr< QgsAbstractGeometry > geom( fromGeos( GEOSGetGeometryN_r( geosinit.ctxt, geos, i ) ) );
1158  if ( geom )
1159  {
1160  geomCollection->addGeometry( geom.release() );
1161  }
1162  }
1163  return std::move( geomCollection );
1164  }
1165  }
1166  return nullptr;
1167 }
1168 
1169 std::unique_ptr<QgsPolygon> QgsGeos::fromGeosPolygon( const GEOSGeometry *geos )
1170 {
1171  if ( GEOSGeomTypeId_r( geosinit.ctxt, geos ) != GEOS_POLYGON )
1172  {
1173  return nullptr;
1174  }
1175 
1176  int nCoordDims = GEOSGeom_getCoordinateDimension_r( geosinit.ctxt, geos );
1177  int nDims = GEOSGeom_getDimensions_r( geosinit.ctxt, geos );
1178  bool hasZ = ( nCoordDims == 3 );
1179  bool hasM = ( ( nDims - nCoordDims ) == 1 );
1180 
1181  std::unique_ptr< QgsPolygon > polygon( new QgsPolygon() );
1182 
1183  const GEOSGeometry *ring = GEOSGetExteriorRing_r( geosinit.ctxt, geos );
1184  if ( ring )
1185  {
1186  polygon->setExteriorRing( sequenceToLinestring( ring, hasZ, hasM ).release() );
1187  }
1188 
1189  QVector<QgsCurve *> interiorRings;
1190  for ( int i = 0; i < GEOSGetNumInteriorRings_r( geosinit.ctxt, geos ); ++i )
1191  {
1192  ring = GEOSGetInteriorRingN_r( geosinit.ctxt, geos, i );
1193  if ( ring )
1194  {
1195  interiorRings.push_back( sequenceToLinestring( ring, hasZ, hasM ).release() );
1196  }
1197  }
1198  polygon->setInteriorRings( interiorRings );
1199 
1200  return polygon;
1201 }
1202 
1203 std::unique_ptr<QgsLineString> QgsGeos::sequenceToLinestring( const GEOSGeometry *geos, bool hasZ, bool hasM )
1204 {
1205  const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( geosinit.ctxt, geos );
1206  unsigned int nPoints;
1207  GEOSCoordSeq_getSize_r( geosinit.ctxt, cs, &nPoints );
1208  QVector< double > xOut( nPoints );
1209  QVector< double > yOut( nPoints );
1210  QVector< double > zOut;
1211  if ( hasZ )
1212  zOut.resize( nPoints );
1213  QVector< double > mOut;
1214  if ( hasM )
1215  mOut.resize( nPoints );
1216  double *x = xOut.data();
1217  double *y = yOut.data();
1218  double *z = zOut.data();
1219  double *m = mOut.data();
1220  for ( unsigned int i = 0; i < nPoints; ++i )
1221  {
1222  GEOSCoordSeq_getX_r( geosinit.ctxt, cs, i, x++ );
1223  GEOSCoordSeq_getY_r( geosinit.ctxt, cs, i, y++ );
1224  if ( hasZ )
1225  {
1226  GEOSCoordSeq_getZ_r( geosinit.ctxt, cs, i, z++ );
1227  }
1228  if ( hasM )
1229  {
1230  GEOSCoordSeq_getOrdinate_r( geosinit.ctxt, cs, i, 3, m++ );
1231  }
1232  }
1233  std::unique_ptr< QgsLineString > line( new QgsLineString( xOut, yOut, zOut, mOut ) );
1234  return line;
1235 }
1236 
1237 int QgsGeos::numberOfGeometries( GEOSGeometry *g )
1238 {
1239  if ( !g )
1240  return 0;
1241 
1242  int geometryType = GEOSGeomTypeId_r( geosinit.ctxt, g );
1243  if ( geometryType == GEOS_POINT || geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING
1244  || geometryType == GEOS_POLYGON )
1245  return 1;
1246 
1247  //calling GEOSGetNumGeometries is save for multi types and collections also in geos2
1248  return GEOSGetNumGeometries_r( geosinit.ctxt, g );
1249 }
1250 
1251 QgsPoint QgsGeos::coordSeqPoint( const GEOSCoordSequence *cs, int i, bool hasZ, bool hasM )
1252 {
1253  if ( !cs )
1254  {
1255  return QgsPoint();
1256  }
1257 
1258  double x, y;
1259  double z = 0;
1260  double m = 0;
1261  GEOSCoordSeq_getX_r( geosinit.ctxt, cs, i, &x );
1262  GEOSCoordSeq_getY_r( geosinit.ctxt, cs, i, &y );
1263  if ( hasZ )
1264  {
1265  GEOSCoordSeq_getZ_r( geosinit.ctxt, cs, i, &z );
1266  }
1267  if ( hasM )
1268  {
1269  GEOSCoordSeq_getOrdinate_r( geosinit.ctxt, cs, i, 3, &m );
1270  }
1271 
1273  if ( hasZ && hasM )
1274  {
1276  }
1277  else if ( hasZ )
1278  {
1279  t = QgsWkbTypes::PointZ;
1280  }
1281  else if ( hasM )
1282  {
1283  t = QgsWkbTypes::PointM;
1284  }
1285  return QgsPoint( t, x, y, z, m );
1286 }
1287 
1288 geos::unique_ptr QgsGeos::asGeos( const QgsAbstractGeometry *geom, double precision )
1289 {
1290  if ( !geom )
1291  return nullptr;
1292 
1293  int coordDims = 2;
1294  if ( geom->is3D() )
1295  {
1296  ++coordDims;
1297  }
1298  if ( geom->isMeasure() )
1299  {
1300  ++coordDims;
1301  }
1302 
1304  {
1305  int geosType = GEOS_GEOMETRYCOLLECTION;
1306 
1308  {
1309  switch ( QgsWkbTypes::geometryType( geom->wkbType() ) )
1310  {
1312  geosType = GEOS_MULTIPOINT;
1313  break;
1314 
1316  geosType = GEOS_MULTILINESTRING;
1317  break;
1318 
1320  geosType = GEOS_MULTIPOLYGON;
1321  break;
1322 
1325  return nullptr;
1326  break;
1327  }
1328  }
1329 
1330 
1332 
1333  if ( !c )
1334  return nullptr;
1335 
1336  QVector< GEOSGeometry * > geomVector( c->numGeometries() );
1337  for ( int i = 0; i < c->numGeometries(); ++i )
1338  {
1339  geomVector[i] = asGeos( c->geometryN( i ), precision ).release();
1340  }
1341  return createGeosCollection( geosType, geomVector );
1342  }
1343  else
1344  {
1345  switch ( QgsWkbTypes::geometryType( geom->wkbType() ) )
1346  {
1348  return createGeosPoint( static_cast<const QgsPoint *>( geom ), coordDims, precision );
1349  break;
1350 
1352  return createGeosLinestring( static_cast<const QgsLineString *>( geom ), precision );
1353  break;
1354 
1356  return createGeosPolygon( static_cast<const QgsPolygon *>( geom ), precision );
1357  break;
1358 
1361  return nullptr;
1362  break;
1363  }
1364  }
1365  return nullptr;
1366 }
1367 
1368 std::unique_ptr<QgsAbstractGeometry> QgsGeos::overlay( const QgsAbstractGeometry *geom, Overlay op, QString *errorMsg ) const
1369 {
1370  if ( !mGeos || !geom )
1371  {
1372  return nullptr;
1373  }
1374 
1375  geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
1376  if ( !geosGeom )
1377  {
1378  return nullptr;
1379  }
1380 
1381  try
1382  {
1383  geos::unique_ptr opGeom;
1384  switch ( op )
1385  {
1386  case OverlayIntersection:
1387  opGeom.reset( GEOSIntersection_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) );
1388  break;
1389  case OverlayDifference:
1390  opGeom.reset( GEOSDifference_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) );
1391  break;
1392  case OverlayUnion:
1393  {
1394  geos::unique_ptr unionGeometry( GEOSUnion_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) );
1395 
1396  if ( unionGeometry && GEOSGeomTypeId_r( geosinit.ctxt, unionGeometry.get() ) == GEOS_MULTILINESTRING )
1397  {
1398  geos::unique_ptr mergedLines( GEOSLineMerge_r( geosinit.ctxt, unionGeometry.get() ) );
1399  if ( mergedLines )
1400  {
1401  unionGeometry = std::move( mergedLines );
1402  }
1403  }
1404 
1405  opGeom = std::move( unionGeometry );
1406  }
1407  break;
1408  case OverlaySymDifference:
1409  opGeom.reset( GEOSSymDifference_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) );
1410  break;
1411  default: //unknown op
1412  return nullptr;
1413  }
1414  return fromGeos( opGeom.get() );
1415  }
1416  catch ( GEOSException &e )
1417  {
1418  if ( errorMsg )
1419  {
1420  *errorMsg = e.what();
1421  }
1422  return nullptr;
1423  }
1424 }
1425 
1426 bool QgsGeos::relation( const QgsAbstractGeometry *geom, Relation r, QString *errorMsg ) const
1427 {
1428  if ( !mGeos || !geom )
1429  {
1430  return false;
1431  }
1432 
1433  geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
1434  if ( !geosGeom )
1435  {
1436  return false;
1437  }
1438 
1439  bool result = false;
1440  try
1441  {
1442  if ( mGeosPrepared ) //use faster version with prepared geometry
1443  {
1444  switch ( r )
1445  {
1446  case RelationIntersects:
1447  result = ( GEOSPreparedIntersects_r( geosinit.ctxt, mGeosPrepared.get(), geosGeom.get() ) == 1 );
1448  break;
1449  case RelationTouches:
1450  result = ( GEOSPreparedTouches_r( geosinit.ctxt, mGeosPrepared.get(), geosGeom.get() ) == 1 );
1451  break;
1452  case RelationCrosses:
1453  result = ( GEOSPreparedCrosses_r( geosinit.ctxt, mGeosPrepared.get(), geosGeom.get() ) == 1 );
1454  break;
1455  case RelationWithin:
1456  result = ( GEOSPreparedWithin_r( geosinit.ctxt, mGeosPrepared.get(), geosGeom.get() ) == 1 );
1457  break;
1458  case RelationContains:
1459  result = ( GEOSPreparedContains_r( geosinit.ctxt, mGeosPrepared.get(), geosGeom.get() ) == 1 );
1460  break;
1461  case RelationDisjoint:
1462  result = ( GEOSPreparedDisjoint_r( geosinit.ctxt, mGeosPrepared.get(), geosGeom.get() ) == 1 );
1463  break;
1464  case RelationOverlaps:
1465  result = ( GEOSPreparedOverlaps_r( geosinit.ctxt, mGeosPrepared.get(), geosGeom.get() ) == 1 );
1466  break;
1467  default:
1468  return false;
1469  }
1470  return result;
1471  }
1472 
1473  switch ( r )
1474  {
1475  case RelationIntersects:
1476  result = ( GEOSIntersects_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) == 1 );
1477  break;
1478  case RelationTouches:
1479  result = ( GEOSTouches_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) == 1 );
1480  break;
1481  case RelationCrosses:
1482  result = ( GEOSCrosses_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) == 1 );
1483  break;
1484  case RelationWithin:
1485  result = ( GEOSWithin_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) == 1 );
1486  break;
1487  case RelationContains:
1488  result = ( GEOSContains_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) == 1 );
1489  break;
1490  case RelationDisjoint:
1491  result = ( GEOSDisjoint_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) == 1 );
1492  break;
1493  case RelationOverlaps:
1494  result = ( GEOSOverlaps_r( geosinit.ctxt, mGeos.get(), geosGeom.get() ) == 1 );
1495  break;
1496  default:
1497  return false;
1498  }
1499  }
1500  catch ( GEOSException &e )
1501  {
1502  if ( errorMsg )
1503  {
1504  *errorMsg = e.what();
1505  }
1506  return false;
1507  }
1508 
1509  return result;
1510 }
1511 
1512 QgsAbstractGeometry *QgsGeos::buffer( double distance, int segments, QString *errorMsg ) const
1513 {
1514  if ( !mGeos )
1515  {
1516  return nullptr;
1517  }
1518 
1520  try
1521  {
1522  geos.reset( GEOSBuffer_r( geosinit.ctxt, mGeos.get(), distance, segments ) );
1523  }
1524  CATCH_GEOS_WITH_ERRMSG( nullptr );
1525  return fromGeos( geos.get() ).release();
1526 }
1527 
1528 QgsAbstractGeometry *QgsGeos::buffer( double distance, int segments, int endCapStyle, int joinStyle, double miterLimit, QString *errorMsg ) const
1529 {
1530  if ( !mGeos )
1531  {
1532  return nullptr;
1533  }
1534 
1536  try
1537  {
1538  geos.reset( GEOSBufferWithStyle_r( geosinit.ctxt, mGeos.get(), distance, segments, endCapStyle, joinStyle, miterLimit ) );
1539  }
1540  CATCH_GEOS_WITH_ERRMSG( nullptr );
1541  return fromGeos( geos.get() ).release();
1542 }
1543 
1544 QgsAbstractGeometry *QgsGeos::simplify( double tolerance, QString *errorMsg ) const
1545 {
1546  if ( !mGeos )
1547  {
1548  return nullptr;
1549  }
1551  try
1552  {
1553  geos.reset( GEOSTopologyPreserveSimplify_r( geosinit.ctxt, mGeos.get(), tolerance ) );
1554  }
1555  CATCH_GEOS_WITH_ERRMSG( nullptr );
1556  return fromGeos( geos.get() ).release();
1557 }
1558 
1559 QgsAbstractGeometry *QgsGeos::interpolate( double distance, QString *errorMsg ) const
1560 {
1561  if ( !mGeos )
1562  {
1563  return nullptr;
1564  }
1566  try
1567  {
1568  geos.reset( GEOSInterpolate_r( geosinit.ctxt, mGeos.get(), distance ) );
1569  }
1570  CATCH_GEOS_WITH_ERRMSG( nullptr );
1571  return fromGeos( geos.get() ).release();
1572 }
1573 
1574 QgsPoint *QgsGeos::centroid( QString *errorMsg ) const
1575 {
1576  if ( !mGeos )
1577  {
1578  return nullptr;
1579  }
1580 
1582  double x;
1583  double y;
1584 
1585  try
1586  {
1587  geos.reset( GEOSGetCentroid_r( geosinit.ctxt, mGeos.get() ) );
1588 
1589  if ( !geos )
1590  return nullptr;
1591 
1592  GEOSGeomGetX_r( geosinit.ctxt, geos.get(), &x );
1593  GEOSGeomGetY_r( geosinit.ctxt, geos.get(), &y );
1594  }
1595  CATCH_GEOS_WITH_ERRMSG( nullptr );
1596 
1597  return new QgsPoint( x, y );
1598 }
1599 
1600 QgsAbstractGeometry *QgsGeos::envelope( QString *errorMsg ) const
1601 {
1602  if ( !mGeos )
1603  {
1604  return nullptr;
1605  }
1607  try
1608  {
1609  geos.reset( GEOSEnvelope_r( geosinit.ctxt, mGeos.get() ) );
1610  }
1611  CATCH_GEOS_WITH_ERRMSG( nullptr );
1612  return fromGeos( geos.get() ).release();
1613 }
1614 
1615 QgsPoint *QgsGeos::pointOnSurface( QString *errorMsg ) const
1616 {
1617  if ( !mGeos )
1618  {
1619  return nullptr;
1620  }
1621 
1622  double x;
1623  double y;
1624 
1626  try
1627  {
1628  geos.reset( GEOSPointOnSurface_r( geosinit.ctxt, mGeos.get() ) );
1629 
1630  if ( !geos || GEOSisEmpty_r( geosinit.ctxt, geos.get() ) != 0 )
1631  {
1632  return nullptr;
1633  }
1634 
1635  GEOSGeomGetX_r( geosinit.ctxt, geos.get(), &x );
1636  GEOSGeomGetY_r( geosinit.ctxt, geos.get(), &y );
1637  }
1638  CATCH_GEOS_WITH_ERRMSG( nullptr );
1639 
1640  return new QgsPoint( x, y );
1641 }
1642 
1643 QgsAbstractGeometry *QgsGeos::convexHull( QString *errorMsg ) const
1644 {
1645  if ( !mGeos )
1646  {
1647  return nullptr;
1648  }
1649 
1650  try
1651  {
1652  geos::unique_ptr cHull( GEOSConvexHull_r( geosinit.ctxt, mGeos.get() ) );
1653  std::unique_ptr< QgsAbstractGeometry > cHullGeom = fromGeos( cHull.get() );
1654  return cHullGeom.release();
1655  }
1656  CATCH_GEOS_WITH_ERRMSG( nullptr );
1657 }
1658 
1659 bool QgsGeos::isValid( QString *errorMsg ) const
1660 {
1661  if ( !mGeos )
1662  {
1663  return false;
1664  }
1665 
1666  try
1667  {
1668  return GEOSisValid_r( geosinit.ctxt, mGeos.get() );
1669  }
1670  CATCH_GEOS_WITH_ERRMSG( false );
1671 }
1672 
1673 bool QgsGeos::isEqual( const QgsAbstractGeometry *geom, QString *errorMsg ) const
1674 {
1675  if ( !mGeos || !geom )
1676  {
1677  return false;
1678  }
1679 
1680  try
1681  {
1682  geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
1683  if ( !geosGeom )
1684  {
1685  return false;
1686  }
1687  bool equal = GEOSEquals_r( geosinit.ctxt, mGeos.get(), geosGeom.get() );
1688  return equal;
1689  }
1690  CATCH_GEOS_WITH_ERRMSG( false );
1691 }
1692 
1693 bool QgsGeos::isEmpty( QString *errorMsg ) const
1694 {
1695  if ( !mGeos )
1696  {
1697  return false;
1698  }
1699 
1700  try
1701  {
1702  return GEOSisEmpty_r( geosinit.ctxt, mGeos.get() );
1703  }
1704  CATCH_GEOS_WITH_ERRMSG( false );
1705 }
1706 
1707 bool QgsGeos::isSimple( QString *errorMsg ) const
1708 {
1709  if ( !mGeos )
1710  {
1711  return false;
1712  }
1713 
1714  try
1715  {
1716  return GEOSisSimple_r( geosinit.ctxt, mGeos.get() );
1717  }
1718  CATCH_GEOS_WITH_ERRMSG( false );
1719 }
1720 
1721 GEOSCoordSequence *QgsGeos::createCoordinateSequence( const QgsCurve *curve, double precision, bool forceClose )
1722 {
1723  std::unique_ptr< QgsLineString > segmentized;
1724  const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( curve );
1725 
1726  if ( !line )
1727  {
1728  segmentized.reset( curve->curveToLine() );
1729  line = segmentized.get();
1730  }
1731 
1732  if ( !line )
1733  {
1734  return nullptr;
1735  }
1736 
1737  bool hasZ = line->is3D();
1738  bool hasM = false; //line->isMeasure(); //disabled until geos supports m-coordinates
1739  int coordDims = 2;
1740  if ( hasZ )
1741  {
1742  ++coordDims;
1743  }
1744  if ( hasM )
1745  {
1746  ++coordDims;
1747  }
1748 
1749  int numPoints = line->numPoints();
1750 
1751  int numOutPoints = numPoints;
1752  if ( forceClose && ( line->pointN( 0 ) != line->pointN( numPoints - 1 ) ) )
1753  {
1754  ++numOutPoints;
1755  }
1756 
1757  GEOSCoordSequence *coordSeq = nullptr;
1758  try
1759  {
1760  coordSeq = GEOSCoordSeq_create_r( geosinit.ctxt, numOutPoints, coordDims );
1761  if ( !coordSeq )
1762  {
1763  QgsDebugMsg( QStringLiteral( "GEOS Exception: Could not create coordinate sequence for %1 points in %2 dimensions" ).arg( numPoints ).arg( coordDims ) );
1764  return nullptr;
1765  }
1766 
1767  const double *xData = line->xData();
1768  const double *yData = line->yData();
1769  const double *zData = hasZ ? line->zData() : nullptr;
1770  const double *mData = hasM ? line->mData() : nullptr;
1771 
1772  if ( precision > 0. )
1773  {
1774  for ( int i = 0; i < numOutPoints; ++i )
1775  {
1776  if ( i >= numPoints )
1777  {
1778  // start reading back from start of line
1779  xData = line->xData();
1780  yData = line->yData();
1781  zData = hasZ ? line->zData() : nullptr;
1782  mData = hasM ? line->mData() : nullptr;
1783  }
1784  GEOSCoordSeq_setX_r( geosinit.ctxt, coordSeq, i, std::round( *xData++ / precision ) * precision );
1785  GEOSCoordSeq_setY_r( geosinit.ctxt, coordSeq, i, std::round( *yData++ / precision ) * precision );
1786  if ( hasZ )
1787  {
1788  GEOSCoordSeq_setOrdinate_r( geosinit.ctxt, coordSeq, i, 2, std::round( *zData++ / precision ) * precision );
1789  }
1790  if ( hasM )
1791  {
1792  GEOSCoordSeq_setOrdinate_r( geosinit.ctxt, coordSeq, i, 3, line->mAt( *mData++ ) );
1793  }
1794  }
1795  }
1796  else
1797  {
1798  for ( int i = 0; i < numOutPoints; ++i )
1799  {
1800  if ( i >= numPoints )
1801  {
1802  // start reading back from start of line
1803  xData = line->xData();
1804  yData = line->yData();
1805  zData = hasZ ? line->zData() : nullptr;
1806  mData = hasM ? line->mData() : nullptr;
1807  }
1808  GEOSCoordSeq_setX_r( geosinit.ctxt, coordSeq, i, *xData++ );
1809  GEOSCoordSeq_setY_r( geosinit.ctxt, coordSeq, i, *yData++ );
1810  if ( hasZ )
1811  {
1812  GEOSCoordSeq_setOrdinate_r( geosinit.ctxt, coordSeq, i, 2, *zData++ );
1813  }
1814  if ( hasM )
1815  {
1816  GEOSCoordSeq_setOrdinate_r( geosinit.ctxt, coordSeq, i, 3, *mData++ );
1817  }
1818  }
1819  }
1820  }
1821  CATCH_GEOS( nullptr )
1822 
1823  return coordSeq;
1824 }
1825 
1826 geos::unique_ptr QgsGeos::createGeosPoint( const QgsAbstractGeometry *point, int coordDims, double precision )
1827 {
1828  const QgsPoint *pt = qgsgeometry_cast<const QgsPoint *>( point );
1829  if ( !pt )
1830  return nullptr;
1831 
1832  return createGeosPointXY( pt->x(), pt->y(), pt->is3D(), pt->z(), pt->isMeasure(), pt->m(), coordDims, precision );
1833 }
1834 
1835 geos::unique_ptr QgsGeos::createGeosPointXY( double x, double y, bool hasZ, double z, bool hasM, double m, int coordDims, double precision )
1836 {
1837  Q_UNUSED( hasM );
1838  Q_UNUSED( m );
1839 
1840  geos::unique_ptr geosPoint;
1841 
1842  try
1843  {
1844  GEOSCoordSequence *coordSeq = GEOSCoordSeq_create_r( geosinit.ctxt, 1, coordDims );
1845  if ( !coordSeq )
1846  {
1847  QgsDebugMsg( QStringLiteral( "GEOS Exception: Could not create coordinate sequence for point with %1 dimensions" ).arg( coordDims ) );
1848  return nullptr;
1849  }
1850  if ( precision > 0. )
1851  {
1852  GEOSCoordSeq_setX_r( geosinit.ctxt, coordSeq, 0, std::round( x / precision ) * precision );
1853  GEOSCoordSeq_setY_r( geosinit.ctxt, coordSeq, 0, std::round( y / precision ) * precision );
1854  if ( hasZ )
1855  {
1856  GEOSCoordSeq_setOrdinate_r( geosinit.ctxt, coordSeq, 0, 2, std::round( z / precision ) * precision );
1857  }
1858  }
1859  else
1860  {
1861  GEOSCoordSeq_setX_r( geosinit.ctxt, coordSeq, 0, x );
1862  GEOSCoordSeq_setY_r( geosinit.ctxt, coordSeq, 0, y );
1863  if ( hasZ )
1864  {
1865  GEOSCoordSeq_setOrdinate_r( geosinit.ctxt, coordSeq, 0, 2, z );
1866  }
1867  }
1868 #if 0 //disabled until geos supports m-coordinates
1869  if ( hasM )
1870  {
1871  GEOSCoordSeq_setOrdinate_r( geosinit.ctxt, coordSeq, 0, 3, m );
1872  }
1873 #endif
1874  geosPoint.reset( GEOSGeom_createPoint_r( geosinit.ctxt, coordSeq ) );
1875  }
1876  CATCH_GEOS( nullptr )
1877  return geosPoint;
1878 }
1879 
1880 geos::unique_ptr QgsGeos::createGeosLinestring( const QgsAbstractGeometry *curve, double precision )
1881 {
1882  const QgsCurve *c = qgsgeometry_cast<const QgsCurve *>( curve );
1883  if ( !c )
1884  return nullptr;
1885 
1886  GEOSCoordSequence *coordSeq = createCoordinateSequence( c, precision );
1887  if ( !coordSeq )
1888  return nullptr;
1889 
1890  geos::unique_ptr geosGeom;
1891  try
1892  {
1893  geosGeom.reset( GEOSGeom_createLineString_r( geosinit.ctxt, coordSeq ) );
1894  }
1895  CATCH_GEOS( nullptr )
1896  return geosGeom;
1897 }
1898 
1899 geos::unique_ptr QgsGeos::createGeosPolygon( const QgsAbstractGeometry *poly, double precision )
1900 {
1901  const QgsCurvePolygon *polygon = qgsgeometry_cast<const QgsCurvePolygon *>( poly );
1902  if ( !polygon )
1903  return nullptr;
1904 
1905  const QgsCurve *exteriorRing = polygon->exteriorRing();
1906  if ( !exteriorRing )
1907  {
1908  return nullptr;
1909  }
1910 
1911  geos::unique_ptr geosPolygon;
1912  try
1913  {
1914  geos::unique_ptr exteriorRingGeos( GEOSGeom_createLinearRing_r( geosinit.ctxt, createCoordinateSequence( exteriorRing, precision, true ) ) );
1915 
1916  int nHoles = polygon->numInteriorRings();
1917  GEOSGeometry **holes = nullptr;
1918  if ( nHoles > 0 )
1919  {
1920  holes = new GEOSGeometry*[ nHoles ];
1921  }
1922 
1923  for ( int i = 0; i < nHoles; ++i )
1924  {
1925  const QgsCurve *interiorRing = polygon->interiorRing( i );
1926  holes[i] = GEOSGeom_createLinearRing_r( geosinit.ctxt, createCoordinateSequence( interiorRing, precision, true ) );
1927  }
1928  geosPolygon.reset( GEOSGeom_createPolygon_r( geosinit.ctxt, exteriorRingGeos.release(), holes, nHoles ) );
1929  delete[] holes;
1930  }
1931  CATCH_GEOS( nullptr )
1932 
1933  return geosPolygon;
1934 }
1935 
1936 QgsAbstractGeometry *QgsGeos::offsetCurve( double distance, int segments, int joinStyle, double miterLimit, QString *errorMsg ) const
1937 {
1938  if ( !mGeos )
1939  return nullptr;
1940 
1941  geos::unique_ptr offset;
1942  try
1943  {
1944  offset.reset( GEOSOffsetCurve_r( geosinit.ctxt, mGeos.get(), distance, segments, joinStyle, miterLimit ) );
1945  }
1946  CATCH_GEOS_WITH_ERRMSG( nullptr )
1947  std::unique_ptr< QgsAbstractGeometry > offsetGeom = fromGeos( offset.get() );
1948  return offsetGeom.release();
1949 }
1950 
1951 std::unique_ptr<QgsAbstractGeometry> QgsGeos::singleSidedBuffer( double distance, int segments, int side, int joinStyle, double miterLimit, QString *errorMsg ) const
1952 {
1953  if ( !mGeos )
1954  {
1955  return nullptr;
1956  }
1957 
1959  try
1960  {
1961  geos::buffer_params_unique_ptr bp( GEOSBufferParams_create_r( geosinit.ctxt ) );
1962  GEOSBufferParams_setSingleSided_r( geosinit.ctxt, bp.get(), 1 );
1963  GEOSBufferParams_setQuadrantSegments_r( geosinit.ctxt, bp.get(), segments );
1964  GEOSBufferParams_setJoinStyle_r( geosinit.ctxt, bp.get(), joinStyle );
1965  GEOSBufferParams_setMitreLimit_r( geosinit.ctxt, bp.get(), miterLimit ); //#spellok
1966 
1967  if ( side == 1 )
1968  {
1969  distance = -distance;
1970  }
1971  geos.reset( GEOSBufferWithParams_r( geosinit.ctxt, mGeos.get(), bp.get(), distance ) );
1972  }
1973  CATCH_GEOS_WITH_ERRMSG( nullptr );
1974  return fromGeos( geos.get() );
1975 }
1976 
1977 std::unique_ptr<QgsAbstractGeometry> QgsGeos::reshapeGeometry( const QgsLineString &reshapeWithLine, EngineOperationResult *errorCode, QString *errorMsg ) const
1978 {
1979  if ( !mGeos || mGeometry->dimension() == 0 )
1980  {
1981  if ( errorCode ) { *errorCode = InvalidBaseGeometry; }
1982  return nullptr;
1983  }
1984 
1985  if ( reshapeWithLine.numPoints() < 2 )
1986  {
1987  if ( errorCode ) { *errorCode = InvalidInput; }
1988  return nullptr;
1989  }
1990 
1991  geos::unique_ptr reshapeLineGeos = createGeosLinestring( &reshapeWithLine, mPrecision );
1992 
1993  //single or multi?
1994  int numGeoms = GEOSGetNumGeometries_r( geosinit.ctxt, mGeos.get() );
1995  if ( numGeoms == -1 )
1996  {
1997  if ( errorCode )
1998  {
1999  *errorCode = InvalidBaseGeometry;
2000  }
2001  return nullptr;
2002  }
2003 
2004  bool isMultiGeom = false;
2005  int geosTypeId = GEOSGeomTypeId_r( geosinit.ctxt, mGeos.get() );
2006  if ( geosTypeId == GEOS_MULTILINESTRING || geosTypeId == GEOS_MULTIPOLYGON )
2007  isMultiGeom = true;
2008 
2009  bool isLine = ( mGeometry->dimension() == 1 );
2010 
2011  if ( !isMultiGeom )
2012  {
2013  geos::unique_ptr reshapedGeometry;
2014  if ( isLine )
2015  {
2016  reshapedGeometry = reshapeLine( mGeos.get(), reshapeLineGeos.get(), mPrecision );
2017  }
2018  else
2019  {
2020  reshapedGeometry = reshapePolygon( mGeos.get(), reshapeLineGeos.get(), mPrecision );
2021  }
2022 
2023  if ( errorCode )
2024  *errorCode = Success;
2025  std::unique_ptr< QgsAbstractGeometry > reshapeResult = fromGeos( reshapedGeometry.get() );
2026  return reshapeResult;
2027  }
2028  else
2029  {
2030  try
2031  {
2032  //call reshape for each geometry part and replace mGeos with new geometry if reshape took place
2033  bool reshapeTookPlace = false;
2034 
2035  geos::unique_ptr currentReshapeGeometry;
2036  GEOSGeometry **newGeoms = new GEOSGeometry*[numGeoms];
2037 
2038  for ( int i = 0; i < numGeoms; ++i )
2039  {
2040  if ( isLine )
2041  currentReshapeGeometry = reshapeLine( GEOSGetGeometryN_r( geosinit.ctxt, mGeos.get(), i ), reshapeLineGeos.get(), mPrecision );
2042  else
2043  currentReshapeGeometry = reshapePolygon( GEOSGetGeometryN_r( geosinit.ctxt, mGeos.get(), i ), reshapeLineGeos.get(), mPrecision );
2044 
2045  if ( currentReshapeGeometry )
2046  {
2047  newGeoms[i] = currentReshapeGeometry.release();
2048  reshapeTookPlace = true;
2049  }
2050  else
2051  {
2052  newGeoms[i] = GEOSGeom_clone_r( geosinit.ctxt, GEOSGetGeometryN_r( geosinit.ctxt, mGeos.get(), i ) );
2053  }
2054  }
2055 
2056  geos::unique_ptr newMultiGeom;
2057  if ( isLine )
2058  {
2059  newMultiGeom.reset( GEOSGeom_createCollection_r( geosinit.ctxt, GEOS_MULTILINESTRING, newGeoms, numGeoms ) );
2060  }
2061  else //multipolygon
2062  {
2063  newMultiGeom.reset( GEOSGeom_createCollection_r( geosinit.ctxt, GEOS_MULTIPOLYGON, newGeoms, numGeoms ) );
2064  }
2065 
2066  delete[] newGeoms;
2067  if ( !newMultiGeom )
2068  {
2069  if ( errorCode ) { *errorCode = EngineError; }
2070  return nullptr;
2071  }
2072 
2073  if ( reshapeTookPlace )
2074  {
2075  if ( errorCode )
2076  *errorCode = Success;
2077  std::unique_ptr< QgsAbstractGeometry > reshapedMultiGeom = fromGeos( newMultiGeom.get() );
2078  return reshapedMultiGeom;
2079  }
2080  else
2081  {
2082  if ( errorCode )
2083  {
2084  *errorCode = NothingHappened;
2085  }
2086  return nullptr;
2087  }
2088  }
2089  CATCH_GEOS_WITH_ERRMSG( nullptr )
2090  }
2091 }
2092 
2093 QgsGeometry QgsGeos::mergeLines( QString *errorMsg ) const
2094 {
2095  if ( !mGeos )
2096  {
2097  return QgsGeometry();
2098  }
2099 
2100  if ( GEOSGeomTypeId_r( geosinit.ctxt, mGeos.get() ) != GEOS_MULTILINESTRING )
2101  return QgsGeometry();
2102 
2104  try
2105  {
2106  geos.reset( GEOSLineMerge_r( geosinit.ctxt, mGeos.get() ) );
2107  }
2109  return QgsGeometry( fromGeos( geos.get() ) );
2110 }
2111 
2112 QgsGeometry QgsGeos::closestPoint( const QgsGeometry &other, QString *errorMsg ) const
2113 {
2114  if ( !mGeos || other.isNull() )
2115  {
2116  return QgsGeometry();
2117  }
2118 
2119  geos::unique_ptr otherGeom( asGeos( other.constGet(), mPrecision ) );
2120  if ( !otherGeom )
2121  {
2122  return QgsGeometry();
2123  }
2124 
2125  double nx = 0.0;
2126  double ny = 0.0;
2127  try
2128  {
2129  geos::coord_sequence_unique_ptr nearestCoord( GEOSNearestPoints_r( geosinit.ctxt, mGeos.get(), otherGeom.get() ) );
2130 
2131  ( void )GEOSCoordSeq_getX_r( geosinit.ctxt, nearestCoord.get(), 0, &nx );
2132  ( void )GEOSCoordSeq_getY_r( geosinit.ctxt, nearestCoord.get(), 0, &ny );
2133  }
2134  catch ( GEOSException &e )
2135  {
2136  if ( errorMsg )
2137  {
2138  *errorMsg = e.what();
2139  }
2140  return QgsGeometry();
2141  }
2142 
2143  return QgsGeometry( new QgsPoint( nx, ny ) );
2144 }
2145 
2146 QgsGeometry QgsGeos::shortestLine( const QgsGeometry &other, QString *errorMsg ) const
2147 {
2148  if ( !mGeos || other.isNull() )
2149  {
2150  return QgsGeometry();
2151  }
2152 
2153  geos::unique_ptr otherGeom( asGeos( other.constGet(), mPrecision ) );
2154  if ( !otherGeom )
2155  {
2156  return QgsGeometry();
2157  }
2158 
2159  double nx1 = 0.0;
2160  double ny1 = 0.0;
2161  double nx2 = 0.0;
2162  double ny2 = 0.0;
2163  try
2164  {
2165  geos::coord_sequence_unique_ptr nearestCoord( GEOSNearestPoints_r( geosinit.ctxt, mGeos.get(), otherGeom.get() ) );
2166 
2167  ( void )GEOSCoordSeq_getX_r( geosinit.ctxt, nearestCoord.get(), 0, &nx1 );
2168  ( void )GEOSCoordSeq_getY_r( geosinit.ctxt, nearestCoord.get(), 0, &ny1 );
2169  ( void )GEOSCoordSeq_getX_r( geosinit.ctxt, nearestCoord.get(), 1, &nx2 );
2170  ( void )GEOSCoordSeq_getY_r( geosinit.ctxt, nearestCoord.get(), 1, &ny2 );
2171  }
2172  catch ( GEOSException &e )
2173  {
2174  if ( errorMsg )
2175  {
2176  *errorMsg = e.what();
2177  }
2178  return QgsGeometry();
2179  }
2180 
2181  QgsLineString *line = new QgsLineString();
2182  line->addVertex( QgsPoint( nx1, ny1 ) );
2183  line->addVertex( QgsPoint( nx2, ny2 ) );
2184  return QgsGeometry( line );
2185 }
2186 
2187 double QgsGeos::lineLocatePoint( const QgsPoint &point, QString *errorMsg ) const
2188 {
2189  if ( !mGeos )
2190  {
2191  return -1;
2192  }
2193 
2194  geos::unique_ptr otherGeom( asGeos( &point, mPrecision ) );
2195  if ( !otherGeom )
2196  {
2197  return -1;
2198  }
2199 
2200  double distance = -1;
2201  try
2202  {
2203  distance = GEOSProject_r( geosinit.ctxt, mGeos.get(), otherGeom.get() );
2204  }
2205  catch ( GEOSException &e )
2206  {
2207  if ( errorMsg )
2208  {
2209  *errorMsg = e.what();
2210  }
2211  return -1;
2212  }
2213 
2214  return distance;
2215 }
2216 
2217 QgsGeometry QgsGeos::polygonize( const QVector<const QgsAbstractGeometry *> &geometries, QString *errorMsg )
2218 {
2219  GEOSGeometry **const lineGeosGeometries = new GEOSGeometry*[ geometries.size()];
2220  int validLines = 0;
2221  for ( const QgsAbstractGeometry *g : geometries )
2222  {
2223  geos::unique_ptr l = asGeos( g );
2224  if ( l )
2225  {
2226  lineGeosGeometries[validLines] = l.release();
2227  validLines++;
2228  }
2229  }
2230 
2231  try
2232  {
2233  geos::unique_ptr result( GEOSPolygonize_r( geosinit.ctxt, lineGeosGeometries, validLines ) );
2234  for ( int i = 0; i < validLines; ++i )
2235  {
2236  GEOSGeom_destroy_r( geosinit.ctxt, lineGeosGeometries[i] );
2237  }
2238  delete[] lineGeosGeometries;
2239  return QgsGeometry( fromGeos( result.get() ) );
2240  }
2241  catch ( GEOSException &e )
2242  {
2243  if ( errorMsg )
2244  {
2245  *errorMsg = e.what();
2246  }
2247  for ( int i = 0; i < validLines; ++i )
2248  {
2249  GEOSGeom_destroy_r( geosinit.ctxt, lineGeosGeometries[i] );
2250  }
2251  delete[] lineGeosGeometries;
2252  return QgsGeometry();
2253  }
2254 }
2255 
2256 QgsGeometry QgsGeos::voronoiDiagram( const QgsAbstractGeometry *extent, double tolerance, bool edgesOnly, QString *errorMsg ) const
2257 {
2258  if ( !mGeos )
2259  {
2260  return QgsGeometry();
2261  }
2262 
2263  geos::unique_ptr extentGeosGeom;
2264  if ( extent )
2265  {
2266  extentGeosGeom = asGeos( extent, mPrecision );
2267  if ( !extentGeosGeom )
2268  {
2269  return QgsGeometry();
2270  }
2271  }
2272 
2274  try
2275  {
2276  geos.reset( GEOSVoronoiDiagram_r( geosinit.ctxt, mGeos.get(), extentGeosGeom.get(), tolerance, edgesOnly ) );
2277 
2278  if ( !geos || GEOSisEmpty_r( geosinit.ctxt, geos.get() ) != 0 )
2279  {
2280  return QgsGeometry();
2281  }
2282 
2283  return QgsGeometry( fromGeos( geos.get() ) );
2284  }
2286 }
2287 
2288 QgsGeometry QgsGeos::delaunayTriangulation( double tolerance, bool edgesOnly, QString *errorMsg ) const
2289 {
2290  if ( !mGeos )
2291  {
2292  return QgsGeometry();
2293  }
2294 
2296  try
2297  {
2298  geos.reset( GEOSDelaunayTriangulation_r( geosinit.ctxt, mGeos.get(), tolerance, edgesOnly ) );
2299 
2300  if ( !geos || GEOSisEmpty_r( geosinit.ctxt, geos.get() ) != 0 )
2301  {
2302  return QgsGeometry();
2303  }
2304 
2305  return QgsGeometry( fromGeos( geos.get() ) );
2306  }
2308 }
2309 
2310 
2312 static bool _linestringEndpoints( const GEOSGeometry *linestring, double &x1, double &y1, double &x2, double &y2 )
2313 {
2314  const GEOSCoordSequence *coordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, linestring );
2315  if ( !coordSeq )
2316  return false;
2317 
2318  unsigned int coordSeqSize;
2319  if ( GEOSCoordSeq_getSize_r( geosinit.ctxt, coordSeq, &coordSeqSize ) == 0 )
2320  return false;
2321 
2322  if ( coordSeqSize < 2 )
2323  return false;
2324 
2325  GEOSCoordSeq_getX_r( geosinit.ctxt, coordSeq, 0, &x1 );
2326  GEOSCoordSeq_getY_r( geosinit.ctxt, coordSeq, 0, &y1 );
2327  GEOSCoordSeq_getX_r( geosinit.ctxt, coordSeq, coordSeqSize - 1, &x2 );
2328  GEOSCoordSeq_getY_r( geosinit.ctxt, coordSeq, coordSeqSize - 1, &y2 );
2329  return true;
2330 }
2331 
2332 
2334 static geos::unique_ptr _mergeLinestrings( const GEOSGeometry *line1, const GEOSGeometry *line2, const QgsPointXY &intersectionPoint )
2335 {
2336  double x1, y1, x2, y2;
2337  if ( !_linestringEndpoints( line1, x1, y1, x2, y2 ) )
2338  return nullptr;
2339 
2340  double rx1, ry1, rx2, ry2;
2341  if ( !_linestringEndpoints( line2, rx1, ry1, rx2, ry2 ) )
2342  return nullptr;
2343 
2344  bool intersectionAtOrigLineEndpoint =
2345  ( intersectionPoint.x() == x1 && intersectionPoint.y() == y1 ) ||
2346  ( intersectionPoint.x() == x2 && intersectionPoint.y() == y2 );
2347  bool intersectionAtReshapeLineEndpoint =
2348  ( intersectionPoint.x() == rx1 && intersectionPoint.y() == ry1 ) ||
2349  ( intersectionPoint.x() == rx2 && intersectionPoint.y() == ry2 );
2350 
2351  // the intersection must be at the begin/end of both lines
2352  if ( intersectionAtOrigLineEndpoint && intersectionAtReshapeLineEndpoint )
2353  {
2354  geos::unique_ptr g1( GEOSGeom_clone_r( geosinit.ctxt, line1 ) );
2355  geos::unique_ptr g2( GEOSGeom_clone_r( geosinit.ctxt, line2 ) );
2356  GEOSGeometry *geoms[2] = { g1.release(), g2.release() };
2357  geos::unique_ptr multiGeom( GEOSGeom_createCollection_r( geosinit.ctxt, GEOS_MULTILINESTRING, geoms, 2 ) );
2358  geos::unique_ptr res( GEOSLineMerge_r( geosinit.ctxt, multiGeom.get() ) );
2359  return res;
2360  }
2361  else
2362  return nullptr;
2363 }
2364 
2365 
2366 geos::unique_ptr QgsGeos::reshapeLine( const GEOSGeometry *line, const GEOSGeometry *reshapeLineGeos, double precision )
2367 {
2368  if ( !line || !reshapeLineGeos )
2369  return nullptr;
2370 
2371  bool atLeastTwoIntersections = false;
2372  bool oneIntersection = false;
2373  QgsPointXY oneIntersectionPoint;
2374 
2375  try
2376  {
2377  //make sure there are at least two intersection between line and reshape geometry
2378  geos::unique_ptr intersectGeom( GEOSIntersection_r( geosinit.ctxt, line, reshapeLineGeos ) );
2379  if ( intersectGeom )
2380  {
2381  atLeastTwoIntersections = ( GEOSGeomTypeId_r( geosinit.ctxt, intersectGeom.get() ) == GEOS_MULTIPOINT
2382  && GEOSGetNumGeometries_r( geosinit.ctxt, intersectGeom.get() ) > 1 );
2383  // one point is enough when extending line at its endpoint
2384  if ( GEOSGeomTypeId_r( geosinit.ctxt, intersectGeom.get() ) == GEOS_POINT )
2385  {
2386  const GEOSCoordSequence *intersectionCoordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, intersectGeom.get() );
2387  double xi, yi;
2388  GEOSCoordSeq_getX_r( geosinit.ctxt, intersectionCoordSeq, 0, &xi );
2389  GEOSCoordSeq_getY_r( geosinit.ctxt, intersectionCoordSeq, 0, &yi );
2390  oneIntersection = true;
2391  oneIntersectionPoint = QgsPointXY( xi, yi );
2392  }
2393  }
2394  }
2395  catch ( GEOSException & )
2396  {
2397  atLeastTwoIntersections = false;
2398  }
2399 
2400  // special case when extending line at its endpoint
2401  if ( oneIntersection )
2402  return _mergeLinestrings( line, reshapeLineGeos, oneIntersectionPoint );
2403 
2404  if ( !atLeastTwoIntersections )
2405  return nullptr;
2406 
2407  //begin and end point of original line
2408  double x1, y1, x2, y2;
2409  if ( !_linestringEndpoints( line, x1, y1, x2, y2 ) )
2410  return nullptr;
2411 
2412  geos::unique_ptr beginLineVertex = createGeosPointXY( x1, y1, false, 0, false, 0, 2, precision );
2413  geos::unique_ptr endLineVertex = createGeosPointXY( x2, y2, false, 0, false, 0, 2, precision );
2414 
2415  bool isRing = false;
2416  if ( GEOSGeomTypeId_r( geosinit.ctxt, line ) == GEOS_LINEARRING
2417  || GEOSEquals_r( geosinit.ctxt, beginLineVertex.get(), endLineVertex.get() ) == 1 )
2418  isRing = true;
2419 
2420  //node line and reshape line
2421  geos::unique_ptr nodedGeometry = nodeGeometries( reshapeLineGeos, line );
2422  if ( !nodedGeometry )
2423  {
2424  return nullptr;
2425  }
2426 
2427  //and merge them together
2428  geos::unique_ptr mergedLines( GEOSLineMerge_r( geosinit.ctxt, nodedGeometry.get() ) );
2429  if ( !mergedLines )
2430  {
2431  return nullptr;
2432  }
2433 
2434  int numMergedLines = GEOSGetNumGeometries_r( geosinit.ctxt, mergedLines.get() );
2435  if ( numMergedLines < 2 ) //some special cases. Normally it is >2
2436  {
2437  if ( numMergedLines == 1 ) //reshape line is from begin to endpoint. So we keep the reshapeline
2438  {
2439  geos::unique_ptr result( GEOSGeom_clone_r( geosinit.ctxt, reshapeLineGeos ) );
2440  return result;
2441  }
2442  else
2443  return nullptr;
2444  }
2445 
2446  QVector<GEOSGeometry *> resultLineParts; //collection with the line segments that will be contained in result
2447  QVector<GEOSGeometry *> probableParts; //parts where we can decide on inclusion only after going through all the candidates
2448 
2449  for ( int i = 0; i < numMergedLines; ++i )
2450  {
2451  const GEOSGeometry *currentGeom = nullptr;
2452 
2453  currentGeom = GEOSGetGeometryN_r( geosinit.ctxt, mergedLines.get(), i );
2454  const GEOSCoordSequence *currentCoordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, currentGeom );
2455  unsigned int currentCoordSeqSize;
2456  GEOSCoordSeq_getSize_r( geosinit.ctxt, currentCoordSeq, &currentCoordSeqSize );
2457  if ( currentCoordSeqSize < 2 )
2458  continue;
2459 
2460  //get the two endpoints of the current line merge result
2461  double xBegin, xEnd, yBegin, yEnd;
2462  GEOSCoordSeq_getX_r( geosinit.ctxt, currentCoordSeq, 0, &xBegin );
2463  GEOSCoordSeq_getY_r( geosinit.ctxt, currentCoordSeq, 0, &yBegin );
2464  GEOSCoordSeq_getX_r( geosinit.ctxt, currentCoordSeq, currentCoordSeqSize - 1, &xEnd );
2465  GEOSCoordSeq_getY_r( geosinit.ctxt, currentCoordSeq, currentCoordSeqSize - 1, &yEnd );
2466  geos::unique_ptr beginCurrentGeomVertex = createGeosPointXY( xBegin, yBegin, false, 0, false, 0, 2, precision );
2467  geos::unique_ptr endCurrentGeomVertex = createGeosPointXY( xEnd, yEnd, false, 0, false, 0, 2, precision );
2468 
2469  //check how many endpoints of the line merge result are on the (original) line
2470  int nEndpointsOnOriginalLine = 0;
2471  if ( pointContainedInLine( beginCurrentGeomVertex.get(), line ) == 1 )
2472  nEndpointsOnOriginalLine += 1;
2473 
2474  if ( pointContainedInLine( endCurrentGeomVertex.get(), line ) == 1 )
2475  nEndpointsOnOriginalLine += 1;
2476 
2477  //check how many endpoints equal the endpoints of the original line
2478  int nEndpointsSameAsOriginalLine = 0;
2479  if ( GEOSEquals_r( geosinit.ctxt, beginCurrentGeomVertex.get(), beginLineVertex.get() ) == 1
2480  || GEOSEquals_r( geosinit.ctxt, beginCurrentGeomVertex.get(), endLineVertex.get() ) == 1 )
2481  nEndpointsSameAsOriginalLine += 1;
2482 
2483  if ( GEOSEquals_r( geosinit.ctxt, endCurrentGeomVertex.get(), beginLineVertex.get() ) == 1
2484  || GEOSEquals_r( geosinit.ctxt, endCurrentGeomVertex.get(), endLineVertex.get() ) == 1 )
2485  nEndpointsSameAsOriginalLine += 1;
2486 
2487  //check if the current geometry overlaps the original geometry (GEOSOverlap does not seem to work with linestrings)
2488  bool currentGeomOverlapsOriginalGeom = false;
2489  bool currentGeomOverlapsReshapeLine = false;
2490  if ( lineContainedInLine( currentGeom, line ) == 1 )
2491  currentGeomOverlapsOriginalGeom = true;
2492 
2493  if ( lineContainedInLine( currentGeom, reshapeLineGeos ) == 1 )
2494  currentGeomOverlapsReshapeLine = true;
2495 
2496  //logic to decide if this part belongs to the result
2497  if ( !isRing && nEndpointsSameAsOriginalLine == 1 && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom )
2498  {
2499  resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) );
2500  }
2501  //for closed rings, we take one segment from the candidate list
2502  else if ( isRing && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom )
2503  {
2504  probableParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) );
2505  }
2506  else if ( nEndpointsOnOriginalLine == 2 && !currentGeomOverlapsOriginalGeom )
2507  {
2508  resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) );
2509  }
2510  else if ( nEndpointsSameAsOriginalLine == 2 && !currentGeomOverlapsOriginalGeom )
2511  {
2512  resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) );
2513  }
2514  else if ( currentGeomOverlapsOriginalGeom && currentGeomOverlapsReshapeLine )
2515  {
2516  resultLineParts.push_back( GEOSGeom_clone_r( geosinit.ctxt, currentGeom ) );
2517  }
2518  }
2519 
2520  //add the longest segment from the probable list for rings (only used for polygon rings)
2521  if ( isRing && !probableParts.isEmpty() )
2522  {
2523  geos::unique_ptr maxGeom; //the longest geometry in the probabla list
2524  GEOSGeometry *currentGeom = nullptr;
2525  double maxLength = -std::numeric_limits<double>::max();
2526  double currentLength = 0;
2527  for ( int i = 0; i < probableParts.size(); ++i )
2528  {
2529  currentGeom = probableParts.at( i );
2530  GEOSLength_r( geosinit.ctxt, currentGeom, &currentLength );
2531  if ( currentLength > maxLength )
2532  {
2533  maxLength = currentLength;
2534  maxGeom.reset( currentGeom );
2535  }
2536  else
2537  {
2538  GEOSGeom_destroy_r( geosinit.ctxt, currentGeom );
2539  }
2540  }
2541  resultLineParts.push_back( maxGeom.release() );
2542  }
2543 
2544  geos::unique_ptr result;
2545  if ( resultLineParts.empty() )
2546  return nullptr;
2547 
2548  if ( resultLineParts.size() == 1 ) //the whole result was reshaped
2549  {
2550  result.reset( resultLineParts[0] );
2551  }
2552  else //>1
2553  {
2554  GEOSGeometry **lineArray = new GEOSGeometry*[resultLineParts.size()];
2555  for ( int i = 0; i < resultLineParts.size(); ++i )
2556  {
2557  lineArray[i] = resultLineParts[i];
2558  }
2559 
2560  //create multiline from resultLineParts
2561  geos::unique_ptr multiLineGeom( GEOSGeom_createCollection_r( geosinit.ctxt, GEOS_MULTILINESTRING, lineArray, resultLineParts.size() ) );
2562  delete [] lineArray;
2563 
2564  //then do a linemerge with the newly combined partstrings
2565  result.reset( GEOSLineMerge_r( geosinit.ctxt, multiLineGeom.get() ) );
2566  }
2567 
2568  //now test if the result is a linestring. Otherwise something went wrong
2569  if ( GEOSGeomTypeId_r( geosinit.ctxt, result.get() ) != GEOS_LINESTRING )
2570  {
2571  return nullptr;
2572  }
2573 
2574  return result;
2575 }
2576 
2577 geos::unique_ptr QgsGeos::reshapePolygon( const GEOSGeometry *polygon, const GEOSGeometry *reshapeLineGeos, double precision )
2578 {
2579  //go through outer shell and all inner rings and check if there is exactly one intersection of a ring and the reshape line
2580  int nIntersections = 0;
2581  int lastIntersectingRing = -2;
2582  const GEOSGeometry *lastIntersectingGeom = nullptr;
2583 
2584  int nRings = GEOSGetNumInteriorRings_r( geosinit.ctxt, polygon );
2585  if ( nRings < 0 )
2586  return nullptr;
2587 
2588  //does outer ring intersect?
2589  const GEOSGeometry *outerRing = GEOSGetExteriorRing_r( geosinit.ctxt, polygon );
2590  if ( GEOSIntersects_r( geosinit.ctxt, outerRing, reshapeLineGeos ) == 1 )
2591  {
2592  ++nIntersections;
2593  lastIntersectingRing = -1;
2594  lastIntersectingGeom = outerRing;
2595  }
2596 
2597  //do inner rings intersect?
2598  const GEOSGeometry **innerRings = new const GEOSGeometry*[nRings];
2599 
2600  try
2601  {
2602  for ( int i = 0; i < nRings; ++i )
2603  {
2604  innerRings[i] = GEOSGetInteriorRingN_r( geosinit.ctxt, polygon, i );
2605  if ( GEOSIntersects_r( geosinit.ctxt, innerRings[i], reshapeLineGeos ) == 1 )
2606  {
2607  ++nIntersections;
2608  lastIntersectingRing = i;
2609  lastIntersectingGeom = innerRings[i];
2610  }
2611  }
2612  }
2613  catch ( GEOSException & )
2614  {
2615  nIntersections = 0;
2616  }
2617 
2618  if ( nIntersections != 1 ) //reshape line is only allowed to intersect one ring
2619  {
2620  delete [] innerRings;
2621  return nullptr;
2622  }
2623 
2624  //we have one intersecting ring, let's try to reshape it
2625  geos::unique_ptr reshapeResult = reshapeLine( lastIntersectingGeom, reshapeLineGeos, precision );
2626  if ( !reshapeResult )
2627  {
2628  delete [] innerRings;
2629  return nullptr;
2630  }
2631 
2632  //if reshaping took place, we need to reassemble the polygon and its rings
2633  GEOSGeometry *newRing = nullptr;
2634  const GEOSCoordSequence *reshapeSequence = GEOSGeom_getCoordSeq_r( geosinit.ctxt, reshapeResult.get() );
2635  GEOSCoordSequence *newCoordSequence = GEOSCoordSeq_clone_r( geosinit.ctxt, reshapeSequence );
2636 
2637  reshapeResult.reset();
2638 
2639  newRing = GEOSGeom_createLinearRing_r( geosinit.ctxt, newCoordSequence );
2640  if ( !newRing )
2641  {
2642  delete [] innerRings;
2643  return nullptr;
2644  }
2645 
2646  GEOSGeometry *newOuterRing = nullptr;
2647  if ( lastIntersectingRing == -1 )
2648  newOuterRing = newRing;
2649  else
2650  newOuterRing = GEOSGeom_clone_r( geosinit.ctxt, outerRing );
2651 
2652  //check if all the rings are still inside the outer boundary
2653  QVector<GEOSGeometry *> ringList;
2654  if ( nRings > 0 )
2655  {
2656  GEOSGeometry *outerRingPoly = GEOSGeom_createPolygon_r( geosinit.ctxt, GEOSGeom_clone_r( geosinit.ctxt, newOuterRing ), nullptr, 0 );
2657  if ( outerRingPoly )
2658  {
2659  GEOSGeometry *currentRing = nullptr;
2660  for ( int i = 0; i < nRings; ++i )
2661  {
2662  if ( lastIntersectingRing == i )
2663  currentRing = newRing;
2664  else
2665  currentRing = GEOSGeom_clone_r( geosinit.ctxt, innerRings[i] );
2666 
2667  //possibly a ring is no longer contained in the result polygon after reshape
2668  if ( GEOSContains_r( geosinit.ctxt, outerRingPoly, currentRing ) == 1 )
2669  ringList.push_back( currentRing );
2670  else
2671  GEOSGeom_destroy_r( geosinit.ctxt, currentRing );
2672  }
2673  }
2674  GEOSGeom_destroy_r( geosinit.ctxt, outerRingPoly );
2675  }
2676 
2677  GEOSGeometry **newInnerRings = new GEOSGeometry*[ringList.size()];
2678  for ( int i = 0; i < ringList.size(); ++i )
2679  newInnerRings[i] = ringList.at( i );
2680 
2681  delete [] innerRings;
2682 
2683  geos::unique_ptr reshapedPolygon( GEOSGeom_createPolygon_r( geosinit.ctxt, newOuterRing, newInnerRings, ringList.size() ) );
2684  delete[] newInnerRings;
2685 
2686  return reshapedPolygon;
2687 }
2688 
2689 int QgsGeos::lineContainedInLine( const GEOSGeometry *line1, const GEOSGeometry *line2 )
2690 {
2691  if ( !line1 || !line2 )
2692  {
2693  return -1;
2694  }
2695 
2696  double bufferDistance = std::pow( 10.0L, geomDigits( line2 ) - 11 );
2697 
2698  geos::unique_ptr bufferGeom( GEOSBuffer_r( geosinit.ctxt, line2, bufferDistance, DEFAULT_QUADRANT_SEGMENTS ) );
2699  if ( !bufferGeom )
2700  return -2;
2701 
2702  geos::unique_ptr intersectionGeom( GEOSIntersection_r( geosinit.ctxt, bufferGeom.get(), line1 ) );
2703 
2704  //compare ratio between line1Length and intersectGeomLength (usually close to 1 if line1 is contained in line2)
2705  double intersectGeomLength;
2706  double line1Length;
2707 
2708  GEOSLength_r( geosinit.ctxt, intersectionGeom.get(), &intersectGeomLength );
2709  GEOSLength_r( geosinit.ctxt, line1, &line1Length );
2710 
2711  double intersectRatio = line1Length / intersectGeomLength;
2712  if ( intersectRatio > 0.9 && intersectRatio < 1.1 )
2713  return 1;
2714 
2715  return 0;
2716 }
2717 
2718 int QgsGeos::pointContainedInLine( const GEOSGeometry *point, const GEOSGeometry *line )
2719 {
2720  if ( !point || !line )
2721  return -1;
2722 
2723  double bufferDistance = std::pow( 10.0L, geomDigits( line ) - 11 );
2724 
2725  geos::unique_ptr lineBuffer( GEOSBuffer_r( geosinit.ctxt, line, bufferDistance, 8 ) );
2726  if ( !lineBuffer )
2727  return -2;
2728 
2729  bool contained = false;
2730  if ( GEOSContains_r( geosinit.ctxt, lineBuffer.get(), point ) == 1 )
2731  contained = true;
2732 
2733  return contained;
2734 }
2735 
2736 int QgsGeos::geomDigits( const GEOSGeometry *geom )
2737 {
2738  geos::unique_ptr bbox( GEOSEnvelope_r( geosinit.ctxt, geom ) );
2739  if ( !bbox.get() )
2740  return -1;
2741 
2742  const GEOSGeometry *bBoxRing = GEOSGetExteriorRing_r( geosinit.ctxt, bbox.get() );
2743  if ( !bBoxRing )
2744  return -1;
2745 
2746  const GEOSCoordSequence *bBoxCoordSeq = GEOSGeom_getCoordSeq_r( geosinit.ctxt, bBoxRing );
2747 
2748  if ( !bBoxCoordSeq )
2749  return -1;
2750 
2751  unsigned int nCoords = 0;
2752  if ( !GEOSCoordSeq_getSize_r( geosinit.ctxt, bBoxCoordSeq, &nCoords ) )
2753  return -1;
2754 
2755  int maxDigits = -1;
2756  for ( unsigned int i = 0; i < nCoords - 1; ++i )
2757  {
2758  double t;
2759  GEOSCoordSeq_getX_r( geosinit.ctxt, bBoxCoordSeq, i, &t );
2760 
2761  int digits;
2762  digits = std::ceil( std::log10( std::fabs( t ) ) );
2763  if ( digits > maxDigits )
2764  maxDigits = digits;
2765 
2766  GEOSCoordSeq_getY_r( geosinit.ctxt, bBoxCoordSeq, i, &t );
2767  digits = std::ceil( std::log10( std::fabs( t ) ) );
2768  if ( digits > maxDigits )
2769  maxDigits = digits;
2770  }
2771 
2772  return maxDigits;
2773 }
2774 
2775 GEOSContextHandle_t QgsGeos::getGEOSHandler()
2776 {
2777  return geosinit.ctxt;
2778 }
bool isMeasure() const
Returns true if the geometry contains m values.
A rectangle specified with double values.
Definition: qgsrectangle.h:40
double y
Definition: qgspoint.h:42
bool disjoint(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if geom is disjoint from this.
Definition: qgsgeos.cpp:518
QgsAbstractGeometry * intersection(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Calculate the intersection of this and geom.
Definition: qgsgeos.cpp:217
QgsGeometry mergeLines(QString *errorMsg=nullptr) const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
Definition: qgsgeos.cpp:2093
#define CATCH_GEOS(r)
Definition: qgsgeos.cpp:33
bool isNull() const
Returns true if the geometry is null (ie, contains no underlying geometry accessible via geometry() )...
QgsGeos(const QgsAbstractGeometry *geometry, double precision=0)
GEOS geometry engine constructor.
Definition: qgsgeos.cpp:145
void setXMaximum(double x)
Set the maximum x value.
Definition: qgsrectangle.h:134
const double * mData() const
Returns a const pointer to the m vertex data, or a nullptr if the linestring does not have m values...
Multi point geometry collection.
Definition: qgsmultipoint.h:29
static bool isMultiType(Type type)
Returns true if the WKB type is a multi type.
Definition: qgswkbtypes.h:557
The source geometry is not multi.
Definition: qgsgeometry.h:125
bool isEmpty(QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:1693
#define QgsDebugMsg(str)
Definition: qgslogger.h:38
QgsPoint * pointOnSurface(QString *errorMsg=nullptr) const override
Calculate a point that is guaranteed to be on the surface of this.
Definition: qgsgeos.cpp:1615
double y
Definition: qgspointxy.h:48
QgsGeometry shortestLine(const QgsGeometry &other, QString *errorMsg=nullptr) const
Returns the shortest line joining this geometry to the other geometry.
Definition: qgsgeos.cpp:2146
double area(QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:586
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:251
const QgsAbstractGeometry * mGeometry
const QgsCurve * interiorRing(int i) const
QgsAbstractGeometry * buffer(double distance, int segments, QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:1512
Multi line string geometry collection.
Curve polygon geometry type.
static std::unique_ptr< QgsGeometryCollection > createCollectionOfType(QgsWkbTypes::Type type)
Returns a new geometry collection matching a specified WKB type.
double length(QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:603
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:104
bool isEqual(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if this is equal to geom.
Definition: qgsgeos.cpp:1673
bool isValid(QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:1659
QgsGeometry closestPoint(const QgsGeometry &other, QString *errorMsg=nullptr) const
Returns the closest point on the geometry to the other geometry.
Definition: qgsgeos.cpp:2112
virtual QgsRectangle boundingBox() const =0
Returns the minimal bounding box for the geometry.
static QgsGeometry::OperationResult addPart(QgsGeometry &geometry, GEOSGeometry *newPart)
Adds a new island polygon to a multipolygon feature.
Definition: qgsgeos.cpp:176
void CORE_EXPORT operator()(GEOSGeometry *geom)
Destroys the GEOS geometry geom, using the static QGIS geos context.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
OperationResult
Success or failure of a geometry operation.
Definition: qgsgeometry.h:113
std::unique_ptr< QgsAbstractGeometry > singleSidedBuffer(double distance, int segments, int side, int joinStyle, double miterLimit, QString *errorMsg=nullptr) const
Returns a single sided buffer for a geometry.
Definition: qgsgeos.cpp:1951
static GEOSContextHandle_t getGEOSHandler()
Definition: qgsgeos.cpp:2775
int numPoints() const override
Returns the number of points in the curve.
QgsAbstractGeometry * interpolate(double distance, QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:1559
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
bool within(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if geom is within this.
Definition: qgsgeos.cpp:503
const double * xData() const
Returns a const pointer to the x vertex data.
#define CATCH_GEOS_WITH_ERRMSG(r)
Definition: qgsgeos.cpp:39
int numInteriorRings() const
Operation succeeded.
Nothing happened, without any error.
Type
The WKB type describes the number of dimensions a geometry has.
Definition: qgswkbtypes.h:67
QgsAbstractGeometry * envelope(QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:1600
std::unique_ptr< QgsAbstractGeometry > reshapeGeometry(const QgsLineString &reshapeWithLine, EngineOperationResult *errorCode, QString *errorMsg=nullptr) const
Reshapes the geometry using a line.
Definition: qgsgeos.cpp:1977
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
Definition: qgsgeos.cpp:1081
void addVertex(const QgsPoint &pt)
Adds a new vertex to the end of the line string.
bool touches(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if geom touches this.
Definition: qgsgeos.cpp:493
bool isEmpty() const
Returns true if the rectangle is empty.
Definition: qgsrectangle.h:419
Geometry collection.
double lineLocatePoint(const QgsPoint &point, QString *errorMsg=nullptr) const
Returns a distance representing the location along this linestring of the closest point on this lines...
Definition: qgsgeos.cpp:2187
void prepareGeometry() override
Prepares the geometry, so that subsequent calls to spatial relation methods are much faster...
Definition: qgsgeos.cpp:198
double width() const
Returns the width of the rectangle.
Definition: qgsrectangle.h:201
double mAt(int index) const
Returns the m value of the specified node in the line string.
void setYMinimum(double y)
Set the minimum y value.
Definition: qgsrectangle.h:139
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition: qgsgeos.h:79
double yAt(int index) const override
Returns the y-coordinate of the specified node in the line string.
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:663
double hausdorffDistanceDensify(const QgsAbstractGeometry *geom, double densifyFraction, QString *errorMsg=nullptr) const
Returns the Hausdorff distance between this geometry and geom.
Definition: qgsgeos.cpp:465
bool relatePattern(const QgsAbstractGeometry *geom, const QString &pattern, QString *errorMsg=nullptr) const override
Tests whether two geometries are related by a specified Dimensional Extended 9 Intersection Model (DE...
Definition: qgsgeos.cpp:557
QgsPoint * centroid(QString *errorMsg=nullptr) const override
Calculates the centroid of this.
Definition: qgsgeos.cpp:1574
T qgsgeometry_cast(const QgsAbstractGeometry *geom)
Multi curve geometry collection.
Definition: qgsmulticurve.h:29
double distance(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Calculates the distance between this and geom.
Definition: qgsgeos.cpp:419
static QgsGeometry polygonize(const QVector< const QgsAbstractGeometry *> &geometries, QString *errorMsg=nullptr)
Creates a GeometryCollection geometry containing possible polygons formed from the constituent linewo...
Definition: qgsgeos.cpp:2217
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition: qgspoint.cpp:94
Abstract base class for curved geometry type.
Definition: qgscurve.h:35
Abstract base class for all geometries.
virtual int dimension() const =0
Returns the inherent dimension of the geometry.
std::unique_ptr< GEOSBufferParams, GeosDeleter > buffer_params_unique_ptr
Scoped GEOS buffer params pointer.
Definition: qgsgeos.h:89
QgsWkbTypes::Type wkbType() const
Returns the WKB type of the geometry.
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:37
QgsGeometry delaunayTriangulation(double tolerance=0.0, bool edgesOnly=false, QString *errorMsg=nullptr) const
Returns the Delaunay triangulation for the vertices of the geometry.
Definition: qgsgeos.cpp:2288
const double * yData() const
Returns a const pointer to the y vertex data.
Error occurred while creating a noded geometry.
double x
Definition: qgspointxy.h:47
QgsLineString * clone() const override
Clones the geometry by performing a deep copy.
Error occurred in the geometry engine.
const double * zData() const
Returns a const pointer to the z vertex data, or a nullptr if the linestring does not have z values...
int numGeometries() const
Returns the number of geometries within the collection.
QgsAbstractGeometry * symDifference(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Calculate the symmetric difference of this and geom.
Definition: qgsgeos.cpp:414
Contains geos related utilities and functions.
Definition: qgsgeos.h:41
std::unique_ptr< QgsAbstractGeometry > clip(const QgsRectangle &rectangle, QString *errorMsg=nullptr) const
Performs a fast, non-robust intersection between the geometry and a rectangle.
Definition: qgsgeos.cpp:227
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:176
QgsAbstractGeometry * combine(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Calculate the combination of this and geom.
Definition: qgsgeos.cpp:361
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:161
void geometryChanged() override
Should be called whenever the geometry associated with the engine has been modified and the engine mu...
Definition: qgsgeos.cpp:191
QVector< QgsPoint > QgsPointSequence
static QgsPoint coordSeqPoint(const GEOSCoordSequence *cs, int i, bool hasZ, bool hasM)
Definition: qgsgeos.cpp:1251
static QgsGeometry::OperationResult addPart(QgsAbstractGeometry *geometry, std::unique_ptr< QgsAbstractGeometry > part)
Add a part to multi type geometry.
QgsAbstractGeometry * offsetCurve(double distance, int segments, int joinStyle, double miterLimit, QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:1936
QgsAbstractGeometry * convexHull(QString *errorMsg=nullptr) const override
Calculate the convex hull of this.
Definition: qgsgeos.cpp:1643
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0)
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
Definition: qgsgeos.cpp:166
The base geometry on which the operation is done is invalid or empty.
Definition: qgsgeometry.h:117
Multi polygon geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
bool contains(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if geom contains this.
Definition: qgsgeos.cpp:513
void setYMaximum(double y)
Set the maximum y value.
Definition: qgsrectangle.h:144
std::unique_ptr< QgsAbstractGeometry > subdivide(int maxNodes, QString *errorMsg=nullptr) const
Subdivides the geometry.
Definition: qgsgeos.cpp:341
Line string geometry type, with support for z-dimension and m-values.
Definition: qgslinestring.h:43
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...
const QgsAbstractGeometry * geometryN(int n) const
Returns a const reference to a geometry from within the collection.
QString relate(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Returns the Dimensional Extended 9 Intersection Model (DE-9IM) representation of the relationship bet...
Definition: qgsgeos.cpp:523
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
Definition: qgsrectangle.h:429
QgsPoint pointN(int i) const
Returns the specified point from inside the line string.
EngineOperationResult splitGeometry(const QgsLineString &splitLine, QVector< QgsGeometry > &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, QString *errorMsg=nullptr) const override
Splits this geometry according to a given line.
Definition: qgsgeos.cpp:619
bool intersects(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if geom intersects this.
Definition: qgsgeos.cpp:488
The input is not valid.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:166
double hausdorffDistance(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const
Returns the Hausdorff distance between this geometry and geom.
Definition: qgsgeos.cpp:442
double xAt(int index) const override
Returns the x-coordinate of the specified node in the line string.
QgsAbstractGeometry * difference(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Calculate the difference of this and geom.
Definition: qgsgeos.cpp:222
bool overlaps(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if geom overlaps this.
Definition: qgsgeos.cpp:508
double z
Definition: qgspoint.h:43
Contains geometry relation and modification algorithms.
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:171
static std::unique_ptr< QgsPolygon > fromGeosPolygon(const GEOSGeometry *geos)
Definition: qgsgeos.cpp:1169
std::unique_ptr< GEOSCoordSequence, GeosDeleter > coord_sequence_unique_ptr
Scoped GEOS coordinate sequence pointer.
Definition: qgsgeos.h:94
EngineOperationResult
Success or failure of a geometry operation.
QgsGeometry voronoiDiagram(const QgsAbstractGeometry *extent=nullptr, double tolerance=0.0, bool edgesOnly=false, QString *errorMsg=nullptr) const
Creates a Voronoi diagram for the nodes contained within the geometry.
Definition: qgsgeos.cpp:2256
static QgsGeometry geometryFromGeos(GEOSGeometry *geos)
Creates a new QgsGeometry object, feeding in a geometry in GEOS format.
Definition: qgsgeos.cpp:153
Polygon geometry type.
Definition: qgspolygon.h:31
const QgsCurve * exteriorRing() const
static Type flatType(Type type)
Returns the flat type for a WKB type.
Definition: qgswkbtypes.h:427
The geometry on which the operation occurs is not valid.
#define DEFAULT_QUADRANT_SEGMENTS
Definition: qgsgeos.cpp:31
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
bool isSimple(QString *errorMsg=nullptr) const override
Determines whether the geometry is simple (according to OGC definition).
Definition: qgsgeos.cpp:1707
bool crosses(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr) const override
Checks if geom crosses this.
Definition: qgsgeos.cpp:498
void setXMinimum(double x)
Set the minimum x value.
Definition: qgsrectangle.h:129
QgsAbstractGeometry * simplify(double tolerance, QString *errorMsg=nullptr) const override
Definition: qgsgeos.cpp:1544
virtual bool addGeometry(QgsAbstractGeometry *g)
Adds a geometry and takes ownership. Returns true in case of success.
double m
Definition: qgspoint.h:44
double height() const
Returns the height of the rectangle.
Definition: qgsrectangle.h:208
double x
Definition: qgspoint.h:41