QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsgeos.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgeos.cpp
3 -------------------------------------------------------------------
4Date : 22 Sept 2014
5Copyright : (C) 2014 by Marco Hugentobler
6email : 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
18#include <cstdio>
19#include <limits>
20#include <memory>
21
22#include "qgsabstractgeometry.h"
23#include "qgscircularstring.h"
24#include "qgsfeedback.h"
27#include "qgsgeometryfactory.h"
29#include "qgslinestring.h"
30#include "qgslogger.h"
31#include "qgsmulticurve.h"
32#include "qgsmultilinestring.h"
33#include "qgsmultipoint.h"
34#include "qgsmultipolygon.h"
35#include "qgspolygon.h"
38#include "qgssettingstree.h"
39
40#include <QString>
41
42using namespace Qt::StringLiterals;
43
44#define DEFAULT_QUADRANT_SEGMENTS 8
45
46#define CATCH_GEOS( r ) \
47 catch ( QgsGeosException & ) \
48 { \
49 return r; \
50 }
51
52#define CATCH_GEOS_WITH_ERRMSG( r ) \
53 catch ( QgsGeosException & e ) \
54 { \
55 if ( errorMsg ) \
56 { \
57 *errorMsg = e.what(); \
58 if ( errorMsg->startsWith( "InterruptedException"_L1, Qt::CaseInsensitive ) ) \
59 { \
60 errorMsg->clear(); \
61 } \
62 } \
63 return r; \
64 }
65
67
68static void throwQgsGeosException( const char *fmt, ... )
69{
70 va_list ap;
71 char buffer[1024];
72
73 va_start( ap, fmt );
74 vsnprintf( buffer, sizeof buffer, fmt, ap );
75 va_end( ap );
76
77 QString message = QString::fromUtf8( buffer );
78
79#ifdef _MSC_VER
80 // stupid stupid MSVC, *SOMETIMES* raises it's own exception if we throw QgsGeosException, resulting in a crash!
81 // see https://github.com/qgis/QGIS/issues/22709
82 // if you want to test alternative fixes for this, run the testqgsexpression.cpp test suite - that will crash
83 // and burn on the "line_interpolate_point point" test if a QgsGeosException is thrown.
84 // TODO - find a real fix for the underlying issue
85 try
86 {
87 throw QgsGeosException( message );
88 }
89 catch ( ... )
90 {
91 // oops, msvc threw an exception when we tried to throw the exception!
92 // just throw nothing instead (except your mouse at your monitor)
93 }
94#else
95 throw QgsGeosException( message );
96#endif
97}
98
99
100static void printGEOSNotice( const char *fmt, ... )
101{
102#if defined( QGISDEBUG )
103 va_list ap;
104 char buffer[1024];
105
106 va_start( ap, fmt );
107 vsnprintf( buffer, sizeof buffer, fmt, ap );
108 va_end( ap );
109#else
110 Q_UNUSED( fmt )
111#endif
112}
113
114//
115// QgsGeosContext
116//
117
118#if defined( USE_THREAD_LOCAL ) && !defined( Q_OS_WIN )
119thread_local QgsGeosContext QgsGeosContext::sGeosContext;
120#else
121QThreadStorage< QgsGeosContext * > QgsGeosContext::sGeosContext;
122#endif
123
124
126{
127 mContext = GEOS_init_r();
128 GEOSContext_setNoticeHandler_r( mContext, printGEOSNotice );
129 GEOSContext_setErrorHandler_r( mContext, throwQgsGeosException );
130
131#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
132 // Set CurveToLine and LineToCurve default params to the context.
133 // This ensures that if a GEOS method does not support curves, it will linearize
134 // any curve geometry input if needed, and will also convert any linear output
135 // to a curved type, if the inputs were converted to curves.
136 GEOSCurveToLineParams *curveToLineParams = GEOSCurveToLineParams_create();
137 GEOSContext_setCurveToLineParams_r( mContext, curveToLineParams );
138 GEOSCurveToLineParams_destroy( curveToLineParams );
139
140 // The second part of the conversion is managed by a hidden setting, so that
141 // we can enable/disable it at will to spot missing curve support in GEOS.
143 {
144 GEOSLineToCurveParams *lineToCurveParams = GEOSLineToCurveParams_create();
145 GEOSContext_setLineToCurveParams_r( mContext, lineToCurveParams );
146 GEOSLineToCurveParams_destroy( lineToCurveParams );
147 }
148#endif
149}
150
152{
153 GEOS_finish_r( mContext );
154}
155
156GEOSContextHandle_t QgsGeosContext::get()
157{
158#if defined( USE_THREAD_LOCAL ) && !defined( Q_OS_WIN )
159 return sGeosContext.mContext;
160#else
161 GEOSContextHandle_t gContext = nullptr;
162 if ( sGeosContext.hasLocalData() )
163 {
164 gContext = sGeosContext.localData()->mContext;
165 }
166 else
167 {
168 sGeosContext.setLocalData( new QgsGeosContext() );
169 gContext = sGeosContext.localData()->mContext;
170 }
171 return gContext;
172#endif
173}
174
175//
176// geos
177//
178
180{
181 GEOSGeom_destroy_r( QgsGeosContext::get(), geom );
182}
183
184void geos::GeosDeleter::operator()( const GEOSPreparedGeometry *geom ) const
185{
186 GEOSPreparedGeom_destroy_r( QgsGeosContext::get(), geom );
187}
188
189void geos::GeosDeleter::operator()( GEOSBufferParams *params ) const
190{
191 GEOSBufferParams_destroy_r( QgsGeosContext::get(), params );
192}
193
194void geos::GeosDeleter::operator()( GEOSCoordSequence *sequence ) const
195{
196 GEOSCoordSeq_destroy_r( QgsGeosContext::get(), sequence );
197}
198
200
201
202const QgsSettingsEntryBool *QgsGeos::settingLineToCurveParam
203 = new QgsSettingsEntryBool( u"line-to-curve-param"_s, QgsSettingsTree::sTreeGeos, false, u"Whether to convert any linear output of a GEOS method to a curved type, if the inputs were converted to curves."_s );
204
205QgsGeos::QgsGeos( const QgsAbstractGeometry *geometry, double precision, Qgis::GeosCreationFlags flags )
206 : QgsGeometryEngine( geometry )
207 , mGeos( nullptr )
208 , mPrecision( precision )
209{
210 cacheGeos( flags );
211}
212
214{
216 GEOSGeom_destroy_r( QgsGeosContext::get(), geos );
217 return g;
218}
219
225
226std::unique_ptr<QgsAbstractGeometry> QgsGeos::makeValid( Qgis::MakeValidMethod method, bool keepCollapsed, QString *errorMsg, QgsFeedback *feedback ) const
227{
228 if ( !mGeos )
229 {
230 return nullptr;
231 }
232
233 GEOSContextHandle_t context = QgsGeosContext::get();
234
235#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 10, 0 )
236 if ( method != Qgis::MakeValidMethod::Linework )
237 throw QgsNotSupportedException( QObject::tr( "The structured method to make geometries valid requires a QGIS build based on GEOS 3.10 or later" ) );
238
239 if ( keepCollapsed )
240 throw QgsNotSupportedException( QObject::tr( "The keep collapsed option for making geometries valid requires a QGIS build based on GEOS 3.10 or later" ) );
242 try
243 {
244 geos.reset( GEOSMakeValid_r( context, mGeos.get() ) );
245 }
246 CATCH_GEOS_WITH_ERRMSG( nullptr )
247#else
248
249 GEOSMakeValidParams *params = GEOSMakeValidParams_create_r( context );
250 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
251 switch ( method )
252 {
254 GEOSMakeValidParams_setMethod_r( context, params, GEOS_MAKE_VALID_LINEWORK );
255 break;
256
258 GEOSMakeValidParams_setMethod_r( context, params, GEOS_MAKE_VALID_STRUCTURE );
259 break;
260 }
261
262 GEOSMakeValidParams_setKeepCollapsed_r( context, params, keepCollapsed ? 1 : 0 );
263
265 try
266 {
267 geos.reset( GEOSMakeValidWithParams_r( context, mGeos.get(), params ) );
268 GEOSMakeValidParams_destroy_r( context, params );
269 }
270 catch ( QgsGeosException &e )
271 {
272 if ( errorMsg )
273 {
274 *errorMsg = e.what();
275 }
276 GEOSMakeValidParams_destroy_r( context, params );
277 return nullptr;
278 }
279#endif
280
281 return fromGeos( geos.get() );
282}
283
284geos::unique_ptr QgsGeos::asGeos( const QgsGeometry &geometry, double precision, Qgis::GeosCreationFlags flags )
285{
286 if ( geometry.isNull() )
287 {
288 return nullptr;
289 }
290
291 return asGeos( geometry.constGet(), precision, flags );
292}
293
295{
296 if ( geometry.isNull() )
297 {
299 }
300 if ( !newPart )
301 {
303 }
304
305 std::unique_ptr< QgsAbstractGeometry > geom = fromGeos( newPart );
306 return QgsGeometryEditUtils::addPart( geometry.get(), std::move( geom ) );
307}
308
310{
311 mGeos.reset();
312 mGeosPrepared.reset();
314}
315
317{
318 if ( mGeosPrepared )
319 {
320 // Already prepared
321 return;
322 }
323 if ( mGeos )
324 {
325#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
326 if ( mGeometry->hasCurvedSegments() )
327 {
328 // Segmentize the input until GEOSPrepare_r accepts curves
329 std::unique_ptr< QgsAbstractGeometry > segmentized( mGeometry->segmentize() );
330 mGeosPrepared.reset( GEOSPrepare_r( QgsGeosContext::get(), asGeos( segmentized.release() ).release() ) );
331 }
332 else
333 {
334#endif
335 mGeosPrepared.reset( GEOSPrepare_r( QgsGeosContext::get(), mGeos.get() ) );
336#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
337 }
338#endif
339 }
340}
341
342void QgsGeos::cacheGeos( Qgis::GeosCreationFlags flags ) const
343{
344 if ( mGeos )
345 {
346 // Already cached
347 return;
348 }
349 if ( !mGeometry )
350 {
351 return;
352 }
353
354 mGeos = asGeos( mGeometry, mPrecision, flags );
355}
356
357QgsAbstractGeometry *QgsGeos::intersection( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
358{
359 return overlay( geom, OverlayIntersection, errorMsg, parameters, feedback ).release();
360}
361
362QgsAbstractGeometry *QgsGeos::difference( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
363{
364 return overlay( geom, OverlayDifference, errorMsg, parameters, feedback ).release();
365}
366
367std::unique_ptr<QgsAbstractGeometry> QgsGeos::clip( const QgsRectangle &rect, QString *errorMsg, QgsFeedback *feedback ) const
368{
369 if ( !mGeos || rect.isNull() || rect.isEmpty() )
370 {
371 return nullptr;
372 }
373
374 try
375 {
376 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
377 geos::unique_ptr opGeom( GEOSClipByRect_r( QgsGeosContext::get(), mGeos.get(), rect.xMinimum(), rect.yMinimum(), rect.xMaximum(), rect.yMaximum() ) );
378 return fromGeos( opGeom.get() );
379 }
380 catch ( QgsGeosException &e )
381 {
382 logError( u"GEOS"_s, e.what() );
383 if ( errorMsg )
384 {
385 *errorMsg = e.what();
386 }
387 return nullptr;
388 }
389}
390
391void QgsGeos::subdivideRecursive( const GEOSGeometry *currentPart, int maxNodes, int depth, QgsGeometryCollection *parts, const QgsRectangle &clipRect, double gridSize ) const
392{
393 GEOSContextHandle_t context = QgsGeosContext::get();
394 int partType = GEOSGeomTypeId_r( context, currentPart );
395 if ( qgsDoubleNear( clipRect.width(), 0.0 ) && qgsDoubleNear( clipRect.height(), 0.0 ) )
396 {
397 if ( partType == GEOS_POINT )
398 {
399 parts->addGeometry( fromGeos( currentPart ).release() );
400 return;
401 }
402 else
403 {
404 return;
405 }
406 }
407
408 if ( partType == GEOS_MULTILINESTRING || partType == GEOS_MULTIPOLYGON || partType == GEOS_GEOMETRYCOLLECTION )
409 {
410 int partCount = GEOSGetNumGeometries_r( context, currentPart );
411 for ( int i = 0; i < partCount; ++i )
412 {
413 subdivideRecursive( GEOSGetGeometryN_r( context, currentPart, i ), maxNodes, depth, parts, clipRect, gridSize );
414 }
415 return;
416 }
417
418 if ( depth > 50 )
419 {
420 parts->addGeometry( fromGeos( currentPart ).release() );
421 return;
422 }
423
424 int vertexCount = GEOSGetNumCoordinates_r( context, currentPart );
425 if ( vertexCount == 0 )
426 {
427 return;
428 }
429 else if ( vertexCount < maxNodes )
430 {
431 parts->addGeometry( fromGeos( currentPart ).release() );
432 return;
433 }
434
435 // chop clipping rect in half by longest side
436 double width = clipRect.width();
437 double height = clipRect.height();
438 QgsRectangle halfClipRect1 = clipRect;
439 QgsRectangle halfClipRect2 = clipRect;
440 if ( width > height )
441 {
442 halfClipRect1.setXMaximum( clipRect.xMinimum() + width / 2.0 );
443 halfClipRect2.setXMinimum( halfClipRect1.xMaximum() );
444 }
445 else
446 {
447 halfClipRect1.setYMaximum( clipRect.yMinimum() + height / 2.0 );
448 halfClipRect2.setYMinimum( halfClipRect1.yMaximum() );
449 }
450
451 if ( height <= 0 )
452 {
453 halfClipRect1.setYMinimum( halfClipRect1.yMinimum() - std::numeric_limits<double>::epsilon() );
454 halfClipRect2.setYMinimum( halfClipRect2.yMinimum() - std::numeric_limits<double>::epsilon() );
455 halfClipRect1.setYMaximum( halfClipRect1.yMaximum() + std::numeric_limits<double>::epsilon() );
456 halfClipRect2.setYMaximum( halfClipRect2.yMaximum() + std::numeric_limits<double>::epsilon() );
457 }
458 if ( width <= 0 )
459 {
460 halfClipRect1.setXMinimum( halfClipRect1.xMinimum() - std::numeric_limits<double>::epsilon() );
461 halfClipRect2.setXMinimum( halfClipRect2.xMinimum() - std::numeric_limits<double>::epsilon() );
462 halfClipRect1.setXMaximum( halfClipRect1.xMaximum() + std::numeric_limits<double>::epsilon() );
463 halfClipRect2.setXMaximum( halfClipRect2.xMaximum() + std::numeric_limits<double>::epsilon() );
464 }
465
466 geos::unique_ptr clipPart1( GEOSClipByRect_r( context, currentPart, halfClipRect1.xMinimum(), halfClipRect1.yMinimum(), halfClipRect1.xMaximum(), halfClipRect1.yMaximum() ) );
467 geos::unique_ptr clipPart2( GEOSClipByRect_r( context, currentPart, halfClipRect2.xMinimum(), halfClipRect2.yMinimum(), halfClipRect2.xMaximum(), halfClipRect2.yMaximum() ) );
468
469 ++depth;
470
471 if ( clipPart1 )
472 {
473 if ( gridSize > 0 )
474 {
475 clipPart1.reset( GEOSIntersectionPrec_r( context, mGeos.get(), clipPart1.get(), gridSize ) );
476 }
477 subdivideRecursive( clipPart1.get(), maxNodes, depth, parts, halfClipRect1, gridSize );
478 }
479 if ( clipPart2 )
480 {
481 if ( gridSize > 0 )
482 {
483 clipPart2.reset( GEOSIntersectionPrec_r( context, mGeos.get(), clipPart2.get(), gridSize ) );
484 }
485 subdivideRecursive( clipPart2.get(), maxNodes, depth, parts, halfClipRect2, gridSize );
486 }
487}
488
489std::unique_ptr<QgsAbstractGeometry> QgsGeos::subdivide( int maxNodes, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
490{
491 if ( !mGeos )
492 {
493 return nullptr;
494 }
495
496 // minimum allowed max is 8
497 maxNodes = std::max( maxNodes, 8 );
498
499 std::unique_ptr< QgsGeometryCollection > parts = QgsGeometryFactory::createCollectionOfType( mGeometry->wkbType() );
500 try
501 {
502 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
503 subdivideRecursive( mGeos.get(), maxNodes, 0, parts.get(), mGeometry->boundingBox(), parameters.gridSize() );
504 }
505 CATCH_GEOS_WITH_ERRMSG( nullptr )
506
507 return std::move( parts );
508}
509
510QgsAbstractGeometry *QgsGeos::combine( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
511{
512 return overlay( geom, OverlayUnion, errorMsg, parameters, feedback ).release();
513}
514
515QgsAbstractGeometry *QgsGeos::combine( const QVector<QgsAbstractGeometry *> &geomList, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
516{
517 std::vector<geos::unique_ptr> geosGeometries;
518 geosGeometries.reserve( geomList.size() );
519 for ( const QgsAbstractGeometry *g : geomList )
520 {
521 if ( !g )
522 continue;
523
524 geosGeometries.emplace_back( asGeos( g, mPrecision ) );
525 }
526
527 GEOSContextHandle_t context = QgsGeosContext::get();
528 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
529 geos::unique_ptr geomUnion;
530 try
531 {
532 geos::unique_ptr geomCollection = createGeosCollection( GEOS_GEOMETRYCOLLECTION, geosGeometries );
533 if ( parameters.gridSize() > 0 )
534 {
535 geomUnion.reset( GEOSUnaryUnionPrec_r( context, geomCollection.get(), parameters.gridSize() ) );
536 }
537 else
538 {
539 geomUnion.reset( GEOSUnaryUnion_r( context, geomCollection.get() ) );
540 }
541 }
542 CATCH_GEOS_WITH_ERRMSG( nullptr )
543
544 std::unique_ptr< QgsAbstractGeometry > result = fromGeos( geomUnion.get() );
545 return result.release();
546}
547
548QgsAbstractGeometry *QgsGeos::combine( const QVector<QgsGeometry> &geomList, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
549{
550 std::vector<geos::unique_ptr> geosGeometries;
551 geosGeometries.reserve( geomList.size() );
552 for ( const QgsGeometry &g : geomList )
553 {
554 if ( g.isNull() )
555 continue;
556
557 geosGeometries.emplace_back( asGeos( g.constGet(), mPrecision ) );
558 }
559
560 GEOSContextHandle_t context = QgsGeosContext::get();
561 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
562 geos::unique_ptr geomUnion;
563 try
564 {
565 geos::unique_ptr geomCollection = createGeosCollection( GEOS_GEOMETRYCOLLECTION, geosGeometries );
566
567 if ( parameters.gridSize() > 0 )
568 {
569 geomUnion.reset( GEOSUnaryUnionPrec_r( context, geomCollection.get(), parameters.gridSize() ) );
570 }
571 else
572 {
573 geomUnion.reset( GEOSUnaryUnion_r( context, geomCollection.get() ) );
574 }
575 }
576 CATCH_GEOS_WITH_ERRMSG( nullptr )
577
578 std::unique_ptr< QgsAbstractGeometry > result = fromGeos( geomUnion.get() );
579 return result.release();
580}
581
582QgsAbstractGeometry *QgsGeos::symDifference( const QgsAbstractGeometry *geom, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
583{
584 return overlay( geom, OverlaySymDifference, errorMsg, parameters, feedback ).release();
585}
586
587static bool isZVerticalLine( const QgsAbstractGeometry *geom, double tolerance = 4 * std::numeric_limits<double>::epsilon() )
588{
589 // checks if the Geometry if a purely vertical 3D line LineString Z((X Y Z1, X Y Z2, ..., X Y Zn))
590 // This is needed because QgsGeos is not able to handle this type of geometry on distance computation.
591
593 {
594 return false;
595 }
596
597 bool isVertical = true;
598 if ( const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( geom ) )
599 {
600 const int nrPoints = line->numPoints();
601 if ( nrPoints == 1 )
602 {
603 return true;
604 }
605
606 // if the 2D part of two points of the line are different, this means
607 // that the line is not purely vertical
608 const double sqrTolerance = tolerance * tolerance;
609 const double *lineX = line->xData();
610 const double *lineY = line->yData();
611 for ( int iVert = nrPoints - 1, jVert = 0; jVert < nrPoints; iVert = jVert++ )
612 {
613 if ( QgsGeometryUtilsBase::sqrDistance2D( lineX[iVert], lineY[iVert], lineX[jVert], lineY[jVert] ) > sqrTolerance )
614 {
615 isVertical = false;
616 break;
617 }
618 }
619 }
620
621 return isVertical;
622}
623
624double QgsGeos::distance( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
625{
626 double distance = -1.0;
627 if ( !mGeos )
628 {
629 return distance;
630 }
631
632 geos::unique_ptr otherGeosGeom;
633 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
634
635 // GEOSPreparedDistance_r is not able to properly compute the distance if one
636 // of the geometries if a vertical line (LineString Z((X Y Z1, X Y Z2, ..., X Y Zn))).
637 // In that case, replace `geom` by a single point.
638 // However, GEOSDistance_r works.
639 if ( mGeosPrepared && isZVerticalLine( geom->simplifiedTypeRef() ) )
640 {
641 QgsPoint firstPoint = geom->vertexAt( QgsVertexId( 0, 0, 0 ) );
642 otherGeosGeom = asGeos( &firstPoint, mPrecision );
643 }
644 else
645 {
646 otherGeosGeom = asGeos( geom, mPrecision );
647 }
648
649 if ( !otherGeosGeom )
650 {
651 return distance;
652 }
653
654 GEOSContextHandle_t context = QgsGeosContext::get();
655 try
656 {
657 if ( mGeosPrepared && !isZVerticalLine( mGeometry->simplifiedTypeRef() ) )
658 {
659 GEOSPreparedDistance_r( context, mGeosPrepared.get(), otherGeosGeom.get(), &distance );
660 }
661 else
662 {
663 GEOSDistance_r( context, mGeos.get(), otherGeosGeom.get(), &distance );
664 }
665 }
667
668 return distance;
669}
670
671double QgsGeos::distance( double x, double y, QString *errorMsg, QgsFeedback *feedback ) const
672{
673 double distance = -1.0;
674 if ( !mGeos )
675 {
676 return distance;
677 }
678
679 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
680 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
681 if ( !point )
682 return distance;
683
684 GEOSContextHandle_t context = QgsGeosContext::get();
685 try
686 {
687 if ( mGeosPrepared )
688 {
689 GEOSPreparedDistance_r( context, mGeosPrepared.get(), point.get(), &distance );
690 }
691 else
692 {
693 GEOSDistance_r( context, mGeos.get(), point.get(), &distance );
694 }
695 }
697
698 return distance;
699}
700
701bool QgsGeos::distanceWithin( const QgsAbstractGeometry *geom, double maxdist, QString *errorMsg, QgsFeedback *feedback ) const
702{
703 if ( !mGeos )
704 {
705 return false;
706 }
707
708 if ( qgsDoubleNear( maxdist, 0.0 ) )
709 {
710 return intersects( geom, errorMsg, feedback );
711 }
712
713 geos::unique_ptr otherGeosGeom;
714
715 // GEOSPreparedDistanceWithin_r GEOSPreparedDistance_r are not able to properly compute the distance if one
716 // of the geometries if a vertical line (LineString Z((X Y Z1, X Y Z2, ..., X Y Zn))).
717 // In that case, replace `geom` by a single point.
718 // However, GEOSDistanceWithin_r and GEOSDistance_r work.
719 if ( mGeosPrepared && isZVerticalLine( geom->simplifiedTypeRef() ) )
720 {
721 QgsPoint firstPoint = geom->vertexAt( QgsVertexId( 0, 0, 0 ) );
722 otherGeosGeom = asGeos( &firstPoint );
723 }
724 else
725 {
726 otherGeosGeom = asGeos( geom, mPrecision );
727 }
728
729 if ( !otherGeosGeom )
730 {
731 return false;
732 }
733
734 // TODO: optimize implementation of this function to early-exit if
735 // any part of othergeosGeom is found to be within the given
736 // distance
737 double distance;
738
739 GEOSContextHandle_t context = QgsGeosContext::get();
740 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
741 try
742 {
743 if ( mGeosPrepared && !isZVerticalLine( mGeometry->simplifiedTypeRef() ) )
744 {
745#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
746 return GEOSPreparedDistanceWithin_r( context, mGeosPrepared.get(), otherGeosGeom.get(), maxdist );
747#else
748 GEOSPreparedDistance_r( context, mGeosPrepared.get(), otherGeosGeom.get(), &distance );
749#endif
750 }
751 else
752 {
753#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
754 return GEOSDistanceWithin_r( context, mGeos.get(), otherGeosGeom.get(), maxdist );
755#else
756 GEOSDistance_r( context, mGeos.get(), otherGeosGeom.get(), &distance );
757#endif
758 }
759 }
761
762 return distance <= maxdist;
763}
764
765bool QgsGeos::contains( double x, double y, QString *errorMsg, QgsFeedback *feedback ) const
766{
767 bool result = false;
768 GEOSContextHandle_t context = QgsGeosContext::get();
769 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
770 try
771 {
772#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
773 // defer point creation until after prepared geometry check, we may not need it
774#else
775 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
776 if ( !point )
777 return false;
778#endif
779 if ( mGeosPrepared ) //use faster version with prepared geometry
780 {
781#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
782 return GEOSPreparedContainsXY_r( context, mGeosPrepared.get(), x, y ) == 1;
783#else
784 return GEOSPreparedContains_r( context, mGeosPrepared.get(), point.get() ) == 1;
785#endif
786 }
787
788#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
789 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
790 if ( !point )
791 return false;
792#endif
793
794 result = ( GEOSContains_r( context, mGeos.get(), point.get() ) == 1 );
795 }
796 catch ( QgsGeosException &e )
797 {
798 logError( u"GEOS"_s, e.what() );
799 if ( errorMsg )
800 {
801 *errorMsg = e.what();
802 }
803 return false;
804 }
805
806 return result;
807}
808
809double QgsGeos::hausdorffDistance( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
810{
811 double distance = -1.0;
812 if ( !mGeos )
813 {
814 return distance;
815 }
816
817 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
818 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
819 if ( !otherGeosGeom )
820 {
821 return distance;
822 }
823
824 try
825 {
826 GEOSHausdorffDistance_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), &distance );
827 }
829
830 return distance;
831}
832
833double QgsGeos::hausdorffDistanceDensify( const QgsAbstractGeometry *geom, double densifyFraction, QString *errorMsg, QgsFeedback *feedback ) const
834{
835 double distance = -1.0;
836 if ( !mGeos )
837 {
838 return distance;
839 }
840
841 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
842 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
843 if ( !otherGeosGeom )
844 {
845 return distance;
846 }
847
848 try
849 {
850 GEOSHausdorffDistanceDensify_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), densifyFraction, &distance );
851 }
853
854 return distance;
855}
856
857double QgsGeos::frechetDistance( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
858{
859 double distance = -1.0;
860 if ( !mGeos )
861 {
862 return distance;
863 }
864
865 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
866 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
867 if ( !otherGeosGeom )
868 {
869 return distance;
870 }
871
872 try
873 {
874 GEOSFrechetDistance_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), &distance );
875 }
877
878 return distance;
879}
880
881double QgsGeos::frechetDistanceDensify( const QgsAbstractGeometry *geom, double densifyFraction, QString *errorMsg, QgsFeedback *feedback ) const
882{
883 double distance = -1.0;
884 if ( !mGeos )
885 {
886 return distance;
887 }
888
889 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
890 geos::unique_ptr otherGeosGeom( asGeos( geom, mPrecision ) );
891 if ( !otherGeosGeom )
892 {
893 return distance;
894 }
895
896 try
897 {
898 GEOSFrechetDistanceDensify_r( QgsGeosContext::get(), mGeos.get(), otherGeosGeom.get(), densifyFraction, &distance );
899 }
901
902 return distance;
903}
904
905bool QgsGeos::intersects( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
906{
907 if ( !mGeos || !geom )
908 {
909 return false;
910 }
911
912 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
913#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
914 // special optimised case for point intersects
916 {
917 if ( mGeosPrepared )
918 {
919 try
920 {
921 return GEOSPreparedIntersectsXY_r( QgsGeosContext::get(), mGeosPrepared.get(), point->x(), point->y() ) == 1;
922 }
923 catch ( QgsGeosException &e )
924 {
925 logError( u"GEOS"_s, e.what() );
926 if ( errorMsg )
927 {
928 *errorMsg = e.what();
929 }
930 return false;
931 }
932 }
933 }
934#endif
935
936 return relation( geom, RelationIntersects, errorMsg );
937}
938
939bool QgsGeos::touches( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
940{
941 return relation( geom, RelationTouches, errorMsg, feedback );
942}
943
944bool QgsGeos::crosses( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
945{
946 return relation( geom, RelationCrosses, errorMsg, feedback );
947}
948
949bool QgsGeos::within( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
950{
951 return relation( geom, RelationWithin, errorMsg, feedback );
952}
953
954bool QgsGeos::overlaps( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
955{
956 return relation( geom, RelationOverlaps, errorMsg, feedback );
957}
958
959bool QgsGeos::contains( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
960{
961 if ( !mGeos || !geom )
962 {
963 return false;
964 }
965
966#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 12, 0 )
967 // special optimised case for point containment
969 {
970 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
971 if ( mGeosPrepared )
972 {
973 try
974 {
975 return GEOSPreparedContainsXY_r( QgsGeosContext::get(), mGeosPrepared.get(), point->x(), point->y() ) == 1;
976 }
977 catch ( QgsGeosException &e )
978 {
979 logError( u"GEOS"_s, e.what() );
980 if ( errorMsg )
981 {
982 *errorMsg = e.what();
983 }
984 return false;
985 }
986 }
987 }
988#endif
989
990 return relation( geom, RelationContains, errorMsg, feedback );
991}
992
993bool QgsGeos::disjoint( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
994{
995 return relation( geom, RelationDisjoint, errorMsg, feedback );
996}
997
998QString QgsGeos::relate( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
999{
1000 if ( !mGeos )
1001 {
1002 return QString();
1003 }
1004
1005 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
1006 if ( !geosGeom )
1007 {
1008 return QString();
1009 }
1010
1011 QString result;
1012 GEOSContextHandle_t context = QgsGeosContext::get();
1013 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
1014 try
1015 {
1016 char *r = GEOSRelate_r( context, mGeos.get(), geosGeom.get() );
1017 if ( r )
1018 {
1019 result = QString( r );
1020 GEOSFree_r( context, r );
1021 }
1022 }
1023 catch ( QgsGeosException &e )
1024 {
1025 logError( u"GEOS"_s, e.what() );
1026 if ( errorMsg )
1027 {
1028 *errorMsg = e.what();
1029 }
1030 }
1031
1032 return result;
1033}
1034
1035bool QgsGeos::relatePattern( const QgsAbstractGeometry *geom, const QString &pattern, QString *errorMsg, QgsFeedback *feedback ) const
1036{
1037 if ( !mGeos || !geom )
1038 {
1039 return false;
1040 }
1041
1042 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
1043 if ( !geosGeom )
1044 {
1045 return false;
1046 }
1047
1048 bool result = false;
1049 GEOSContextHandle_t context = QgsGeosContext::get();
1050 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
1051
1052 try
1053 {
1054 result = ( GEOSRelatePattern_r( context, mGeos.get(), geosGeom.get(), pattern.toLocal8Bit().constData() ) == 1 );
1055 }
1056 catch ( QgsGeosException &e )
1057 {
1058 logError( u"GEOS"_s, e.what() );
1059 if ( errorMsg )
1060 {
1061 *errorMsg = e.what();
1062 }
1063 }
1064
1065 return result;
1066}
1067
1068double QgsGeos::area( QString *errorMsg ) const
1069{
1070 double area = -1.0;
1071 if ( !mGeos )
1072 {
1073 return area;
1074 }
1075
1076 try
1077 {
1078 if ( GEOSArea_r( QgsGeosContext::get(), mGeos.get(), &area ) != 1 )
1079 return -1.0;
1080 }
1082 return area;
1083}
1084
1085double QgsGeos::length( QString *errorMsg ) const
1086{
1087 double length = -1.0;
1088 if ( !mGeos )
1089 {
1090 return length;
1091 }
1092 try
1093 {
1094 if ( GEOSLength_r( QgsGeosContext::get(), mGeos.get(), &length ) != 1 )
1095 return -1.0;
1096 }
1098 return length;
1099}
1100
1101
1103 const QgsAbstractGeometry &splitGeom, QVector<QgsGeometry > &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, QString *errorMsg
1104) const
1105{
1106#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1107 if ( !mGeos || !mGeometry )
1108 {
1109 return InvalidBaseGeometry;
1110 }
1111
1112 if ( mGeometry->dimension() == 0 && QgsWkbTypes::flatType( mGeometry->wkbType() ) != Qgis::WkbType::GeometryCollection )
1113 {
1114 return SplitCannotSplitPoint; //cannot split points
1115 }
1116
1117 GEOSContextHandle_t context = QgsGeosContext::get();
1118 EngineOperationResult returnCode = Success;
1119
1120 try
1121 {
1122 if ( !GEOSisValid_r( context, mGeos.get() ) )
1123 return InvalidBaseGeometry;
1124
1125 geos::unique_ptr splitGeosGeom = asGeos( &splitGeom, mPrecision );
1126 if ( !splitGeosGeom || !GEOSisValid_r( context, splitGeosGeom.get() ) || !GEOSisSimple_r( context, splitGeosGeom.get() ) )
1127 {
1128 return InvalidInput;
1129 }
1130
1131 // TODO: Currently, points cannot split polygons, but it could change in the
1132 // future in GEOS. Remove this block when that happens. (See GEOS issue #1481)
1134 {
1135 return EngineError;
1136 }
1137
1138 if ( topological )
1139 {
1140 //find out candidate points for topological corrections
1141 if ( !topologicalTestPointsSplit( splitGeosGeom.get(), topologyTestPoints, errorMsg ) )
1142 {
1143 return InvalidInput; // TODO: is it really an invalid input?
1144 }
1145 }
1146
1147 newGeometries.clear();
1148
1149 geos::unique_ptr split( GEOSSplit_r( context, mGeos.get(), splitGeosGeom.get() ) );
1150 if ( !split )
1151 {
1152 returnCode = EngineError;
1153 }
1154 else
1155 {
1156 const int nParts = GEOSGetNumGeometries_r( context, split.get() );
1157 if ( nParts == 0 )
1158 {
1159 return NothingHappened;
1160 }
1161 for ( int i = 0; i < nParts; ++i )
1162 {
1163 newGeometries << QgsGeometry( fromGeos( GEOSGetGeometryN_r( context, split.get(), i ) ) );
1164 }
1165 returnCode = Success;
1166 }
1167 }
1169
1170 return returnCode;
1171#else
1173 {
1174 const QgsLineString *splitLine = qgis::down_cast< const QgsLineString * >( &splitGeom );
1175 if ( splitLine )
1176 {
1177 return splitGeometry( *splitLine, newGeometries, topological, topologyTestPoints, errorMsg, false );
1178 }
1179 else
1180 {
1181 return InvalidInput;
1182 }
1183 }
1184 else
1185 {
1186 return MethodNotImplemented;
1187 }
1188#endif
1189}
1190
1192 const QgsLineString &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, QString *errorMsg, bool skipIntersectionCheck
1193) const
1194{
1195 EngineOperationResult returnCode = Success;
1196 if ( !mGeos || !mGeometry )
1197 {
1198 return InvalidBaseGeometry;
1199 }
1200
1201 //return if this type is point/multipoint
1202 if ( mGeometry->dimension() == 0 )
1203 {
1204 return SplitCannotSplitPoint; //cannot split points
1205 }
1206
1207 GEOSContextHandle_t context = QgsGeosContext::get();
1208 if ( !GEOSisValid_r( context, mGeos.get() ) )
1209 return InvalidBaseGeometry;
1210
1211 //make sure splitLine is valid
1212 if ( ( mGeometry->dimension() == 1 && splitLine.numPoints() < 1 ) || ( mGeometry->dimension() == 2 && splitLine.numPoints() < 2 ) )
1213 return InvalidInput;
1214
1215 newGeometries.clear();
1216 geos::unique_ptr splitLineGeos;
1217
1218 try
1219 {
1220 if ( splitLine.numPoints() > 1 )
1221 {
1222 splitLineGeos = createGeosLinestring( &splitLine, mPrecision );
1223 }
1224 else if ( splitLine.numPoints() == 1 )
1225 {
1226 splitLineGeos = createGeosPointXY( splitLine.xAt( 0 ), splitLine.yAt( 0 ), false, 0, false, 0, 2, mPrecision );
1227 }
1228 else
1229 {
1230 return InvalidInput;
1231 }
1232
1233 if ( !GEOSisValid_r( context, splitLineGeos.get() ) || !GEOSisSimple_r( context, splitLineGeos.get() ) )
1234 {
1235 return InvalidInput;
1236 }
1237
1238 if ( topological )
1239 {
1240 //find out candidate points for topological corrections
1241 if ( !topologicalTestPointsSplit( splitLineGeos.get(), topologyTestPoints, errorMsg ) )
1242 {
1243 return InvalidInput; // TODO: is it really an invalid input?
1244 }
1245 }
1246
1247 //call split function depending on geometry type
1248 if ( mGeometry->dimension() == 1 )
1249 {
1250 returnCode = splitLinearGeometry( splitLineGeos.get(), newGeometries, skipIntersectionCheck );
1251 }
1252 else if ( mGeometry->dimension() == 2 )
1253 {
1254 returnCode = splitPolygonGeometry( splitLineGeos.get(), newGeometries, skipIntersectionCheck );
1255 }
1256 else
1257 {
1258 return InvalidInput;
1259 }
1260 }
1262
1263 return returnCode;
1264}
1265
1266
1267bool QgsGeos::topologicalTestPointsSplit( const GEOSGeometry *splitLine, QgsPointSequence &testPoints, QString *errorMsg ) const
1268{
1269 //Find out the intersection points between splitLineGeos and this geometry.
1270 //These points need to be tested for topological correctness by the calling function
1271 //if topological editing is enabled
1272
1273 if ( !mGeos )
1274 {
1275 return false;
1276 }
1277
1278 GEOSContextHandle_t context = QgsGeosContext::get();
1279 try
1280 {
1281 testPoints.clear();
1282 geos::unique_ptr intersectionGeom( GEOSIntersection_r( context, mGeos.get(), splitLine ) );
1283 if ( !intersectionGeom )
1284 return false;
1285
1286 // TODO: Remove this if block when this method has curve support (e.g., CircularString or CoumpoundCurve).
1287 // That is, when we extract vertices from curve intersections.
1288 if ( !( GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_POINT
1289 || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_LINESTRING
1290 || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_MULTIPOINT
1291 || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_MULTILINESTRING ) )
1292 {
1293 if ( errorMsg )
1294 {
1295 *errorMsg = u"Extracting topological points from curves or polygons is not yet supported."_s;
1296 }
1297 return false;
1298 }
1299
1300 bool simple = false;
1301 int nIntersectGeoms = 1;
1302 if ( GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_LINESTRING || GEOSGeomTypeId_r( context, intersectionGeom.get() ) == GEOS_POINT )
1303 simple = true;
1304
1305 if ( !simple )
1306 nIntersectGeoms = GEOSGetNumGeometries_r( context, intersectionGeom.get() );
1307
1308 for ( int i = 0; i < nIntersectGeoms; ++i )
1309 {
1310 const GEOSGeometry *currentIntersectGeom = nullptr;
1311 if ( simple )
1312 currentIntersectGeom = intersectionGeom.get();
1313 else
1314 currentIntersectGeom = GEOSGetGeometryN_r( context, intersectionGeom.get(), i );
1315
1316 const GEOSCoordSequence *lineSequence = GEOSGeom_getCoordSeq_r( context, currentIntersectGeom );
1317 unsigned int sequenceSize = 0;
1318 double x, y, z;
1319 if ( GEOSCoordSeq_getSize_r( context, lineSequence, &sequenceSize ) != 0 )
1320 {
1321 for ( unsigned int i = 0; i < sequenceSize; ++i )
1322 {
1323 if ( GEOSCoordSeq_getXYZ_r( context, lineSequence, i, &x, &y, &z ) )
1324 {
1325 testPoints.push_back( QgsPoint( x, y, z ) );
1326 }
1327 }
1328 }
1329 }
1330 }
1332
1333 return true;
1334}
1335
1336geos::unique_ptr QgsGeos::linePointDifference( GEOSGeometry *GEOSsplitPoint ) const
1337{
1338 GEOSContextHandle_t context = QgsGeosContext::get();
1339 int type = GEOSGeomTypeId_r( context, mGeos.get() );
1340
1341 std::unique_ptr< QgsMultiCurve > multiCurve;
1342 if ( type == GEOS_MULTILINESTRING )
1343 {
1344 multiCurve.reset( qgsgeometry_cast<QgsMultiCurve *>( mGeometry->clone() ) );
1345 }
1346 else if ( type == GEOS_LINESTRING )
1347 {
1348 multiCurve = std::make_unique<QgsMultiCurve>();
1349 multiCurve->addGeometry( mGeometry->clone() );
1350 }
1351 else
1352 {
1353 return nullptr;
1354 }
1355
1356 if ( !multiCurve )
1357 {
1358 return nullptr;
1359 }
1360
1361
1362 // we might have a point or a multipoint, depending on number of
1363 // intersections between the geometry and the split geometry
1364 std::unique_ptr< QgsMultiPoint > splitPoints;
1365 {
1366 std::unique_ptr< QgsAbstractGeometry > splitGeom( fromGeos( GEOSsplitPoint ) );
1367
1368 if ( qgsgeometry_cast<QgsMultiPoint *>( splitGeom.get() ) )
1369 {
1370 splitPoints.reset( qgis::down_cast<QgsMultiPoint *>( splitGeom.release() ) );
1371 }
1372 else if ( qgsgeometry_cast<QgsPoint *>( splitGeom.get() ) )
1373 {
1374 splitPoints = std::make_unique< QgsMultiPoint >();
1375 if ( qgsgeometry_cast<QgsPoint *>( splitGeom.get() ) )
1376 {
1377 splitPoints->addGeometry( qgis::down_cast<QgsPoint *>( splitGeom.release() ) );
1378 }
1379 }
1380 }
1381
1382 if ( !splitPoints )
1383 return nullptr;
1384
1385 QgsMultiCurve lines;
1386
1387 //For each part
1388 for ( int geometryIndex = 0; geometryIndex < multiCurve->numGeometries(); ++geometryIndex )
1389 {
1390 const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( multiCurve->geometryN( geometryIndex ) );
1391 if ( !line )
1392 {
1393 const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( multiCurve->geometryN( geometryIndex ) );
1394 line = curve->curveToLine();
1395 }
1396 if ( !line )
1397 {
1398 return nullptr;
1399 }
1400 // we gather the intersection points and their distance from previous node grouped by segment
1401 QMap< int, QVector< QPair< double, QgsPoint > > > pointMap;
1402 for ( int splitPointIndex = 0; splitPointIndex < splitPoints->numGeometries(); ++splitPointIndex )
1403 {
1404 const QgsPoint *intersectionPoint = splitPoints->pointN( splitPointIndex );
1405
1406 QgsPoint segmentPoint2D;
1407 QgsVertexId nextVertex;
1408 // With closestSegment we only get a 2D point so we need to interpolate if we
1409 // don't want to lose Z data
1410 line->closestSegment( *intersectionPoint, segmentPoint2D, nextVertex );
1411
1412 // The intersection might belong to another part, skip it
1413 // Note: cannot test for equality because of Z
1414 if ( !qgsDoubleNear( intersectionPoint->x(), segmentPoint2D.x() ) || !qgsDoubleNear( intersectionPoint->y(), segmentPoint2D.y() ) )
1415 {
1416 continue;
1417 }
1418
1419 const QgsLineString segment = QgsLineString( line->pointN( nextVertex.vertex - 1 ), line->pointN( nextVertex.vertex ) );
1420 const double distance = segmentPoint2D.distance( line->pointN( nextVertex.vertex - 1 ) );
1421
1422 // Due to precision issues, distance can be a tad larger than the actual segment length, making interpolatePoint() return nullptr
1423 // In that case we'll use the segment's endpoint instead of interpolating
1424 std::unique_ptr< QgsPoint > correctSegmentPoint( distance > segment.length() ? segment.endPoint().clone() : segment.interpolatePoint( distance ) );
1425
1426 const QPair< double, QgsPoint > pair = qMakePair( distance, *correctSegmentPoint.get() );
1427 if ( pointMap.contains( nextVertex.vertex - 1 ) )
1428 pointMap[nextVertex.vertex - 1].append( pair );
1429 else
1430 pointMap[nextVertex.vertex - 1] = QVector< QPair< double, QgsPoint > >() << pair;
1431 }
1432
1433 // When we have more than one intersection point on a segment we need those points
1434 // to be sorted by their distance from the previous geometry vertex
1435 for ( auto &p : pointMap )
1436 {
1437 std::sort( p.begin(), p.end(), []( const QPair< double, QgsPoint > &a, const QPair< double, QgsPoint > &b ) { return a.first < b.first; } );
1438 }
1439
1440 //For each segment
1441 QgsLineString newLine;
1442 int nVertices = line->numPoints();
1443 QgsPoint splitPoint;
1444 for ( int vertexIndex = 0; vertexIndex < nVertices; ++vertexIndex )
1445 {
1446 QgsPoint currentPoint = line->pointN( vertexIndex );
1447 newLine.addVertex( currentPoint );
1448 if ( pointMap.contains( vertexIndex ) )
1449 {
1450 // For each intersecting point
1451 for ( int k = 0; k < pointMap[vertexIndex].size(); ++k )
1452 {
1453 splitPoint = pointMap[vertexIndex][k].second;
1454 if ( splitPoint == currentPoint )
1455 {
1456 lines.addGeometry( newLine.clone() );
1457 newLine = QgsLineString();
1458 newLine.addVertex( currentPoint );
1459 }
1460 else if ( splitPoint == line->pointN( vertexIndex + 1 ) )
1461 {
1462 newLine.addVertex( line->pointN( vertexIndex + 1 ) );
1463 lines.addGeometry( newLine.clone() );
1464 newLine = QgsLineString();
1465 }
1466 else
1467 {
1468 newLine.addVertex( splitPoint );
1469 lines.addGeometry( newLine.clone() );
1470 newLine = QgsLineString();
1471 newLine.addVertex( splitPoint );
1472 }
1473 }
1474 }
1475 }
1476 lines.addGeometry( newLine.clone() );
1477 }
1478
1479 return asGeos( &lines, mPrecision );
1480}
1481
1482QgsGeometryEngine::EngineOperationResult QgsGeos::splitLinearGeometry( const GEOSGeometry *splitLine, QVector<QgsGeometry> &newGeometries, bool skipIntersectionCheck ) const
1483{
1484 Q_UNUSED( skipIntersectionCheck )
1485 if ( !splitLine )
1486 return InvalidInput;
1487
1488 if ( !mGeos )
1489 return InvalidBaseGeometry;
1490
1491 GEOSContextHandle_t context = QgsGeosContext::get();
1492
1493 geos::unique_ptr intersectGeom( GEOSIntersection_r( context, splitLine, mGeos.get() ) );
1494 if ( !intersectGeom || GEOSisEmpty_r( context, intersectGeom.get() ) )
1495 return NothingHappened;
1496
1497 //check that split line has no linear intersection
1498 const int linearIntersect = GEOSRelatePattern_r( context, mGeos.get(), splitLine, "1********" );
1499 if ( linearIntersect > 0 )
1500 return InvalidInput;
1501
1502 geos::unique_ptr splitGeom = linePointDifference( intersectGeom.get() );
1503
1504 if ( !splitGeom )
1505 return InvalidBaseGeometry;
1506
1507 std::vector<geos::unique_ptr> lineGeoms;
1508
1509 const int splitType = GEOSGeomTypeId_r( context, splitGeom.get() );
1510 if ( splitType == GEOS_MULTILINESTRING )
1511 {
1512 const int nGeoms = GEOSGetNumGeometries_r( context, splitGeom.get() );
1513 lineGeoms.reserve( nGeoms );
1514 for ( int i = 0; i < nGeoms; ++i )
1515 lineGeoms.emplace_back( GEOSGeom_clone_r( context, GEOSGetGeometryN_r( context, splitGeom.get(), i ) ) );
1516 }
1517 else
1518 {
1519 lineGeoms.emplace_back( GEOSGeom_clone_r( context, splitGeom.get() ) );
1520 }
1521
1522 mergeGeometriesMultiTypeSplit( lineGeoms );
1523
1524 for ( geos::unique_ptr &lineGeom : lineGeoms )
1525 {
1526 newGeometries << QgsGeometry( fromGeos( lineGeom.get() ) );
1527 }
1528
1529 return Success;
1530}
1531
1532QgsGeometryEngine::EngineOperationResult QgsGeos::splitPolygonGeometry( const GEOSGeometry *splitLine, QVector<QgsGeometry> &newGeometries, bool skipIntersectionCheck ) const
1533{
1534 if ( !splitLine )
1535 return InvalidInput;
1536
1537 if ( !mGeos )
1538 return InvalidBaseGeometry;
1539
1540 // we will need prepared geometry for intersection tests
1541 const_cast<QgsGeos *>( this )->prepareGeometry();
1542 if ( !mGeosPrepared )
1543 return EngineError;
1544
1545 GEOSContextHandle_t context = QgsGeosContext::get();
1546
1547 //first test if linestring intersects geometry. If not, return straight away
1548 if ( !skipIntersectionCheck && !GEOSPreparedIntersects_r( context, mGeosPrepared.get(), splitLine ) )
1549 return NothingHappened;
1550
1551 //first union all the polygon rings together (to get them noded, see JTS developer guide)
1552 geos::unique_ptr nodedGeometry = nodeGeometries( splitLine, mGeos.get() );
1553 if ( !nodedGeometry )
1554 return NodedGeometryError; //an error occurred during noding
1555
1556 const GEOSGeometry *noded = nodedGeometry.get();
1557 geos::unique_ptr polygons( GEOSPolygonize_r( context, &noded, 1 ) );
1558 if ( !polygons )
1559 {
1560 return InvalidBaseGeometry;
1561 }
1562 const int numberOfGeometriesPolygon = numberOfGeometries( polygons.get() );
1563 if ( numberOfGeometriesPolygon == 0 )
1564 {
1565 return InvalidBaseGeometry;
1566 }
1567
1568 //test every polygon is contained in original geometry
1569 //include in result if yes
1570 std::vector<geos::unique_ptr> testedGeometries;
1571
1572 // test whether the polygon parts returned from polygonize algorithm actually
1573 // belong to the source polygon geometry (if the source polygon contains some holes,
1574 // those would be also returned by polygonize and we need to skip them)
1575 for ( int i = 0; i < numberOfGeometriesPolygon; i++ )
1576 {
1577 const GEOSGeometry *polygon = GEOSGetGeometryN_r( context, polygons.get(), i );
1578
1579 geos::unique_ptr pointOnSurface( GEOSPointOnSurface_r( context, polygon ) );
1580 if ( pointOnSurface && GEOSPreparedIntersects_r( context, mGeosPrepared.get(), pointOnSurface.get() ) )
1581 testedGeometries.emplace_back( GEOSGeom_clone_r( context, polygon ) );
1582 }
1583
1584 const size_t nGeometriesThis = numberOfGeometries( mGeos.get() ); //original number of geometries
1585 if ( testedGeometries.empty() || testedGeometries.size() == nGeometriesThis )
1586 {
1587 //no split done, preserve original geometry
1588 return NothingHappened;
1589 }
1590
1591 // For multi-part geometries, try to identify parts that have been unchanged and try to merge them back
1592 // to a single multi-part geometry. For example, if there's a multi-polygon with three parts, but only
1593 // one part is being split, this function makes sure that the other two parts will be kept in a multi-part
1594 // geometry rather than being separated into two single-part geometries.
1595 mergeGeometriesMultiTypeSplit( testedGeometries );
1596
1597 size_t i;
1598 for ( i = 0; i < testedGeometries.size() && GEOSisValid_r( context, testedGeometries[i].get() ); ++i )
1599 ;
1600
1601 if ( i < testedGeometries.size() )
1602 {
1603 return InvalidBaseGeometry;
1604 }
1605
1606 for ( geos::unique_ptr &testedGeometry : testedGeometries )
1607 {
1608 newGeometries << QgsGeometry( fromGeos( testedGeometry.get() ) );
1609 }
1610
1611 return Success;
1612}
1613
1614geos::unique_ptr QgsGeos::nodeGeometries( const GEOSGeometry *splitLine, const GEOSGeometry *geom )
1615{
1616 if ( !splitLine || !geom )
1617 return nullptr;
1618
1619 geos::unique_ptr geometryBoundary;
1620 GEOSContextHandle_t context = QgsGeosContext::get();
1621 if ( GEOSGeom_getDimensions_r( context, geom ) == 2 )
1622 geometryBoundary.reset( GEOSBoundary_r( context, geom ) );
1623 else
1624 geometryBoundary.reset( GEOSGeom_clone_r( context, geom ) );
1625
1626 geos::unique_ptr splitLineClone( GEOSGeom_clone_r( context, splitLine ) );
1627 geos::unique_ptr unionGeometry( GEOSUnion_r( context, splitLineClone.get(), geometryBoundary.get() ) );
1628
1629 return unionGeometry;
1630}
1631
1632int QgsGeos::mergeGeometriesMultiTypeSplit( std::vector<geos::unique_ptr> &splitResult ) const
1633{
1634 if ( !mGeos )
1635 return 1;
1636
1637 //convert mGeos to geometry collection
1638 GEOSContextHandle_t context = QgsGeosContext::get();
1639 int type = GEOSGeomTypeId_r( context, mGeos.get() );
1640 if ( type != GEOS_GEOMETRYCOLLECTION && type != GEOS_MULTILINESTRING && type != GEOS_MULTIPOLYGON && type != GEOS_MULTIPOINT )
1641 return 0;
1642
1643 //collect all the geometries that belong to the initial multifeature
1644 std::vector<geos::unique_ptr> unionGeom;
1645
1646 std::vector<geos::unique_ptr> newSplitResult;
1647
1648 for ( size_t i = 0; i < splitResult.size(); ++i )
1649 {
1650 //is this geometry a part of the original multitype?
1651 bool isPart = false;
1652 for ( int j = 0; j < GEOSGetNumGeometries_r( context, mGeos.get() ); j++ )
1653 {
1654 if ( GEOSEquals_r( context, splitResult[i].get(), GEOSGetGeometryN_r( context, mGeos.get(), j ) ) )
1655 {
1656 isPart = true;
1657 break;
1658 }
1659 }
1660
1661 if ( isPart )
1662 {
1663 unionGeom.emplace_back( std::move( splitResult[i] ) );
1664 }
1665 else
1666 {
1667 std::vector<geos::unique_ptr> geomVector;
1668 geomVector.emplace_back( std::move( splitResult[i] ) );
1669
1670 if ( type == GEOS_MULTILINESTRING )
1671 newSplitResult.emplace_back( createGeosCollection( GEOS_MULTILINESTRING, geomVector ) );
1672 else if ( type == GEOS_MULTIPOLYGON )
1673 newSplitResult.emplace_back( createGeosCollection( GEOS_MULTIPOLYGON, geomVector ) );
1674 }
1675 }
1676
1677 splitResult = std::move( newSplitResult );
1678
1679 //make multifeature out of unionGeom
1680 if ( !unionGeom.empty() )
1681 {
1682 if ( type == GEOS_MULTILINESTRING )
1683 splitResult.emplace_back( createGeosCollection( GEOS_MULTILINESTRING, unionGeom ) );
1684 else if ( type == GEOS_MULTIPOLYGON )
1685 splitResult.emplace_back( createGeosCollection( GEOS_MULTIPOLYGON, unionGeom ) );
1686 }
1687
1688 return 0;
1689}
1690
1691geos::unique_ptr QgsGeos::createGeosCollection( int typeId, std::vector<geos::unique_ptr> &geoms )
1692{
1693 std::vector<GEOSGeometry *> geomarr;
1694 geomarr.reserve( geoms.size() );
1695
1696 GEOSContextHandle_t context = QgsGeosContext::get();
1697 for ( geos::unique_ptr &geomUniquePtr : geoms )
1698 {
1699 if ( geomUniquePtr )
1700 {
1701 if ( !GEOSisEmpty_r( context, geomUniquePtr.get() ) )
1702 {
1703 // don't add empty parts to a geos collection, it can cause crashes in GEOS
1704 // transfer ownership of the geometries to GEOSGeom_createCollection_r()
1705 geomarr.emplace_back( geomUniquePtr.release() );
1706 }
1707 }
1708 }
1709 geos::unique_ptr geomRes;
1710
1711 try
1712 {
1713 geomRes.reset( GEOSGeom_createCollection_r( context, typeId, geomarr.data(), geomarr.size() ) );
1714 }
1715 catch ( QgsGeosException & )
1716 {
1717 for ( GEOSGeometry *geom : geomarr )
1718 {
1719 GEOSGeom_destroy_r( context, geom );
1720 }
1721 }
1722
1723 return geomRes;
1724}
1725
1726std::unique_ptr<QgsAbstractGeometry> QgsGeos::fromGeos( const GEOSGeometry *geos )
1727{
1728 if ( !geos )
1729 {
1730 return nullptr;
1731 }
1732
1733 GEOSContextHandle_t context = QgsGeosContext::get();
1734#ifdef GEOS_SUPPORTS_ZM
1735 bool hasZ = GEOSHasZ_r( context, geos );
1736 bool hasM = GEOSHasM_r( context, geos );
1737#else
1738 int nCoordDims = GEOSGeom_getCoordinateDimension_r( context, geos );
1739 int nDims = GEOSGeom_getDimensions_r( context, geos );
1740 bool hasZ = ( nCoordDims == 3 );
1741 bool hasM = ( ( nDims - nCoordDims ) == 1 );
1742#endif
1743
1744 switch ( GEOSGeomTypeId_r( context, geos ) )
1745 {
1746 case GEOS_POINT: // a point
1747 {
1748 if ( GEOSisEmpty_r( context, geos ) )
1749 return nullptr;
1750
1751 const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( context, geos );
1752 unsigned int nPoints = 0;
1753 GEOSCoordSeq_getSize_r( context, cs, &nPoints );
1754 if ( nPoints == 0 )
1755 {
1756 return nullptr;
1757 }
1758 // Since GEOS 3.13, Points with NAN coordinates are not considered empty anymore
1759 // See: https://github.com/libgeos/geos/pull/927
1760 // Handle this change by checking if QgsPoint is empty
1761 const QgsPoint point = coordSeqPoint( cs, 0, hasZ, hasM );
1762 return !point.isEmpty() ? std::unique_ptr<QgsAbstractGeometry>( point.clone() ) : nullptr;
1763 }
1764 case GEOS_LINESTRING:
1765 {
1766 return sequenceToLinestring( geos, hasZ, hasM );
1767 }
1768#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1769 case GEOS_CIRCULARSTRING:
1770 {
1771 return sequenceToCircularString( geos, hasZ, hasM );
1772 }
1773 case GEOS_COMPOUNDCURVE:
1774 {
1775 auto compoundCurve = std::make_unique< QgsCompoundCurve >();
1776 const int nCurves = GEOSGetNumCurves_r( context, geos );
1777 for ( int i = 0; i < nCurves; i++ )
1778 {
1779 std::unique_ptr< QgsSimpleCurve > curve = sequenceToSimpleCurve( GEOSGetCurveN_r( context, geos, i ), hasZ, hasM );
1780 compoundCurve->addCurve( curve.release(), true );
1781 }
1782 return std::move( compoundCurve );
1783 }
1784#endif
1785 case GEOS_POLYGON:
1786 {
1787 return fromGeosPolygon( geos );
1788 }
1789#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1790 case GEOS_CURVEPOLYGON:
1791 {
1792 return fromGeosCurvePolygon( geos );
1793 }
1794#endif
1795 case GEOS_MULTIPOINT:
1796 {
1797 auto multiPoint = std::make_unique<QgsMultiPoint>();
1798 const int nParts = GEOSGetNumGeometries_r( context, geos );
1799 multiPoint->reserve( nParts );
1800 for ( int i = 0; i < nParts; ++i )
1801 {
1802 const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( context, GEOSGetGeometryN_r( context, geos, i ) );
1803 if ( cs )
1804 {
1805 unsigned int nPoints = 0;
1806 GEOSCoordSeq_getSize_r( context, cs, &nPoints );
1807 if ( nPoints > 0 )
1808 multiPoint->addGeometry( coordSeqPoint( cs, 0, hasZ, hasM ).clone() );
1809 }
1810 }
1811 return std::move( multiPoint );
1812 }
1813 case GEOS_MULTILINESTRING:
1814 {
1815 auto multiLineString = std::make_unique<QgsMultiLineString>();
1816 const int nParts = GEOSGetNumGeometries_r( context, geos );
1817 multiLineString->reserve( nParts );
1818 for ( int i = 0; i < nParts; ++i )
1819 {
1820 std::unique_ptr< QgsLineString > line( sequenceToLinestring( GEOSGetGeometryN_r( context, geos, i ), hasZ, hasM ) );
1821 if ( line )
1822 {
1823 multiLineString->addGeometry( line.release() );
1824 }
1825 }
1826 return std::move( multiLineString );
1827 }
1828#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1829 case GEOS_MULTICURVE:
1830 {
1831 auto multiCurve = std::make_unique<QgsMultiCurve>();
1832 const int nParts = GEOSGetNumGeometries_r( context, geos );
1833 multiCurve->reserve( nParts );
1834 for ( int i = 0; i < nParts; ++i )
1835 {
1836 std::unique_ptr< QgsAbstractGeometry > curve( fromGeos( GEOSGetGeometryN_r( context, geos, i ) ) );
1837 multiCurve->addGeometry( curve.release() );
1838 }
1839 return std::move( multiCurve );
1840 }
1841#endif
1842 case GEOS_MULTIPOLYGON:
1843 {
1844 auto multiPolygon = std::make_unique<QgsMultiPolygon>();
1845
1846 const int nParts = GEOSGetNumGeometries_r( context, geos );
1847 multiPolygon->reserve( nParts );
1848 for ( int i = 0; i < nParts; ++i )
1849 {
1850 std::unique_ptr< QgsPolygon > poly = fromGeosPolygon( GEOSGetGeometryN_r( context, geos, i ) );
1851 if ( poly )
1852 {
1853 multiPolygon->addGeometry( poly.release() );
1854 }
1855 }
1856 return std::move( multiPolygon );
1857 }
1858#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1859 case GEOS_MULTISURFACE:
1860 {
1861 auto multiSurface = std::make_unique<QgsMultiSurface>();
1862 const int nParts = GEOSGetNumGeometries_r( context, geos );
1863 multiSurface->reserve( nParts );
1864 for ( int i = 0; i < nParts; ++i )
1865 {
1866 std::unique_ptr< QgsAbstractGeometry > polygon( fromGeos( GEOSGetGeometryN_r( context, geos, i ) ) );
1867 multiSurface->addGeometry( polygon.release() );
1868 }
1869 return std::move( multiSurface );
1870 }
1871#endif
1872 case GEOS_GEOMETRYCOLLECTION:
1873 {
1874 auto geomCollection = std::make_unique<QgsGeometryCollection>();
1875 const int nParts = GEOSGetNumGeometries_r( context, geos );
1876 geomCollection->reserve( nParts );
1877 for ( int i = 0; i < nParts; ++i )
1878 {
1879 std::unique_ptr< QgsAbstractGeometry > geom( fromGeos( GEOSGetGeometryN_r( context, geos, i ) ) );
1880 if ( geom )
1881 {
1882 geomCollection->addGeometry( geom.release() );
1883 }
1884 }
1885 return std::move( geomCollection );
1886 }
1887 }
1888 return nullptr;
1889}
1890
1891#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1892std::unique_ptr<QgsCurvePolygon> QgsGeos::fromGeosCurvePolygon( const GEOSGeometry *geos )
1893{
1894 GEOSContextHandle_t context = QgsGeosContext::get();
1895 if ( GEOSGeomTypeId_r( context, geos ) != GEOS_CURVEPOLYGON )
1896 {
1897 return nullptr;
1898 }
1899
1900#ifdef GEOS_SUPPORTS_ZM
1901 bool hasZ = GEOSHasZ_r( context, geos );
1902 bool hasM = GEOSHasM_r( context, geos );
1903#else
1904 int nCoordDims = GEOSGeom_getCoordinateDimension_r( context, geos );
1905 int nDims = GEOSGeom_getDimensions_r( context, geos );
1906 bool hasZ = ( nCoordDims == 3 );
1907 bool hasM = ( ( nDims - nCoordDims ) == 1 );
1908#endif
1909
1910 auto curvePolygon = std::make_unique<QgsCurvePolygon>();
1911
1912 const GEOSGeometry *ring = GEOSGetExteriorRing_r( context, geos );
1913 if ( ring )
1914 {
1915 if ( GEOSGeomTypeId_r( context, ring ) == GEOS_COMPOUNDCURVE )
1916 {
1917 curvePolygon->setExteriorRing( qgis::down_cast< QgsCompoundCurve *>( fromGeos( ring ).release() ) );
1918 }
1919 else
1920 {
1921 curvePolygon->setExteriorRing( sequenceToSimpleCurve( ring, hasZ, hasM ).release() );
1922 }
1923 }
1924
1925 QVector<QgsCurve *> interiorRings;
1926 const int ringCount = GEOSGetNumInteriorRings_r( context, geos );
1927 interiorRings.reserve( ringCount );
1928 for ( int i = 0; i < ringCount; ++i )
1929 {
1930 ring = GEOSGetInteriorRingN_r( context, geos, i );
1931 if ( ring )
1932 {
1933 if ( GEOSGeomTypeId_r( context, ring ) == GEOS_COMPOUNDCURVE )
1934 {
1935 interiorRings.push_back( qgis::down_cast< QgsCompoundCurve *>( fromGeos( ring ).release() ) );
1936 }
1937 else
1938 {
1939 interiorRings.push_back( sequenceToSimpleCurve( ring, hasZ, hasM ).release() );
1940 }
1941 }
1942 }
1943 curvePolygon->setInteriorRings( interiorRings );
1944
1945 return curvePolygon;
1946}
1947#endif
1948
1949std::unique_ptr<QgsPolygon> QgsGeos::fromGeosPolygon( const GEOSGeometry *geos )
1950{
1951 GEOSContextHandle_t context = QgsGeosContext::get();
1952 if ( GEOSGeomTypeId_r( context, geos ) != GEOS_POLYGON )
1953 {
1954 return nullptr;
1955 }
1956
1957#ifdef GEOS_SUPPORTS_ZM
1958 bool hasZ = GEOSHasZ_r( context, geos );
1959 bool hasM = GEOSHasM_r( context, geos );
1960#else
1961 int nCoordDims = GEOSGeom_getCoordinateDimension_r( context, geos );
1962 int nDims = GEOSGeom_getDimensions_r( context, geos );
1963 bool hasZ = ( nCoordDims == 3 );
1964 bool hasM = ( ( nDims - nCoordDims ) == 1 );
1965#endif
1966
1967 auto polygon = std::make_unique<QgsPolygon>();
1968
1969 const GEOSGeometry *ring = GEOSGetExteriorRing_r( context, geos );
1970 if ( ring )
1971 {
1972 polygon->setExteriorRing( sequenceToLinestring( ring, hasZ, hasM ).release() );
1973 }
1974
1975 QVector<QgsCurve *> interiorRings;
1976 const int ringCount = GEOSGetNumInteriorRings_r( context, geos );
1977 interiorRings.reserve( ringCount );
1978 for ( int i = 0; i < ringCount; ++i )
1979 {
1980 ring = GEOSGetInteriorRingN_r( context, geos, i );
1981 if ( ring )
1982 {
1983 interiorRings.push_back( sequenceToLinestring( ring, hasZ, hasM ).release() );
1984 }
1985 }
1986 polygon->setInteriorRings( interiorRings );
1987
1988 return polygon;
1989}
1990
1991std::unique_ptr<QgsSimpleCurve> QgsGeos::sequenceToSimpleCurve( const GEOSGeometry *geos, bool hasZ, bool hasM )
1992{
1993 GEOSContextHandle_t context = QgsGeosContext::get();
1994
1995 const int geometryType = GEOSGeomTypeId_r( context, geos );
1996 if ( !( geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING || geometryType == GEOS_CIRCULARSTRING ) )
1997 return nullptr;
1998
1999 const GEOSCoordSequence *cs = GEOSGeom_getCoordSeq_r( context, geos );
2000
2001 unsigned int nPoints;
2002 GEOSCoordSeq_getSize_r( context, cs, &nPoints );
2003
2004 QVector< double > xOut( nPoints );
2005 QVector< double > yOut( nPoints );
2006 QVector< double > zOut;
2007 if ( hasZ )
2008 zOut.resize( nPoints );
2009 QVector< double > mOut;
2010 if ( hasM )
2011 mOut.resize( nPoints );
2012
2013 double *x = xOut.data();
2014 double *y = yOut.data();
2015 double *z = zOut.data();
2016 double *m = mOut.data();
2017
2018#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
2019 GEOSCoordSeq_copyToArrays_r( context, cs, x, y, hasZ ? z : nullptr, hasM ? m : nullptr );
2020#else
2021 for ( unsigned int i = 0; i < nPoints; ++i )
2022 {
2023 if ( hasZ )
2024 GEOSCoordSeq_getXYZ_r( context, cs, i, x++, y++, z++ );
2025 else
2026 GEOSCoordSeq_getXY_r( context, cs, i, x++, y++ );
2027 if ( hasM )
2028 {
2029 GEOSCoordSeq_getOrdinate_r( context, cs, i, 3, m++ );
2030 }
2031 }
2032#endif
2033
2034 std::unique_ptr< QgsSimpleCurve > simpleCurve;
2035 if ( geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING )
2036 {
2037 simpleCurve = std::make_unique<QgsLineString>( xOut, yOut, zOut, mOut );
2038 }
2039 else if ( geometryType == GEOS_CIRCULARSTRING )
2040 {
2041 simpleCurve = std::make_unique<QgsCircularString>( xOut, yOut, zOut, mOut );
2042 }
2043 return simpleCurve;
2044}
2045
2046std::unique_ptr<QgsLineString> QgsGeos::sequenceToLinestring( const GEOSGeometry *geos, bool hasZ, bool hasM )
2047{
2048 return std::unique_ptr<QgsLineString>( qgis::down_cast<QgsLineString *>( sequenceToSimpleCurve( geos, hasZ, hasM ).release() ) );
2049}
2050
2051#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2052std::unique_ptr<QgsCircularString> QgsGeos::sequenceToCircularString( const GEOSGeometry *geos, bool hasZ, bool hasM )
2053{
2054 return std::unique_ptr<QgsCircularString>( qgis::down_cast<QgsCircularString *>( sequenceToSimpleCurve( geos, hasZ, hasM ).release() ) );
2055}
2056#endif
2057
2058int QgsGeos::numberOfGeometries( GEOSGeometry *g )
2059{
2060 if ( !g )
2061 return 0;
2062
2063 GEOSContextHandle_t context = QgsGeosContext::get();
2064 int geometryType = GEOSGeomTypeId_r( context, g );
2065 if ( geometryType == GEOS_POINT || geometryType == GEOS_LINESTRING || geometryType == GEOS_LINEARRING || geometryType == GEOS_POLYGON )
2066 return 1;
2067
2068 //calling GEOSGetNumGeometries is save for multi types and collections also in geos2
2069 return GEOSGetNumGeometries_r( context, g );
2070}
2071
2072QgsPoint QgsGeos::coordSeqPoint( const GEOSCoordSequence *cs, int i, bool hasZ, bool hasM )
2073{
2074 if ( !cs )
2075 {
2076 return QgsPoint();
2077 }
2078
2079 GEOSContextHandle_t context = QgsGeosContext::get();
2080
2081 double x, y;
2082 double z = 0;
2083 double m = 0;
2084 if ( hasZ )
2085 GEOSCoordSeq_getXYZ_r( context, cs, i, &x, &y, &z );
2086 else
2087 GEOSCoordSeq_getXY_r( context, cs, i, &x, &y );
2088 if ( hasM )
2089 {
2090 GEOSCoordSeq_getOrdinate_r( context, cs, i, 3, &m );
2091 }
2092
2094 if ( hasZ && hasM )
2095 {
2097 }
2098 else if ( hasZ )
2099 {
2101 }
2102 else if ( hasM )
2103 {
2105 }
2106 return QgsPoint( t, x, y, z, m );
2107}
2108
2110{
2111 if ( !geom )
2112 return nullptr;
2113
2114 int coordDims = 2;
2115 if ( geom->is3D() )
2116 {
2117 ++coordDims;
2118 }
2119 if ( geom->isMeasure() )
2120 {
2121 ++coordDims;
2122 }
2123
2125 {
2126 int geosType;
2127 switch ( QgsWkbTypes::flatType( geom->wkbType() ) )
2128 {
2130 geosType = GEOS_MULTIPOINT;
2131 break;
2132
2134#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2136#endif
2137 geosType = GEOS_MULTILINESTRING;
2138 break;
2139
2141#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2143#endif
2144 geosType = GEOS_MULTIPOLYGON;
2145 break;
2146
2147#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2149 geosType = GEOS_MULTICURVE;
2150 break;
2151
2153 geosType = GEOS_MULTISURFACE;
2154 break;
2155#endif
2156
2158 geosType = GEOS_GEOMETRYCOLLECTION;
2159 break;
2160
2163 default:
2164 return nullptr;
2165 }
2166
2168
2169 if ( !c )
2170 return nullptr;
2171
2172 std::vector<geos::unique_ptr> geomVector;
2173 geomVector.reserve( c->numGeometries() );
2174 for ( int i = 0; i < c->numGeometries(); ++i )
2175 {
2176 geos::unique_ptr geosGeom = asGeos( c->geometryN( i ), precision, flags );
2177 if ( flags & Qgis::GeosCreationFlag::RejectOnInvalidSubGeometry && !geosGeom )
2178 {
2179 return nullptr;
2180 }
2181 geomVector.emplace_back( std::move( geosGeom ) );
2182 }
2183 return createGeosCollection( geosType, geomVector );
2184 }
2185 else
2186 {
2187 switch ( QgsWkbTypes::flatType( geom->wkbType() ) )
2188 {
2190 return createGeosPoint( geom, coordDims, precision, flags );
2191
2195#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2197 return createGeosLinestring( geom, precision, flags );
2198#else // GEOS >= 3.15
2199 return createGeosSimpleCurve( geom, precision, flags );
2200
2202 return createGeosCompoundCurve( geom, precision, flags );
2203#endif
2204
2207#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2209#endif
2210 return createGeosPolygon( geom, precision, flags );
2211
2212#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2214 return createGeosCurvePolygon( geom, precision, flags );
2215#endif
2216
2217 case Qgis::WkbType::TIN:
2219 {
2220 // PolyhedralSurface and TIN support
2221 // convert it to a geos MultiPolygon
2223 if ( !polyhedralSurface )
2224 return nullptr;
2225
2226 std::vector<geos::unique_ptr> geomVector;
2227 geomVector.reserve( polyhedralSurface->numPatches() );
2228 for ( int i = 0; i < polyhedralSurface->numPatches(); ++i )
2229 {
2230 geos::unique_ptr geosPolygon = createGeosPolygon( polyhedralSurface->patchN( i ), precision );
2231 if ( flags & Qgis::GeosCreationFlag::RejectOnInvalidSubGeometry && !geosPolygon )
2232 {
2233 return nullptr;
2234 }
2235 geomVector.emplace_back( std::move( geosPolygon ) );
2236 }
2237
2238 return createGeosCollection( GEOS_MULTIPOLYGON, geomVector );
2239 }
2240
2243 default:
2244 return nullptr;
2245 }
2246 }
2247 return nullptr;
2248}
2249
2250std::unique_ptr<QgsAbstractGeometry> QgsGeos::overlay( const QgsAbstractGeometry *geom, Overlay op, QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
2251{
2252 if ( !mGeos || !geom )
2253 {
2254 return nullptr;
2255 }
2256
2257 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2258 if ( !geosGeom )
2259 {
2260 return nullptr;
2261 }
2262
2263 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2264
2265 const double gridSize = parameters.gridSize();
2266
2267 GEOSContextHandle_t context = QgsGeosContext::get();
2268 try
2269 {
2270 geos::unique_ptr opGeom;
2271 switch ( op )
2272 {
2273 case OverlayIntersection:
2274 if ( gridSize > 0 )
2275 {
2276 opGeom.reset( GEOSIntersectionPrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2277 }
2278 else
2279 {
2280 opGeom.reset( GEOSIntersection_r( context, mGeos.get(), geosGeom.get() ) );
2281 }
2282 break;
2283
2284 case OverlayDifference:
2285 if ( gridSize > 0 )
2286 {
2287 opGeom.reset( GEOSDifferencePrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2288 }
2289 else
2290 {
2291 opGeom.reset( GEOSDifference_r( context, mGeos.get(), geosGeom.get() ) );
2292 }
2293 break;
2294
2295 case OverlayUnion:
2296 {
2297 geos::unique_ptr unionGeometry;
2298 if ( gridSize > 0 )
2299 {
2300 unionGeometry.reset( GEOSUnionPrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2301 }
2302 else
2303 {
2304 unionGeometry.reset( GEOSUnion_r( context, mGeos.get(), geosGeom.get() ) );
2305 }
2306
2307#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 15, 0 )
2308 if ( unionGeometry && GEOSGeomTypeId_r( context, unionGeometry.get() ) == GEOS_MULTILINESTRING )
2309 {
2310 geos::unique_ptr mergedLines( GEOSLineMerge_r( context, unionGeometry.get() ) );
2311 if ( mergedLines )
2312 {
2313 unionGeometry = std::move( mergedLines );
2314 }
2315 }
2316#endif
2317
2318 opGeom = std::move( unionGeometry );
2319 }
2320 break;
2321
2322 case OverlaySymDifference:
2323 if ( gridSize > 0 )
2324 {
2325 opGeom.reset( GEOSSymDifferencePrec_r( context, mGeos.get(), geosGeom.get(), gridSize ) );
2326 }
2327 else
2328 {
2329 opGeom.reset( GEOSSymDifference_r( context, mGeos.get(), geosGeom.get() ) );
2330 }
2331 break;
2332 }
2333 return fromGeos( opGeom.get() );
2334 }
2335 catch ( QgsGeosException &e )
2336 {
2337 logError( u"GEOS"_s, e.what() );
2338 if ( errorMsg )
2339 {
2340 *errorMsg = e.what();
2341 }
2342 return nullptr;
2343 }
2344}
2345
2346bool QgsGeos::relation( const QgsAbstractGeometry *geom, Relation r, QString *errorMsg, QgsFeedback *feedback ) const
2347{
2348 if ( !mGeos || !geom )
2349 {
2350 return false;
2351 }
2352
2353 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2354 if ( !geosGeom )
2355 {
2356 return false;
2357 }
2358
2359 GEOSContextHandle_t context = QgsGeosContext::get();
2360 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2361
2362 bool result = false;
2363 try
2364 {
2365 if ( mGeosPrepared ) //use faster version with prepared geometry
2366 {
2367 switch ( r )
2368 {
2369 case RelationIntersects:
2370 result = ( GEOSPreparedIntersects_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2371 break;
2372 case RelationTouches:
2373 result = ( GEOSPreparedTouches_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2374 break;
2375 case RelationCrosses:
2376 result = ( GEOSPreparedCrosses_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2377 break;
2378 case RelationWithin:
2379 result = ( GEOSPreparedWithin_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2380 break;
2381 case RelationContains:
2382 result = ( GEOSPreparedContains_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2383 break;
2384 case RelationDisjoint:
2385 result = ( GEOSPreparedDisjoint_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2386 break;
2387 case RelationOverlaps:
2388 result = ( GEOSPreparedOverlaps_r( context, mGeosPrepared.get(), geosGeom.get() ) == 1 );
2389 break;
2390 }
2391 return result;
2392 }
2393
2394 switch ( r )
2395 {
2396 case RelationIntersects:
2397 result = ( GEOSIntersects_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2398 break;
2399 case RelationTouches:
2400 result = ( GEOSTouches_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2401 break;
2402 case RelationCrosses:
2403 result = ( GEOSCrosses_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2404 break;
2405 case RelationWithin:
2406 result = ( GEOSWithin_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2407 break;
2408 case RelationContains:
2409 result = ( GEOSContains_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2410 break;
2411 case RelationDisjoint:
2412 result = ( GEOSDisjoint_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2413 break;
2414 case RelationOverlaps:
2415 result = ( GEOSOverlaps_r( context, mGeos.get(), geosGeom.get() ) == 1 );
2416 break;
2417 }
2418 }
2419 catch ( QgsGeosException &e )
2420 {
2421 logError( u"GEOS"_s, e.what() );
2422 if ( errorMsg )
2423 {
2424 *errorMsg = e.what();
2425 }
2426 return false;
2427 }
2428
2429 return result;
2430}
2431
2432QgsAbstractGeometry *QgsGeos::buffer( double distance, int segments, QString *errorMsg, QgsFeedback *feedback ) const
2433{
2434 if ( !mGeos )
2435 {
2436 return nullptr;
2437 }
2438
2440 try
2441 {
2442 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2443
2444 geos.reset( GEOSBuffer_r( QgsGeosContext::get(), mGeos.get(), distance, segments ) );
2445 }
2446 CATCH_GEOS_WITH_ERRMSG( nullptr )
2447 return fromGeos( geos.get() ).release();
2448}
2449
2450QgsAbstractGeometry *QgsGeos::buffer( double distance, int segments, Qgis::EndCapStyle endCapStyle, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback ) const
2451{
2452 geos::unique_ptr geos = buffer( mGeos.get(), distance, segments, endCapStyle, joinStyle, miterLimit, errorMsg, feedback );
2453 return fromGeos( geos.get() ).release();
2454}
2455
2457 const GEOSGeometry *geometry, double distance, int segments, Qgis::EndCapStyle endCapStyle, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback
2458)
2459{
2460 if ( !geometry )
2461 {
2462 return nullptr;
2463 }
2464
2466 try
2467 {
2468 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2469 geos.reset( GEOSBufferWithStyle_r( QgsGeosContext::get(), geometry, distance, segments, static_cast< int >( endCapStyle ), static_cast< int >( joinStyle ), miterLimit ) );
2470 }
2471 CATCH_GEOS_WITH_ERRMSG( nullptr )
2472 return geos;
2473}
2474
2475QgsAbstractGeometry *QgsGeos::simplify( double tolerance, QString *errorMsg, QgsFeedback *feedback ) const
2476{
2477 if ( !mGeos )
2478 {
2479 return nullptr;
2480 }
2482 try
2483 {
2484 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2485 geos.reset( GEOSTopologyPreserveSimplify_r( QgsGeosContext::get(), mGeos.get(), tolerance ) );
2486 }
2487 CATCH_GEOS_WITH_ERRMSG( nullptr )
2488 return fromGeos( geos.get() ).release();
2489}
2490
2491QgsAbstractGeometry *QgsGeos::interpolate( double distance, QString *errorMsg, QgsFeedback *feedback ) const
2492{
2493 if ( !mGeos )
2494 {
2495 return nullptr;
2496 }
2498 try
2499 {
2500 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2501 geos.reset( GEOSInterpolate_r( QgsGeosContext::get(), mGeos.get(), distance ) );
2502 }
2503 CATCH_GEOS_WITH_ERRMSG( nullptr )
2504 return fromGeos( geos.get() ).release();
2505}
2506
2507QgsPoint *QgsGeos::centroid( QString *errorMsg, QgsFeedback *feedback ) const
2508{
2509 if ( !mGeos )
2510 {
2511 return nullptr;
2512 }
2513
2515 double x;
2516 double y;
2517
2518 GEOSContextHandle_t context = QgsGeosContext::get();
2519 try
2520 {
2521 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2522 geos.reset( GEOSGetCentroid_r( context, mGeos.get() ) );
2523
2524 if ( !geos )
2525 return nullptr;
2526
2527 GEOSGeomGetX_r( context, geos.get(), &x );
2528 GEOSGeomGetY_r( context, geos.get(), &y );
2529 }
2530 CATCH_GEOS_WITH_ERRMSG( nullptr )
2531
2532 return new QgsPoint( x, y );
2533}
2534
2535QgsAbstractGeometry *QgsGeos::envelope( QString *errorMsg ) const
2536{
2537 if ( !mGeos )
2538 {
2539 return nullptr;
2540 }
2542 try
2543 {
2544 geos.reset( GEOSEnvelope_r( QgsGeosContext::get(), mGeos.get() ) );
2545 }
2546 CATCH_GEOS_WITH_ERRMSG( nullptr )
2547 return fromGeos( geos.get() ).release();
2548}
2549
2550QgsPoint *QgsGeos::pointOnSurface( QString *errorMsg, QgsFeedback *feedback ) const
2551{
2552 if ( !mGeos )
2553 {
2554 return nullptr;
2555 }
2556
2557 double x;
2558 double y;
2559
2560 GEOSContextHandle_t context = QgsGeosContext::get();
2562 try
2563 {
2564 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2565 geos.reset( GEOSPointOnSurface_r( context, mGeos.get() ) );
2566
2567 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
2568 {
2569 return nullptr;
2570 }
2571
2572 GEOSGeomGetX_r( context, geos.get(), &x );
2573 GEOSGeomGetY_r( context, geos.get(), &y );
2574 }
2575 CATCH_GEOS_WITH_ERRMSG( nullptr )
2576
2577 return new QgsPoint( x, y );
2578}
2579
2580QgsAbstractGeometry *QgsGeos::convexHull( QString *errorMsg, QgsFeedback *feedback ) const
2581{
2582 if ( !mGeos )
2583 {
2584 return nullptr;
2585 }
2586
2587 try
2588 {
2589 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2590 geos::unique_ptr cHull( GEOSConvexHull_r( QgsGeosContext::get(), mGeos.get() ) );
2591 std::unique_ptr< QgsAbstractGeometry > cHullGeom = fromGeos( cHull.get() );
2592 return cHullGeom.release();
2593 }
2594 CATCH_GEOS_WITH_ERRMSG( nullptr )
2595}
2596
2597std::unique_ptr< QgsAbstractGeometry > QgsGeos::concaveHull( double targetPercent, bool allowHoles, QString *errorMsg, QgsFeedback *feedback ) const
2598{
2599#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 11, 0 )
2600 ( void ) allowHoles;
2601 ( void ) targetPercent;
2602 ( void ) errorMsg;
2603 throw QgsNotSupportedException( QObject::tr( "Calculating concaveHull requires a QGIS build based on GEOS 3.11 or later" ) );
2604#else
2605 if ( !mGeos )
2606 {
2607 return nullptr;
2608 }
2609
2610 try
2611 {
2612 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2613 geos::unique_ptr concaveHull( GEOSConcaveHull_r( QgsGeosContext::get(), mGeos.get(), targetPercent, allowHoles ) );
2614 std::unique_ptr< QgsAbstractGeometry > concaveHullGeom = fromGeos( concaveHull.get() );
2615 return concaveHullGeom;
2616 }
2617 CATCH_GEOS_WITH_ERRMSG( nullptr )
2618#endif
2619}
2620
2621std::unique_ptr<QgsAbstractGeometry> QgsGeos::concaveHullOfPolygons( double lengthRatio, bool allowHoles, bool isTight, QString *errorMsg, QgsFeedback *feedback ) const
2622{
2623#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 11, 0 )
2624 ( void ) allowHoles;
2625 ( void ) targetPercent;
2626 ( void ) errorMsg;
2627 throw QgsNotSupportedException( QObject::tr( "Calculating concaveHullOfPolygons requires a QGIS build based on GEOS 3.11 or later" ) );
2628#else
2629 if ( !mGeos )
2630 {
2631 return nullptr;
2632 }
2633
2634 try
2635 {
2636 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2637 geos::unique_ptr concaveHull( GEOSConcaveHullOfPolygons_r( QgsGeosContext::get(), mGeos.get(), lengthRatio, isTight ? 1 : 0, allowHoles ? 1 : 0 ) );
2638 std::unique_ptr< QgsAbstractGeometry > concaveHullGeom = fromGeos( concaveHull.get() );
2639 return concaveHullGeom;
2640 }
2641 CATCH_GEOS_WITH_ERRMSG( nullptr )
2642#endif
2643}
2644
2645Qgis::CoverageValidityResult QgsGeos::validateCoverage( double gapWidth, std::unique_ptr<QgsAbstractGeometry> *invalidEdges, QString *errorMsg, QgsFeedback *feedback ) const
2646{
2647#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 12, 0 )
2648 ( void ) gapWidth;
2649 ( void ) invalidEdges;
2650 ( void ) errorMsg;
2651 throw QgsNotSupportedException( QObject::tr( "Validating coverages requires a QGIS build based on GEOS 3.12 or later" ) );
2652#else
2653 if ( !mGeos )
2654 {
2655 if ( errorMsg )
2656 *errorMsg = u"Input geometry was not set"_s;
2658 }
2659
2660 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2661 GEOSContextHandle_t context = QgsGeosContext::get();
2662 try
2663 {
2664 GEOSGeometry *invalidEdgesGeos = nullptr;
2665 const int result = GEOSCoverageIsValid_r( context, mGeos.get(), gapWidth, invalidEdges ? &invalidEdgesGeos : nullptr );
2666 if ( invalidEdges && invalidEdgesGeos )
2667 {
2668 *invalidEdges = fromGeos( invalidEdgesGeos );
2669 }
2670 if ( invalidEdgesGeos )
2671 {
2672 GEOSGeom_destroy_r( context, invalidEdgesGeos );
2673 invalidEdgesGeos = nullptr;
2674 }
2675
2676 switch ( result )
2677 {
2678 case 0:
2680 case 1:
2682 case 2:
2683 break;
2684 }
2686 }
2688#endif
2689}
2690
2691std::unique_ptr<QgsAbstractGeometry> QgsGeos::simplifyCoverageVW( double tolerance, bool preserveBoundary, QString *errorMsg, QgsFeedback *feedback ) const
2692{
2693#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 12, 0 )
2694 ( void ) tolerance;
2695 ( void ) preserveBoundary;
2696 ( void ) errorMsg;
2697 throw QgsNotSupportedException( QObject::tr( "Simplifying coverages requires a QGIS build based on GEOS 3.12 or later" ) );
2698#else
2699 if ( !mGeos )
2700 {
2701 if ( errorMsg )
2702 *errorMsg = u"Input geometry was not set"_s;
2703 return nullptr;
2704 }
2705
2706 try
2707 {
2708 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2709 geos::unique_ptr simplified( GEOSCoverageSimplifyVW_r( QgsGeosContext::get(), mGeos.get(), tolerance, preserveBoundary ? 1 : 0 ) );
2710 std::unique_ptr< QgsAbstractGeometry > simplifiedGeom = fromGeos( simplified.get() );
2711 return simplifiedGeom;
2712 }
2713 CATCH_GEOS_WITH_ERRMSG( nullptr )
2714#endif
2715}
2716
2717std::unique_ptr<QgsAbstractGeometry> QgsGeos::unionCoverage( QString *errorMsg, QgsFeedback *feedback ) const
2718{
2719 if ( !mGeos )
2720 {
2721 if ( errorMsg )
2722 *errorMsg = u"Input geometry was not set"_s;
2723 return nullptr;
2724 }
2725
2726 try
2727 {
2728 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2729 geos::unique_ptr unioned( GEOSCoverageUnion_r( QgsGeosContext::get(), mGeos.get() ) );
2730 std::unique_ptr< QgsAbstractGeometry > result = fromGeos( unioned.get() );
2731 return result;
2732 }
2733 CATCH_GEOS_WITH_ERRMSG( nullptr )
2734}
2735
2736std::unique_ptr< QgsAbstractGeometry > QgsGeos::cleanCoverage( const QgsCoverageCleanParameters &parameters, QString *errorMsg, QgsFeedback *feedback ) const
2737{
2738#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 14, 0 )
2739 ( void ) parameters;
2740 ( void ) errorMsg;
2741 ( void ) feedback;
2742 throw QgsNotSupportedException( QObject::tr( "Cleaning coverages requires a QGIS build based on GEOS 3.14 or later" ) );
2743#else
2744 if ( !mGeos )
2745 {
2746 if ( errorMsg )
2747 *errorMsg = u"Input geometry was not set"_s;
2748 return nullptr;
2749 }
2750
2751 GEOSCoverageCleanParams *params = nullptr;
2752 try
2753 {
2754 params = GEOSCoverageCleanParams_create_r( QgsGeosContext::get() );
2755 if ( parameters.snappingDistance() >= 0 )
2756 {
2757 GEOSCoverageCleanParams_setSnappingDistance_r( QgsGeosContext::get(), params, parameters.snappingDistance() );
2758 }
2759 GEOSCoverageCleanParams_setGapMaximumWidth_r( QgsGeosContext::get(), params, parameters.maximumGapWidth() );
2760 switch ( parameters.overlapMergeStrategy() )
2761 {
2763 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 0 );
2764 break;
2766 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 1 );
2767 break;
2769 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 2 );
2770 break;
2772 GEOSCoverageCleanParams_setOverlapMergeStrategy_r( QgsGeosContext::get(), params, 3 );
2773 break;
2774 }
2775
2776 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2777 geos::unique_ptr cleaned( GEOSCoverageCleanWithParams_r( QgsGeosContext::get(), mGeos.get(), params ) );
2778 GEOSCoverageCleanParams_destroy_r( QgsGeosContext::get(), params );
2779
2780 std::unique_ptr< QgsAbstractGeometry> cleanedGeom = fromGeos( cleaned.get() );
2781
2782 return cleanedGeom;
2783 }
2784 catch ( QgsGeosException &e )
2785 {
2786 if ( params )
2787 {
2788 GEOSCoverageCleanParams_destroy_r( QgsGeosContext::get(), params );
2789 params = nullptr;
2790 }
2791
2792 if ( errorMsg )
2793 {
2794 *errorMsg = e.what();
2795 if ( errorMsg->startsWith( "InterruptedException"_L1, Qt::CaseInsensitive ) )
2796 {
2797 errorMsg->clear();
2798 }
2799 }
2800 return nullptr;
2801 }
2802#endif
2803}
2804
2805bool QgsGeos::isValid( QString *errorMsg, const bool allowSelfTouchingHoles, QgsGeometry *errorLoc, QgsFeedback *feedback ) const
2806{
2807 if ( !mGeos )
2808 {
2809 if ( errorMsg )
2810 *errorMsg = QObject::tr( "QGIS geometry cannot be converted to a GEOS geometry", "GEOS Error" );
2811 return false;
2812 }
2813
2814 GEOSContextHandle_t context = QgsGeosContext::get();
2815 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2816 try
2817 {
2818 GEOSGeometry *g1 = nullptr;
2819 char *r = nullptr;
2820 char res = GEOSisValidDetail_r( context, mGeos.get(), allowSelfTouchingHoles ? GEOSVALID_ALLOW_SELFTOUCHING_RING_FORMING_HOLE : 0, &r, &g1 );
2821 const bool invalid = res != 1;
2822
2823 QString error;
2824 if ( r )
2825 {
2826 error = QString( r );
2827 GEOSFree_r( context, r );
2828 }
2829
2830 if ( invalid && errorMsg )
2831 {
2832 // Copied from https://github.com/libgeos/geos/blob/main/src/operation/valid/TopologyValidationError.cpp
2833 static const std::map< QString, QString > sTranslatedErrors {
2834 { u"topology validation error"_s, QObject::tr( "Topology validation error", "GEOS Error" ) },
2835 { u"repeated point"_s, QObject::tr( "Repeated point", "GEOS Error" ) },
2836 { u"hole lies outside shell"_s, QObject::tr( "Hole lies outside shell", "GEOS Error" ) },
2837 { u"holes are nested"_s, QObject::tr( "Holes are nested", "GEOS Error" ) },
2838 { u"interior is disconnected"_s, QObject::tr( "Interior is disconnected", "GEOS Error" ) },
2839 { u"self-intersection"_s, QObject::tr( "Self-intersection", "GEOS Error" ) },
2840 { u"ring self-intersection"_s, QObject::tr( "Ring self-intersection", "GEOS Error" ) },
2841 { u"nested shells"_s, QObject::tr( "Nested shells", "GEOS Error" ) },
2842 { u"duplicate rings"_s, QObject::tr( "Duplicate rings", "GEOS Error" ) },
2843 { u"too few points in geometry component"_s, QObject::tr( "Too few points in geometry component", "GEOS Error" ) },
2844 { u"invalid coordinate"_s, QObject::tr( "Invalid coordinate", "GEOS Error" ) },
2845 { u"ring is not closed"_s, QObject::tr( "Ring is not closed", "GEOS Error" ) },
2846 };
2847
2848 const auto translatedError = sTranslatedErrors.find( error.toLower() );
2849 if ( translatedError != sTranslatedErrors.end() )
2850 *errorMsg = translatedError->second;
2851 else
2852 *errorMsg = error;
2853
2854 if ( g1 && errorLoc )
2855 {
2856 *errorLoc = geometryFromGeos( g1 );
2857 }
2858 else if ( g1 )
2859 {
2860 GEOSGeom_destroy_r( context, g1 );
2861 }
2862 }
2863 return !invalid;
2864 }
2865 CATCH_GEOS_WITH_ERRMSG( false )
2866}
2867
2868bool QgsGeos::isEqual( const QgsAbstractGeometry *geom, QString *errorMsg, QgsFeedback *feedback ) const
2869{
2870 if ( !mGeos || !geom )
2871 {
2872 return false;
2873 }
2874
2875 try
2876 {
2877 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2878 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2879 if ( !geosGeom )
2880 {
2881 return false;
2882 }
2883 bool equal = GEOSEquals_r( QgsGeosContext::get(), mGeos.get(), geosGeom.get() );
2884 return equal;
2885 }
2886 CATCH_GEOS_WITH_ERRMSG( false )
2887}
2888
2889bool QgsGeos::isFuzzyEqual( const QgsAbstractGeometry *geom, double epsilon, QString *errorMsg, QgsFeedback *feedback ) const
2890{
2891 if ( !mGeos || !geom )
2892 {
2893 return false;
2894 }
2895
2896 try
2897 {
2898 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
2899
2900 geos::unique_ptr geosGeom( asGeos( geom, mPrecision ) );
2901 if ( !geosGeom )
2902 {
2903 return false;
2904 }
2905 bool equal = GEOSEqualsExact_r( QgsGeosContext::get(), mGeos.get(), geosGeom.get(), epsilon );
2906 return equal;
2907 }
2908 CATCH_GEOS_WITH_ERRMSG( false )
2909}
2910
2911bool QgsGeos::isEmpty( QString *errorMsg ) const
2912{
2913 if ( !mGeos )
2914 {
2915 return false;
2916 }
2917
2918 try
2919 {
2920 return GEOSisEmpty_r( QgsGeosContext::get(), mGeos.get() );
2921 }
2922 CATCH_GEOS_WITH_ERRMSG( false )
2923}
2924
2925bool QgsGeos::isSimple( QString *errorMsg ) const
2926{
2927 if ( !mGeos )
2928 {
2929 return false;
2930 }
2931
2932 try
2933 {
2934 return GEOSisSimple_r( QgsGeosContext::get(), mGeos.get() );
2935 }
2936 CATCH_GEOS_WITH_ERRMSG( false )
2937}
2938
2939GEOSCoordSequence *QgsGeos::createCoordinateSequence( const QgsCurve *curve, double precision, bool forceClose )
2940{
2941 GEOSContextHandle_t context = QgsGeosContext::get();
2942 const QgsSimpleCurve *simpleCurve;
2943
2944#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2946 {
2947 simpleCurve = qgsgeometry_cast< const QgsCircularString * >( curve );
2948 }
2949 else
2950 {
2951#endif
2952 simpleCurve = qgsgeometry_cast< const QgsLineString *>( curve );
2953
2954 std::unique_ptr< QgsLineString > segmentized;
2955 if ( !simpleCurve )
2956 {
2957 segmentized.reset( curve->curveToLine() );
2958 simpleCurve = segmentized.get();
2959 }
2960#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
2961 }
2962#endif
2963
2964 if ( !simpleCurve )
2965 {
2966 return nullptr;
2967 }
2968 GEOSCoordSequence *coordSeq = nullptr;
2969
2970 const int numPoints = simpleCurve->numPoints();
2971
2972 const bool hasZ = simpleCurve->is3D();
2973#ifdef GEOS_SUPPORTS_ZM
2974 const bool hasM = simpleCurve->isMeasure();
2975#else
2976 const bool hasM = false; //disabled until geos supports m-coordinates
2977#endif
2978
2979#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
2980 if ( qgsDoubleNear( precision, 0 ) )
2981 {
2982 if ( !forceClose || ( simpleCurve->pointN( 0 ) == simpleCurve->pointN( numPoints - 1 ) ) )
2983 {
2984 // use optimised method if we don't have to force close an open ring
2985 try
2986 {
2987#ifdef GEOS_SUPPORTS_ZM
2988 coordSeq = GEOSCoordSeq_copyFromArrays_r( context, simpleCurve->xData(), simpleCurve->yData(), simpleCurve->zData(), simpleCurve->mData(), numPoints );
2989#else
2990 coordSeq = GEOSCoordSeq_copyFromArrays_r( context, simpleCurve->xData(), simpleCurve->yData(), simpleCurve->zData(), nullptr, numPoints );
2991#endif
2992 if ( !coordSeq )
2993 {
2994 QgsDebugError( u"GEOS Exception: Could not create coordinate sequence for %1 points"_s.arg( numPoints ) );
2995 return nullptr;
2996 }
2997 }
2998 CATCH_GEOS( nullptr )
2999 }
3000 else
3001 {
3002 QVector< double > x = simpleCurve->xVector();
3003 if ( numPoints > 0 )
3004 x.append( x.at( 0 ) );
3005 QVector< double > y = simpleCurve->yVector();
3006 if ( numPoints > 0 )
3007 y.append( y.at( 0 ) );
3008 QVector< double > z = simpleCurve->zVector();
3009 if ( hasZ && numPoints > 0 )
3010 z.append( z.at( 0 ) );
3011 QVector< double > m = simpleCurve->mVector();
3012 if ( hasM && numPoints > 0 )
3013 m.append( m.at( 0 ) );
3014 try
3015 {
3016 coordSeq = GEOSCoordSeq_copyFromArrays_r( context, x.constData(), y.constData(), !hasZ ? nullptr : z.constData(), !hasM ? nullptr : m.constData(), numPoints + 1 );
3017 if ( !coordSeq )
3018 {
3019 QgsDebugError( u"GEOS Exception: Could not create closed coordinate sequence for %1 points"_s.arg( numPoints + 1 ) );
3020 return nullptr;
3021 }
3022 }
3023 CATCH_GEOS( nullptr )
3024 }
3025 return coordSeq;
3026 }
3027#endif
3028
3029 int coordDims = 2;
3030
3031 if ( hasZ )
3032 {
3033 ++coordDims;
3034 }
3035 if ( hasM )
3036 {
3037 ++coordDims;
3038 }
3039
3040 int numOutPoints = numPoints;
3041 if ( forceClose && ( simpleCurve->pointN( 0 ) != simpleCurve->pointN( numPoints - 1 ) ) )
3042 {
3043 ++numOutPoints;
3044 }
3045
3046 try
3047 {
3048 coordSeq = GEOSCoordSeq_create_r( context, numOutPoints, coordDims );
3049 if ( !coordSeq )
3050 {
3051 QgsDebugError( u"GEOS Exception: Could not create coordinate sequence for %1 points in %2 dimensions"_s.arg( numPoints ).arg( coordDims ) );
3052 return nullptr;
3053 }
3054
3055 const double *xData = simpleCurve->xData();
3056 const double *yData = simpleCurve->yData();
3057 const double *zData = hasZ ? simpleCurve->zData() : nullptr;
3058 const double *mData = hasM ? simpleCurve->mData() : nullptr;
3059
3060 if ( precision > 0. )
3061 {
3062 for ( int i = 0; i < numOutPoints; ++i )
3063 {
3064 if ( i >= numPoints )
3065 {
3066 // start reading back from start of line
3067 xData = simpleCurve->xData();
3068 yData = simpleCurve->yData();
3069 zData = hasZ ? simpleCurve->zData() : nullptr;
3070 mData = hasM ? simpleCurve->mData() : nullptr;
3071 }
3072 if ( hasZ )
3073 {
3074 GEOSCoordSeq_setXYZ_r( context, coordSeq, i, std::round( *xData++ / precision ) * precision, std::round( *yData++ / precision ) * precision, std::round( *zData++ / precision ) * precision );
3075 }
3076 else
3077 {
3078 GEOSCoordSeq_setXY_r( context, coordSeq, i, std::round( *xData++ / precision ) * precision, std::round( *yData++ / precision ) * precision );
3079 }
3080 if ( hasM )
3081 {
3082 GEOSCoordSeq_setOrdinate_r( context, coordSeq, i, 3, *mData++ );
3083 }
3084 }
3085 }
3086 else
3087 {
3088 for ( int i = 0; i < numOutPoints; ++i )
3089 {
3090 if ( i >= numPoints )
3091 {
3092 // start reading back from start of line
3093 xData = simpleCurve->xData();
3094 yData = simpleCurve->yData();
3095 zData = hasZ ? simpleCurve->zData() : nullptr;
3096 mData = hasM ? simpleCurve->mData() : nullptr;
3097 }
3098 if ( hasZ )
3099 {
3100 GEOSCoordSeq_setXYZ_r( context, coordSeq, i, *xData++, *yData++, *zData++ );
3101 }
3102 else
3103 {
3104 GEOSCoordSeq_setXY_r( context, coordSeq, i, *xData++, *yData++ );
3105 }
3106 if ( hasM )
3107 {
3108 GEOSCoordSeq_setOrdinate_r( context, coordSeq, i, 3, *mData++ );
3109 }
3110 }
3111 }
3112 }
3113 CATCH_GEOS( nullptr )
3114
3115 return coordSeq;
3116}
3117
3118geos::unique_ptr QgsGeos::createGeosPoint( const QgsAbstractGeometry *point, int coordDims, double precision, Qgis::GeosCreationFlags )
3119{
3120 const QgsPoint *pt = qgsgeometry_cast<const QgsPoint *>( point );
3121 if ( !pt )
3122 return nullptr;
3123
3124 return createGeosPointXY( pt->x(), pt->y(), pt->is3D(), pt->z(), pt->isMeasure(), pt->m(), coordDims, precision );
3125}
3126
3127geos::unique_ptr QgsGeos::createGeosPointXY( double x, double y, bool hasZ, double z, bool hasM, double m, int coordDims, double precision, Qgis::GeosCreationFlags )
3128{
3129#ifndef GEOS_SUPPORTS_ZM
3130 Q_UNUSED( hasM )
3131 Q_UNUSED( m )
3132#endif
3133
3134 geos::unique_ptr geosPoint;
3135 GEOSContextHandle_t context = QgsGeosContext::get();
3136 try
3137 {
3138 if ( coordDims == 2 )
3139 {
3140 // optimised constructor
3141 if ( precision > 0. )
3142 geosPoint.reset( GEOSGeom_createPointFromXY_r( context, std::round( x / precision ) * precision, std::round( y / precision ) * precision ) );
3143 else
3144 geosPoint.reset( GEOSGeom_createPointFromXY_r( context, x, y ) );
3145 return geosPoint;
3146 }
3147
3148#ifdef GEOS_SUPPORTS_ZM
3149 GEOSCoordSequence *coordSeq = GEOSCoordSeq_createWithDimensions_r( context, 1, hasZ ? 1 : 0, hasM ? 1 : 0 );
3150#else
3151 GEOSCoordSequence *coordSeq = GEOSCoordSeq_create_r( context, 1, coordDims );
3152#endif
3153 if ( !coordSeq )
3154 {
3155 QgsDebugError( u"GEOS Exception: Could not create coordinate sequence for point with %1 dimensions"_s.arg( coordDims ) );
3156 return nullptr;
3157 }
3158 if ( precision > 0. )
3159 {
3160 GEOSCoordSeq_setX_r( context, coordSeq, 0, std::round( x / precision ) * precision );
3161 GEOSCoordSeq_setY_r( context, coordSeq, 0, std::round( y / precision ) * precision );
3162 if ( hasZ )
3163 {
3164#ifdef GEOS_SUPPORTS_ZM
3165 GEOSCoordSeq_setZ_r( context, coordSeq, 0, z );
3166#else
3167 GEOSCoordSeq_setOrdinate_r( context, coordSeq, 0, 2, std::round( z / precision ) * precision );
3168#endif
3169 }
3170 }
3171 else
3172 {
3173 GEOSCoordSeq_setX_r( context, coordSeq, 0, x );
3174 GEOSCoordSeq_setY_r( context, coordSeq, 0, y );
3175 if ( hasZ )
3176 {
3177#ifdef GEOS_SUPPORTS_ZM
3178 GEOSCoordSeq_setZ_r( context, coordSeq, 0, z );
3179#else
3180 GEOSCoordSeq_setOrdinate_r( context, coordSeq, 0, 2, z );
3181#endif
3182 }
3183 }
3184#ifdef GEOS_SUPPORTS_ZM
3185 if ( hasM )
3186 {
3187 GEOSCoordSeq_setM_r( context, coordSeq, 0, m );
3188 }
3189#endif
3190 geosPoint.reset( GEOSGeom_createPoint_r( context, coordSeq ) );
3191 }
3192 CATCH_GEOS( nullptr )
3193 return geosPoint;
3194}
3195
3196geos::unique_ptr QgsGeos::createGeosLinestring( const QgsAbstractGeometry *curve, double precision, Qgis::GeosCreationFlags )
3197{
3198 const QgsCurve *c = qgsgeometry_cast<const QgsCurve *>( curve );
3199 if ( !c )
3200 return nullptr;
3201
3202 GEOSCoordSequence *coordSeq = createCoordinateSequence( c, precision );
3203 if ( !coordSeq )
3204 return nullptr;
3205
3206 geos::unique_ptr geosGeom;
3207 try
3208 {
3209 geosGeom.reset( GEOSGeom_createLineString_r( QgsGeosContext::get(), coordSeq ) );
3210 }
3211 CATCH_GEOS( nullptr )
3212 return geosGeom;
3213}
3214
3215#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
3216geos::unique_ptr QgsGeos::createGeosSimpleCurve( const QgsAbstractGeometry *curve, double precision, Qgis::GeosCreationFlags )
3217{
3218 const QgsCurve *c = qgsgeometry_cast<const QgsCurve *>( curve );
3219 if ( !c )
3220 return nullptr;
3221
3222 if ( !c->isSimpleCurve() )
3223 return nullptr;
3224
3225 GEOSCoordSequence *coordSeq = createCoordinateSequence( c, precision );
3226 if ( !coordSeq )
3227 return nullptr;
3228
3229 geos::unique_ptr geosGeom;
3230 try
3231 {
3232 if ( !c->hasCurvedSegments() )
3233 {
3234 geosGeom.reset( GEOSGeom_createLineString_r( QgsGeosContext::get(), coordSeq ) );
3235 }
3236 else
3237 {
3238 geosGeom.reset( GEOSGeom_createCircularString_r( QgsGeosContext::get(), coordSeq ) );
3239 }
3240 }
3241 CATCH_GEOS( nullptr )
3242 return geosGeom;
3243}
3244
3245geos::unique_ptr QgsGeos::createGeosCompoundCurve( const QgsAbstractGeometry *curve, double precision, Qgis::GeosCreationFlags flags )
3246{
3247 const QgsCompoundCurve *c = qgsgeometry_cast<const QgsCompoundCurve *>( curve );
3248 if ( !c )
3249 return nullptr;
3250
3251 GEOSContextHandle_t context = QgsGeosContext::get();
3252 geos::unique_ptr geosCurve;
3253
3254 try
3255 {
3256 const int nCurves = c->nCurves();
3257 GEOSGeometry **curves = new GEOSGeometry *[nCurves];
3258
3259 for ( int i = 0; i < nCurves; i++ )
3260 {
3261 if ( c->curveAt( i )->isSimpleCurve() )
3262 {
3263 curves[i] = createGeosSimpleCurve( c->curveAt( i ), precision, flags ).release();
3264 }
3265 }
3266 geosCurve.reset( GEOSGeom_createCompoundCurve_r( context, curves, nCurves ) );
3267 delete[] curves;
3268 }
3269 CATCH_GEOS( nullptr )
3270 return geosCurve;
3271}
3272
3273geos::unique_ptr QgsGeos::createGeosCurvePolygon( const QgsAbstractGeometry *poly, double precision, Qgis::GeosCreationFlags flags )
3274{
3275 const QgsCurvePolygon *polygon = qgsgeometry_cast<const QgsCurvePolygon *>( poly );
3276 if ( !polygon )
3277 return nullptr;
3278
3279 const QgsCurve *exteriorRing = polygon->exteriorRing();
3280 if ( !exteriorRing )
3281 {
3282 return nullptr;
3283 }
3284
3285 GEOSContextHandle_t context = QgsGeosContext::get();
3286 geos::unique_ptr geosCurvePolygon;
3287 try
3288 {
3289 geos::unique_ptr exteriorRingGeos;
3290 if ( exteriorRing->isSimpleCurve() )
3291 {
3292 exteriorRingGeos.reset( createGeosSimpleCurve( exteriorRing, precision, flags ).release() );
3293 }
3294 else
3295 {
3296 exteriorRingGeos.reset( createGeosCompoundCurve( exteriorRing, precision, flags ).release() );
3297 }
3298
3299 const int nInteriorRings = polygon->numInteriorRings();
3300 QList< const QgsCurve * > holesToExport;
3301 holesToExport.reserve( nInteriorRings );
3302 for ( int i = 0; i < nInteriorRings; ++i )
3303 {
3304 const QgsCurve *interiorRing = polygon->interiorRing( i );
3305 if ( !( flags & Qgis::GeosCreationFlag::SkipEmptyInteriorRings ) || !interiorRing->isEmpty() )
3306 {
3307 holesToExport << interiorRing;
3308 }
3309 }
3310
3311 GEOSGeometry **holes = nullptr;
3312 if ( !holesToExport.empty() )
3313 {
3314 holes = new GEOSGeometry *[holesToExport.size()];
3315 for ( int i = 0; i < holesToExport.size(); ++i )
3316 {
3317 if ( holesToExport[i]->isSimpleCurve() )
3318 {
3319 holes[i] = createGeosSimpleCurve( holesToExport[i], precision, flags ).release();
3320 }
3321 else
3322 {
3323 holes[i] = createGeosCompoundCurve( holesToExport[i], precision, flags ).release();
3324 }
3325 }
3326 }
3327
3328 geosCurvePolygon.reset( GEOSGeom_createCurvePolygon_r( context, exteriorRingGeos.release(), holes, holesToExport.size() ) );
3329 delete[] holes;
3330 }
3331 CATCH_GEOS( nullptr )
3332
3333 return geosCurvePolygon;
3334}
3335#endif
3336
3337geos::unique_ptr QgsGeos::createGeosPolygon( const QgsAbstractGeometry *poly, double precision, Qgis::GeosCreationFlags flags )
3338{
3339 const QgsCurvePolygon *polygon = qgsgeometry_cast<const QgsCurvePolygon *>( poly );
3340 if ( !polygon )
3341 return nullptr;
3342
3343 const QgsCurve *exteriorRing = polygon->exteriorRing();
3344 if ( !exteriorRing )
3345 {
3346 return nullptr;
3347 }
3348
3349 GEOSContextHandle_t context = QgsGeosContext::get();
3350 geos::unique_ptr geosPolygon;
3351 try
3352 {
3353 geos::unique_ptr exteriorRingGeos( GEOSGeom_createLinearRing_r( context, createCoordinateSequence( exteriorRing, precision, true ) ) );
3354
3355 const int nInteriorRings = polygon->numInteriorRings();
3356 QList< const QgsCurve * > holesToExport;
3357 holesToExport.reserve( nInteriorRings );
3358 for ( int i = 0; i < nInteriorRings; ++i )
3359 {
3360 const QgsCurve *interiorRing = polygon->interiorRing( i );
3361 if ( !( flags & Qgis::GeosCreationFlag::SkipEmptyInteriorRings ) || !interiorRing->isEmpty() )
3362 {
3363 holesToExport << interiorRing;
3364 }
3365 }
3366
3367 GEOSGeometry **holes = nullptr;
3368 if ( !holesToExport.empty() )
3369 {
3370 holes = new GEOSGeometry *[holesToExport.size()];
3371 for ( int i = 0; i < holesToExport.size(); ++i )
3372 {
3373 holes[i] = GEOSGeom_createLinearRing_r( context, createCoordinateSequence( holesToExport[i], precision, true ) );
3374 }
3375 }
3376
3377 geosPolygon.reset( GEOSGeom_createPolygon_r( context, exteriorRingGeos.release(), holes, holesToExport.size() ) );
3378 delete[] holes;
3379 }
3380 CATCH_GEOS( nullptr )
3381
3382 return geosPolygon;
3383}
3384
3385geos::unique_ptr QgsGeos::offsetCurve( const GEOSGeometry *geometry, double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback )
3386{
3387 if ( !geometry )
3388 return nullptr;
3389
3390 geos::unique_ptr offset;
3391 try
3392 {
3393 // Force quadrant segments to be at least 8, see
3394 // https://github.com/qgis/QGIS/issues/53165#issuecomment-1563470832
3395 if ( segments < 8 )
3396 segments = 8;
3397 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3398 offset.reset( GEOSOffsetCurve_r( QgsGeosContext::get(), geometry, distance, segments, static_cast< int >( joinStyle ), miterLimit ) );
3399 }
3400 CATCH_GEOS_WITH_ERRMSG( nullptr )
3401 return offset;
3402}
3403
3404QgsAbstractGeometry *QgsGeos::offsetCurve( double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback ) const
3405{
3406 geos::unique_ptr res = offsetCurve( mGeos.get(), distance, segments, joinStyle, miterLimit, errorMsg, feedback );
3407 if ( !res )
3408 return nullptr;
3409
3410 return fromGeos( res.get() ).release();
3411}
3412
3413std::unique_ptr<QgsAbstractGeometry> QgsGeos::singleSidedBuffer(
3414 double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg, QgsFeedback *feedback
3415) const
3416{
3417 if ( !mGeos )
3418 {
3419 return nullptr;
3420 }
3421
3423 GEOSContextHandle_t context = QgsGeosContext::get();
3424 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3425 try
3426 {
3427 geos::buffer_params_unique_ptr bp( GEOSBufferParams_create_r( context ) );
3428 GEOSBufferParams_setSingleSided_r( context, bp.get(), 1 );
3429 GEOSBufferParams_setQuadrantSegments_r( context, bp.get(), segments );
3430 GEOSBufferParams_setJoinStyle_r( context, bp.get(), static_cast< int >( joinStyle ) );
3431 GEOSBufferParams_setMitreLimit_r( context, bp.get(), miterLimit ); //#spellok
3432
3433 if ( side == Qgis::BufferSide::Right )
3434 {
3435 distance = -distance;
3436 }
3437 geos.reset( GEOSBufferWithParams_r( context, mGeos.get(), bp.get(), distance ) );
3438 }
3439 CATCH_GEOS_WITH_ERRMSG( nullptr )
3440 return fromGeos( geos.get() );
3441}
3442
3443std::unique_ptr<QgsAbstractGeometry> QgsGeos::maximumInscribedCircle( double tolerance, QString *errorMsg, QgsFeedback *feedback ) const
3444{
3445 if ( !mGeos )
3446 {
3447 return nullptr;
3448 }
3449
3451 try
3452 {
3453 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3454 geos.reset( GEOSMaximumInscribedCircle_r( QgsGeosContext::get(), mGeos.get(), tolerance ) );
3455 }
3456 CATCH_GEOS_WITH_ERRMSG( nullptr )
3457 return fromGeos( geos.get() );
3458}
3459
3460std::unique_ptr<QgsAbstractGeometry> QgsGeos::largestEmptyCircle( double tolerance, const QgsAbstractGeometry *boundary, QString *errorMsg, QgsFeedback *feedback ) const
3461{
3462 if ( !mGeos )
3463 {
3464 return nullptr;
3465 }
3466
3468 try
3469 {
3470 geos::unique_ptr boundaryGeos;
3471 if ( boundary )
3472 boundaryGeos = asGeos( boundary );
3473
3474 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3475 geos.reset( GEOSLargestEmptyCircle_r( QgsGeosContext::get(), mGeos.get(), boundaryGeos.get(), tolerance ) );
3476 }
3477 CATCH_GEOS_WITH_ERRMSG( nullptr )
3478 return fromGeos( geos.get() );
3479}
3480
3481std::unique_ptr<QgsAbstractGeometry> QgsGeos::minimumWidth( QString *errorMsg, QgsFeedback *feedback ) const
3482{
3483 if ( !mGeos )
3484 {
3485 return nullptr;
3486 }
3487
3489 try
3490 {
3491 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3492 geos.reset( GEOSMinimumWidth_r( QgsGeosContext::get(), mGeos.get() ) );
3493 }
3494 CATCH_GEOS_WITH_ERRMSG( nullptr )
3495 return fromGeos( geos.get() );
3496}
3497
3498double QgsGeos::minimumClearance( QString *errorMsg, QgsFeedback *feedback ) const
3499{
3500 if ( !mGeos )
3501 {
3502 return std::numeric_limits< double >::quiet_NaN();
3503 }
3504
3506 double res = 0;
3507 try
3508 {
3509 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3510 if ( GEOSMinimumClearance_r( QgsGeosContext::get(), mGeos.get(), &res ) != 0 )
3511 return std::numeric_limits< double >::quiet_NaN();
3512 }
3513 CATCH_GEOS_WITH_ERRMSG( std::numeric_limits< double >::quiet_NaN() )
3514 return res;
3515}
3516
3517std::unique_ptr<QgsAbstractGeometry> QgsGeos::minimumClearanceLine( QString *errorMsg, QgsFeedback *feedback ) const
3518{
3519 if ( !mGeos )
3520 {
3521 return nullptr;
3522 }
3523
3525 try
3526 {
3527 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3528 geos.reset( GEOSMinimumClearanceLine_r( QgsGeosContext::get(), mGeos.get() ) );
3529 }
3530 CATCH_GEOS_WITH_ERRMSG( nullptr )
3531 return fromGeos( geos.get() );
3532}
3533
3534std::unique_ptr<QgsAbstractGeometry> QgsGeos::node( QString *errorMsg, QgsFeedback *feedback ) const
3535{
3536 if ( !mGeos )
3537 {
3538 return nullptr;
3539 }
3540
3542 try
3543 {
3544 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3545 geos.reset( GEOSNode_r( QgsGeosContext::get(), mGeos.get() ) );
3546 }
3547 CATCH_GEOS_WITH_ERRMSG( nullptr )
3548 return fromGeos( geos.get() );
3549}
3550
3551std::unique_ptr<QgsAbstractGeometry> QgsGeos::sharedPaths( const QgsAbstractGeometry *other, QString *errorMsg, QgsFeedback *feedback ) const
3552{
3553 if ( !mGeos || !other )
3554 {
3555 return nullptr;
3556 }
3557
3559 try
3560 {
3561 geos::unique_ptr otherGeos = asGeos( other );
3562 if ( !otherGeos )
3563 return nullptr;
3564
3565 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3566 geos.reset( GEOSSharedPaths_r( QgsGeosContext::get(), mGeos.get(), otherGeos.get() ) );
3567 }
3568 CATCH_GEOS_WITH_ERRMSG( nullptr )
3569 return fromGeos( geos.get() );
3570}
3571
3572std::unique_ptr<QgsAbstractGeometry> QgsGeos::reshapeGeometry( const QgsLineString &reshapeWithLine, EngineOperationResult *errorCode, QString *errorMsg ) const
3573{
3574 if ( !mGeos || mGeometry->dimension() == 0 )
3575 {
3576 if ( errorCode )
3577 {
3578 *errorCode = InvalidBaseGeometry;
3579 }
3580 return nullptr;
3581 }
3582
3583 if ( reshapeWithLine.numPoints() < 2 )
3584 {
3585 if ( errorCode )
3586 {
3587 *errorCode = InvalidInput;
3588 }
3589 return nullptr;
3590 }
3591
3592 geos::unique_ptr reshapeLineGeos = createGeosLinestring( &reshapeWithLine, mPrecision );
3593
3594 GEOSContextHandle_t context = QgsGeosContext::get();
3595 //single or multi?
3596 int numGeoms = GEOSGetNumGeometries_r( context, mGeos.get() );
3597 if ( numGeoms == -1 )
3598 {
3599 if ( errorCode )
3600 {
3601 *errorCode = InvalidBaseGeometry;
3602 }
3603 return nullptr;
3604 }
3605
3606 bool isMultiGeom = false;
3607 int geosTypeId = GEOSGeomTypeId_r( context, mGeos.get() );
3608 if ( geosTypeId == GEOS_MULTILINESTRING || geosTypeId == GEOS_MULTIPOLYGON )
3609 isMultiGeom = true;
3610
3611 bool isLine = ( mGeometry->dimension() == 1 );
3612
3613 if ( !isMultiGeom )
3614 {
3615 geos::unique_ptr reshapedGeometry;
3616 if ( isLine )
3617 {
3618 reshapedGeometry = reshapeLine( mGeos.get(), reshapeLineGeos.get(), mPrecision );
3619 }
3620 else
3621 {
3622 reshapedGeometry = reshapePolygon( mGeos.get(), reshapeLineGeos.get(), mPrecision );
3623 }
3624
3625 if ( errorCode )
3626 {
3627 if ( reshapedGeometry )
3628 *errorCode = Success;
3629 else
3630 *errorCode = NothingHappened;
3631 }
3632
3633 std::unique_ptr< QgsAbstractGeometry > reshapeResult = fromGeos( reshapedGeometry.get() );
3634 return reshapeResult;
3635 }
3636 else
3637 {
3638 try
3639 {
3640 //call reshape for each geometry part and replace mGeos with new geometry if reshape took place
3641 bool reshapeTookPlace = false;
3642
3643 geos::unique_ptr currentReshapeGeometry;
3644 GEOSGeometry **newGeoms = new GEOSGeometry *[numGeoms];
3645
3646 for ( int i = 0; i < numGeoms; ++i )
3647 {
3648 if ( isLine )
3649 currentReshapeGeometry = reshapeLine( GEOSGetGeometryN_r( context, mGeos.get(), i ), reshapeLineGeos.get(), mPrecision );
3650 else
3651 currentReshapeGeometry = reshapePolygon( GEOSGetGeometryN_r( context, mGeos.get(), i ), reshapeLineGeos.get(), mPrecision );
3652
3653 if ( currentReshapeGeometry )
3654 {
3655 newGeoms[i] = currentReshapeGeometry.release();
3656 reshapeTookPlace = true;
3657 }
3658 else
3659 {
3660 newGeoms[i] = GEOSGeom_clone_r( context, GEOSGetGeometryN_r( context, mGeos.get(), i ) );
3661 }
3662 }
3663
3664 geos::unique_ptr newMultiGeom;
3665 if ( isLine )
3666 {
3667 newMultiGeom.reset( GEOSGeom_createCollection_r( context, GEOS_MULTILINESTRING, newGeoms, numGeoms ) );
3668 }
3669 else //multipolygon
3670 {
3671 newMultiGeom.reset( GEOSGeom_createCollection_r( context, GEOS_MULTIPOLYGON, newGeoms, numGeoms ) );
3672 }
3673
3674 delete[] newGeoms;
3675 if ( !newMultiGeom )
3676 {
3677 if ( errorCode )
3678 {
3679 *errorCode = EngineError;
3680 }
3681 return nullptr;
3682 }
3683
3684 if ( reshapeTookPlace )
3685 {
3686 if ( errorCode )
3687 *errorCode = Success;
3688 std::unique_ptr< QgsAbstractGeometry > reshapedMultiGeom = fromGeos( newMultiGeom.get() );
3689 return reshapedMultiGeom;
3690 }
3691 else
3692 {
3693 if ( errorCode )
3694 {
3695 *errorCode = NothingHappened;
3696 }
3697 return nullptr;
3698 }
3699 }
3700 CATCH_GEOS_WITH_ERRMSG( nullptr )
3701 }
3702}
3703
3704std::unique_ptr< QgsAbstractGeometry > QgsGeos::mergeLines( QString *errorMsg, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
3705{
3706 if ( !mGeos )
3707 {
3708 return nullptr;
3709 }
3710
3711 GEOSContextHandle_t context = QgsGeosContext::get();
3712 if ( GEOSGeomTypeId_r( context, mGeos.get() ) != GEOS_MULTILINESTRING )
3713 return nullptr;
3714
3715 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3717 try
3718 {
3719 double gridSize = parameters.gridSize();
3720 if ( gridSize > 0 )
3721 {
3722 geos::unique_ptr geosFixedSize( GEOSGeom_setPrecision_r( context, mGeos.get(), gridSize, 0 ) );
3723 geos.reset( GEOSLineMerge_r( context, geosFixedSize.get() ) );
3724 }
3725 else
3726 geos.reset( GEOSLineMerge_r( context, mGeos.get() ) );
3727 }
3728 CATCH_GEOS_WITH_ERRMSG( nullptr )
3729 return fromGeos( geos.get() );
3730}
3731
3732std::unique_ptr<QgsAbstractGeometry> QgsGeos::closestPoint( const QgsGeometry &other, QString *errorMsg, QgsFeedback *feedback ) const
3733{
3734 if ( !mGeos || isEmpty() || other.isEmpty() )
3735 {
3736 return nullptr;
3737 }
3738
3739 geos::unique_ptr otherGeom( asGeos( other.constGet(), mPrecision ) );
3740 if ( !otherGeom )
3741 {
3742 return nullptr;
3743 }
3744
3745 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3746 GEOSContextHandle_t context = QgsGeosContext::get();
3747 double nx = 0.0;
3748 double ny = 0.0;
3749 try
3750 {
3752 if ( mGeosPrepared ) // use faster version with prepared geometry
3753 {
3754 nearestCoord.reset( GEOSPreparedNearestPoints_r( context, mGeosPrepared.get(), otherGeom.get() ) );
3755 }
3756 else
3757 {
3758 nearestCoord.reset( GEOSNearestPoints_r( context, mGeos.get(), otherGeom.get() ) );
3759 }
3760
3761 ( void ) GEOSCoordSeq_getX_r( context, nearestCoord.get(), 0, &nx );
3762 ( void ) GEOSCoordSeq_getY_r( context, nearestCoord.get(), 0, &ny );
3763 }
3764 catch ( QgsGeosException &e )
3765 {
3766 logError( u"GEOS"_s, e.what() );
3767 if ( errorMsg )
3768 {
3769 *errorMsg = e.what();
3770 }
3771 return nullptr;
3772 }
3773
3774 return std::make_unique< QgsPoint >( nx, ny );
3775}
3776
3777std::unique_ptr<QgsAbstractGeometry> QgsGeos::shortestLine( const QgsGeometry &other, QString *errorMsg, QgsFeedback *feedback ) const
3778{
3779 if ( !mGeos || other.isEmpty() )
3780 {
3781 return nullptr;
3782 }
3783
3784 return shortestLine( other.constGet(), errorMsg, feedback );
3785}
3786
3787std::unique_ptr< QgsAbstractGeometry > QgsGeos::shortestLine( const QgsAbstractGeometry *other, QString *errorMsg, QgsFeedback *feedback ) const
3788{
3789 if ( !other || other->isEmpty() )
3790 return nullptr;
3791
3792 geos::unique_ptr otherGeom( asGeos( other, mPrecision ) );
3793 if ( !otherGeom )
3794 {
3795 return nullptr;
3796 }
3797
3798 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3799 GEOSContextHandle_t context = QgsGeosContext::get();
3800 double nx1 = 0.0;
3801 double ny1 = 0.0;
3802 double nx2 = 0.0;
3803 double ny2 = 0.0;
3804 try
3805 {
3806 geos::coord_sequence_unique_ptr nearestCoord( GEOSNearestPoints_r( context, mGeos.get(), otherGeom.get() ) );
3807
3808 if ( !nearestCoord )
3809 {
3810 if ( errorMsg )
3811 *errorMsg = u"GEOS returned no nearest points"_s;
3812 return nullptr;
3813 }
3814
3815 ( void ) GEOSCoordSeq_getX_r( context, nearestCoord.get(), 0, &nx1 );
3816 ( void ) GEOSCoordSeq_getY_r( context, nearestCoord.get(), 0, &ny1 );
3817 ( void ) GEOSCoordSeq_getX_r( context, nearestCoord.get(), 1, &nx2 );
3818 ( void ) GEOSCoordSeq_getY_r( context, nearestCoord.get(), 1, &ny2 );
3819 }
3820 catch ( QgsGeosException &e )
3821 {
3822 logError( u"GEOS"_s, e.what() );
3823 if ( errorMsg )
3824 {
3825 *errorMsg = e.what();
3826 }
3827 return nullptr;
3828 }
3829
3830 auto line = std::make_unique< QgsLineString >();
3831 line->addVertex( QgsPoint( nx1, ny1 ) );
3832 line->addVertex( QgsPoint( nx2, ny2 ) );
3833 return line;
3834}
3835
3836double QgsGeos::lineLocatePoint( const QgsPoint &point, QString *errorMsg, QgsFeedback *feedback ) const
3837{
3838 if ( !mGeos )
3839 {
3840 return -1;
3841 }
3842
3843 geos::unique_ptr otherGeom( asGeos( &point, mPrecision ) );
3844 if ( !otherGeom )
3845 {
3846 return -1;
3847 }
3848
3849 double distance = -1;
3850 try
3851 {
3852 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3853 distance = GEOSProject_r( QgsGeosContext::get(), mGeos.get(), otherGeom.get() );
3854 }
3855 catch ( QgsGeosException &e )
3856 {
3857 logError( u"GEOS"_s, e.what() );
3858 if ( errorMsg )
3859 {
3860 *errorMsg = e.what();
3861 }
3862 return -1;
3863 }
3864
3865 return distance;
3866}
3867
3868double QgsGeos::lineLocatePoint( double x, double y, QString *errorMsg, QgsFeedback *feedback ) const
3869{
3870 if ( !mGeos )
3871 {
3872 return -1;
3873 }
3874
3875 geos::unique_ptr point = createGeosPointXY( x, y, false, 0, false, 0, 2, 0 );
3876 if ( !point )
3877 return false;
3878
3879 double distance = -1;
3880 try
3881 {
3882 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3883 distance = GEOSProject_r( QgsGeosContext::get(), mGeos.get(), point.get() );
3884 }
3885 catch ( QgsGeosException &e )
3886 {
3887 logError( u"GEOS"_s, e.what() );
3888 if ( errorMsg )
3889 {
3890 *errorMsg = e.what();
3891 }
3892 return -1;
3893 }
3894
3895 return distance;
3896}
3897
3898QgsGeometry QgsGeos::polygonize( const QVector<const QgsAbstractGeometry *> &geometries, QString *errorMsg, QgsFeedback *feedback )
3899{
3900 GEOSGeometry **const lineGeosGeometries = new GEOSGeometry *[geometries.size()];
3901 int validLines = 0;
3902 for ( const QgsAbstractGeometry *g : geometries )
3903 {
3904 geos::unique_ptr l = asGeos( g );
3905 if ( l )
3906 {
3907 lineGeosGeometries[validLines] = l.release();
3908 validLines++;
3909 }
3910 }
3911
3912 GEOSContextHandle_t context = QgsGeosContext::get();
3913 try
3914 {
3915 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3916 geos::unique_ptr result( GEOSPolygonize_r( context, lineGeosGeometries, validLines ) );
3917 for ( int i = 0; i < validLines; ++i )
3918 {
3919 GEOSGeom_destroy_r( context, lineGeosGeometries[i] );
3920 }
3921 delete[] lineGeosGeometries;
3922 return QgsGeometry( fromGeos( result.get() ) );
3923 }
3924 catch ( QgsGeosException &e )
3925 {
3926 if ( errorMsg )
3927 {
3928 *errorMsg = e.what();
3929 }
3930 for ( int i = 0; i < validLines; ++i )
3931 {
3932 GEOSGeom_destroy_r( context, lineGeosGeometries[i] );
3933 }
3934 delete[] lineGeosGeometries;
3935 return QgsGeometry();
3936 }
3937}
3938
3939std::unique_ptr<QgsAbstractGeometry> QgsGeos::voronoiDiagram( const QgsAbstractGeometry *extent, double tolerance, bool edgesOnly, QString *errorMsg, QgsFeedback *feedback ) const
3940{
3941 if ( !mGeos )
3942 {
3943 return nullptr;
3944 }
3945
3946 geos::unique_ptr extentGeosGeom;
3947 if ( extent )
3948 {
3949 extentGeosGeom = asGeos( extent, mPrecision );
3950 if ( !extentGeosGeom )
3951 {
3952 return nullptr;
3953 }
3954 }
3955
3957 GEOSContextHandle_t context = QgsGeosContext::get();
3958 try
3959 {
3960 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3961 geos.reset( GEOSVoronoiDiagram_r( context, mGeos.get(), extentGeosGeom.get(), tolerance, edgesOnly ) );
3962
3963 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
3964 {
3965 return nullptr;
3966 }
3967
3968 return fromGeos( geos.get() );
3969 }
3970 CATCH_GEOS_WITH_ERRMSG( nullptr )
3971}
3972
3973std::unique_ptr<QgsAbstractGeometry> QgsGeos::delaunayTriangulation( double tolerance, bool edgesOnly, QString *errorMsg, QgsFeedback *feedback ) const
3974{
3975 if ( !mGeos )
3976 {
3977 return nullptr;
3978 }
3979
3980 GEOSContextHandle_t context = QgsGeosContext::get();
3982 try
3983 {
3984 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
3985 geos.reset( GEOSDelaunayTriangulation_r( context, mGeos.get(), tolerance, edgesOnly ) );
3986
3987 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
3988 {
3989 return nullptr;
3990 }
3991
3992 return fromGeos( geos.get() );
3993 }
3994 CATCH_GEOS_WITH_ERRMSG( nullptr )
3995}
3996
3997std::unique_ptr<QgsAbstractGeometry> QgsGeos::constrainedDelaunayTriangulation( QString *errorMsg, QgsFeedback *feedback ) const
3998{
3999#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 11, 0 )
4000 ( void ) errorMsg;
4001 throw QgsNotSupportedException( QObject::tr( "Calculating constrainedDelaunayTriangulation requires a QGIS build based on GEOS 3.11 or later" ) );
4002#else
4003 if ( !mGeos )
4004 {
4005 return nullptr;
4006 }
4007
4009 GEOSContextHandle_t context = QgsGeosContext::get();
4010 try
4011 {
4012 QgsScopedGeosContextRegisterFeedback interrupt( feedback );
4013 geos.reset( GEOSConstrainedDelaunayTriangulation_r( context, mGeos.get() ) );
4014
4015 if ( !geos || GEOSisEmpty_r( context, geos.get() ) != 0 )
4016 {
4017 return nullptr;
4018 }
4019
4020 std::unique_ptr< QgsAbstractGeometry > res = fromGeos( geos.get() );
4021 if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( res.get() ) )
4022 {
4023 return std::unique_ptr< QgsAbstractGeometry >( collection->extractPartsByType( Qgis::WkbType::Polygon, true ) );
4024 }
4025 else
4026 {
4027 return res;
4028 }
4029 }
4030 CATCH_GEOS_WITH_ERRMSG( nullptr )
4031#endif
4032}
4033
4035static bool _linestringEndpoints( const GEOSGeometry *linestring, double &x1, double &y1, double &x2, double &y2 )
4036{
4037 GEOSContextHandle_t context = QgsGeosContext::get();
4038 const GEOSCoordSequence *coordSeq = GEOSGeom_getCoordSeq_r( context, linestring );
4039 if ( !coordSeq )
4040 return false;
4041
4042 unsigned int coordSeqSize;
4043 if ( GEOSCoordSeq_getSize_r( context, coordSeq, &coordSeqSize ) == 0 )
4044 return false;
4045
4046 if ( coordSeqSize < 2 )
4047 return false;
4048
4049 GEOSCoordSeq_getX_r( context, coordSeq, 0, &x1 );
4050 GEOSCoordSeq_getY_r( context, coordSeq, 0, &y1 );
4051 GEOSCoordSeq_getX_r( context, coordSeq, coordSeqSize - 1, &x2 );
4052 GEOSCoordSeq_getY_r( context, coordSeq, coordSeqSize - 1, &y2 );
4053 return true;
4054}
4055
4056
4058static geos::unique_ptr _mergeLinestrings( const GEOSGeometry *line1, const GEOSGeometry *line2, const QgsPointXY &intersectionPoint )
4059{
4060 double x1, y1, x2, y2;
4061 if ( !_linestringEndpoints( line1, x1, y1, x2, y2 ) )
4062 return nullptr;
4063
4064 double rx1, ry1, rx2, ry2;
4065 if ( !_linestringEndpoints( line2, rx1, ry1, rx2, ry2 ) )
4066 return nullptr;
4067
4068 bool intersectionAtOrigLineEndpoint = ( intersectionPoint.x() == x1 && intersectionPoint.y() == y1 ) != ( intersectionPoint.x() == x2 && intersectionPoint.y() == y2 );
4069 bool intersectionAtReshapeLineEndpoint = ( intersectionPoint.x() == rx1 && intersectionPoint.y() == ry1 ) || ( intersectionPoint.x() == rx2 && intersectionPoint.y() == ry2 );
4070
4071 GEOSContextHandle_t context = QgsGeosContext::get();
4072 // the intersection must be at the begin/end of both lines
4073 if ( intersectionAtOrigLineEndpoint && intersectionAtReshapeLineEndpoint )
4074 {
4075 geos::unique_ptr g1( GEOSGeom_clone_r( context, line1 ) );
4076 geos::unique_ptr g2( GEOSGeom_clone_r( context, line2 ) );
4077 GEOSGeometry *geoms[2] = { g1.release(), g2.release() };
4078 geos::unique_ptr multiGeom( GEOSGeom_createCollection_r( context, GEOS_MULTILINESTRING, geoms, 2 ) );
4079 geos::unique_ptr res( GEOSLineMerge_r( context, multiGeom.get() ) );
4080
4081 //keep the original orientation if the result has a start or end point in common with the original line
4082 //and this point is not the start or the end point for both lines
4083 double x1res, y1res, x2res, y2res;
4084 if ( !_linestringEndpoints( res.get(), x1res, y1res, x2res, y2res ) )
4085 return nullptr;
4086 if ( ( x1res == x2 && y1res == y2 ) || ( x2res == x1 && y2res == y1 ) )
4087 res.reset( GEOSReverse_r( context, res.get() ) );
4088
4089 return res;
4090 }
4091 else
4092 return nullptr;
4093}
4094
4095
4096geos::unique_ptr QgsGeos::reshapeLine( const GEOSGeometry *line, const GEOSGeometry *reshapeLineGeos, double precision )
4097{
4098 if ( !line || !reshapeLineGeos )
4099 return nullptr;
4100
4101 bool atLeastTwoIntersections = false;
4102 bool oneIntersection = false;
4103 QgsPointXY oneIntersectionPoint;
4104
4105 GEOSContextHandle_t context = QgsGeosContext::get();
4106 try
4107 {
4108 //make sure there are at least two intersection between line and reshape geometry
4109 geos::unique_ptr intersectGeom( GEOSIntersection_r( context, line, reshapeLineGeos ) );
4110 if ( intersectGeom )
4111 {
4112 const int geomType = GEOSGeomTypeId_r( context, intersectGeom.get() );
4113 atLeastTwoIntersections = ( geomType == GEOS_MULTIPOINT && GEOSGetNumGeometries_r( context, intersectGeom.get() ) > 1 )
4114 || ( geomType == GEOS_GEOMETRYCOLLECTION && GEOSGetNumGeometries_r( context, intersectGeom.get() ) > 0 ) // a collection implies at least two points!
4115 || ( geomType == GEOS_MULTILINESTRING && GEOSGetNumGeometries_r( context, intersectGeom.get() ) > 0 );
4116 // one point is enough when extending line at its endpoint
4117 if ( GEOSGeomTypeId_r( context, intersectGeom.get() ) == GEOS_POINT )
4118 {
4119 const GEOSCoordSequence *intersectionCoordSeq = GEOSGeom_getCoordSeq_r( context, intersectGeom.get() );
4120 double xi, yi;
4121 GEOSCoordSeq_getX_r( context, intersectionCoordSeq, 0, &xi );
4122 GEOSCoordSeq_getY_r( context, intersectionCoordSeq, 0, &yi );
4123 oneIntersection = true;
4124 oneIntersectionPoint = QgsPointXY( xi, yi );
4125 }
4126 }
4127 }
4128 catch ( QgsGeosException & )
4129 {
4130 atLeastTwoIntersections = false;
4131 }
4132
4133 // special case when extending line at its endpoint
4134 if ( oneIntersection )
4135 return _mergeLinestrings( line, reshapeLineGeos, oneIntersectionPoint );
4136
4137 if ( !atLeastTwoIntersections )
4138 return nullptr;
4139
4140 //begin and end point of original line
4141 double x1, y1, x2, y2;
4142 if ( !_linestringEndpoints( line, x1, y1, x2, y2 ) )
4143 return nullptr;
4144
4145 geos::unique_ptr beginLineVertex = createGeosPointXY( x1, y1, false, 0, false, 0, 2, precision );
4146 geos::unique_ptr endLineVertex = createGeosPointXY( x2, y2, false, 0, false, 0, 2, precision );
4147
4148 bool isRing = false;
4149 if ( GEOSGeomTypeId_r( context, line ) == GEOS_LINEARRING || GEOSEquals_r( context, beginLineVertex.get(), endLineVertex.get() ) == 1 )
4150 isRing = true;
4151
4152 //node line and reshape line
4153 geos::unique_ptr nodedGeometry = nodeGeometries( reshapeLineGeos, line );
4154 if ( !nodedGeometry )
4155 {
4156 return nullptr;
4157 }
4158
4159 //and merge them together
4160 geos::unique_ptr mergedLines( GEOSLineMerge_r( context, nodedGeometry.get() ) );
4161 if ( !mergedLines )
4162 {
4163 return nullptr;
4164 }
4165
4166 int numMergedLines = GEOSGetNumGeometries_r( context, mergedLines.get() );
4167 if ( numMergedLines < 2 ) //some special cases. Normally it is >2
4168 {
4169 if ( numMergedLines == 1 ) //reshape line is from begin to endpoint. So we keep the reshapeline
4170 {
4171 geos::unique_ptr result( GEOSGeom_clone_r( context, reshapeLineGeos ) );
4172 return result;
4173 }
4174 else
4175 return nullptr;
4176 }
4177
4178 QVector<GEOSGeometry *> resultLineParts; //collection with the line segments that will be contained in result
4179 QVector<GEOSGeometry *> probableParts; //parts where we can decide on inclusion only after going through all the candidates
4180
4181 for ( int i = 0; i < numMergedLines; ++i )
4182 {
4183 const GEOSGeometry *currentGeom = GEOSGetGeometryN_r( context, mergedLines.get(), i );
4184
4185 // have we already added this part?
4186 bool alreadyAdded = false;
4187 double distance = 0;
4188 double bufferDistance = std::pow( 10.0L, geomDigits( currentGeom ) - 11 );
4189 for ( const GEOSGeometry *other : std::as_const( resultLineParts ) )
4190 {
4191 GEOSHausdorffDistance_r( context, currentGeom, other, &distance );
4192 if ( distance < bufferDistance )
4193 {
4194 alreadyAdded = true;
4195 break;
4196 }
4197 }
4198 if ( alreadyAdded )
4199 continue;
4200
4201 const GEOSCoordSequence *currentCoordSeq = GEOSGeom_getCoordSeq_r( context, currentGeom );
4202 unsigned int currentCoordSeqSize;
4203 GEOSCoordSeq_getSize_r( context, currentCoordSeq, &currentCoordSeqSize );
4204 if ( currentCoordSeqSize < 2 )
4205 continue;
4206
4207 //get the two endpoints of the current line merge result
4208 double xBegin, xEnd, yBegin, yEnd;
4209 GEOSCoordSeq_getX_r( context, currentCoordSeq, 0, &xBegin );
4210 GEOSCoordSeq_getY_r( context, currentCoordSeq, 0, &yBegin );
4211 GEOSCoordSeq_getX_r( context, currentCoordSeq, currentCoordSeqSize - 1, &xEnd );
4212 GEOSCoordSeq_getY_r( context, currentCoordSeq, currentCoordSeqSize - 1, &yEnd );
4213 geos::unique_ptr beginCurrentGeomVertex = createGeosPointXY( xBegin, yBegin, false, 0, false, 0, 2, precision );
4214 geos::unique_ptr endCurrentGeomVertex = createGeosPointXY( xEnd, yEnd, false, 0, false, 0, 2, precision );
4215
4216 //check how many endpoints of the line merge result are on the (original) line
4217 int nEndpointsOnOriginalLine = 0;
4218 if ( pointContainedInLine( beginCurrentGeomVertex.get(), line ) == 1 )
4219 nEndpointsOnOriginalLine += 1;
4220
4221 if ( pointContainedInLine( endCurrentGeomVertex.get(), line ) == 1 )
4222 nEndpointsOnOriginalLine += 1;
4223
4224 //check how many endpoints equal the endpoints of the original line
4225 int nEndpointsSameAsOriginalLine = 0;
4226 if ( GEOSEquals_r( context, beginCurrentGeomVertex.get(), beginLineVertex.get() ) == 1 || GEOSEquals_r( context, beginCurrentGeomVertex.get(), endLineVertex.get() ) == 1 )
4227 nEndpointsSameAsOriginalLine += 1;
4228
4229 if ( GEOSEquals_r( context, endCurrentGeomVertex.get(), beginLineVertex.get() ) == 1 || GEOSEquals_r( context, endCurrentGeomVertex.get(), endLineVertex.get() ) == 1 )
4230 nEndpointsSameAsOriginalLine += 1;
4231
4232 //check if the current geometry overlaps the original geometry (GEOSOverlap does not seem to work with linestrings)
4233 bool currentGeomOverlapsOriginalGeom = false;
4234 bool currentGeomOverlapsReshapeLine = false;
4235 if ( lineContainedInLine( currentGeom, line ) == 1 )
4236 currentGeomOverlapsOriginalGeom = true;
4237
4238 if ( lineContainedInLine( currentGeom, reshapeLineGeos ) == 1 )
4239 currentGeomOverlapsReshapeLine = true;
4240
4241 //logic to decide if this part belongs to the result
4242 if ( !isRing && nEndpointsSameAsOriginalLine == 1 && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom )
4243 {
4244 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4245 }
4246 //for closed rings, we take one segment from the candidate list
4247 else if ( isRing && nEndpointsOnOriginalLine == 2 && currentGeomOverlapsOriginalGeom )
4248 {
4249 probableParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4250 }
4251 else if ( nEndpointsOnOriginalLine == 2 && !currentGeomOverlapsOriginalGeom )
4252 {
4253 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4254 }
4255 else if ( nEndpointsSameAsOriginalLine == 2 && !currentGeomOverlapsOriginalGeom )
4256 {
4257 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4258 }
4259 else if ( currentGeomOverlapsOriginalGeom && currentGeomOverlapsReshapeLine )
4260 {
4261 resultLineParts.push_back( GEOSGeom_clone_r( context, currentGeom ) );
4262 }
4263 }
4264
4265 //add the longest segment from the probable list for rings (only used for polygon rings)
4266 if ( isRing && !probableParts.isEmpty() )
4267 {
4268 geos::unique_ptr maxGeom; //the longest geometry in the probabla list
4269 GEOSGeometry *currentGeom = nullptr;
4270 double maxLength = -std::numeric_limits<double>::max();
4271 double currentLength = 0;
4272 for ( int i = 0; i < probableParts.size(); ++i )
4273 {
4274 currentGeom = probableParts.at( i );
4275 GEOSLength_r( context, currentGeom, &currentLength );
4276 if ( currentLength > maxLength )
4277 {
4278 maxLength = currentLength;
4279 maxGeom.reset( currentGeom );
4280 }
4281 else
4282 {
4283 GEOSGeom_destroy_r( context, currentGeom );
4284 }
4285 }
4286 resultLineParts.push_back( maxGeom.release() );
4287 }
4288
4289 geos::unique_ptr result;
4290 if ( resultLineParts.empty() )
4291 return nullptr;
4292
4293 if ( resultLineParts.size() == 1 ) //the whole result was reshaped
4294 {
4295 result.reset( resultLineParts[0] );
4296 }
4297 else //>1
4298 {
4299 GEOSGeometry **lineArray = new GEOSGeometry *[resultLineParts.size()];
4300 for ( int i = 0; i < resultLineParts.size(); ++i )
4301 {
4302 lineArray[i] = resultLineParts[i];
4303 }
4304
4305 //create multiline from resultLineParts
4306 geos::unique_ptr multiLineGeom( GEOSGeom_createCollection_r( context, GEOS_MULTILINESTRING, lineArray, resultLineParts.size() ) );
4307 delete[] lineArray;
4308
4309 //then do a linemerge with the newly combined partstrings
4310 result.reset( GEOSLineMerge_r( context, multiLineGeom.get() ) );
4311 }
4312
4313 //now test if the result is a linestring. Otherwise something went wrong
4314 if ( GEOSGeomTypeId_r( context, result.get() ) != GEOS_LINESTRING )
4315 {
4316 return nullptr;
4317 }
4318
4319 //keep the original orientation
4320 bool reverseLine = false;
4321 if ( isRing )
4322 {
4323 //for closed linestring check clockwise/counter-clockwise
4324 char isResultCCW = 0, isOriginCCW = 0;
4325 if ( GEOSCoordSeq_isCCW_r( context, GEOSGeom_getCoordSeq_r( context, result.get() ), &isResultCCW ) && GEOSCoordSeq_isCCW_r( context, GEOSGeom_getCoordSeq_r( context, line ), &isOriginCCW ) )
4326 {
4327 //reverse line if orientations are different
4328 reverseLine = ( isOriginCCW == 1 && isResultCCW == 0 ) || ( isOriginCCW == 0 && isResultCCW == 1 );
4329 }
4330 }
4331 else
4332 {
4333 //for linestring, check if the result has a start or end point in common with the original line
4334 double x1res, y1res, x2res, y2res;
4335 if ( !_linestringEndpoints( result.get(), x1res, y1res, x2res, y2res ) )
4336 return nullptr;
4337 geos::unique_ptr beginResultLineVertex = createGeosPointXY( x1res, y1res, false, 0, false, 0, 2, precision );
4338 geos::unique_ptr endResultLineVertex = createGeosPointXY( x2res, y2res, false, 0, false, 0, 2, precision );
4339 reverseLine = GEOSEquals_r( context, beginLineVertex.get(), endResultLineVertex.get() ) == 1 || GEOSEquals_r( context, endLineVertex.get(), beginResultLineVertex.get() ) == 1;
4340 }
4341 if ( reverseLine )
4342 result.reset( GEOSReverse_r( context, result.get() ) );
4343
4344 return result;
4345}
4346
4347geos::unique_ptr QgsGeos::reshapePolygon( const GEOSGeometry *polygon, const GEOSGeometry *reshapeLineGeos, double precision )
4348{
4349 //go through outer shell and all inner rings and check if there is exactly one intersection of a ring and the reshape line
4350 int nIntersections = 0;
4351 int lastIntersectingRing = -2;
4352 const GEOSGeometry *lastIntersectingGeom = nullptr;
4353
4354 GEOSContextHandle_t context = QgsGeosContext::get();
4355 int nRings = GEOSGetNumInteriorRings_r( context, polygon );
4356 if ( nRings < 0 )
4357 return nullptr;
4358
4359 //does outer ring intersect?
4360 const GEOSGeometry *outerRing = GEOSGetExteriorRing_r( context, polygon );
4361 if ( GEOSIntersects_r( context, outerRing, reshapeLineGeos ) == 1 )
4362 {
4363 ++nIntersections;
4364 lastIntersectingRing = -1;
4365 lastIntersectingGeom = outerRing;
4366 }
4367
4368 //do inner rings intersect?
4369 const GEOSGeometry **innerRings = new const GEOSGeometry *[nRings];
4370
4371 try
4372 {
4373 for ( int i = 0; i < nRings; ++i )
4374 {
4375 innerRings[i] = GEOSGetInteriorRingN_r( context, polygon, i );
4376 if ( GEOSIntersects_r( context, innerRings[i], reshapeLineGeos ) == 1 )
4377 {
4378 ++nIntersections;
4379 lastIntersectingRing = i;
4380 lastIntersectingGeom = innerRings[i];
4381 }
4382 }
4383 }
4384 catch ( QgsGeosException & )
4385 {
4386 nIntersections = 0;
4387 }
4388
4389 if ( nIntersections != 1 ) //reshape line is only allowed to intersect one ring
4390 {
4391 delete[] innerRings;
4392 return nullptr;
4393 }
4394
4395 //we have one intersecting ring, let's try to reshape it
4396 geos::unique_ptr reshapeResult = reshapeLine( lastIntersectingGeom, reshapeLineGeos, precision );
4397 if ( !reshapeResult )
4398 {
4399 delete[] innerRings;
4400 return nullptr;
4401 }
4402
4403 //if reshaping took place, we need to reassemble the polygon and its rings
4404 GEOSGeometry *newRing = nullptr;
4405 const GEOSCoordSequence *reshapeSequence = GEOSGeom_getCoordSeq_r( context, reshapeResult.get() );
4406 GEOSCoordSequence *newCoordSequence = GEOSCoordSeq_clone_r( context, reshapeSequence );
4407
4408 reshapeResult.reset();
4409
4410 try
4411 {
4412 newRing = GEOSGeom_createLinearRing_r( context, newCoordSequence );
4413 }
4414 catch ( QgsGeosException & )
4415 {
4416 // nothing to do: on exception newRing will be null
4417 }
4418
4419 if ( !newRing )
4420 {
4421 delete[] innerRings;
4422 return nullptr;
4423 }
4424
4425 GEOSGeometry *newOuterRing = nullptr;
4426 if ( lastIntersectingRing == -1 )
4427 newOuterRing = newRing;
4428 else
4429 newOuterRing = GEOSGeom_clone_r( context, outerRing );
4430
4431 //check if all the rings are still inside the outer boundary
4432 QVector<GEOSGeometry *> ringList;
4433 if ( nRings > 0 )
4434 {
4435 GEOSGeometry *outerRingPoly = GEOSGeom_createPolygon_r( context, GEOSGeom_clone_r( context, newOuterRing ), nullptr, 0 );
4436 if ( outerRingPoly )
4437 {
4438 ringList.reserve( nRings );
4439 GEOSGeometry *currentRing = nullptr;
4440 for ( int i = 0; i < nRings; ++i )
4441 {
4442 if ( lastIntersectingRing == i )
4443 currentRing = newRing;
4444 else
4445 currentRing = GEOSGeom_clone_r( context, innerRings[i] );
4446
4447 //possibly a ring is no longer contained in the result polygon after reshape
4448 if ( GEOSContains_r( context, outerRingPoly, currentRing ) == 1 )
4449 ringList.push_back( currentRing );
4450 else
4451 GEOSGeom_destroy_r( context, currentRing );
4452 }
4453 }
4454 GEOSGeom_destroy_r( context, outerRingPoly );
4455 }
4456
4457 GEOSGeometry **newInnerRings = new GEOSGeometry *[ringList.size()];
4458 for ( int i = 0; i < ringList.size(); ++i )
4459 newInnerRings[i] = ringList.at( i );
4460
4461 delete[] innerRings;
4462
4463 geos::unique_ptr reshapedPolygon( GEOSGeom_createPolygon_r( context, newOuterRing, newInnerRings, ringList.size() ) );
4464 delete[] newInnerRings;
4465
4466 return reshapedPolygon;
4467}
4468
4469int QgsGeos::lineContainedInLine( const GEOSGeometry *line1, const GEOSGeometry *line2 )
4470{
4471 if ( !line1 || !line2 )
4472 {
4473 return -1;
4474 }
4475
4476 double bufferDistance = std::pow( 10.0L, geomDigits( line2 ) - 11 );
4477
4478 GEOSContextHandle_t context = QgsGeosContext::get();
4479 geos::unique_ptr bufferGeom( GEOSBuffer_r( context, line2, bufferDistance, DEFAULT_QUADRANT_SEGMENTS ) );
4480 if ( !bufferGeom )
4481 return -2;
4482
4483 geos::unique_ptr intersectionGeom( GEOSIntersection_r( context, bufferGeom.get(), line1 ) );
4484
4485 //compare ratio between line1Length and intersectGeomLength (usually close to 1 if line1 is contained in line2)
4486 double intersectGeomLength;
4487 double line1Length;
4488
4489 GEOSLength_r( context, intersectionGeom.get(), &intersectGeomLength );
4490 GEOSLength_r( context, line1, &line1Length );
4491
4492 double intersectRatio = line1Length / intersectGeomLength;
4493 if ( intersectRatio > 0.9 && intersectRatio < 1.1 )
4494 return 1;
4495
4496 return 0;
4497}
4498
4499int QgsGeos::pointContainedInLine( const GEOSGeometry *point, const GEOSGeometry *line )
4500{
4501 if ( !point || !line )
4502 return -1;
4503
4504 double bufferDistance = std::pow( 10.0L, geomDigits( line ) - 11 );
4505
4506 GEOSContextHandle_t context = QgsGeosContext::get();
4507 geos::unique_ptr lineBuffer( GEOSBuffer_r( context, line, bufferDistance, 8 ) );
4508 if ( !lineBuffer )
4509 return -2;
4510
4511 bool contained = false;
4512 if ( GEOSContains_r( context, lineBuffer.get(), point ) == 1 )
4513 contained = true;
4514
4515 return contained;
4516}
4517
4518int QgsGeos::geomDigits( const GEOSGeometry *geom )
4519{
4520 GEOSContextHandle_t context = QgsGeosContext::get();
4521 geos::unique_ptr bbox( GEOSEnvelope_r( context, geom ) );
4522 if ( !bbox )
4523 return -1;
4524
4525 const GEOSGeometry *bBoxRing = GEOSGetExteriorRing_r( context, bbox.get() );
4526 if ( !bBoxRing )
4527 return -1;
4528
4529 const GEOSCoordSequence *bBoxCoordSeq = GEOSGeom_getCoordSeq_r( context, bBoxRing );
4530
4531 if ( !bBoxCoordSeq )
4532 return -1;
4533
4534 unsigned int nCoords = 0;
4535 if ( !GEOSCoordSeq_getSize_r( context, bBoxCoordSeq, &nCoords ) )
4536 return -1;
4537
4538 int maxDigits = -1;
4539 for ( unsigned int i = 0; i < nCoords - 1; ++i )
4540 {
4541 double t;
4542 GEOSCoordSeq_getX_r( context, bBoxCoordSeq, i, &t );
4543
4544 int digits;
4545 digits = std::ceil( std::log10( std::fabs( t ) ) );
4546 if ( digits > maxDigits )
4547 maxDigits = digits;
4548
4549 GEOSCoordSeq_getY_r( context, bBoxCoordSeq, i, &t );
4550 digits = std::ceil( std::log10( std::fabs( t ) ) );
4551 if ( digits > maxDigits )
4552 maxDigits = digits;
4553 }
4554
4555 return maxDigits;
4556}
4557
4559#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 14, 0 )
4560 : mFeedback( feedback )
4561{
4562 GEOSContext_setInterruptCallback_r( QgsGeosContext::get(), &callback, reinterpret_cast< void * >( mFeedback ) );
4563}
4564#else
4565{
4566 ( void ) feedback;
4567}
4568#endif
4569
4570
4572{
4573#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 14, 0 )
4574 GEOSContext_setInterruptCallback_r( QgsGeosContext::get(), nullptr, nullptr );
4575#endif
4576}
4577
4578#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 14, 0 )
4579int QgsScopedGeosContextRegisterFeedback::callback( void *userData )
4580{
4581 if ( !userData )
4582 return 0;
4583
4584 QgsFeedback *feedback = reinterpret_cast< QgsFeedback * >( userData );
4585 return feedback && feedback->isCanceled() ? 1 : 0;
4586}
4587#endif
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:62
BufferSide
Side of line to buffer.
Definition qgis.h:2268
@ Right
Buffer to right of line.
Definition qgis.h:2270
@ LongestBorder
Polygon with longest common border is selected to merge overlapping polygons into.
Definition qgis.h:7130
@ MaximumArea
Polygon with largest area is selected to merge overlapping polygons into.
Definition qgis.h:7131
@ MinimumArea
Polygon with minimum area is selected to merge overlapping polygons into.
Definition qgis.h:7132
@ MinimumIndex
Polygon with smallest input index is selected to merge overlapping polygons into.
Definition qgis.h:7133
GeometryOperationResult
Success or failure of a geometry operation.
Definition qgis.h:2212
@ AddPartNotMultiGeometry
The source geometry is not multi.
Definition qgis.h:2223
@ InvalidBaseGeometry
The base geometry on which the operation is done is invalid or empty.
Definition qgis.h:2215
@ RejectOnInvalidSubGeometry
Don't allow geometries with invalid sub-geometries to be created.
Definition qgis.h:2332
@ SkipEmptyInteriorRings
Skip any empty polygon interior ring.
Definition qgis.h:2333
QFlags< GeosCreationFlag > GeosCreationFlags
Geos geometry creation behavior flags.
Definition qgis.h:2342
@ Point
Points.
Definition qgis.h:400
@ Polygon
Polygons.
Definition qgis.h:402
JoinStyle
Join styles for buffers.
Definition qgis.h:2293
EndCapStyle
End cap styles for buffers.
Definition qgis.h:2280
CoverageValidityResult
Coverage validity results.
Definition qgis.h:2351
@ Valid
Coverage is valid.
Definition qgis.h:2353
@ Invalid
Coverage is invalid. Invalidity includes polygons that overlap, that have gaps smaller than the gap w...
Definition qgis.h:2352
@ Error
An exception occurred while determining validity.
Definition qgis.h:2354
MakeValidMethod
Algorithms to use when repairing invalid geometries.
Definition qgis.h:2364
@ Linework
Combines all rings into a set of noded lines and then extracts valid polygons from that linework.
Definition qgis.h:2365
@ Structure
Structured method, first makes all rings valid and then merges shells and subtracts holes from shells...
Definition qgis.h:2366
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:314
@ CompoundCurve
CompoundCurve.
Definition qgis.h:325
@ Point
Point.
Definition qgis.h:316
@ LineString
LineString.
Definition qgis.h:317
@ TIN
TIN.
Definition qgis.h:330
@ MultiPoint
MultiPoint.
Definition qgis.h:320
@ LineStringZM
LineStringZM.
Definition qgis.h:366
@ Polygon
Polygon.
Definition qgis.h:318
@ MultiPolygon
MultiPolygon.
Definition qgis.h:322
@ Triangle
Triangle.
Definition qgis.h:319
@ NurbsCurve
NurbsCurve.
Definition qgis.h:331
@ NoGeometry
No geometry.
Definition qgis.h:332
@ MultiLineString
MultiLineString.
Definition qgis.h:321
@ Unknown
Unknown.
Definition qgis.h:315
@ PointM
PointM.
Definition qgis.h:349
@ CircularString
CircularString.
Definition qgis.h:324
@ PointZ
PointZ.
Definition qgis.h:333
@ GeometryCollection
GeometryCollection.
Definition qgis.h:323
@ MultiCurve
MultiCurve.
Definition qgis.h:327
@ CurvePolygon
CurvePolygon.
Definition qgis.h:326
@ PointZM
PointZM.
Definition qgis.h:365
@ LineStringZ
LineStringZ.
Definition qgis.h:334
@ PolyhedralSurface
PolyhedralSurface.
Definition qgis.h:329
@ MultiSurface
MultiSurface.
Definition qgis.h:328
Abstract base class for all geometries.
virtual const QgsAbstractGeometry * simplifiedTypeRef() const
Returns a reference to the simplest lossless representation of this geometry, e.g.
bool isMeasure() const
Returns true if the geometry contains m values.
bool is3D() const
Returns true if the geometry is 3D and contains a z-value.
virtual QgsPoint vertexAt(QgsVertexId id) const =0
Returns the point corresponding to a specified vertex id.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
virtual bool isEmpty() const
Returns true if the geometry is empty.
Encapsulates parameters for a coverage cleaning operation.
double maximumGapWidth() const
Returns the maximum gap width.
Qgis::CoverageCleanOverlapMergeStrategy overlapMergeStrategy() const
Returns the overlap merge strategy to use during cleaning.
double snappingDistance() const
Returns the snapping distance.
int numInteriorRings() const
Returns the number of interior rings contained with the curve polygon.
const QgsCurve * exteriorRing() const
Returns the curve polygon's exterior ring.
const QgsCurve * interiorRing(int i) const
Retrieves an interior ring from the curve polygon.
Abstract base class for curved geometry type.
Definition qgscurve.h:36
virtual bool isSimpleCurve() const =0
This method returns true for classes that can be cast to the QgsSimpleCurve class.
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.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
virtual bool addGeometry(QgsAbstractGeometry *g)
Adds a geometry and takes ownership. Returns true in case of success.
static Qgis::GeometryOperationResult addPart(QgsAbstractGeometry *geometry, std::unique_ptr< QgsAbstractGeometry > part)
Add a part to multi type geometry.
const QgsAbstractGeometry * mGeometry
EngineOperationResult
Success or failure of a geometry operation.
@ NothingHappened
Nothing happened, without any error.
@ InvalidBaseGeometry
The geometry on which the operation occurs is not valid.
@ InvalidInput
The input is not valid.
@ NodedGeometryError
Error occurred while creating a noded geometry.
@ EngineError
Error occurred in the geometry engine.
@ SplitCannotSplitPoint
Points cannot be split.
@ Success
Operation succeeded.
@ MethodNotImplemented
Method not implemented in geometry engine.
QgsGeometryEngine(const QgsAbstractGeometry *geometry)
void logError(const QString &engineName, const QString &message) const
Logs an error message encountered during an operation.
static std::unique_ptr< QgsGeometryCollection > createCollectionOfType(Qgis::WkbType type)
Returns a new geometry collection matching a specified WKB type.
Encapsulates parameters under which a geometry operation is performed.
double gridSize() const
Returns the grid size which will be used to snap vertices of a geometry.
static double sqrDistance2D(double x1, double y1, double x2, double y2)
Returns the squared 2D distance between (x1, y1) and (x2, y2).
A geometry is the spatial representation of a feature.
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.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
Used to create and store a GEOS context object, correctly freeing the context upon destruction.
Definition qgsgeos.h:63
static GEOSContextHandle_t get()
Returns a thread local instance of a GEOS context, safe for use in the current thread.
std::unique_ptr< QgsAbstractGeometry > singleSidedBuffer(double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a single sided buffer for a geometry.
Definition qgsgeos.cpp:3413
double minimumClearance(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Computes the minimum clearance of a geometry.
Definition qgsgeos.cpp:3498
bool intersects(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom intersects this.
Definition qgsgeos.cpp:905
bool distanceWithin(const QgsAbstractGeometry *geom, double maxdistance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom is within maxdistance distance from this geometry.
Definition qgsgeos.cpp:701
std::unique_ptr< QgsAbstractGeometry > concaveHull(double targetPercent, bool allowHoles=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a possibly concave geometry that encloses the input geometry.
Definition qgsgeos.cpp:2597
std::unique_ptr< QgsAbstractGeometry > reshapeGeometry(const QgsLineString &reshapeWithLine, EngineOperationResult *errorCode, QString *errorMsg=nullptr) const
Reshapes the geometry using a line.
Definition qgsgeos.cpp:3572
double distance(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculates the distance between this and geom.
Definition qgsgeos.cpp:624
std::unique_ptr< QgsAbstractGeometry > sharedPaths(const QgsAbstractGeometry *other, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Find paths shared between the two given lineal geometries (this and other).
Definition qgsgeos.cpp:3551
std::unique_ptr< QgsAbstractGeometry > minimumClearanceLine(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a LineString whose endpoints define the minimum clearance of a geometry.
Definition qgsgeos.cpp:3517
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlags())
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
Definition qgsgeos.cpp:284
QgsAbstractGeometry * symDifference(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the symmetric difference of this and geom.
Definition qgsgeos.cpp:582
std::unique_ptr< QgsAbstractGeometry > closestPoint(const QgsGeometry &other, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the closest point on the geometry to the other geometry.
Definition qgsgeos.cpp:3732
std::unique_ptr< QgsAbstractGeometry > unionCoverage(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap.
Definition qgsgeos.cpp:2717
bool isFuzzyEqual(const QgsAbstractGeometry *geom, double epsilon, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if this is equal to geom ie.
Definition qgsgeos.cpp:2889
QgsAbstractGeometry * simplify(double tolerance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Simplifies the geometery.
Definition qgsgeos.cpp:2475
static const QgsSettingsEntryBool * settingLineToCurveParam
Settings entry - Whether to convert any linear output of a GEOS method to a curved type,...
Definition qgsgeos.h:199
static geos::unique_ptr offsetCurve(const GEOSGeometry *geometry, double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr)
Directly calculates the offset curve for a GEOS geometry object and returns a GEOS geometry result.
Definition qgsgeos.cpp:3385
std::unique_ptr< QgsAbstractGeometry > cleanCoverage(const QgsCoverageCleanParameters &parameters, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Operates on a coverage (represented as a list of polygonal geometry), to fix cases where the geometry...
Definition qgsgeos.cpp:2736
QgsAbstractGeometry * intersection(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the intersection of this and geom.
Definition qgsgeos.cpp:357
double lineLocatePoint(const QgsPoint &point, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a distance representing the location along this linestring of the closest point on this lines...
Definition qgsgeos.cpp:3836
std::unique_ptr< QgsAbstractGeometry > subdivide(int maxNodes, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Subdivides the geometry.
Definition qgsgeos.cpp:489
bool touches(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom touches this.
Definition qgsgeos.cpp:939
static std::unique_ptr< QgsPolygon > fromGeosPolygon(const GEOSGeometry *geos)
Definition qgsgeos.cpp:1949
std::unique_ptr< QgsAbstractGeometry > largestEmptyCircle(double tolerance, const QgsAbstractGeometry *boundary=nullptr, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance.
Definition qgsgeos.cpp:3460
QgsAbstractGeometry * envelope(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:2535
Qgis::CoverageValidityResult validateCoverage(double gapWidth, std::unique_ptr< QgsAbstractGeometry > *invalidEdges, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Analyze a coverage (represented as a collection of polygonal geometry with exactly matching edge geom...
Definition qgsgeos.cpp:2645
QgsAbstractGeometry * buffer(double distance, int segments, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Buffers the geometry.
Definition qgsgeos.cpp:2432
QString relate(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Returns the Dimensional Extended 9 Intersection Model (DE-9IM) representation of the relationship bet...
Definition qgsgeos.cpp:998
std::unique_ptr< QgsAbstractGeometry > constrainedDelaunayTriangulation(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a constrained Delaunay triangulation for the vertices of the geometry.
Definition qgsgeos.cpp:3997
bool within(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom is within this.
Definition qgsgeos.cpp:949
bool contains(double x, double y, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns true if the geometry contains the point at (x, y).
Definition qgsgeos.cpp:765
bool isSimple(QString *errorMsg=nullptr) const override
Determines whether the geometry is simple (according to OGC definition).
Definition qgsgeos.cpp:2925
bool isValid(QString *errorMsg=nullptr, bool allowSelfTouchingHoles=false, QgsGeometry *errorLoc=nullptr, QgsFeedback *feedback=nullptr) const override
Returns true if the geometry is valid.
Definition qgsgeos.cpp:2805
std::unique_ptr< QgsAbstractGeometry > minimumWidth(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a linestring geometry which represents the minimum diameter of the geometry.
Definition qgsgeos.cpp:3481
std::unique_ptr< QgsAbstractGeometry > simplifyCoverageVW(double tolerance, bool preserveBoundary, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geomet...
Definition qgsgeos.cpp:2691
QgsGeos(const QgsAbstractGeometry *geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
GEOS geometry engine constructor.
Definition qgsgeos.cpp:205
std::unique_ptr< QgsAbstractGeometry > shortestLine(const QgsGeometry &other, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the shortest line joining this geometry to the other geometry.
Definition qgsgeos.cpp:3777
QgsAbstractGeometry * convexHull(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculate the convex hull of this geometry.
Definition qgsgeos.cpp:2580
void prepareGeometry() override
Prepares the geometry, so that subsequent calls to spatial relation methods are much faster.
Definition qgsgeos.cpp:316
std::unique_ptr< QgsAbstractGeometry > makeValid(Qgis::MakeValidMethod method=Qgis::MakeValidMethod::Linework, bool keepCollapsed=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Repairs the geometry using GEOS make valid routine.
Definition qgsgeos.cpp:226
QgsPoint * pointOnSurface(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculate a point that is guaranteed to be on the surface of this.
Definition qgsgeos.cpp:2550
static std::unique_ptr< QgsAbstractGeometry > fromGeos(const GEOSGeometry *geos)
Create a geometry from a GEOSGeometry.
Definition qgsgeos.cpp:1726
std::unique_ptr< QgsAbstractGeometry > node(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.
Definition qgsgeos.cpp:3534
QgsAbstractGeometry * combine(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the combination of this and geom.
Definition qgsgeos.cpp:510
bool disjoint(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom is disjoint from this.
Definition qgsgeos.cpp:993
bool relatePattern(const QgsAbstractGeometry *geom, const QString &pattern, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Tests whether two geometries are related by a specified Dimensional Extended 9 Intersection Model (DE...
Definition qgsgeos.cpp:1035
double hausdorffDistanceDensify(const QgsAbstractGeometry *geometry, double densifyFraction, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Hausdorff distance between this geometry and another geometry.
Definition qgsgeos.cpp:833
bool isEqual(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Check if geometries are topologically equivalent.
Definition qgsgeos.cpp:2868
static std::unique_ptr< QgsCurvePolygon > fromGeosCurvePolygon(const GEOSGeometry *geos)
Definition qgsgeos.cpp:1892
std::unique_ptr< QgsAbstractGeometry > maximumInscribedCircle(double tolerance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the maximum inscribed circle.
Definition qgsgeos.cpp:3443
std::unique_ptr< QgsAbstractGeometry > voronoiDiagram(const QgsAbstractGeometry *extent=nullptr, double tolerance=0.0, bool edgesOnly=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Creates a Voronoi diagram for the nodes contained within the geometry.
Definition qgsgeos.cpp:3939
double frechetDistanceDensify(const QgsAbstractGeometry *geometry, double densifyFraction, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Fréchet distance between this geometry and another geometry, restricted to discrete point...
Definition qgsgeos.cpp:881
std::unique_ptr< QgsAbstractGeometry > delaunayTriangulation(double tolerance=0.0, bool edgesOnly=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Delaunay triangulation for the vertices of the geometry.
Definition qgsgeos.cpp:3973
bool crosses(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom crosses this.
Definition qgsgeos.cpp:944
std::unique_ptr< QgsAbstractGeometry > concaveHullOfPolygons(double lengthRatio, bool allowHoles=false, bool isTight=false, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Constructs a concave hull of a set of polygons, respecting the polygons as constraints.
Definition qgsgeos.cpp:2621
std::unique_ptr< QgsAbstractGeometry > clip(const QgsRectangle &rectangle, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Performs a fast, non-robust intersection between the geometry and a rectangle.
Definition qgsgeos.cpp:367
bool isEmpty(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:2911
static Qgis::GeometryOperationResult addPart(QgsGeometry &geometry, GEOSGeometry *newPart)
Adds a new island polygon to a multipolygon feature.
Definition qgsgeos.cpp:294
bool overlaps(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Checks if geom overlaps this.
Definition qgsgeos.cpp:954
QgsPoint * centroid(QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculates the centroid of this.
Definition qgsgeos.cpp:2507
std::unique_ptr< QgsAbstractGeometry > mergeLines(QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
Definition qgsgeos.cpp:3704
QgsAbstractGeometry * difference(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const override
Calculate the difference of this and geom.
Definition qgsgeos.cpp:362
void geometryChanged() override
Should be called whenever the geometry associated with the engine has been modified and the engine mu...
Definition qgsgeos.cpp:309
double area(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:1068
double length(QString *errorMsg=nullptr) const override
Definition qgsgeos.cpp:1085
double hausdorffDistance(const QgsAbstractGeometry *geometry, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Hausdorff distance between this geometry and another geometry.
Definition qgsgeos.cpp:809
double frechetDistance(const QgsAbstractGeometry *geometry, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const
Returns the Fréchet distance between this geometry and another geometry, restricted to discrete point...
Definition qgsgeos.cpp:857
QgsAbstractGeometry * interpolate(double distance, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Interpolates a point by distance along the geometry.
Definition qgsgeos.cpp:2491
static QgsPoint coordSeqPoint(const GEOSCoordSequence *cs, int i, bool hasZ, bool hasM)
Definition qgsgeos.cpp:2072
static QgsGeometry polygonize(const QVector< const QgsAbstractGeometry * > &geometries, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr)
Creates a GeometryCollection geometry containing possible polygons formed from the constituent linewo...
Definition qgsgeos.cpp:3898
static QgsGeometry geometryFromGeos(GEOSGeometry *geos)
Creates a new QgsGeometry object, feeding in a geometry in GEOS format.
Definition qgsgeos.cpp:213
QgsGeometryEngine::EngineOperationResult splitGeometry(const QgsAbstractGeometry &splitGeom, QVector< QgsGeometry > &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, QString *errorMsg=nullptr) const override
Splits this geometry according to a given geometry.
Definition qgsgeos.cpp:1102
Line string geometry type, with support for z-dimension and m-values.
double closestSegment(const QgsPoint &pt, QgsPoint &segmentPt, QgsVertexId &vertexAfter, int *leftOf=nullptr, double epsilon=4 *std::numeric_limits< double >::epsilon()) const override
Searches for the closest segment of the geometry to a given point.
void addVertex(const QgsPoint &pt)
Adds a new vertex to the end of the line string.
QgsLineString * clone() const override
Clones the geometry by performing a deep copy.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Custom exception class which is raised when an operation is not supported.
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
QgsPoint * clone() const override
Clones the geometry by performing a deep copy.
Definition qgspoint.cpp:138
double z
Definition qgspoint.h:58
double x
Definition qgspoint.h:56
bool isEmpty() const override
Returns true if the geometry is empty.
Definition qgspoint.cpp:775
double distance(double x, double y) const
Returns the Cartesian 2D distance between this point and a specified x, y coordinate.
Definition qgspoint.h:466
double m
Definition qgspoint.h:59
double y
Definition qgspoint.h:57
Polyhedral surface geometry type.
int numPatches() const
Returns the number of patches contained with the polyhedral surface.
const QgsPolygon * patchN(int i) const
Retrieves a patch from the polyhedral surface.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
void setYMinimum(double y)
Set the minimum y value.
void setXMinimum(double x)
Set the minimum x value.
void setYMaximum(double y)
Set the maximum y value.
void setXMaximum(double x)
Set the maximum x value.
double yMaximum
Scoped object for setting the current thread GEOS context feedback object.
Definition qgsgeos.h:101
QgsScopedGeosContextRegisterFeedback(QgsFeedback *feedback)
Registers a feedback object for GEOS interruption checking.
Definition qgsgeos.cpp:4558
~QgsScopedGeosContextRegisterFeedback()
Resets the GEOS interruption checker for the current thread.
Definition qgsgeos.cpp:4571
static QgsSettingsTreeNode * sTreeGeos
Abstract base class for simple curved geometry type.
double yAt(int index) const override
Returns the y-coordinate of the specified node in the line string.
QVector< double > yVector() const
Returns the y vertex values as a vector.
int numPoints() const override
Returns the number of points in the curve.
const double * mData() const
Returns a const pointer to the m vertex data, or nullptr if the simple curve does not have m values.
QVector< double > zVector() const
Returns the z vertex values as a vector.
QVector< double > xVector() const
Returns the x vertex values as a vector.
double xAt(int index) const override
Returns the x-coordinate of the specified node in the line string.
const double * yData() const
Returns a const pointer to the y vertex data.
QgsPoint pointN(int i) const
Returns the specified point from inside the simple curve.
const double * xData() const
Returns a const pointer to the x vertex data.
QVector< double > mVector() const
Returns the m vertex values as a vector.
const double * zData() const
Returns a const pointer to the z vertex data, or nullptr if the simple curve does not have z values.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
static Q_INVOKABLE bool isMultiType(Qgis::WkbType type)
Returns true if the WKB type is a multi type.
Contains geos related utilities and functions.
Definition qgsgeos.h:129
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition qgsgeos.h:165
std::unique_ptr< GEOSCoordSequence, GeosDeleter > coord_sequence_unique_ptr
Scoped GEOS coordinate sequence pointer.
Definition qgsgeos.h:180
std::unique_ptr< GEOSBufferParams, GeosDeleter > buffer_params_unique_ptr
Scoped GEOS buffer params pointer.
Definition qgsgeos.h:175
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 qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
T qgsgeometry_cast(QgsAbstractGeometry *geom)
QVector< QgsPoint > QgsPointSequence
#define CATCH_GEOS(r)
Definition qgsgeos.cpp:46
#define DEFAULT_QUADRANT_SEGMENTS
Definition qgsgeos.cpp:44
#define CATCH_GEOS_WITH_ERRMSG(r)
Definition qgsgeos.cpp:52
#define QgsDebugError(str)
Definition qgslogger.h:71
QLineF segment(int index, QRectF rect, double radius)
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:35
int vertex
Vertex number.
void CORE_EXPORT operator()(GEOSGeometry *geom) const
Destroys the GEOS geometry geom, using the static QGIS geos context.
struct GEOSGeom_t GEOSGeometry
Definition util.h:41