QGIS API Documentation 4.5.0-Master (c3bae02b63e)
Loading...
Searching...
No Matches
qgsgeometry.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgeometry.cpp - Geometry (stored as Open Geospatial Consortium WKB)
3 -------------------------------------------------------------------
4Date : 02 May 2005
5Copyright : (C) 2005 by Brendan Morley
6email : morb at ozemail dot com dot au
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 "qgsconfig.h"
17#include "qgsgeometry.h"
18
19#include <cmath>
20#include <cstdarg>
21#include <cstdio>
22#include <geos_c.h>
23#include <limits>
24#include <nlohmann/json.hpp>
25
26#include "qgis.h"
27#include "qgsabstractgeometry.h"
28#include "qgscircle.h"
29#include "qgscurve.h"
30#include "qgscurvepolygon.h"
32#include "qgsgeometryfactory.h"
33#include "qgsgeometryutils.h"
35#include "qgsgeos.h"
37#include "qgslinestring.h"
38#include "qgsmaptopixel.h"
39#include "qgsmulticurve.h"
40#include "qgsmultilinestring.h"
41#include "qgsmultipoint.h"
42#include "qgsmultipolygon.h"
43#include "qgsmultisurface.h"
44#include "qgsnurbsutils.h"
45#include "qgspoint.h"
46#include "qgspointxy.h"
47#include "qgspolygon.h"
49#include "qgsrectangle.h"
50#include "qgstriangle.h"
52#include "qgsvectorlayer.h"
53
54#include <QString>
55
56#ifdef HAVE_SFCGAL
57#include "qgssfcgalgeometry.h"
58#endif
59
60#include <QCache>
61#include <QString>
62
63#include "moc_qgsgeometry.cpp"
64
65using namespace Qt::StringLiterals;
66
68{
70 : ref( 1 )
71 {}
72 QgsGeometryPrivate( std::unique_ptr< QgsAbstractGeometry > geometry )
73 : ref( 1 )
74 , geometry( std::move( geometry ) )
75 {}
76 QAtomicInt ref;
77 std::unique_ptr< QgsAbstractGeometry > geometry;
78};
79
83
85{
86 if ( !d->ref.deref() )
87 delete d;
88}
89
91 : d( new QgsGeometryPrivate() )
92{
93 d->geometry.reset( geom );
94}
95
96QgsGeometry::QgsGeometry( std::unique_ptr<QgsAbstractGeometry> geom )
97 : d( new QgsGeometryPrivate( std::move( geom ) ) )
98{}
99
101 : d( other.d )
102{
103 mLastError = other.mLastError;
104 d->ref.ref();
105}
106
108{
109 if ( this != &other )
110 {
111 if ( !d->ref.deref() )
112 {
113 delete d;
114 }
115
116 mLastError = other.mLastError;
117 d = other.d;
118 d->ref.ref();
119 }
120 return *this;
121}
122
123void QgsGeometry::detach()
124{
125 if ( d->ref <= 1 )
126 return;
127
128 std::unique_ptr< QgsAbstractGeometry > cGeom;
129 if ( d->geometry )
130 cGeom.reset( d->geometry->clone() );
131
132 reset( std::move( cGeom ) );
133}
134
135void QgsGeometry::reset( std::unique_ptr<QgsAbstractGeometry> newGeometry )
136{
137 if ( d->ref > 1 )
138 {
139 ( void ) d->ref.deref();
140 d = new QgsGeometryPrivate();
141 }
142 d->geometry = std::move( newGeometry );
143}
144
146{
147 return d->geometry.get();
148}
149
151{
152 detach();
153 return d->geometry.get();
154}
155
157{
158 if ( d->geometry.get() == geometry )
159 {
160 return;
161 }
162
163 reset( std::unique_ptr< QgsAbstractGeometry >( geometry ) );
164}
165
167{
168 return !d->geometry;
169}
170
171typedef QCache< QString, QgsGeometry > WktCache;
172Q_GLOBAL_STATIC_WITH_ARGS( WktCache, sWktCache, ( 2000 ) ) // store up to 2000 geometries
173Q_GLOBAL_STATIC( QMutex, sWktMutex )
174
175QgsGeometry QgsGeometry::fromWkt( const QString &wkt )
176{
177 QMutexLocker lock( sWktMutex() );
178 if ( const QgsGeometry *cached = sWktCache()->object( wkt ) )
179 return *cached;
180 const QgsGeometry result( QgsGeometryFactory::geomFromWkt( wkt ) );
181 sWktCache()->insert( wkt, new QgsGeometry( result ), 1 );
182 return result;
183}
184
186{
187 std::unique_ptr< QgsAbstractGeometry > geom( QgsGeometryFactory::fromPointXY( point ) );
188 if ( geom )
189 {
190 return QgsGeometry( geom.release() );
191 }
192 return QgsGeometry();
193}
194
196{
197 return QgsGeometry( point.clone() );
198}
199
201{
202 std::unique_ptr< QgsAbstractGeometry > geom = QgsGeometryFactory::fromPolylineXY( polyline );
203 if ( geom )
204 {
205 return QgsGeometry( std::move( geom ) );
206 }
207 return QgsGeometry();
208}
209
211{
212 return QgsGeometry( std::make_unique< QgsLineString >( polyline ) );
213}
214
216{
217 std::unique_ptr< QgsPolygon > geom = QgsGeometryFactory::fromPolygonXY( polygon );
218 if ( geom )
219 {
220 return QgsGeometry( std::move( geom ) );
221 }
222 return QgsGeometry();
223}
224
226{
227 std::unique_ptr< QgsMultiPoint > geom = QgsGeometryFactory::fromMultiPointXY( multipoint );
228 if ( geom )
229 {
230 return QgsGeometry( std::move( geom ) );
231 }
232 return QgsGeometry();
233}
234
236{
237 std::unique_ptr< QgsMultiLineString > geom = QgsGeometryFactory::fromMultiPolylineXY( multiline );
238 if ( geom )
239 {
240 return QgsGeometry( std::move( geom ) );
241 }
242 return QgsGeometry();
243}
244
246{
247 std::unique_ptr< QgsMultiPolygon > geom = QgsGeometryFactory::fromMultiPolygonXY( multipoly );
248 if ( geom )
249 {
250 return QgsGeometry( std::move( geom ) );
251 }
252 return QgsGeometry();
253}
254
256{
257 if ( rect.isNull() )
258 return QgsGeometry();
259
260 auto ext = std::make_unique< QgsLineString >(
261 QVector< double >() << rect.xMinimum() << rect.xMaximum() << rect.xMaximum() << rect.xMinimum() << rect.xMinimum(),
262 QVector< double >() << rect.yMinimum() << rect.yMinimum() << rect.yMaximum() << rect.yMaximum() << rect.yMinimum()
263 );
264 auto polygon = std::make_unique< QgsPolygon >();
265 polygon->setExteriorRing( ext.release() );
266 return QgsGeometry( std::move( polygon ) );
267}
268
270{
271 if ( box.is2d() )
272 {
273 return fromRect( box.toRectangle() );
274 }
275
276 auto polyhedralSurface = std::make_unique< QgsPolyhedralSurface >();
277
278 auto ext1 = std::make_unique< QgsLineString >(
279 QVector< double >() << box.xMinimum() << box.xMinimum() << box.xMaximum() << box.xMaximum() << box.xMinimum(),
280 QVector< double >() << box.yMinimum() << box.yMaximum() << box.yMaximum() << box.yMinimum() << box.yMinimum(),
281 QVector< double >() << box.zMinimum() << box.zMinimum() << box.zMinimum() << box.zMinimum() << box.zMinimum()
282 );
283 auto polygon1 = std::make_unique< QgsPolygon >( ext1.release() );
284 polyhedralSurface->addPatch( polygon1.release() );
285
286 auto ext2 = std::make_unique< QgsLineString >(
287 QVector< double >() << box.xMinimum() << box.xMinimum() << box.xMinimum() << box.xMinimum() << box.xMinimum(),
288 QVector< double >() << box.yMinimum() << box.yMaximum() << box.yMaximum() << box.yMinimum() << box.yMinimum(),
289 QVector< double >() << box.zMinimum() << box.zMinimum() << box.zMaximum() << box.zMaximum() << box.zMinimum()
290 );
291 auto polygon2 = std::make_unique< QgsPolygon >( ext2.release() );
292 polyhedralSurface->addPatch( polygon2.release() );
293
294 auto ext3 = std::make_unique< QgsLineString >(
295 QVector< double >() << box.xMinimum() << box.xMaximum() << box.xMaximum() << box.xMinimum() << box.xMinimum(),
296 QVector< double >() << box.yMinimum() << box.yMinimum() << box.yMinimum() << box.yMinimum() << box.yMinimum(),
297 QVector< double >() << box.zMinimum() << box.zMinimum() << box.zMaximum() << box.zMaximum() << box.zMinimum()
298 );
299 auto polygon3 = std::make_unique< QgsPolygon >( ext3.release() );
300 polyhedralSurface->addPatch( polygon3.release() );
301
302 auto ext4 = std::make_unique< QgsLineString >(
303 QVector< double >() << box.xMaximum() << box.xMaximum() << box.xMinimum() << box.xMinimum() << box.xMaximum(),
304 QVector< double >() << box.yMaximum() << box.yMinimum() << box.yMinimum() << box.yMaximum() << box.yMaximum(),
305 QVector< double >() << box.zMaximum() << box.zMaximum() << box.zMaximum() << box.zMaximum() << box.zMaximum()
306 );
307 auto polygon4 = std::make_unique< QgsPolygon >( ext4.release() );
308 polyhedralSurface->addPatch( polygon4.release() );
309
310 auto ext5 = std::make_unique< QgsLineString >(
311 QVector< double >() << box.xMaximum() << box.xMaximum() << box.xMaximum() << box.xMaximum() << box.xMaximum(),
312 QVector< double >() << box.yMaximum() << box.yMinimum() << box.yMinimum() << box.yMaximum() << box.yMaximum(),
313 QVector< double >() << box.zMaximum() << box.zMaximum() << box.zMinimum() << box.zMinimum() << box.zMaximum()
314 );
315 auto polygon5 = std::make_unique< QgsPolygon >( ext5.release() );
316 polyhedralSurface->addPatch( polygon5.release() );
317
318 auto ext6 = std::make_unique< QgsLineString >(
319 QVector< double >() << box.xMaximum() << box.xMaximum() << box.xMinimum() << box.xMinimum() << box.xMaximum(),
320 QVector< double >() << box.yMaximum() << box.yMaximum() << box.yMaximum() << box.yMaximum() << box.yMaximum(),
321 QVector< double >() << box.zMaximum() << box.zMinimum() << box.zMinimum() << box.zMaximum() << box.zMaximum()
322 );
323 auto polygon6 = std::make_unique< QgsPolygon >( ext6.release() );
324 polyhedralSurface->addPatch( polygon6.release() );
325
326 return QgsGeometry( std::move( polyhedralSurface ) );
327}
328
329QgsGeometry QgsGeometry::collectGeometry( const QVector< QgsGeometry > &geometries )
330{
331 QgsGeometry collected;
332
333 for ( const QgsGeometry &g : geometries )
334 {
335 if ( collected.isNull() )
336 {
337 collected = g;
338 collected.convertToMultiType();
339 }
340 else
341 {
342 if ( g.isMultipart() )
343 {
344 for ( auto p = g.const_parts_begin(); p != g.const_parts_end(); ++p )
345 {
346 collected.addPartV2( ( *p )->clone() );
347 }
348 }
349 else
350 {
351 collected.addPart( g );
352 }
353 }
354 }
355 return collected;
356}
357
358QgsGeometry QgsGeometry::collectTinPatches( const QVector<QgsGeometry> &geometries )
359{
360 auto resultTin = std::make_unique<QgsTriangulatedSurface>();
361 bool first = true;
362
363 for ( const QgsGeometry &geom : geometries )
364 {
365 if ( geom.isNull() )
366 continue;
367
368 const QgsAbstractGeometry *abstractGeom = geom.constGet();
369
371 {
372 // Preserve Z/M from first valid geometry
373 if ( first )
374 {
375 if ( tin->is3D() )
376 resultTin->addZValue( 0 );
377 if ( tin->isMeasure() )
378 resultTin->addMValue( 0 );
379 first = false;
380 }
381
382 // Copy all patches (triangles) from the TIN
383 for ( int j = 0; j < tin->numPatches(); ++j )
384 {
385 if ( const QgsPolygon *patch = tin->patchN( j ) )
386 {
387 resultTin->addPatch( patch->clone() );
388 }
389 }
390 }
391 else if ( const QgsTriangle *triangle = qgsgeometry_cast<const QgsTriangle *>( abstractGeom ) )
392 {
393 // Preserve Z/M from first valid geometry
394 if ( first )
395 {
396 if ( triangle->is3D() )
397 resultTin->addZValue( 0 );
398 if ( triangle->isMeasure() )
399 resultTin->addMValue( 0 );
400 first = false;
401 }
402
403 resultTin->addPatch( triangle->clone() );
404 }
405 }
406
407 if ( resultTin->numPatches() == 0 )
408 return QgsGeometry();
409
410 return QgsGeometry( std::move( resultTin ) );
411}
412
413QgsGeometry QgsGeometry::createWedgeBuffer( const QgsPoint &center, const double azimuth, const double angularWidth, const double outerRadius, const double innerRadius )
414{
415 const double startAngle = azimuth - angularWidth * 0.5;
416 const double endAngle = azimuth + angularWidth * 0.5;
417
418 return createWedgeBufferFromAngles( center, startAngle, endAngle, outerRadius, innerRadius );
419}
420
421QgsGeometry QgsGeometry::createWedgeBufferFromAngles( const QgsPoint &center, double startAngle, double endAngle, double outerRadius, double innerRadius )
422{
423 auto wedge = std::make_unique< QgsCompoundCurve >();
424
425 const double DEG_TO_RAD = M_PI / 180.0;
426 const double RAD_TO_DEG = 180.0 / M_PI;
427
428 const double angularWidth = endAngle - startAngle;
429 const bool useShortestArc = QgsGeometryUtilsBase::normalizedAngle( angularWidth * DEG_TO_RAD ) * RAD_TO_DEG <= 180.0;
430
431 if ( std::abs( angularWidth ) >= 360.0 )
432 {
433 auto outerCc = std::make_unique< QgsCompoundCurve >();
434
435 QgsCircle outerCircle = QgsCircle( center, outerRadius );
436 outerCc->addCurve( outerCircle.toCircularString().release() );
437
438 auto cp = std::make_unique< QgsCurvePolygon >();
439 cp->setExteriorRing( outerCc.release() );
440
441 if ( !qgsDoubleNear( innerRadius, 0.0 ) && innerRadius > 0 )
442 {
443 auto innerCc = std::make_unique< QgsCompoundCurve >();
444
445 QgsCircle innerCircle = QgsCircle( center, innerRadius );
446 innerCc->addCurve( innerCircle.toCircularString().release() );
447
448 cp->setInteriorRings( { innerCc.release() } );
449 }
450
451 return QgsGeometry( std::move( cp ) );
452 }
453
454 const QgsPoint outerP1 = center.project( outerRadius, startAngle );
455 const QgsPoint outerP2 = center.project( outerRadius, endAngle );
456
457 wedge->addCurve( new QgsCircularString( QgsCircularString::fromTwoPointsAndCenter( outerP1, outerP2, center, useShortestArc ) ) );
458
459 if ( !qgsDoubleNear( innerRadius, 0.0 ) && innerRadius > 0 )
460 {
461 const QgsPoint innerP1 = center.project( innerRadius, startAngle );
462 const QgsPoint innerP2 = center.project( innerRadius, endAngle );
463 wedge->addCurve( new QgsLineString( outerP2, innerP2 ) );
464 wedge->addCurve( new QgsCircularString( QgsCircularString::fromTwoPointsAndCenter( innerP2, innerP1, center, useShortestArc ) ) );
465 wedge->addCurve( new QgsLineString( innerP1, outerP1 ) );
466 }
467 else
468 {
469 wedge->addCurve( new QgsLineString( outerP2, center ) );
470 wedge->addCurve( new QgsLineString( center, outerP1 ) );
471 }
472
473 auto cp = std::make_unique< QgsCurvePolygon >();
474 cp->setExteriorRing( wedge.release() );
475 return QgsGeometry( std::move( cp ) );
476}
477
478void QgsGeometry::fromWkb( unsigned char *wkb, int length )
479{
480 QgsConstWkbPtr ptr( wkb, length );
481 reset( QgsGeometryFactory::geomFromWkb( ptr ) );
482 delete[] wkb;
483}
484
485void QgsGeometry::fromWkb( const QByteArray &wkb )
486{
487 QgsConstWkbPtr ptr( wkb );
488 reset( QgsGeometryFactory::geomFromWkb( ptr ) );
489}
490
492{
493 if ( !d->geometry )
494 {
496 }
497 else
498 {
499 return d->geometry->wkbType();
500 }
501}
502
504{
505 if ( !d->geometry )
506 {
508 }
509 return QgsWkbTypes::geometryType( d->geometry->wkbType() );
510}
511
513{
514 if ( !d->geometry )
515 {
516 return true;
517 }
518
519 return d->geometry->isEmpty();
520}
521
523{
524 if ( !d->geometry )
525 {
526 return false;
527 }
528 return QgsWkbTypes::isMultiType( d->geometry->wkbType() );
529}
530QgsPointXY QgsGeometry::closestVertex( const QgsPointXY &point, int &closestVertexIndex, int &previousVertexIndex, int &nextVertexIndex, double &sqrDist ) const
531{
532 if ( !d->geometry )
533 {
534 sqrDist = -1;
535 return QgsPointXY();
536 }
537
538 QgsPoint pt( point );
539 QgsVertexId id;
540
541 QgsPoint vp = QgsGeometryUtils::closestVertex( *( d->geometry ), pt, id );
542 if ( !id.isValid() )
543 {
544 sqrDist = -1;
545 return QgsPointXY();
546 }
547 sqrDist = QgsGeometryUtils::sqrDistance2D( pt, vp );
548
549 QgsVertexId prevVertex;
550 QgsVertexId nextVertex;
551 d->geometry->adjacentVertices( id, prevVertex, nextVertex );
552 closestVertexIndex = vertexNrFromVertexId( id );
553 previousVertexIndex = vertexNrFromVertexId( prevVertex );
554 nextVertexIndex = vertexNrFromVertexId( nextVertex );
555 return QgsPointXY( vp.x(), vp.y() );
556}
557
558double QgsGeometry::distanceToVertex( int vertex ) const
559{
560 if ( !d->geometry )
561 {
562 return -1;
563 }
564
565 QgsVertexId id;
566 if ( !vertexIdFromVertexNr( vertex, id ) )
567 {
568 return -1;
569 }
570
571 return QgsGeometryUtils::distanceToVertex( *( d->geometry ), id );
572}
573
574double QgsGeometry::angleAtVertex( int vertex ) const
575{
576 if ( !d->geometry )
577 {
578 return 0;
579 }
580
581 QgsVertexId v2;
582 if ( !vertexIdFromVertexNr( vertex, v2 ) )
583 {
584 return 0;
585 }
586
587 return d->geometry->vertexAngle( v2 );
588}
589
590void QgsGeometry::adjacentVertices( int atVertex, int &beforeVertex, int &afterVertex ) const
591{
592 if ( !d->geometry )
593 {
594 return;
595 }
596
597 QgsVertexId id;
598 if ( !vertexIdFromVertexNr( atVertex, id ) )
599 {
600 beforeVertex = -1;
601 afterVertex = -1;
602 return;
603 }
604
605 QgsVertexId beforeVertexId, afterVertexId;
606 d->geometry->adjacentVertices( id, beforeVertexId, afterVertexId );
607 beforeVertex = vertexNrFromVertexId( beforeVertexId );
608 afterVertex = vertexNrFromVertexId( afterVertexId );
609}
610
611bool QgsGeometry::moveVertex( double x, double y, int atVertex )
612{
613 if ( !d->geometry )
614 {
615 return false;
616 }
617
618 QgsVertexId id;
619 if ( !vertexIdFromVertexNr( atVertex, id ) )
620 {
621 return false;
622 }
623
624 detach();
625
626 return d->geometry->moveVertex( id, QgsPoint( x, y ) );
627}
628
629bool QgsGeometry::moveVertex( const QgsPoint &p, int atVertex )
630{
631 if ( !d->geometry )
632 {
633 return false;
634 }
635
636 QgsVertexId id;
637 if ( !vertexIdFromVertexNr( atVertex, id ) )
638 {
639 return false;
640 }
641
642 detach();
643
644 return d->geometry->moveVertex( id, p );
645}
646
647bool QgsGeometry::deleteVertex( int atVertex )
648{
649 if ( !d->geometry )
650 {
651 return false;
652 }
653
654 //maintain compatibility with < 2.10 API
655 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::MultiPoint )
656 {
657 detach();
658 //delete geometry instead of point
659 return static_cast< QgsGeometryCollection * >( d->geometry.get() )->removeGeometry( atVertex );
660 }
661
662 //if it is a point, set the geometry to nullptr
663 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::Point )
664 {
665 reset( nullptr );
666 return true;
667 }
668
669 QgsVertexId id;
670 if ( !vertexIdFromVertexNr( atVertex, id ) )
671 {
672 return false;
673 }
674
675 detach();
676
677 return d->geometry->deleteVertex( id );
678}
679
680bool QgsGeometry::deleteVertices( const QSet<int> &atVertices )
681{
682 if ( !d->geometry )
683 {
684 return false;
685 }
686
687 // if it is a point, set the geometry to nullptr
688 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::Point )
689 {
690 if ( atVertices.size() != 1 && !atVertices.contains( 0 ) )
691 return false;
692
693 reset( nullptr );
694 return true;
695 }
696
697 QSet<QgsVertexId> vertexIds;
698 for ( int vertex : atVertices )
699 {
700 QgsVertexId id;
701 if ( !vertexIdFromVertexNr( vertex, id ) )
702 return false;
703
704 vertexIds.insert( id );
705 }
706
707 // create a copy of the original geometry to restore it in case of failure
708 std::unique_ptr< QgsAbstractGeometry > originalGeometry( d->geometry->clone() );
709
710 detach();
711
712 if ( !d->geometry->deleteVertices( vertexIds ) )
713 {
714 reset( std::move( originalGeometry ) );
715 return false;
716 }
717
718 return true;
719}
720
722{
723 if ( !d->geometry )
724 return false;
725
726 QgsVertexId id;
727 if ( !vertexIdFromVertexNr( atVertex, id ) )
728 return false;
729
730 detach();
731
732 QgsAbstractGeometry *geom = d->geometry.get();
733
734 // If the geom is a collection, we get the concerned part, otherwise, the part is just the whole geom
735 QgsAbstractGeometry *part = nullptr;
737 if ( owningCollection )
738 part = owningCollection->geometryN( id.part );
739 else
740 part = geom;
741
742 // If the part is a polygon, we get the concerned ring, otherwise, the ring is just the whole part
743 QgsAbstractGeometry *ring = nullptr;
745 if ( owningPolygon )
746 ring = ( id.ring == 0 ) ? owningPolygon->exteriorRing() : owningPolygon->interiorRing( id.ring - 1 );
747 else
748 ring = part;
749
750 // If the ring is not a curve, we're probably on a point geometry
751 QgsCurve *curve = qgsgeometry_cast<QgsCurve *>( ring );
752 if ( !curve )
753 return false;
754
755 bool success = false;
757 if ( cpdCurve )
758 {
759 // If the geom is a already compound curve, we convert inplace, and we're done
760 success = cpdCurve->toggleCircularAtVertex( id );
761 }
762 else
763 {
764 // TODO : move this block before the above, so we call toggleCircularAtVertex only in one place
765 // If the geom is a linestring or cirularstring, we create a compound curve
766 auto cpdCurve = std::make_unique<QgsCompoundCurve>();
767 cpdCurve->addCurve( curve->clone() );
768 success = cpdCurve->toggleCircularAtVertex( QgsVertexId( -1, -1, id.vertex ) );
769
770 // In that case, we must also reassign the instances
771 if ( success )
772 {
773 if ( !owningPolygon && !owningCollection )
774 {
775 // Standalone linestring
776 reset( std::make_unique<QgsCompoundCurve>( *cpdCurve ) ); // <- REVIEW PLZ
777 }
778 else if ( owningPolygon )
779 {
780 // Replace the ring in the owning polygon
781 if ( id.ring == 0 )
782 {
783 owningPolygon->setExteriorRing( cpdCurve.release() );
784 }
785 else
786 {
787 owningPolygon->removeInteriorRing( id.ring - 1 );
788 owningPolygon->addInteriorRing( cpdCurve.release() );
789 }
790 }
791 else if ( owningCollection )
792 {
793 // Replace the curve in the owning collection
794 owningCollection->removeGeometry( id.part );
795 owningCollection->insertGeometry( cpdCurve.release(), id.part );
796 }
797 }
798 }
799
800 return success;
801}
802
803bool QgsGeometry::insertVertex( double x, double y, int beforeVertex )
804{
805 if ( !d->geometry )
806 {
807 return false;
808 }
809
810 //maintain compatibility with < 2.10 API
811 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::MultiPoint )
812 {
813 detach();
814 //insert geometry instead of point
815 return static_cast< QgsGeometryCollection * >( d->geometry.get() )->insertGeometry( new QgsPoint( x, y ), beforeVertex );
816 }
817
818 QgsVertexId id;
819 if ( !vertexIdFromVertexNr( beforeVertex, id ) )
820 {
821 return false;
822 }
823
824 detach();
825
826 return d->geometry->insertVertex( id, QgsPoint( x, y ) );
827}
828
829bool QgsGeometry::insertVertex( const QgsPoint &point, int beforeVertex )
830{
831 if ( !d->geometry )
832 {
833 return false;
834 }
835
836 //maintain compatibility with < 2.10 API
837 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::MultiPoint )
838 {
839 detach();
840 //insert geometry instead of point
841 return static_cast< QgsGeometryCollection * >( d->geometry.get() )->insertGeometry( new QgsPoint( point ), beforeVertex );
842 }
843
844 QgsVertexId id;
845 if ( !vertexIdFromVertexNr( beforeVertex, id ) )
846 {
847 return false;
848 }
849
850 detach();
851
852 return d->geometry->insertVertex( id, point );
853}
854
855bool QgsGeometry::addTopologicalPoint( const QgsPoint &point, double snappingTolerance, double segmentSearchEpsilon )
856{
857 if ( !d->geometry )
858 {
859 return false;
860 }
861
862 const double sqrSnappingTolerance = snappingTolerance * snappingTolerance;
863 int segmentAfterVertex;
864 QgsPointXY snappedPoint;
865 const double sqrDistSegmentSnap = closestSegmentWithContext( point, snappedPoint, segmentAfterVertex, nullptr, segmentSearchEpsilon );
866
867 if ( sqrDistSegmentSnap > sqrSnappingTolerance )
868 return false;
869
870 int atVertex, beforeVertex, afterVertex;
871 double sqrDistVertexSnap;
872 closestVertex( point, atVertex, beforeVertex, afterVertex, sqrDistVertexSnap );
873
874 if ( sqrDistVertexSnap < sqrSnappingTolerance )
875 return false; // the vertex already exists - do not insert it
876
877 // Let's ignore the Z and M values of the supplied topological point and calculate
878 // interpolated values instead, using the previous and next geometry vertices.
879 // This should make sure that the geometry's Z and M values are preserved when adding
880 // topological points and splitting
881 QgsPoint interpolatedPoint( point );
882 if ( d->geometry.get()->is3D() || d->geometry.get()->isMeasure() )
883 {
884 const QgsPoint vertexBefore = vertexAt( segmentAfterVertex - 1 );
885 const QgsPoint vertexAfter = vertexAt( segmentAfterVertex );
886 interpolatedPoint = QgsGeometryUtils::interpolatePointOnSegment( point.x(), point.y(), vertexBefore, vertexAfter );
887 }
888
889 if ( !insertVertex( interpolatedPoint, segmentAfterVertex ) )
890 {
891 QgsDebugError( u"failed to insert topo point"_s );
892 return false;
893 }
894
895 return true;
896}
897
898QgsPoint QgsGeometry::vertexAt( int atVertex ) const
899{
900 if ( !d->geometry )
901 {
902 return QgsPoint();
903 }
904
905 QgsVertexId vId;
906 ( void ) vertexIdFromVertexNr( atVertex, vId );
907 if ( vId.vertex < 0 )
908 {
909 return QgsPoint();
910 }
911 return d->geometry->vertexAt( vId );
912}
913
914double QgsGeometry::sqrDistToVertexAt( QgsPointXY &point, int atVertex ) const
915{
916 QgsPointXY vertexPoint = vertexAt( atVertex );
917 return QgsGeometryUtils::sqrDistance2D( QgsPoint( vertexPoint ), QgsPoint( point ) );
918}
919
921{
922 // avoid calling geos for trivial point calculations
923 if ( d->geometry && QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::Point )
924 {
925 return QgsGeometry( qgsgeometry_cast< const QgsPoint * >( d->geometry.get() )->clone() );
926 }
927
928 QgsGeos geos( d->geometry.get() );
929 mLastError.clear();
930 QgsGeometry result = QgsGeometry( geos.closestPoint( other ) );
931 result.mLastError = mLastError;
932 return result;
933}
934
936{
937 // avoid calling geos for trivial point-to-point line calculations
938 if ( d->geometry && QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::Point && QgsWkbTypes::flatType( other.wkbType() ) == Qgis::WkbType::Point )
939 {
940 return QgsGeometry( std::make_unique< QgsLineString >( *qgsgeometry_cast< const QgsPoint * >( d->geometry.get() ), *qgsgeometry_cast< const QgsPoint * >( other.constGet() ) ) );
941 }
942
943 QgsGeos geos( d->geometry.get() );
944 mLastError.clear();
945 QgsGeometry result = QgsGeometry( geos.shortestLine( other, &mLastError ) );
946 result.mLastError = mLastError;
947 return result;
948}
949
950double QgsGeometry::closestVertexWithContext( const QgsPointXY &point, int &atVertex ) const
951{
952 if ( !d->geometry )
953 {
954 return -1;
955 }
956
957 QgsVertexId vId;
958 QgsPoint pt( point );
959 QgsPoint closestPoint = QgsGeometryUtils::closestVertex( *( d->geometry ), pt, vId );
960 if ( !vId.isValid() )
961 return -1;
962 atVertex = vertexNrFromVertexId( vId );
963 return QgsGeometryUtils::sqrDistance2D( closestPoint, pt );
964}
965
966double QgsGeometry::closestSegmentWithContext( const QgsPointXY &point, QgsPointXY &minDistPoint, int &nextVertexIndex, int *leftOrRightOfSegment, double epsilon ) const
967{
968 if ( !d->geometry )
969 {
970 return -1;
971 }
972
973 QgsPoint segmentPt;
974 QgsVertexId vertexAfter;
975
976 double sqrDist = d->geometry->closestSegment( QgsPoint( point ), segmentPt, vertexAfter, leftOrRightOfSegment, epsilon );
977 if ( sqrDist < 0 )
978 return -1;
979
980 minDistPoint.setX( segmentPt.x() );
981 minDistPoint.setY( segmentPt.y() );
982 nextVertexIndex = vertexNrFromVertexId( vertexAfter );
983 return sqrDist;
984}
985
986Qgis::GeometryOperationResult QgsGeometry::addRing( const QVector<QgsPointXY> &ring )
987{
988 auto ringLine = std::make_unique< QgsLineString >( ring );
989 return addRing( ringLine.release() );
990}
991
993{
994 std::unique_ptr< QgsCurve > r( ring );
995 if ( !d->geometry )
996 {
998 }
999
1000 detach();
1001
1002 return QgsGeometryEditUtils::addRing( d->geometry.get(), std::move( r ) );
1003}
1004
1005Qgis::GeometryOperationResult QgsGeometry::addPart( const QVector<QgsPointXY> &points, Qgis::GeometryType geomType )
1006{
1008 convertPointList( points, l );
1010 return addPart( l, geomType );
1012}
1013
1015{
1017 convertPointList( points, l );
1018 return addPartV2( l, wkbType );
1019}
1020
1022{
1023 std::unique_ptr< QgsAbstractGeometry > partGeom;
1024 if ( points.size() == 1 )
1025 {
1026 partGeom = std::make_unique< QgsPoint >( points[0] );
1027 }
1028 else if ( points.size() > 1 )
1029 {
1030 auto ringLine = std::make_unique< QgsLineString >();
1031 ringLine->setPoints( points );
1032 partGeom = std::move( ringLine );
1033 }
1035 return addPart( partGeom.release(), geomType );
1037}
1038
1040{
1041 std::unique_ptr< QgsAbstractGeometry > partGeom;
1042 if ( points.size() == 1 )
1043 {
1044 partGeom = std::make_unique< QgsPoint >( points[0] );
1045 }
1046 else if ( points.size() > 1 )
1047 {
1048 auto ringLine = std::make_unique< QgsLineString >();
1049 ringLine->setPoints( points );
1050 partGeom = std::move( ringLine );
1051 }
1052 return addPartV2( partGeom.release(), wkbType );
1053}
1054
1056{
1057 std::unique_ptr< QgsAbstractGeometry > p( part );
1058 if ( !d->geometry )
1059 {
1060 switch ( geomType )
1061 {
1063 reset( std::make_unique< QgsMultiPoint >() );
1064 break;
1066 reset( std::make_unique< QgsMultiLineString >() );
1067 break;
1069 reset( std::make_unique< QgsMultiPolygon >() );
1070 break;
1071 default:
1072 reset( nullptr );
1074 }
1075 }
1076 else
1077 {
1078 detach();
1079 }
1080
1082 return QgsGeometryEditUtils::addPart( d->geometry.get(), std::move( p ) );
1083}
1084
1086{
1087 std::unique_ptr< QgsAbstractGeometry > p( part );
1088 if ( !d->geometry )
1089 {
1091 {
1093 reset( std::make_unique< QgsMultiPoint >() );
1094 break;
1096 reset( std::make_unique< QgsMultiLineString >() );
1097 break;
1100 reset( std::make_unique< QgsMultiPolygon >() );
1101 break;
1103 reset( std::make_unique< QgsMultiSurface >() );
1104 break;
1107 reset( std::make_unique< QgsMultiCurve >() );
1108 break;
1110 reset( std::make_unique< QgsPolyhedralSurface >() );
1111 break;
1112 case Qgis::WkbType::TIN:
1113 reset( std::make_unique< QgsTriangulatedSurface >() );
1114 break;
1115 default:
1116 reset( nullptr );
1118 }
1119 }
1120 else
1121 {
1122 detach();
1123 // For TIN and PolyhedralSurface, they already support multiple patches, no conversion needed
1124 const Qgis::WkbType flatType = QgsWkbTypes::flatType( d->geometry->wkbType() );
1125 if ( flatType != Qgis::WkbType::TIN && flatType != Qgis::WkbType::PolyhedralSurface )
1126 {
1128 }
1129 }
1130
1131 return QgsGeometryEditUtils::addPart( d->geometry.get(), std::move( p ) );
1132}
1133
1135{
1136 if ( !d->geometry )
1137 {
1139 }
1140 if ( newPart.isNull() || !newPart.d->geometry )
1141 {
1143 }
1144
1145 return addPartV2( newPart.d->geometry->clone() );
1146}
1147
1148QgsGeometry QgsGeometry::removeInteriorRings( double minimumRingArea ) const
1149{
1150 if ( !d->geometry || type() != Qgis::GeometryType::Polygon )
1151 {
1152 return QgsGeometry();
1153 }
1154
1155 if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
1156 {
1157 const QVector<QgsGeometry> parts = asGeometryCollection();
1158 QVector<QgsGeometry> results;
1159 results.reserve( parts.count() );
1160 for ( const QgsGeometry &part : parts )
1161 {
1162 QgsGeometry result = part.removeInteriorRings( minimumRingArea );
1163 if ( !result.isNull() )
1164 results << result;
1165 }
1166 if ( results.isEmpty() )
1167 return QgsGeometry();
1168
1169 QgsGeometry first = results.takeAt( 0 );
1170 for ( const QgsGeometry &result : std::as_const( results ) )
1171 {
1172 first.addPart( result );
1173 }
1174 return first;
1175 }
1176 else
1177 {
1178 std::unique_ptr< QgsCurvePolygon > newPoly( static_cast< QgsCurvePolygon * >( d->geometry->clone() ) );
1179 newPoly->removeInteriorRings( minimumRingArea );
1180 return QgsGeometry( std::move( newPoly ) );
1181 }
1182}
1183
1184Qgis::GeometryOperationResult QgsGeometry::translate( double dx, double dy, double dz, double dm )
1185{
1186 if ( !d->geometry )
1187 {
1189 }
1190
1191 detach();
1192
1193 d->geometry->transform( QTransform::fromTranslate( dx, dy ), dz, 1.0, dm );
1195}
1196
1198{
1199 if ( !d->geometry )
1200 {
1202 }
1203
1204 detach();
1205
1206 QTransform t = QTransform::fromTranslate( center.x(), center.y() );
1207 t.rotate( -rotation );
1208 t.translate( -center.x(), -center.y() );
1209 d->geometry->transform( t );
1211}
1212
1213// TODO: Remove this method when reshape() no longer calls it.
1214// i.e., when adapted to GEOS 3.15, since GEOS does the right thing.
1215static void removeDuplicateAdjacentPointsAt( QgsAbstractGeometry *geom, const QgsPointSequence &points )
1216{
1217 // this is a workaround for removing duplicated points introduced by GEOS when splitting 3d geometries
1218 // on topologically added points. It makes no sense to be called for 2d geometries, so it shouldn't.
1219 if ( !geom->is3D() )
1220 {
1221 Q_ASSERT( false );
1222 return;
1223 }
1224
1225 for ( const QgsPoint &pt : points )
1226 {
1227 QgsVertexId vertexId, prevVertexId, nextVertexId;
1228 const QgsPoint closestPt = QgsGeometryUtils::closestVertex( *geom, pt, vertexId );
1229 geom->adjacentVertices( vertexId, prevVertexId, nextVertexId );
1230 const double dist = QgsGeometryUtils::sqrDistance2D( pt, closestPt );
1231 if ( dist == 0 )
1232 {
1233 // make sure the geometry is snapped (z) to the topo point
1234 ( void ) geom->moveVertex( vertexId, pt );
1235 // remove adjacent vertices which are duplicates on the XY plane
1236 if ( const QgsPoint v = geom->vertexAt( prevVertexId ); v.x() == pt.x() && v.y() == pt.y() )
1237 ( void ) geom->deleteVertex( prevVertexId );
1238 else if ( const QgsPoint v = geom->vertexAt( nextVertexId ); v.x() == pt.x() && v.y() == pt.y() )
1239 ( void ) geom->deleteVertex( nextVertexId );
1240 }
1241 }
1242}
1243
1245 const QVector<QgsPointXY> &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QVector<QgsPointXY> &topologyTestPoints, bool splitFeature
1246)
1247{
1248 QgsPointSequence split, topology;
1249 convertPointList( splitLine, split );
1250 convertPointList( topologyTestPoints, topology );
1251 Qgis::GeometryOperationResult result = splitGeometry( split, newGeometries, topological, topology, splitFeature );
1252 convertPointList( topology, topologyTestPoints );
1253 return result;
1254}
1256 const QgsPointSequence &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, bool splitFeature, bool skipIntersectionTest
1257)
1258{
1259#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1260 Q_UNUSED( skipIntersectionTest )
1261#endif
1262 if ( !d->geometry )
1263 {
1265 }
1266 if ( splitLine.isEmpty() )
1267 {
1269 }
1270
1271 // We're trying adding the split line's vertices to the geometry so that
1272 // snap to segment always produces a valid split (see https://github.com/qgis/QGIS/issues/29270)
1273 QgsGeometry tmpGeom( *this );
1274 QVector<QgsGeometry > newGeomsTemp;
1275
1276#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1277 for ( const QgsPoint &v : splitLine )
1278 {
1279 tmpGeom.addTopologicalPoint( v );
1280 }
1281
1282 std::unique_ptr< QgsAbstractGeometry > splitGeom;
1283 if ( splitLine.size() > 1 )
1284 {
1285 splitGeom = std::make_unique< QgsLineString >( splitLine );
1286 splitGeom->dropZValue();
1287 splitGeom->dropMValue();
1288 }
1289 else if ( splitLine.size() == 1 )
1290 {
1291 splitGeom = std::make_unique< QgsPoint >( splitLine[0].x(), splitLine[0].y() );
1292 }
1293 QgsGeos geos( tmpGeom.get() );
1294 mLastError.clear();
1295 QgsGeometryEngine::EngineOperationResult result = geos.splitGeometry( *splitGeom.get(), newGeomsTemp, topological, topologyTestPoints, &mLastError );
1296
1297 switch ( result )
1298 {
1300 {
1301 newGeometries = collectSplitGeometries( newGeomsTemp, splitFeature );
1302#else
1303 QgsPointSequence addedTopologicalPoints;
1304 for ( const QgsPoint &v : splitLine )
1305 {
1306 if ( tmpGeom.addTopologicalPoint( v ) )
1307 {
1308 // POLYGON Z geometries need special handling to cater for GEOS limitations.
1309 // Splitting of polygons relies on GEOS extracting lines, unioning with the split line and then polygonizing.
1310 // The problem is that during the union operation GEOS will interpolate new Z values where the split line intersects
1311 // the polygon rings, even though we have added topological points with the correct Z values at that location.
1312 // This results in duplicate vertices and/or wrong Z values on the split geometry.
1313 // Our solution for that is:
1314 // 1. Collect the topo points that were added (these have the desired interpolated Z values).
1315 // 2. Visit the split geometries at the XY location of those topo points and make sure they still have the desired Z value.
1316 // 3. Remove the adjacent vertex to the topo point if it has same XY coordinates. Any vertex with XY coordinates same as a
1317 // topo point was introduced by GEOS and is not wanted.
1318 if ( tmpGeom.constGet()->is3D() && tmpGeom.constGet()->dimension() == 2 )
1319 {
1320 QgsVertexId vId;
1321 const QgsPoint topoPoint = QgsGeometryUtils::closestVertex( *tmpGeom.constGet(), v, vId );
1322 addedTopologicalPoints.append( topoPoint );
1323 }
1324 }
1325 }
1326
1327 QgsLineString splitLineString( splitLine );
1328 splitLineString.dropZValue();
1329 splitLineString.dropMValue();
1330
1331 QgsGeos geos( tmpGeom.get() );
1332 mLastError.clear();
1333 QgsGeometryEngine::EngineOperationResult result = geos.splitGeometry( splitLineString, newGeomsTemp, topological, topologyTestPoints, &mLastError, skipIntersectionTest );
1334
1335 switch ( result )
1336 {
1338 {
1339 if ( !addedTopologicalPoints.isEmpty() )
1340 {
1341 for ( int i = 0; i < newGeomsTemp.size(); ++i )
1342 {
1343 QgsAbstractGeometry *geom = newGeomsTemp[i].get();
1344 removeDuplicateAdjacentPointsAt( geom, addedTopologicalPoints );
1345 }
1346 }
1347 if ( splitFeature && !newGeomsTemp.isEmpty() )
1348 *this = newGeomsTemp.takeAt( 0 );
1349
1350 newGeometries = newGeomsTemp;
1351#endif
1353 }
1366 //default: do not implement default to handle properly all cases
1367 }
1368
1369 // this should never be reached
1370 Q_ASSERT( false );
1372}
1373
1375 const QgsCurve *curve, QVector<QgsGeometry> &newGeometries, bool preserveCircular, bool topological, QgsPointSequence &topologyTestPoints, bool splitFeature
1376)
1377{
1378#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 15, 0 )
1379 Q_UNUSED( preserveCircular );
1380
1381 if ( !d->geometry )
1382 {
1384 }
1385 if ( curve->isEmpty() )
1386 {
1388 }
1389
1390 // We're trying adding the split line's vertices to the geometry so that
1391 // snap to segment always produces a valid split (see https://github.com/qgis/QGIS/issues/29270)
1392 QgsGeometry tmpGeom( *this );
1393 QgsPointSequence curvePoints;
1394 curve->points( curvePoints );
1395
1396 for ( const QgsPoint &v : std::as_const( curvePoints ) )
1397 {
1398 tmpGeom.addTopologicalPoint( v );
1399 }
1400
1401 QVector< QgsGeometry> newGeomsTemp;
1402
1403 QgsGeos geos( tmpGeom.get() );
1404 mLastError.clear();
1405 QgsGeometryEngine::EngineOperationResult result = geos.splitGeometry( *curve, newGeomsTemp, topological, topologyTestPoints, &mLastError );
1406
1407 switch ( result )
1408 {
1410 {
1411 newGeometries = collectSplitGeometries( newGeomsTemp, splitFeature );
1413 }
1426 //default: do not implement default to handle properly all cases
1427 }
1428
1430#else
1431 std::unique_ptr<QgsLineString> segmentizedLine( curve->curveToLine() );
1432 QgsPointSequence points;
1433 segmentizedLine->points( points );
1434 Qgis::GeometryOperationResult result = splitGeometry( points, newGeometries, topological, topologyTestPoints, splitFeature );
1435
1437 {
1438 if ( preserveCircular )
1439 {
1440 for ( int i = 0; i < newGeometries.count(); ++i )
1441 newGeometries[i] = newGeometries[i].convertToCurves();
1442 *this = convertToCurves();
1443 }
1444 }
1445 return result;
1446#endif
1447}
1448
1450{
1451 if ( !d->geometry )
1452 {
1454 }
1455
1456 // We're trying adding the reshape line's vertices to the geometry so that
1457 // snap to segment always produces a valid reshape
1458 QgsPointSequence reshapePoints;
1459 reshapeLineString.points( reshapePoints );
1460 QgsGeometry tmpGeom( *this );
1461 QgsPointSequence addedTopologicalPoints;
1462 for ( const QgsPoint &v : std::as_const( reshapePoints ) )
1463 {
1464 // TODO: Remove this if block when reshape gets curve support, i.e.,
1465 // when adapted to GEOS 3.15, since GEOS does the right thing.
1466 if ( tmpGeom.addTopologicalPoint( v ) )
1467 {
1468 // When reshaping 3D lines or polygons we want to make sure that any topological points added
1469 // are preserved in the final geometry. GEOS will interpolate between geometry and reshapeLineString
1470 // and may create duplicate vertices with different Z values. We will manually snap Z to those topo
1471 // points later and remove any duplicated vertices.
1472 if ( tmpGeom.constGet()->is3D() )
1473 {
1474 QgsVertexId vId;
1475 const QgsPoint topoPoint = QgsGeometryUtils::closestVertex( *tmpGeom.constGet(), v, vId );
1476 addedTopologicalPoints.append( topoPoint );
1477 }
1478 }
1479 }
1480
1481 QgsGeos geos( tmpGeom.get() );
1483 mLastError.clear();
1484 std::unique_ptr< QgsAbstractGeometry > geom( geos.reshapeGeometry( reshapeLineString, &errorCode, &mLastError ) );
1485 if ( errorCode == QgsGeometryEngine::Success && geom )
1486 {
1487 // TODO: Remove this inner if block when reshape gets curve support,
1488 // i.e., when adapted to GEOS 3.15, since GEOS does the right thing.
1489 if ( !addedTopologicalPoints.isEmpty() )
1490 {
1491 removeDuplicateAdjacentPointsAt( geom.get(), addedTopologicalPoints );
1492 }
1493 reset( std::move( geom ) );
1495 }
1496
1497 switch ( errorCode )
1498 {
1509 case QgsGeometryEngine::SplitCannotSplitPoint: // should not happen
1513 }
1514
1515 // should not be reached
1517}
1518
1520{
1521 if ( !d->geometry || !other.d->geometry )
1522 {
1523 return 0;
1524 }
1525
1526 QgsGeos geos( d->geometry.get() );
1527
1528 mLastError.clear();
1529 std::unique_ptr< QgsAbstractGeometry > diffGeom( geos.difference( other.constGet(), &mLastError, QgsGeometryParameters(), feedback ) );
1530 if ( !diffGeom )
1531 {
1532 return 1;
1533 }
1534
1535 reset( std::move( diffGeom ) );
1536 return 0;
1537}
1538
1540{
1541 return difference( other, QgsGeometryParameters(), feedback );
1542}
1543
1545{
1546 if ( d->geometry )
1547 {
1548 return d->geometry->boundingBox();
1549 }
1550 return QgsRectangle();
1551}
1552
1554{
1555 if ( d->geometry )
1556 {
1557 return d->geometry->boundingBox3D();
1558 }
1559 return QgsBox3D();
1560}
1561
1562
1563QgsGeometry QgsGeometry::orientedMinimumBoundingBox( double &area, double &angle, double &width, double &height ) const
1564{
1565 mLastError.clear();
1566
1567 if ( isNull() )
1568 return QgsGeometry();
1569
1570 if ( type() == Qgis::GeometryType::Point && d->geometry->partCount() == 1 )
1571 {
1572 area = 0;
1573 angle = 0;
1574 width = 0;
1575 height = 0;
1576 return QgsGeometry::fromRect( d->geometry->boundingBox() );
1577 }
1578
1579 QgsInternalGeometryEngine engine( *this );
1580 const QgsGeometry res = engine.orientedMinimumBoundingBox( area, angle, width, height );
1581 if ( res.isNull() )
1582 mLastError = engine.lastError();
1583 return res;
1584}
1585
1587{
1588 double area, angle, width, height;
1589 return orientedMinimumBoundingBox( area, angle, width, height );
1590}
1591
1592static QgsCircle __recMinimalEnclosingCircle( QgsMultiPointXY points, QgsMultiPointXY boundary )
1593{
1594 auto l_boundary = boundary.length();
1595 QgsCircle circ_mec;
1596 if ( ( points.length() == 0 ) || ( l_boundary == 3 ) )
1597 {
1598 switch ( l_boundary )
1599 {
1600 case 0:
1601 circ_mec = QgsCircle();
1602 break;
1603 case 1:
1604 circ_mec = QgsCircle( QgsPoint( boundary.last() ), 0 );
1605 boundary.pop_back();
1606 break;
1607 case 2:
1608 {
1609 QgsPointXY p1 = boundary.last();
1610 boundary.pop_back();
1611 QgsPointXY p2 = boundary.last();
1612 boundary.pop_back();
1613 circ_mec = QgsCircle::from2Points( QgsPoint( p1 ), QgsPoint( p2 ) );
1614 }
1615 break;
1616 default:
1617 QgsPoint p1( boundary.at( 0 ) );
1618 QgsPoint p2( boundary.at( 1 ) );
1619 QgsPoint p3( boundary.at( 2 ) );
1620 circ_mec = QgsCircle::minimalCircleFrom3Points( p1, p2, p3 );
1621 break;
1622 }
1623 return circ_mec;
1624 }
1625 else
1626 {
1627 QgsPointXY pxy = points.last();
1628 points.pop_back();
1629 circ_mec = __recMinimalEnclosingCircle( points, boundary );
1630 QgsPoint p( pxy );
1631 if ( !circ_mec.contains( p ) )
1632 {
1633 boundary.append( pxy );
1634 circ_mec = __recMinimalEnclosingCircle( points, boundary );
1635 }
1636 }
1637 return circ_mec;
1638}
1639
1640QgsGeometry QgsGeometry::minimalEnclosingCircle( QgsPointXY &center, double &radius, unsigned int segments ) const
1641{
1642 center = QgsPointXY();
1643 radius = 0;
1644
1645 if ( isEmpty() )
1646 {
1647 return QgsGeometry();
1648 }
1649
1650 /* optimization */
1651 QgsGeometry hull = convexHull();
1652 if ( hull.isNull() )
1653 return QgsGeometry();
1654
1655 QgsMultiPointXY P = hull.convertToPoint( true ).asMultiPoint();
1657
1658 QgsCircle circ = __recMinimalEnclosingCircle( P, R );
1659 center = QgsPointXY( circ.center() );
1660 radius = circ.radius();
1661 QgsGeometry geom;
1662 geom.set( circ.toPolygon( segments ) );
1663 return geom;
1664}
1665
1667{
1668 QgsPointXY center;
1669 double radius;
1670 return minimalEnclosingCircle( center, radius, segments );
1671}
1672
1673QgsGeometry QgsGeometry::orthogonalize( double tolerance, int maxIterations, double angleThreshold ) const
1674{
1675 QgsInternalGeometryEngine engine( *this );
1676
1677 return engine.orthogonalize( tolerance, maxIterations, angleThreshold );
1678}
1679
1680QgsGeometry QgsGeometry::triangularWaves( double wavelength, double amplitude, bool strictWavelength ) const
1681{
1682 QgsInternalGeometryEngine engine( *this );
1683 return engine.triangularWaves( wavelength, amplitude, strictWavelength );
1684}
1685
1686QgsGeometry QgsGeometry::triangularWavesRandomized( double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed ) const
1687{
1688 QgsInternalGeometryEngine engine( *this );
1689 return engine.triangularWavesRandomized( minimumWavelength, maximumWavelength, minimumAmplitude, maximumAmplitude, seed );
1690}
1691
1692QgsGeometry QgsGeometry::squareWaves( double wavelength, double amplitude, bool strictWavelength ) const
1693{
1694 QgsInternalGeometryEngine engine( *this );
1695 return engine.squareWaves( wavelength, amplitude, strictWavelength );
1696}
1697
1698QgsGeometry QgsGeometry::squareWavesRandomized( double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed ) const
1699{
1700 QgsInternalGeometryEngine engine( *this );
1701 return engine.squareWavesRandomized( minimumWavelength, maximumWavelength, minimumAmplitude, maximumAmplitude, seed );
1702}
1703
1704QgsGeometry QgsGeometry::roundWaves( double wavelength, double amplitude, bool strictWavelength ) const
1705{
1706 QgsInternalGeometryEngine engine( *this );
1707 return engine.roundWaves( wavelength, amplitude, strictWavelength );
1708}
1709
1710QgsGeometry QgsGeometry::roundWavesRandomized( double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed ) const
1711{
1712 QgsInternalGeometryEngine engine( *this );
1713 return engine.roundWavesRandomized( minimumWavelength, maximumWavelength, minimumAmplitude, maximumAmplitude, seed );
1714}
1715
1717 const QVector<double> &pattern, Qgis::DashPatternLineEndingRule startRule, Qgis::DashPatternLineEndingRule endRule, Qgis::DashPatternSizeAdjustment adjustment, double patternOffset
1718) const
1719{
1720 QgsInternalGeometryEngine engine( *this );
1721 return engine.applyDashPattern( pattern, startRule, endRule, adjustment, patternOffset );
1722}
1723
1724QgsGeometry QgsGeometry::snappedToGrid( double hSpacing, double vSpacing, double dSpacing, double mSpacing ) const
1725{
1726 if ( !d->geometry )
1727 {
1728 return QgsGeometry();
1729 }
1730 return QgsGeometry( d->geometry->snappedToGrid( hSpacing, vSpacing, dSpacing, mSpacing ) );
1731}
1732
1733bool QgsGeometry::removeDuplicateNodes( double epsilon, bool useZValues )
1734{
1735 if ( !d->geometry )
1736 return false;
1737
1738 detach();
1739 return d->geometry->removeDuplicateNodes( epsilon, useZValues );
1740}
1741
1743{
1744 // fast case, check bounding boxes
1745 if ( !boundingBoxIntersects( r ) )
1746 return false;
1747
1748 const Qgis::WkbType flatType { QgsWkbTypes::flatType( d->geometry->wkbType() ) };
1749 // optimise trivial case for point intersections -- the bounding box test has already given us the answer
1750 if ( flatType == Qgis::WkbType::Point )
1751 {
1752 return true;
1753 }
1754
1755#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 12, 0 )
1756 // Workaround for issue issue GH #51492
1757 // in case of multi polygon, intersection with an empty rect fails
1758 if ( flatType == Qgis::WkbType::MultiPolygon && r.isEmpty() )
1759 {
1760 const QgsPointXY center { r.xMinimum(), r.yMinimum() };
1761 return contains( QgsGeometry::fromPointXY( center ) );
1762 }
1763#endif
1764
1765 QgsGeometry g = fromRect( r );
1766 return intersects( g );
1767}
1768
1769bool QgsGeometry::intersects( const QgsGeometry &geometry ) const
1770{
1771 if ( !d->geometry || geometry.isNull() )
1772 {
1773 return false;
1774 }
1775
1776 QgsGeos geos( d->geometry.get() );
1777 mLastError.clear();
1778 return geos.intersects( geometry.d->geometry.get(), &mLastError );
1779}
1780
1782{
1783 if ( !d->geometry )
1784 {
1785 return false;
1786 }
1787
1788 return d->geometry->boundingBoxIntersects( rectangle );
1789}
1790
1792{
1793 if ( !d->geometry || geometry.isNull() )
1794 {
1795 return false;
1796 }
1797
1798 return d->geometry->boundingBoxIntersects( geometry.constGet()->boundingBox() );
1799}
1800
1801bool QgsGeometry::contains( const QgsPointXY *p ) const
1802{
1803 if ( !d->geometry || !p )
1804 {
1805 return false;
1806 }
1807
1808 QgsGeos geos( d->geometry.get() );
1809 mLastError.clear();
1810 return geos.contains( p->x(), p->y(), &mLastError );
1811}
1812
1813bool QgsGeometry::contains( double x, double y ) const
1814{
1815 if ( !d->geometry )
1816 {
1817 return false;
1818 }
1819
1820 QgsGeos geos( d->geometry.get() );
1821 mLastError.clear();
1822 return geos.contains( x, y, &mLastError );
1823}
1824
1825bool QgsGeometry::contains( const QgsGeometry &geometry ) const
1826{
1827 if ( !d->geometry || geometry.isNull() )
1828 {
1829 return false;
1830 }
1831
1832 QgsGeos geos( d->geometry.get() );
1833 mLastError.clear();
1834 return geos.contains( geometry.d->geometry.get(), &mLastError );
1835}
1836
1837bool QgsGeometry::disjoint( const QgsGeometry &geometry ) const
1838{
1839 if ( !d->geometry || geometry.isNull() )
1840 {
1841 return false;
1842 }
1843
1844 QgsGeos geos( d->geometry.get() );
1845 mLastError.clear();
1846 return geos.disjoint( geometry.d->geometry.get(), &mLastError );
1847}
1848
1849bool QgsGeometry::equals( const QgsGeometry &geometry ) const
1850{
1851 return isExactlyEqual( geometry );
1852}
1853
1854bool QgsGeometry::touches( const QgsGeometry &geometry ) const
1855{
1856 if ( !d->geometry || geometry.isNull() )
1857 {
1858 return false;
1859 }
1860
1861 QgsGeos geos( d->geometry.get() );
1862 mLastError.clear();
1863 return geos.touches( geometry.d->geometry.get(), &mLastError );
1864}
1865
1866bool QgsGeometry::overlaps( const QgsGeometry &geometry ) const
1867{
1868 if ( !d->geometry || geometry.isNull() )
1869 {
1870 return false;
1871 }
1872
1873 QgsGeos geos( d->geometry.get() );
1874 mLastError.clear();
1875 return geos.overlaps( geometry.d->geometry.get(), &mLastError );
1876}
1877
1878bool QgsGeometry::within( const QgsGeometry &geometry ) const
1879{
1880 if ( !d->geometry || geometry.isNull() )
1881 {
1882 return false;
1883 }
1884
1885 QgsGeos geos( d->geometry.get() );
1886 mLastError.clear();
1887 return geos.within( geometry.d->geometry.get(), &mLastError );
1888}
1889
1890bool QgsGeometry::crosses( const QgsGeometry &geometry ) const
1891{
1892 if ( !d->geometry || geometry.isNull() )
1893 {
1894 return false;
1895 }
1896
1897 QgsGeos geos( d->geometry.get() );
1898 mLastError.clear();
1899 return geos.crosses( geometry.d->geometry.get(), &mLastError );
1900}
1901
1902QString QgsGeometry::asWkt( int precision ) const
1903{
1904 if ( !d->geometry )
1905 {
1906 return QString();
1907 }
1908 return d->geometry->asWkt( precision );
1909}
1910
1911QString QgsGeometry::asJson( int precision ) const
1912{
1913 return asGeoJson( precision, Qgis::GeoJsonProfile::Rfc7946 );
1914}
1915
1916QString QgsGeometry::asGeoJson( int precision, Qgis::GeoJsonProfile profile ) const
1917{
1918 return QString::fromStdString( asJsonObject( precision, profile ).dump() );
1919}
1920
1921json QgsGeometry::asJsonObject( int precision, Qgis::GeoJsonProfile profile ) const
1922{
1923 if ( !d->geometry )
1924 {
1925 return nullptr;
1926 }
1927 return d->geometry->asJsonObject( precision, profile );
1928}
1929
1930QVector<QgsGeometry> QgsGeometry::coerceToType( const Qgis::WkbType type, double defaultZ, double defaultM, bool avoidDuplicates ) const
1931{
1932 mLastError.clear();
1933 QVector< QgsGeometry > res;
1934 if ( isNull() )
1935 return res;
1936
1937 if ( wkbType() == type || type == Qgis::WkbType::Unknown )
1938 {
1939 res << *this;
1940 return res;
1941 }
1942
1944 {
1945 return res;
1946 }
1947
1948 QgsGeometry newGeom = *this;
1949
1950 // Curved -> straight
1952 {
1953 newGeom = QgsGeometry( d->geometry.get()->segmentize() );
1954 }
1955
1956 // Handle NurbsCurve: if target is curved but NOT NurbsCurve, and source contains NurbsCurve,
1957 // we need to segmentize the NURBS parts first
1959 {
1960 // Check if geometry contains NurbsCurve that needs conversion
1961 bool hasNurbs = false;
1962 if ( QgsWkbTypes::isNurbsType( newGeom.wkbType() ) )
1963 {
1964 hasNurbs = true;
1965 }
1966 else if ( const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( newGeom.constGet() ) )
1967 {
1968 for ( int i = 0; i < collection->numGeometries(); ++i )
1969 {
1970 if ( QgsWkbTypes::isNurbsType( collection->geometryN( i )->wkbType() ) )
1971 {
1972 hasNurbs = true;
1973 break;
1974 }
1975 }
1976 }
1977 else if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( newGeom.constGet() ) )
1978 {
1979 if ( cp->exteriorRing() && QgsWkbTypes::isNurbsType( cp->exteriorRing()->wkbType() ) )
1980 hasNurbs = true;
1981 for ( int i = 0; !hasNurbs && i < cp->numInteriorRings(); ++i )
1982 {
1983 if ( QgsWkbTypes::isNurbsType( cp->interiorRing( i )->wkbType() ) )
1984 hasNurbs = true;
1985 }
1986 }
1988 {
1989 for ( int i = 0; i < cc->nCurves(); ++i )
1990 {
1991 if ( QgsWkbTypes::isNurbsType( cc->curveAt( i )->wkbType() ) )
1992 {
1993 hasNurbs = true;
1994 break;
1995 }
1996 }
1997 }
1998
1999 if ( hasNurbs )
2000 {
2001 // Segmentize to remove NURBS, then we'll convert back to curve type below
2002 newGeom = QgsGeometry( newGeom.constGet()->segmentize() );
2003 }
2004 }
2005
2006 // polygon -> line
2008 {
2009 // boundary gives us a (multi)line string of exterior + interior rings
2010 newGeom = QgsGeometry( newGeom.constGet()->boundary() );
2011 }
2012 // line -> polygon
2014 {
2015 std::unique_ptr< QgsGeometryCollection > gc( QgsGeometryFactory::createCollectionOfType( type ) );
2016 const QgsGeometry source = newGeom;
2017 for ( auto part = source.const_parts_begin(); part != source.const_parts_end(); ++part )
2018 {
2019 std::unique_ptr< QgsAbstractGeometry > exterior( ( *part )->clone() );
2020 if ( QgsCurve *curve = qgsgeometry_cast< QgsCurve * >( exterior.get() ) )
2021 {
2023 {
2024 auto cp = std::make_unique< QgsCurvePolygon >();
2025 cp->setExteriorRing( curve );
2026 ( void ) exterior.release();
2027 gc->addGeometry( cp.release() );
2028 }
2029 else
2030 {
2031 auto p = std::make_unique< QgsPolygon >();
2032 p->setExteriorRing( qgsgeometry_cast< QgsLineString * >( curve ) );
2033 ( void ) exterior.release();
2034 gc->addGeometry( p.release() );
2035 }
2036 }
2037 }
2038 newGeom = QgsGeometry( std::move( gc ) );
2039 }
2040
2041 // line/polygon -> points
2043 {
2044 // lines/polygons to a point layer, extract all vertices
2045 auto mp = std::make_unique< QgsMultiPoint >();
2046 const QgsGeometry source = newGeom;
2047 QSet< QgsPoint > added;
2048 for ( auto vertex = source.vertices_begin(); vertex != source.vertices_end(); ++vertex )
2049 {
2050 if ( avoidDuplicates && added.contains( *vertex ) )
2051 continue; // avoid duplicate points, e.g. start/end of rings
2052 mp->addGeometry( ( *vertex ).clone() );
2053 added.insert( *vertex );
2054 }
2055 newGeom = QgsGeometry( std::move( mp ) );
2056 }
2057
2058 //(Multi)Polygon to PolyhedralSurface
2060 {
2061 auto polySurface = std::make_unique< QgsPolyhedralSurface >();
2062 const QgsGeometry source = newGeom;
2063 for ( auto part = source.const_parts_begin(); part != source.const_parts_end(); ++part )
2064 {
2065 if ( const QgsPolygon *polygon = qgsgeometry_cast< const QgsPolygon * >( *part ) )
2066 {
2067 polySurface->addPatch( polygon->clone() );
2068 }
2069 }
2070 newGeom = QgsGeometry( std::move( polySurface ) );
2071 }
2072
2073 //(Multi)Polygon/Triangle to TIN
2076 {
2077 auto tin = std::make_unique< QgsTriangulatedSurface >();
2078 const QgsGeometry source = newGeom;
2079 for ( auto part = source.const_parts_begin(); part != source.const_parts_end(); ++part )
2080 {
2081 if ( const QgsTriangle *triangle = qgsgeometry_cast< const QgsTriangle * >( *part ) )
2082 {
2083 tin->addPatch( triangle->clone() );
2084 }
2085 else if ( const QgsPolygon *polygon = qgsgeometry_cast< const QgsPolygon * >( *part ) )
2086 {
2087 // Validate that the polygon can be converted to a triangle (must have exactly 3 vertices + closing point)
2088 if ( polygon->exteriorRing() )
2089 {
2090 const int numPoints = polygon->exteriorRing()->numPoints();
2091 if ( numPoints != 4 )
2092 {
2093 mLastError = QObject::tr( "Cannot convert polygon with %1 vertices to a triangle. A triangle requires exactly 3 vertices." ).arg( numPoints > 0 ? numPoints - 1 : 0 );
2094 return res;
2095 }
2096 auto triangle = std::make_unique< QgsTriangle >();
2097 triangle->setExteriorRing( polygon->exteriorRing()->clone() );
2098 tin->addPatch( triangle.release() );
2099 }
2100 }
2101 }
2102 newGeom = QgsGeometry( std::move( tin ) );
2103 }
2104
2105 // PolyhedralSurface/TIN to (Multi)Polygon
2108 {
2109 auto multiPolygon = std::make_unique< QgsMultiPolygon >();
2111 {
2112 for ( int i = 0; i < polySurface->numPatches(); ++i )
2113 {
2114 const QgsPolygon *patch = polySurface->patchN( i );
2115 auto polygon = std::make_unique< QgsPolygon >();
2116 polygon->setExteriorRing( patch->exteriorRing()->clone() );
2117 for ( int j = 0; j < patch->numInteriorRings(); ++j )
2118 {
2119 polygon->addInteriorRing( patch->interiorRing( j )->clone() );
2120 }
2121 multiPolygon->addGeometry( polygon.release() );
2122 }
2123 }
2124 newGeom = QgsGeometry( std::move( multiPolygon ) );
2125 }
2126
2127 // Polygon -> Triangle
2129 {
2130 if ( const QgsPolygon *polygon = qgsgeometry_cast< const QgsPolygon * >( newGeom.constGet() ) )
2131 {
2132 // Validate that the polygon can be converted to a triangle (must have exactly 3 vertices + closing point)
2133 if ( polygon->exteriorRing() )
2134 {
2135 const int numPoints = polygon->exteriorRing()->numPoints();
2136 if ( numPoints != 4 )
2137 {
2138 mLastError = QObject::tr( "Cannot convert polygon with %1 vertices to a triangle. A triangle requires exactly 3 vertices." ).arg( numPoints > 0 ? numPoints - 1 : 0 );
2139 return res;
2140 }
2141 auto triangle = std::make_unique< QgsTriangle >();
2142 triangle->setExteriorRing( polygon->exteriorRing()->clone() );
2143 newGeom = QgsGeometry( std::move( triangle ) );
2144 }
2145 }
2146 }
2147
2148
2149 // Single -> multi
2150 if ( QgsWkbTypes::isMultiType( type ) && !newGeom.isMultipart() )
2151 {
2152 newGeom.convertToMultiType();
2153 }
2154 // Drop Z/M
2155 if ( newGeom.constGet()->is3D() && !QgsWkbTypes::hasZ( type ) )
2156 {
2157 newGeom.get()->dropZValue();
2158 }
2159 if ( newGeom.constGet()->isMeasure() && !QgsWkbTypes::hasM( type ) )
2160 {
2161 newGeom.get()->dropMValue();
2162 }
2163 // Add Z/M back, set to 0
2164 if ( !newGeom.constGet()->is3D() && QgsWkbTypes::hasZ( type ) )
2165 {
2166 newGeom.get()->addZValue( defaultZ );
2167 }
2168 if ( !newGeom.constGet()->isMeasure() && QgsWkbTypes::hasM( type ) )
2169 {
2170 newGeom.get()->addMValue( defaultM );
2171 }
2172
2173 // Straight -> curve
2175 {
2176 newGeom.convertToCurvedMultiType();
2177 }
2178
2179 // Multi -> single
2180 if ( !QgsWkbTypes::isMultiType( type ) && newGeom.isMultipart() )
2181 {
2182 const QgsGeometryCollection *parts( static_cast< const QgsGeometryCollection * >( newGeom.constGet() ) );
2183 res.reserve( parts->partCount() );
2184 for ( int i = 0; i < parts->partCount(); i++ )
2185 {
2186 const QgsAbstractGeometry *part = parts->geometryN( i );
2188 res << QgsGeometry( part->toCurveType() );
2189 else
2190 res << QgsGeometry( part->clone() );
2191 }
2192 }
2193 // GeometryCollection (of Point/LineString/Polygon) -> MultiPoint/MultiLineString/MultiPolygon
2195 {
2197 const QgsGeometryCollection *geomColl( static_cast< const QgsGeometryCollection * >( newGeom.constGet() ) );
2198
2199 bool allExpectedType = true;
2200 for ( int i = 0; i < geomColl->numGeometries(); ++i )
2201 {
2202 if ( geomColl->geometryN( i )->wkbType() != singleType )
2203 {
2204 allExpectedType = false;
2205 break;
2206 }
2207 }
2208 if ( allExpectedType )
2209 {
2210 std::unique_ptr< QgsGeometryCollection > newGeomCol;
2212 {
2213 newGeomCol = std::make_unique< QgsMultiPoint >();
2214 }
2216 {
2217 newGeomCol = std::make_unique< QgsMultiLineString >();
2218 }
2219 else
2220 {
2221 newGeomCol = std::make_unique< QgsMultiPolygon >();
2222 }
2223 newGeomCol->reserve( geomColl->numGeometries() );
2224 for ( int i = 0; i < geomColl->numGeometries(); ++i )
2225 {
2226 newGeomCol->addGeometry( geomColl->geometryN( i )->clone() );
2227 }
2228 res << QgsGeometry( std::move( newGeomCol ) );
2229 }
2230 else
2231 {
2232 res << newGeom;
2233 }
2234 }
2235 else
2236 {
2237 res << newGeom;
2238 }
2239 return res;
2240}
2241
2242QgsGeometry QgsGeometry::convertToType( Qgis::GeometryType destType, bool destMultipart ) const
2243{
2244 switch ( destType )
2245 {
2247 return convertToPoint( destMultipart );
2248
2250 return convertToLine( destMultipart );
2251
2253 return convertToPolygon( destMultipart );
2254
2255 default:
2256 return QgsGeometry();
2257 }
2258}
2259
2261{
2262 if ( !d->geometry )
2263 {
2264 return false;
2265 }
2266
2267 if ( isMultipart() ) //already multitype, no need to convert
2268 {
2269 return true;
2270 }
2271
2272 std::unique_ptr< QgsAbstractGeometry > geom = QgsGeometryFactory::geomFromWkbType( QgsWkbTypes::multiType( d->geometry->wkbType() ) );
2274 if ( !multiGeom )
2275 {
2276 return false;
2277 }
2278
2279 //try to avoid cloning existing geometry whenever we can
2280
2281 //want to see a magic trick?... gather round kiddies...
2282 detach(); // maybe a clone, hopefully not if we're the only ref to the private data
2283 // now we cheat a bit and steal the private geometry and add it direct to the multigeom
2284 // we can do this because we're the only ref to this geometry, guaranteed by the detach call above
2285 multiGeom->addGeometry( d->geometry.release() );
2286 // and replace it with the multi geometry.
2287 // TADA! a clone free conversion in some cases
2288 d->geometry = std::move( geom );
2289 return true;
2290}
2291
2293{
2294 if ( !d->geometry )
2295 {
2296 return false;
2297 }
2298
2299 switch ( QgsWkbTypes::flatType( d->geometry->wkbType() ) )
2300 {
2305 {
2306 return true;
2307 }
2308 default:
2309 break;
2310 }
2311
2312 std::unique_ptr< QgsAbstractGeometry > geom = QgsGeometryFactory::geomFromWkbType( QgsWkbTypes::curveType( QgsWkbTypes::multiType( d->geometry->wkbType() ) ) );
2314 if ( !multiGeom )
2315 {
2316 return false;
2317 }
2318
2319 QgsGeometryCollection *sourceMultiGeom = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
2320 if ( sourceMultiGeom )
2321 {
2322 for ( int i = 0; i < sourceMultiGeom->numGeometries(); ++i )
2323 {
2324 if ( !multiGeom->addGeometry( sourceMultiGeom->geometryN( i )->clone() ) )
2325 return false;
2326 }
2327 }
2328 else
2329 {
2330 if ( !multiGeom->addGeometry( d->geometry->clone() ) )
2331 return false;
2332 }
2333
2334 reset( std::move( geom ) );
2335 return true;
2336}
2337
2339{
2340 if ( !d->geometry )
2341 {
2342 return false;
2343 }
2344
2345 if ( !isMultipart() ) //already single part, no need to convert
2346 {
2347 return true;
2348 }
2349
2350 QgsGeometryCollection *multiGeom = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
2351 if ( !multiGeom || multiGeom->partCount() < 1 )
2352 return false;
2353
2354 std::unique_ptr< QgsAbstractGeometry > firstPart( multiGeom->geometryN( 0 )->clone() );
2355 reset( std::move( firstPart ) );
2356 return true;
2357}
2358
2359
2361{
2363 if ( !origGeom )
2364 return false;
2365
2366 std::unique_ptr<QgsGeometryCollection> resGeom;
2367 switch ( geomType )
2368 {
2370 resGeom = std::make_unique<QgsMultiPoint>();
2371 break;
2373 resGeom = std::make_unique<QgsMultiLineString>();
2374 break;
2376 resGeom = std::make_unique<QgsMultiPolygon>();
2377 break;
2378 default:
2379 break;
2380 }
2381 if ( !resGeom )
2382 return false;
2383
2384 resGeom->reserve( origGeom->numGeometries() );
2385 for ( int i = 0; i < origGeom->numGeometries(); ++i )
2386 {
2387 const QgsAbstractGeometry *g = origGeom->geometryN( i );
2388 if ( QgsWkbTypes::geometryType( g->wkbType() ) == geomType )
2389 resGeom->addGeometry( g->clone() );
2390 }
2391
2392 set( resGeom.release() );
2393 return true;
2394}
2395
2396
2398{
2399 if ( !d->geometry )
2400 {
2401 return QgsPointXY();
2402 }
2403 if ( const QgsPoint *pt = qgsgeometry_cast<const QgsPoint *>( d->geometry->simplifiedTypeRef() ) )
2404 {
2405 return QgsPointXY( pt->x(), pt->y() );
2406 }
2407 else
2408 {
2409 return QgsPointXY();
2410 }
2411}
2412
2414{
2415 QgsPolylineXY polyLine;
2416 if ( !d->geometry )
2417 {
2418 return polyLine;
2419 }
2420
2421 bool doSegmentation = ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::CompoundCurve || QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::CircularString );
2422 std::unique_ptr< QgsLineString > segmentizedLine;
2423 QgsLineString *line = nullptr;
2424 if ( doSegmentation )
2425 {
2426 QgsCurve *curve = qgsgeometry_cast<QgsCurve *>( d->geometry.get() );
2427 if ( !curve )
2428 {
2429 return polyLine;
2430 }
2431 segmentizedLine.reset( curve->curveToLine() );
2432 line = segmentizedLine.get();
2433 }
2434 else
2435 {
2436 line = qgsgeometry_cast<QgsLineString *>( d->geometry.get() );
2437 if ( !line )
2438 {
2439 return polyLine;
2440 }
2441 }
2442
2443 int nVertices = line->numPoints();
2444 polyLine.resize( nVertices );
2445 QgsPointXY *data = polyLine.data();
2446 const double *xData = line->xData();
2447 const double *yData = line->yData();
2448 for ( int i = 0; i < nVertices; ++i )
2449 {
2450 data->setX( *xData++ );
2451 data->setY( *yData++ );
2452 data++;
2453 }
2454
2455 return polyLine;
2456}
2457
2459{
2460 if ( !d->geometry )
2461 return QgsPolygonXY();
2462
2463 bool doSegmentation = ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::CurvePolygon );
2464
2465 QgsPolygon *p = nullptr;
2466 std::unique_ptr< QgsPolygon > segmentized;
2467 if ( doSegmentation )
2468 {
2469 QgsCurvePolygon *curvePoly = qgsgeometry_cast<QgsCurvePolygon *>( d->geometry.get() );
2470 if ( !curvePoly )
2471 {
2472 return QgsPolygonXY();
2473 }
2474 segmentized.reset( curvePoly->toPolygon() );
2475 p = segmentized.get();
2476 }
2477 else
2478 {
2479 p = qgsgeometry_cast<QgsPolygon *>( d->geometry.get() );
2480 }
2481
2482 if ( !p )
2483 {
2484 return QgsPolygonXY();
2485 }
2486
2487 QgsPolygonXY polygon;
2488 convertPolygon( *p, polygon );
2489
2490 return polygon;
2491}
2492
2494{
2495 if ( !d->geometry || QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::MultiPoint )
2496 {
2497 return QgsMultiPointXY();
2498 }
2499
2500 const QgsMultiPoint *mp = qgsgeometry_cast<QgsMultiPoint *>( d->geometry.get() );
2501 if ( !mp )
2502 {
2503 return QgsMultiPointXY();
2504 }
2505
2506 int nPoints = mp->numGeometries();
2507 QgsMultiPointXY multiPoint( nPoints );
2508 for ( int i = 0; i < nPoints; ++i )
2509 {
2510 const QgsPoint *pt = mp->pointN( i );
2511 multiPoint[i].setX( pt->x() );
2512 multiPoint[i].setY( pt->y() );
2513 }
2514 return multiPoint;
2515}
2516
2518{
2519 if ( !d->geometry )
2520 {
2521 return QgsMultiPolylineXY();
2522 }
2523
2524 QgsGeometryCollection *geomCollection = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
2525 if ( !geomCollection )
2526 {
2527 return QgsMultiPolylineXY();
2528 }
2529
2530 int nLines = geomCollection->numGeometries();
2531 if ( nLines < 1 )
2532 {
2533 return QgsMultiPolylineXY();
2534 }
2535
2537 mpl.reserve( nLines );
2538 for ( int i = 0; i < nLines; ++i )
2539 {
2540 const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( geomCollection->geometryN( i ) );
2541 std::unique_ptr< QgsLineString > segmentized;
2542 if ( !line )
2543 {
2544 const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( geomCollection->geometryN( i ) );
2545 if ( !curve )
2546 {
2547 continue;
2548 }
2549 segmentized.reset( curve->curveToLine() );
2550 line = segmentized.get();
2551 }
2552
2553 QgsPolylineXY polyLine;
2554 int nVertices = line->numPoints();
2555 polyLine.resize( nVertices );
2556 QgsPointXY *data = polyLine.data();
2557 const double *xData = line->xData();
2558 const double *yData = line->yData();
2559 for ( int i = 0; i < nVertices; ++i )
2560 {
2561 data->setX( *xData++ );
2562 data->setY( *yData++ );
2563 data++;
2564 }
2565 mpl.append( polyLine );
2566 }
2567 return mpl;
2568}
2569
2571{
2572 if ( !d->geometry )
2573 {
2574 return QgsMultiPolygonXY();
2575 }
2576
2577 const QgsGeometryCollection *geomCollection = qgsgeometry_cast<const QgsGeometryCollection *>( d->geometry.get() );
2578 if ( !geomCollection )
2579 {
2580 return QgsMultiPolygonXY();
2581 }
2582
2583 const int nPolygons = geomCollection->numGeometries();
2584 if ( nPolygons < 1 )
2585 {
2586 return QgsMultiPolygonXY();
2587 }
2588
2590 mp.reserve( nPolygons );
2591 for ( int i = 0; i < nPolygons; ++i )
2592 {
2593 const QgsPolygon *polygon = qgsgeometry_cast<const QgsPolygon *>( geomCollection->geometryN( i ) );
2594 if ( !polygon )
2595 {
2596 const QgsCurvePolygon *cPolygon = qgsgeometry_cast<const QgsCurvePolygon *>( geomCollection->geometryN( i ) );
2597 if ( cPolygon )
2598 {
2599 polygon = cPolygon->toPolygon();
2600 }
2601 else
2602 {
2603 continue;
2604 }
2605 }
2606
2607 QgsPolygonXY poly;
2608 convertPolygon( *polygon, poly );
2609 mp.push_back( poly );
2610 }
2611 return mp;
2612}
2613
2614double QgsGeometry::area() const
2615{
2616 if ( !d->geometry )
2617 {
2618 return -1.0;
2619 }
2620
2621 return d->geometry->area();
2622}
2623
2625{
2626 if ( !d->geometry )
2627 {
2628 throw QgsInvalidArgumentException( "Cannot compute 3D area: geometry is null." );
2629 }
2630
2631 return d->geometry->area3D();
2632}
2633
2635{
2636 if ( !d->geometry )
2637 {
2638 return -1.0;
2639 }
2640
2641 switch ( QgsWkbTypes::geometryType( d->geometry->wkbType() ) )
2642 {
2644 return 0.0;
2645
2647 return d->geometry->length();
2648
2650 return d->geometry->perimeter();
2651
2654 return d->geometry->length();
2655 }
2656 return -1;
2657}
2658
2659double QgsGeometry::distance( const QgsGeometry &geom ) const
2660{
2661 if ( !d->geometry || !geom.d->geometry )
2662 {
2663 return -1.0;
2664 }
2665
2666 // avoid calling geos for trivial point-to-point distance calculations
2667 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::Point && QgsWkbTypes::flatType( geom.wkbType() ) == Qgis::WkbType::Point )
2668 {
2669 return qgsgeometry_cast< const QgsPoint * >( d->geometry.get() )->distance( *qgsgeometry_cast< const QgsPoint * >( geom.constGet() ) );
2670 }
2671
2672 QgsGeos g( d->geometry.get() );
2673 mLastError.clear();
2674 return g.distance( geom.d->geometry.get(), &mLastError );
2675}
2676
2678{
2679 if ( !d->geometry || !geom.d->geometry )
2680 {
2681 return -1.0;
2682 }
2683
2684 QgsGeos g( d->geometry.get() );
2685 mLastError.clear();
2686 return g.hausdorffDistance( geom.d->geometry.get(), &mLastError );
2687}
2688
2689double QgsGeometry::hausdorffDistanceDensify( const QgsGeometry &geom, double densifyFraction ) const
2690{
2691 if ( !d->geometry || !geom.d->geometry )
2692 {
2693 return -1.0;
2694 }
2695
2696 QgsGeos g( d->geometry.get() );
2697 mLastError.clear();
2698 return g.hausdorffDistanceDensify( geom.d->geometry.get(), densifyFraction, &mLastError );
2699}
2700
2701
2703{
2704 if ( !d->geometry || !geom.d->geometry )
2705 {
2706 return -1.0;
2707 }
2708
2709 QgsGeos g( d->geometry.get() );
2710 mLastError.clear();
2711 return g.frechetDistance( geom.d->geometry.get(), &mLastError );
2712}
2713
2714double QgsGeometry::frechetDistanceDensify( const QgsGeometry &geom, double densifyFraction ) const
2715{
2716 if ( !d->geometry || !geom.d->geometry )
2717 {
2718 return -1.0;
2719 }
2720
2721 QgsGeos g( d->geometry.get() );
2722 mLastError.clear();
2723 return g.frechetDistanceDensify( geom.d->geometry.get(), densifyFraction, &mLastError );
2724}
2725
2727{
2728 if ( !d->geometry || d->geometry.get()->isEmpty() )
2730 return d->geometry->vertices_begin();
2731}
2732
2734{
2735 if ( !d->geometry || d->geometry.get()->isEmpty() )
2737 return d->geometry->vertices_end();
2738}
2739
2741{
2742 if ( !d->geometry || d->geometry.get()->isEmpty() )
2743 return QgsVertexIterator();
2744 return QgsVertexIterator( d->geometry.get() );
2745}
2746
2748{
2749 if ( !d->geometry )
2751
2752 detach();
2753 return d->geometry->parts_begin();
2754}
2755
2757{
2758 if ( !d->geometry )
2760 return d->geometry->parts_end();
2761}
2762
2764{
2765 if ( !d->geometry )
2767 return d->geometry->const_parts_begin();
2768}
2769
2771{
2772 if ( !d->geometry )
2774 return d->geometry->const_parts_end();
2775}
2776
2778{
2779 if ( !d->geometry )
2780 return QgsGeometryPartIterator();
2781
2782 detach();
2783 return QgsGeometryPartIterator( d->geometry.get() );
2784}
2785
2787{
2788 if ( !d->geometry )
2790
2791 return QgsGeometryConstPartIterator( d->geometry.get() );
2792}
2793
2794QgsGeometry QgsGeometry::buffer( double distance, int segments, QgsFeedback *feedback ) const
2795{
2796 if ( !d->geometry )
2797 {
2798 return QgsGeometry();
2799 }
2800
2801 QgsGeos g( d->geometry.get() );
2802 mLastError.clear();
2803 std::unique_ptr<QgsAbstractGeometry> geom( g.buffer( distance, segments, &mLastError, feedback ) );
2804 if ( !geom )
2805 {
2806 QgsGeometry result;
2807 result.mLastError = mLastError;
2808 return result;
2809 }
2810 return QgsGeometry( std::move( geom ) );
2811}
2812
2813QgsGeometry QgsGeometry::buffer( double distance, int segments, Qgis::EndCapStyle endCapStyle, Qgis::JoinStyle joinStyle, double miterLimit, QgsFeedback *feedback ) const
2814{
2815 if ( !d->geometry )
2816 {
2817 return QgsGeometry();
2818 }
2819
2820 QgsGeos g( d->geometry.get() );
2821 mLastError.clear();
2822 QgsAbstractGeometry *geom = g.buffer( distance, segments, endCapStyle, joinStyle, miterLimit, &mLastError, feedback );
2823 if ( !geom )
2824 {
2825 QgsGeometry result;
2826 result.mLastError = mLastError;
2827 return result;
2828 }
2829 return QgsGeometry( geom );
2830}
2831
2832QgsGeometry QgsGeometry::offsetCurve( double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit ) const
2833{
2834 if ( !d->geometry || type() != Qgis::GeometryType::Line )
2835 {
2836 return QgsGeometry();
2837 }
2838
2839 if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
2840 {
2841 const QVector<QgsGeometry> parts = asGeometryCollection();
2842 QVector<QgsGeometry> results;
2843 results.reserve( parts.count() );
2844 for ( const QgsGeometry &part : parts )
2845 {
2846 QgsGeometry result = part.offsetCurve( distance, segments, joinStyle, miterLimit );
2847 if ( !result.isNull() )
2848 results << result;
2849 }
2850 if ( results.isEmpty() )
2851 return QgsGeometry();
2852
2853 QgsGeometry first = results.takeAt( 0 );
2854 for ( const QgsGeometry &result : std::as_const( results ) )
2855 {
2856 first.addPart( result );
2857 }
2858 return first;
2859 }
2860 else
2861 {
2862 QgsGeos geos( d->geometry.get() );
2863 mLastError.clear();
2864
2865 // GEOS can flip the curve orientation in some circumstances. So record previous orientation and correct if required
2866 const Qgis::AngularDirection prevOrientation = qgsgeometry_cast< const QgsCurve * >( d->geometry.get() )->orientation();
2867
2868 std::unique_ptr< QgsAbstractGeometry > offsetGeom( geos.offsetCurve( distance, segments, joinStyle, miterLimit, &mLastError ) );
2869 if ( !offsetGeom )
2870 {
2871 QgsGeometry result;
2872 result.mLastError = mLastError;
2873 return result;
2874 }
2875
2876 if ( const QgsCurve *offsetCurve = qgsgeometry_cast< const QgsCurve * >( offsetGeom.get() ) )
2877 {
2878 const Qgis::AngularDirection newOrientation = offsetCurve->orientation();
2879 if ( newOrientation != prevOrientation )
2880 {
2881 // GEOS has flipped line orientation, flip it back
2882 std::unique_ptr< QgsAbstractGeometry > flipped( offsetCurve->reversed() );
2883 offsetGeom = std::move( flipped );
2884 }
2885 }
2886 return QgsGeometry( std::move( offsetGeom ) );
2887 }
2888}
2889
2890QgsGeometry QgsGeometry::singleSidedBuffer( double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle, double miterLimit ) const
2891{
2892 if ( !d->geometry || type() != Qgis::GeometryType::Line )
2893 {
2894 return QgsGeometry();
2895 }
2896
2897 if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
2898 {
2899 const QVector<QgsGeometry> parts = asGeometryCollection();
2900 QVector<QgsGeometry> results;
2901 results.reserve( parts.count() );
2902 for ( const QgsGeometry &part : parts )
2903 {
2904 QgsGeometry result = part.singleSidedBuffer( distance, segments, side, joinStyle, miterLimit );
2905 if ( !result.isNull() )
2906 results << result;
2907 }
2908 if ( results.isEmpty() )
2909 return QgsGeometry();
2910
2911 QgsGeometry first = results.takeAt( 0 );
2912 for ( const QgsGeometry &result : std::as_const( results ) )
2913 {
2914 first.addPart( result );
2915 }
2916 return first;
2917 }
2918 else
2919 {
2920 QgsGeos geos( d->geometry.get() );
2921 mLastError.clear();
2922 std::unique_ptr< QgsAbstractGeometry > bufferGeom = geos.singleSidedBuffer( distance, segments, side, joinStyle, miterLimit, &mLastError );
2923 if ( !bufferGeom )
2924 {
2925 QgsGeometry result;
2926 result.mLastError = mLastError;
2927 return result;
2928 }
2929 return QgsGeometry( std::move( bufferGeom ) );
2930 }
2931}
2932
2933QgsGeometry QgsGeometry::taperedBuffer( double startWidth, double endWidth, int segments ) const
2934{
2935 QgsInternalGeometryEngine engine( *this );
2936
2937 return engine.taperedBuffer( startWidth, endWidth, segments );
2938}
2939
2941{
2942 QgsInternalGeometryEngine engine( *this );
2943
2944 return engine.variableWidthBufferByM( segments );
2945}
2946
2947QgsGeometry QgsGeometry::extendLine( double startDistance, double endDistance, double startDeflection, double endDeflection ) const
2948{
2949 if ( !d->geometry || type() != Qgis::GeometryType::Line )
2950 {
2951 return QgsGeometry();
2952 }
2953
2954 if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
2955 {
2956 const QVector<QgsGeometry> parts = asGeometryCollection();
2957 QVector<QgsGeometry> results;
2958 results.reserve( parts.count() );
2959 for ( const QgsGeometry &part : parts )
2960 {
2961 QgsGeometry result = part.extendLine( startDistance, endDistance, startDeflection, endDeflection );
2962 if ( !result.isNull() )
2963 results << result;
2964 }
2965 if ( results.isEmpty() )
2966 return QgsGeometry();
2967
2968 QgsGeometry first = results.takeAt( 0 );
2969 for ( const QgsGeometry &result : std::as_const( results ) )
2970 {
2971 first.addPart( result );
2972 }
2973 return first;
2974 }
2975 else
2976 {
2977 QgsLineString *line = qgsgeometry_cast< QgsLineString * >( d->geometry.get() );
2978 if ( !line )
2979 return QgsGeometry();
2980
2981 std::unique_ptr< QgsLineString > newLine( line->clone() );
2982 newLine->extend( startDistance, endDistance, startDeflection, endDeflection );
2983 return QgsGeometry( std::move( newLine ) );
2984 }
2985}
2986
2987QgsGeometry QgsGeometry::simplify( double tolerance, QgsFeedback *feedback ) const
2988{
2989 if ( !d->geometry )
2990 {
2991 return QgsGeometry();
2992 }
2993
2994 QgsGeos geos( d->geometry.get() );
2995 mLastError.clear();
2996 std::unique_ptr< QgsAbstractGeometry > simplifiedGeom( geos.simplify( tolerance, &mLastError, feedback ) );
2997 if ( !simplifiedGeom )
2998 {
2999 QgsGeometry result;
3000 result.mLastError = mLastError;
3001 return result;
3002 }
3003 return QgsGeometry( std::move( simplifiedGeom ) );
3004}
3005
3006QgsGeometry QgsGeometry::densifyByCount( int extraNodesPerSegment ) const
3007{
3008 QgsInternalGeometryEngine engine( *this );
3009
3010 return engine.densifyByCount( extraNodesPerSegment );
3011}
3012
3014{
3015 QgsInternalGeometryEngine engine( *this );
3016
3017 return engine.densifyByDistance( distance );
3018}
3019
3020QgsGeometry QgsGeometry::convertToCurves( double distanceTolerance, double angleTolerance ) const
3021{
3022 QgsInternalGeometryEngine engine( *this );
3023
3024 return engine.convertToCurves( distanceTolerance, angleTolerance );
3025}
3026
3028{
3029 if ( !d->geometry )
3030 {
3031 return QgsGeometry();
3032 }
3033
3034 // avoid calling geos for trivial point centroids
3035 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::Point )
3036 {
3037 QgsGeometry c = *this;
3038 c.get()->dropZValue();
3039 c.get()->dropMValue();
3040 return c;
3041 }
3042
3043 QgsGeos geos( d->geometry.get() );
3044
3045 mLastError.clear();
3046 QgsGeometry result( geos.centroid( &mLastError ) );
3047 result.mLastError = mLastError;
3048 return result;
3049}
3050
3052{
3053 if ( !d->geometry )
3054 {
3055 return QgsGeometry();
3056 }
3057
3058 QgsGeos geos( d->geometry.get() );
3059
3060 mLastError.clear();
3061 QgsGeometry result( geos.pointOnSurface( &mLastError ) );
3062 result.mLastError = mLastError;
3063 return result;
3064}
3065
3066QgsGeometry QgsGeometry::poleOfInaccessibility( double precision, double *distanceToBoundary ) const
3067{
3068 QgsInternalGeometryEngine engine( *this );
3069
3070 return engine.poleOfInaccessibility( precision, distanceToBoundary );
3071}
3072
3073QgsGeometry QgsGeometry::largestEmptyCircle( double tolerance, const QgsGeometry &boundary ) const
3074{
3075 if ( !d->geometry )
3076 {
3077 return QgsGeometry();
3078 }
3079
3080 QgsGeos geos( d->geometry.get() );
3081
3082 mLastError.clear();
3083 QgsGeometry result( geos.largestEmptyCircle( tolerance, boundary.constGet(), &mLastError ) );
3084 result.mLastError = mLastError;
3085 return result;
3086}
3087
3089{
3090 if ( !d->geometry )
3091 {
3092 return QgsGeometry();
3093 }
3094
3095 QgsGeos geos( d->geometry.get() );
3096
3097 mLastError.clear();
3098 QgsGeometry result( geos.minimumWidth( &mLastError ) );
3099 result.mLastError = mLastError;
3100 return result;
3101}
3102
3104{
3105 if ( !d->geometry )
3106 {
3107 return std::numeric_limits< double >::quiet_NaN();
3108 }
3109
3110 QgsGeos geos( d->geometry.get() );
3111
3112 mLastError.clear();
3113 return geos.minimumClearance( &mLastError );
3114}
3115
3117{
3118 if ( !d->geometry )
3119 {
3120 return QgsGeometry();
3121 }
3122
3123 QgsGeos geos( d->geometry.get() );
3124
3125 mLastError.clear();
3126 QgsGeometry result( geos.minimumClearanceLine( &mLastError ) );
3127 result.mLastError = mLastError;
3128 return result;
3129}
3130
3132{
3133 if ( !d->geometry )
3134 {
3135 return QgsGeometry();
3136 }
3137 QgsGeos geos( d->geometry.get() );
3138 mLastError.clear();
3139 std::unique_ptr< QgsAbstractGeometry > cHull( geos.convexHull( &mLastError ) );
3140 if ( !cHull )
3141 {
3142 QgsGeometry geom;
3143 geom.mLastError = mLastError;
3144 return geom;
3145 }
3146 return QgsGeometry( std::move( cHull ) );
3147}
3148
3149QgsGeometry QgsGeometry::concaveHull( double targetPercent, bool allowHoles, QgsFeedback *feedback ) const
3150{
3151 if ( !d->geometry )
3152 {
3153 return QgsGeometry();
3154 }
3155 QgsGeos geos( d->geometry.get() );
3156 mLastError.clear();
3157 std::unique_ptr< QgsAbstractGeometry > concaveHull( geos.concaveHull( targetPercent, allowHoles, &mLastError, feedback ) );
3158 if ( !concaveHull )
3159 {
3160 QgsGeometry geom;
3161 geom.mLastError = mLastError;
3162 return geom;
3163 }
3164 return QgsGeometry( std::move( concaveHull ) );
3165}
3166
3167QgsGeometry QgsGeometry::concaveHullOfPolygons( double lengthRatio, bool allowHoles, bool isTight, QgsFeedback *feedback ) const
3168{
3169 if ( !d->geometry )
3170 {
3171 return QgsGeometry();
3172 }
3173
3175 {
3176 QgsGeometry geom;
3177 geom.mLastError = u"Only Polygon or MultiPolygon geometries are supported"_s;
3178 return geom;
3179 }
3180
3181 QgsGeos geos( d->geometry.get() );
3182 mLastError.clear();
3183 std::unique_ptr< QgsAbstractGeometry > concaveHull( geos.concaveHullOfPolygons( lengthRatio, allowHoles, isTight, &mLastError, feedback ) );
3184 if ( !concaveHull )
3185 {
3186 QgsGeometry geom;
3187 geom.mLastError = mLastError;
3188 return geom;
3189 }
3190 return QgsGeometry( std::move( concaveHull ) );
3191}
3192
3193QgsGeometry QgsGeometry::voronoiDiagram( const QgsGeometry &extent, double tolerance, bool edgesOnly ) const
3194{
3195 if ( !d->geometry )
3196 {
3197 return QgsGeometry();
3198 }
3199
3200 QgsGeos geos( d->geometry.get() );
3201 mLastError.clear();
3202 QgsGeometry result = QgsGeometry( geos.voronoiDiagram( extent.constGet(), tolerance, edgesOnly, &mLastError ) );
3203 result.mLastError = mLastError;
3204 return result;
3205}
3206
3207QgsGeometry QgsGeometry::delaunayTriangulation( double tolerance, bool edgesOnly ) const
3208{
3209 if ( !d->geometry )
3210 {
3211 return QgsGeometry();
3212 }
3213
3214 QgsGeos geos( d->geometry.get() );
3215 mLastError.clear();
3216 QgsGeometry result = QgsGeometry( geos.delaunayTriangulation( tolerance, edgesOnly ) );
3217 result.mLastError = mLastError;
3218 return result;
3219}
3220
3222{
3223 if ( !d->geometry )
3224 {
3225 return QgsGeometry();
3226 }
3227
3228 QgsGeos geos( d->geometry.get() );
3229 mLastError.clear();
3230 QgsGeometry result( geos.constrainedDelaunayTriangulation() );
3231 result.mLastError = mLastError;
3232 return result;
3233}
3234
3236{
3237 if ( !d->geometry )
3238 {
3239 return QgsGeometry();
3240 }
3241
3242 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::GeometryCollection
3243 && QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::MultiPolygon
3244 && QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::Polygon )
3245 return QgsGeometry();
3246
3247 QgsGeos geos( d->geometry.get() );
3248 mLastError.clear();
3249 const QgsGeometry result = QgsGeometry( geos.unionCoverage( &mLastError ) );
3250 result.mLastError = mLastError;
3251 return result;
3252}
3253
3255{
3256 if ( !d->geometry )
3257 {
3259 }
3260
3261 QgsGeos geos( d->geometry.get() );
3262 mLastError.clear();
3263 std::unique_ptr< QgsAbstractGeometry > invalidEdgesGeom;
3264
3265 const Qgis::CoverageValidityResult result = geos.validateCoverage( gapWidth, invalidEdges ? &invalidEdgesGeom : nullptr, &mLastError );
3266
3267 if ( invalidEdges && invalidEdgesGeom )
3268 *invalidEdges = QgsGeometry( std::move( invalidEdgesGeom ) );
3269
3270 return result;
3271}
3272
3273QgsGeometry QgsGeometry::simplifyCoverageVW( double tolerance, bool preserveBoundary ) const
3274{
3275 if ( !d->geometry )
3276 {
3277 return QgsGeometry();
3278 }
3279
3280 QgsGeos geos( d->geometry.get() );
3281 mLastError.clear();
3282 QgsGeometry result( geos.simplifyCoverageVW( tolerance, preserveBoundary, &mLastError ) );
3283 result.mLastError = mLastError;
3284 return result;
3285}
3286
3288{
3289 if ( !d->geometry )
3290 {
3291 return QgsGeometry();
3292 }
3293
3294 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::GeometryCollection
3295 && QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::MultiPolygon
3296 && QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::Polygon )
3297 return QgsGeometry();
3298
3299 QgsGeos geos( d->geometry.get() );
3300 mLastError.clear();
3301 const QgsGeometry result( geos.cleanCoverage( parameters, &mLastError, feedback ) );
3302 result.mLastError = mLastError;
3303 return result;
3304}
3305
3307{
3308 if ( !d->geometry )
3309 {
3310 return QgsGeometry();
3311 }
3312
3313 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::GeometryCollection
3314 && QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::MultiPolygon
3315 && QgsWkbTypes::flatType( d->geometry->wkbType() ) != Qgis::WkbType::Polygon )
3316 return QgsGeometry();
3317
3318 QgsGeos geos( d->geometry.get() );
3319 mLastError.clear();
3320 const QgsGeometry result( geos.extractCoverageEdges( edgeType, &mLastError, feedback ) );
3321 result.mLastError = mLastError;
3322 return result;
3323}
3324
3326{
3327 if ( !d->geometry )
3328 {
3329 return QgsGeometry();
3330 }
3331
3332 QgsGeos geos( d->geometry.get() );
3333 mLastError.clear();
3334 QgsGeometry result( geos.node( &mLastError ) );
3335 result.mLastError = mLastError;
3336 return result;
3337}
3338
3340{
3341 if ( !d->geometry )
3342 {
3343 return QgsGeometry();
3344 }
3345
3346 QgsGeos geos( d->geometry.get() );
3347 mLastError.clear();
3348 QgsGeometry result( geos.sharedPaths( other.constGet(), &mLastError ) );
3349 result.mLastError = mLastError;
3350 return result;
3351}
3352
3353QgsGeometry QgsGeometry::subdivide( int maxNodes, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
3354{
3355 if ( !d->geometry )
3356 {
3357 return QgsGeometry();
3358 }
3359
3360 const QgsAbstractGeometry *geom = d->geometry.get();
3361 std::unique_ptr< QgsAbstractGeometry > segmentizedCopy;
3362 if ( QgsWkbTypes::isCurvedType( d->geometry->wkbType() ) )
3363 {
3364 segmentizedCopy.reset( d->geometry->segmentize() );
3365 geom = segmentizedCopy.get();
3366 }
3367
3368 QgsGeos geos( geom );
3369 mLastError.clear();
3370 std::unique_ptr< QgsAbstractGeometry > result( geos.subdivide( maxNodes, &mLastError, parameters, feedback ) );
3371 if ( !result )
3372 {
3373 QgsGeometry geom;
3374 geom.mLastError = mLastError;
3375 return geom;
3376 }
3377 return QgsGeometry( std::move( result ) );
3378}
3379
3381{
3382 if ( !d->geometry )
3383 {
3384 return QgsGeometry();
3385 }
3386
3387 QgsGeometry line = *this;
3389 return QgsGeometry();
3390 else if ( type() == Qgis::GeometryType::Polygon )
3391 {
3392 line = QgsGeometry( d->geometry->boundary() );
3393 }
3394
3395 const QgsCurve *curve = nullptr;
3397 {
3398 // if multi part, iterate through parts to find target part
3399 for ( int part = 0; part < collection->numGeometries(); ++part )
3400 {
3401 const QgsCurve *candidate = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( part ) );
3402 if ( !candidate )
3403 continue;
3404 const double candidateLength = candidate->length();
3405 if ( candidateLength >= distance )
3406 {
3407 curve = candidate;
3408 break;
3409 }
3410
3411 distance -= candidateLength;
3412 }
3413 }
3414 else
3415 {
3417 }
3418 if ( !curve )
3419 return QgsGeometry();
3420
3421 std::unique_ptr< QgsPoint > result( curve->interpolatePoint( distance ) );
3422 if ( !result )
3423 {
3424 return QgsGeometry();
3425 }
3426 return QgsGeometry( std::move( result ) );
3427}
3428
3429double QgsGeometry::lineLocatePoint( const QgsGeometry &point ) const
3430{
3431 if ( type() != Qgis::GeometryType::Line )
3432 return -1;
3433
3435 return -1;
3436
3437 QgsGeometry segmentized = *this;
3439 {
3440 segmentized = QgsGeometry( static_cast< QgsCurve * >( d->geometry.get() )->segmentize() );
3441 }
3442
3443 QgsGeos geos( d->geometry.get() );
3444 mLastError.clear();
3445 return geos.lineLocatePoint( *( static_cast< QgsPoint * >( point.d->geometry.get() ) ), &mLastError );
3446}
3447
3449{
3450 if ( !d->geometry || d->geometry->isEmpty() )
3451 return 0.0;
3452
3453 const QgsAbstractGeometry *geom = d->geometry->simplifiedTypeRef();
3455 return 0.0;
3456
3457 // always operate on segmentized geometries
3458 QgsGeometry segmentized = *this;
3459 if ( QgsWkbTypes::isCurvedType( geom->wkbType() ) )
3460 {
3461 segmentized = QgsGeometry( static_cast< const QgsCurve * >( geom )->segmentize() );
3462 }
3463
3464 QgsVertexId previous;
3465 QgsVertexId next;
3466 if ( !QgsGeometryUtils::verticesAtDistance( *segmentized.constGet(), distance, previous, next ) )
3467 return 0.0;
3468
3469 if ( previous == next )
3470 {
3471 // distance coincided exactly with a vertex
3472 QgsVertexId v2 = previous;
3473 QgsVertexId v1;
3474 QgsVertexId v3;
3475 segmentized.constGet()->adjacentVertices( v2, v1, v3 );
3476 if ( v1.isValid() && v3.isValid() )
3477 {
3478 QgsPoint p1 = segmentized.constGet()->vertexAt( v1 );
3479 QgsPoint p2 = segmentized.constGet()->vertexAt( v2 );
3480 QgsPoint p3 = segmentized.constGet()->vertexAt( v3 );
3481 double angle1 = QgsGeometryUtilsBase::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
3482 double angle2 = QgsGeometryUtilsBase::lineAngle( p2.x(), p2.y(), p3.x(), p3.y() );
3483 return QgsGeometryUtilsBase::averageAngle( angle1, angle2 );
3484 }
3485 else if ( v3.isValid() )
3486 {
3487 QgsPoint p1 = segmentized.constGet()->vertexAt( v2 );
3488 QgsPoint p2 = segmentized.constGet()->vertexAt( v3 );
3489 return QgsGeometryUtilsBase::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
3490 }
3491 else
3492 {
3493 QgsPoint p1 = segmentized.constGet()->vertexAt( v1 );
3494 QgsPoint p2 = segmentized.constGet()->vertexAt( v2 );
3495 return QgsGeometryUtilsBase::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
3496 }
3497 }
3498 else
3499 {
3500 QgsPoint p1 = segmentized.constGet()->vertexAt( previous );
3501 QgsPoint p2 = segmentized.constGet()->vertexAt( next );
3502 return QgsGeometryUtilsBase::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
3503 }
3504}
3505
3506QgsGeometry QgsGeometry::intersection( const QgsGeometry &geometry, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
3507{
3508 if ( !d->geometry || geometry.isNull() )
3509 {
3510 return QgsGeometry();
3511 }
3512
3513 QgsGeos geos( d->geometry.get() );
3514
3515 mLastError.clear();
3516 std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.intersection( geometry.d->geometry.get(), &mLastError, parameters, feedback ) );
3517
3518 if ( !resultGeom )
3519 {
3520 QgsGeometry geom;
3521 geom.mLastError = mLastError;
3522 return geom;
3523 }
3524
3525 return QgsGeometry( std::move( resultGeom ) );
3526}
3527
3528QgsGeometry QgsGeometry::combine( const QgsGeometry &geometry, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
3529{
3530 if ( !d->geometry || geometry.isNull() )
3531 {
3532 return QgsGeometry();
3533 }
3534
3535 QgsGeos geos( d->geometry.get() );
3536 mLastError.clear();
3537 std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.combine( geometry.d->geometry.get(), &mLastError, parameters, feedback ) );
3538 if ( !resultGeom )
3539 {
3540 QgsGeometry geom;
3541 geom.mLastError = mLastError;
3542 return geom;
3543 }
3544 return QgsGeometry( std::move( resultGeom ) );
3545}
3546
3548{
3549 if ( !d->geometry )
3550 {
3551 return QgsGeometry();
3552 }
3553
3554 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::LineString )
3555 {
3556 // special case - a single linestring was passed
3557 return QgsGeometry( *this );
3558 }
3559
3560 QgsGeos geos( d->geometry.get() );
3561 mLastError.clear();
3562 QgsGeometry result( geos.mergeLines( &mLastError, parameters ) );
3563 result.mLastError = mLastError;
3564 return result;
3565}
3566
3567QgsGeometry QgsGeometry::difference( const QgsGeometry &geometry, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
3568{
3569 if ( !d->geometry || geometry.isNull() )
3570 {
3571 return QgsGeometry();
3572 }
3573
3574 QgsGeos geos( d->geometry.get() );
3575
3576 mLastError.clear();
3577 std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.difference( geometry.d->geometry.get(), &mLastError, parameters, feedback ) );
3578 if ( !resultGeom )
3579 {
3580 QgsGeometry geom;
3581 geom.mLastError = mLastError;
3582 return geom;
3583 }
3584 return QgsGeometry( std::move( resultGeom ) );
3585}
3586
3587QgsGeometry QgsGeometry::symDifference( const QgsGeometry &geometry, const QgsGeometryParameters &parameters, QgsFeedback *feedback ) const
3588{
3589 if ( !d->geometry || geometry.isNull() )
3590 {
3591 return QgsGeometry();
3592 }
3593
3594 QgsGeos geos( d->geometry.get() );
3595
3596 mLastError.clear();
3597 std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.symDifference( geometry.d->geometry.get(), &mLastError, parameters, feedback ) );
3598 if ( !resultGeom )
3599 {
3600 QgsGeometry geom;
3601 geom.mLastError = mLastError;
3602 return geom;
3603 }
3604 return QgsGeometry( std::move( resultGeom ) );
3605}
3606
3608{
3609 QgsInternalGeometryEngine engine( *this );
3610
3611 return engine.extrude( x, y );
3612}
3613
3615
3616QVector<QgsPointXY> QgsGeometry::randomPointsInPolygon( int count, const std::function< bool( const QgsPointXY & ) > &acceptPoint, unsigned long seed, QgsFeedback *feedback, int maxTriesPerPoint ) const
3617{
3619 return QVector< QgsPointXY >();
3620
3621 QgsInternalGeometryEngine engine( *this );
3622 const QVector<QgsPointXY> res = engine.randomPointsInPolygon( count, acceptPoint, seed, feedback, maxTriesPerPoint );
3623 mLastError = engine.lastError();
3624 return res;
3625}
3626
3627QVector<QgsPointXY> QgsGeometry::randomPointsInPolygon( int count, unsigned long seed, QgsFeedback *feedback ) const
3628{
3630 return QVector< QgsPointXY >();
3631
3632 QgsInternalGeometryEngine engine( *this );
3633 const QVector<QgsPointXY> res = engine.randomPointsInPolygon( count, []( const QgsPointXY & ) { return true; }, seed, feedback, 0 );
3634 mLastError = engine.lastError();
3635 return res;
3636}
3638
3640{
3641 return d->geometry ? d->geometry->wkbSize( flags ) : 0;
3642}
3643
3645{
3646 return d->geometry ? d->geometry->asWkb( flags ) : QByteArray();
3647}
3648
3649QVector<QgsGeometry> QgsGeometry::asGeometryCollection() const
3650{
3651 QVector<QgsGeometry> geometryList;
3652 if ( !d->geometry )
3653 {
3654 return geometryList;
3655 }
3656
3658 if ( gc )
3659 {
3660 int numGeom = gc->numGeometries();
3661 geometryList.reserve( numGeom );
3662 for ( int i = 0; i < numGeom; ++i )
3663 {
3664 geometryList.append( QgsGeometry( gc->geometryN( i )->clone() ) );
3665 }
3666 }
3667 else //a singlepart geometry
3668 {
3669 geometryList.append( *this );
3670 }
3671
3672 return geometryList;
3673}
3674
3676{
3677 QgsPointXY point = asPoint();
3678 return point.toQPointF();
3679}
3680
3682{
3683 const QgsAbstractGeometry *part = constGet();
3684
3685 // if a geometry collection, get first part only
3687 {
3688 if ( collection->numGeometries() > 0 )
3689 part = collection->geometryN( 0 );
3690 else
3691 return QPolygonF();
3692 }
3693
3694 if ( const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( part ) )
3695 return curve->asQPolygonF();
3696 else if ( const QgsCurvePolygon *polygon = qgsgeometry_cast< const QgsCurvePolygon * >( part ) )
3697 return polygon->exteriorRing() ? polygon->exteriorRing()->asQPolygonF() : QPolygonF();
3698 return QPolygonF();
3699}
3700
3701bool QgsGeometry::deleteRing( int ringNum, int partNum )
3702{
3703 if ( !d->geometry )
3704 {
3705 return false;
3706 }
3707
3708 detach();
3709 bool ok = QgsGeometryEditUtils::deleteRing( d->geometry.get(), ringNum, partNum );
3710 return ok;
3711}
3712
3713bool QgsGeometry::deletePart( int partNum )
3714{
3715 if ( !d->geometry )
3716 {
3717 return false;
3718 }
3719
3720 if ( !isMultipart() && partNum < 1 )
3721 {
3722 set( nullptr );
3723 return true;
3724 }
3725
3726 detach();
3727 bool ok = QgsGeometryEditUtils::deletePart( d->geometry.get(), partNum );
3728 return ok;
3729}
3730
3731Qgis::GeometryOperationResult QgsGeometry::avoidIntersectionsV2( const QList<QgsVectorLayer *> &avoidIntersectionsLayers, const QHash<QgsVectorLayer *, QSet<QgsFeatureId> > &ignoreFeatures )
3732{
3733 if ( !d->geometry )
3734 {
3736 }
3737
3738 Qgis::WkbType geomTypeBeforeModification = wkbType();
3739
3740 bool haveInvalidGeometry = false;
3741 bool geomModified = false;
3742
3743 std::unique_ptr< QgsAbstractGeometry > diffGeom = QgsGeometryEditUtils::avoidIntersections( *( d->geometry ), avoidIntersectionsLayers, haveInvalidGeometry, ignoreFeatures );
3744 if ( diffGeom )
3745 {
3746 reset( std::move( diffGeom ) );
3747 geomModified = true;
3748 }
3749
3750 if ( geomTypeBeforeModification != wkbType() )
3752 if ( haveInvalidGeometry )
3754 if ( !geomModified )
3756
3758}
3759
3791
3792QgsGeometry QgsGeometry::makeValid( Qgis::MakeValidMethod method, bool keepCollapsed, QgsFeedback *feedback ) const
3793{
3794 if ( !d->geometry )
3795 return QgsGeometry();
3796
3797 mLastError.clear();
3798 QgsGeos geos( d->geometry.get() );
3799 std::unique_ptr< QgsAbstractGeometry > g( geos.makeValid( method, keepCollapsed, &mLastError, feedback ) );
3800
3801 QgsGeometry result = QgsGeometry( std::move( g ) );
3802 result.mLastError = mLastError;
3803 return result;
3804}
3805
3810
3812{
3813 if ( !d->geometry )
3814 {
3816 }
3817
3818 if ( isMultipart() )
3819 {
3820 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( d->geometry.get() );
3821 const QgsAbstractGeometry *g = collection->geometryN( 0 );
3823 {
3824 return cp->exteriorRing() ? cp->exteriorRing()->orientation() : Qgis::AngularDirection::NoOrientation;
3825 }
3826 }
3827 else
3828 {
3829 if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( d->geometry.get() ) )
3830 {
3831 return cp->exteriorRing() ? cp->exteriorRing()->orientation() : Qgis::AngularDirection::NoOrientation;
3832 }
3833 }
3834
3836}
3837
3839{
3840 if ( !d->geometry )
3841 return QgsGeometry();
3842
3843 if ( isMultipart() )
3844 {
3845 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( d->geometry.get() );
3846 std::unique_ptr< QgsGeometryCollection > newCollection( collection->createEmptyWithSameType() );
3847 newCollection->reserve( collection->numGeometries() );
3848 for ( int i = 0; i < collection->numGeometries(); ++i )
3849 {
3850 const QgsAbstractGeometry *g = collection->geometryN( i );
3852 {
3853 std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
3854 corrected->forceClockwise();
3855 newCollection->addGeometry( corrected.release() );
3856 }
3857 else
3858 {
3859 newCollection->addGeometry( g->clone() );
3860 }
3861 }
3862 return QgsGeometry( std::move( newCollection ) );
3863 }
3864 else
3865 {
3866 if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( d->geometry.get() ) )
3867 {
3868 std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
3869 corrected->forceClockwise();
3870 return QgsGeometry( std::move( corrected ) );
3871 }
3872 else
3873 {
3874 // not a curve polygon, so return unchanged
3875 return *this;
3876 }
3877 }
3878}
3879
3881{
3882 if ( !d->geometry )
3883 return QgsGeometry();
3884
3885 if ( isMultipart() )
3886 {
3887 const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( d->geometry.get() );
3888 std::unique_ptr< QgsGeometryCollection > newCollection( collection->createEmptyWithSameType() );
3889 newCollection->reserve( collection->numGeometries() );
3890 for ( int i = 0; i < collection->numGeometries(); ++i )
3891 {
3892 const QgsAbstractGeometry *g = collection->geometryN( i );
3894 {
3895 std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
3896 corrected->forceCounterClockwise();
3897 newCollection->addGeometry( corrected.release() );
3898 }
3899 else
3900 {
3901 newCollection->addGeometry( g->clone() );
3902 }
3903 }
3904 return QgsGeometry( std::move( newCollection ) );
3905 }
3906 else
3907 {
3908 if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( d->geometry.get() ) )
3909 {
3910 std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
3911 corrected->forceCounterClockwise();
3912 return QgsGeometry( std::move( corrected ) );
3913 }
3914 else
3915 {
3916 // not a curve polygon, so return unchanged
3917 return *this;
3918 }
3919 }
3920}
3921
3922
3923void QgsGeometry::validateGeometry( QVector<QgsGeometry::Error> &errors, const Qgis::GeometryValidationEngine method, const Qgis::GeometryValidityFlags flags ) const
3924{
3925 errors.clear();
3926 if ( !d->geometry )
3927 return;
3928
3929 // avoid expensive calcs for trivial point geometries
3930 if ( QgsWkbTypes::geometryType( d->geometry->wkbType() ) == Qgis::GeometryType::Point )
3931 {
3932 return;
3933 }
3934
3935 switch ( method )
3936 {
3938 QgsGeometryValidator::validateGeometry( *this, errors, method );
3939 return;
3940
3942 {
3943 QgsGeos geos( d->geometry.get(), 0, Qgis::GeosCreationFlags() );
3944 QString error;
3945 QgsGeometry errorLoc;
3946 if ( !geos.isValid( &error, flags & Qgis::GeometryValidityFlag::AllowSelfTouchingHoles, &errorLoc ) )
3947 {
3948 if ( errorLoc.isNull() )
3949 {
3950 errors.append( QgsGeometry::Error( error ) );
3951 }
3952 else
3953 {
3954 const QgsPointXY point = errorLoc.asPoint();
3955 errors.append( QgsGeometry::Error( error, point ) );
3956 }
3957 return;
3958 }
3959 break;
3960 }
3962 {
3963#ifdef HAVE_SFCGAL
3964 QString errorMsg;
3965 QgsGeometry errorLoc;
3966 const QgsSfcgalGeometry sfcgalGeom( d->geometry.get() );
3967 if ( !QgsSfcgalEngine::isValid( sfcgalGeom.sfcgalGeometry().get(), nullptr, &errorMsg, &errorLoc ) )
3968 {
3969 if ( errorLoc.isNull() )
3970 {
3971 errors.append( QgsGeometry::Error( errorMsg ) );
3972 }
3973 else
3974 {
3975 const QgsPointXY point = errorLoc.asPoint();
3976 errors.append( QgsGeometry::Error( errorMsg, point ) );
3977 }
3978 return;
3979 }
3980#else
3981 throw QgsNotSupportedException( u"This operation requires a QGIS installation with SFCGAL support enabled. Please use a version of QGIS that includes SFCGAL."_s );
3982#endif
3983 }
3984 }
3985}
3986
3988{
3989 if ( !d->geometry )
3990 {
3991 return;
3992 }
3993
3994 detach();
3995 d->geometry->normalize();
3996}
3997
3999{
4000 if ( !d->geometry )
4001 {
4002 return false;
4003 }
4004
4005 return d->geometry->isValid( mLastError, flags );
4006}
4007
4009{
4010 if ( !d->geometry )
4011 return false;
4012
4013 QgsGeos geos( d->geometry.get() );
4014 mLastError.clear();
4015 return geos.isSimple( &mLastError );
4016}
4017
4018bool QgsGeometry::isAxisParallelRectangle( double maximumDeviation, bool simpleRectanglesOnly ) const
4019{
4020 if ( !d->geometry )
4021 return false;
4022
4023 QgsInternalGeometryEngine engine( *this );
4024 return engine.isAxisParallelRectangle( maximumDeviation, simpleRectanglesOnly );
4025}
4026
4028{
4030}
4031
4033{
4034 // === WARNING ===
4035 // if tolerance/epsilon value is changed in `geos.isFuzzyEqual` or in implementation of `QgsAbstractGeometry::operator==`, documentation must be updaded accordingly and also changed in expression helper files (resources/function_help/json)
4036
4037 if ( !d->geometry || g.isNull() )
4038 {
4039 return false;
4040 }
4041
4042 // fast check - are they shared copies of the same underlying geometry?
4043 if ( d == g.d )
4044 return true;
4045
4046 // fast check - distinct geometry types?
4047 if ( type() != g.type() )
4048 return false;
4049
4050 mLastError.clear();
4051 switch ( backend )
4052 {
4054 {
4055 // avoid calling geos for trivial point case
4056 if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == Qgis::WkbType::Point && QgsWkbTypes::flatType( g.d->geometry->wkbType() ) == Qgis::WkbType::Point )
4057 return *d->geometry == *g.d->geometry;
4058
4059 // another nice fast check upfront -- if the bounding boxes aren't equal, the geometries themselves can't be equal!
4060 if ( d->geometry->boundingBox() != g.d->geometry->boundingBox() )
4061 return false;
4062
4063 QgsGeos geos( d->geometry.get() );
4064 // fuzzy check call, with near zero epsilon, will behave as an exact comparison
4065 return geos.isFuzzyEqual( g.d->geometry.get(), 1e-8, &mLastError );
4066 }
4067
4069 {
4070 // another nice fast check upfront -- if the bounding boxes aren't equal, the geometries themselves can't be equal!
4071 if ( ( !d->geometry->is3D() && d->geometry->boundingBox() != g.d->geometry->boundingBox() ) || ( d->geometry->is3D() && d->geometry->boundingBox3D() != g.d->geometry->boundingBox3D() ) )
4072 return false;
4073
4074 // slower check - actually test the geometries
4075 return *d->geometry == *g.d->geometry;
4076 }
4077 }
4079}
4080
4082{
4083 if ( !d->geometry || !g.d->geometry )
4084 {
4085 return false;
4086 }
4087
4088 // fast check - are they shared copies of the same underlying geometry?
4089 if ( d == g.d )
4090 return true;
4091
4092 // fast check - distinct geometry types?
4093 if ( type() != g.type() )
4094 return false;
4095
4096 mLastError.clear();
4097 switch ( backend )
4098 {
4100 {
4101 // another nice fast check upfront -- if the bounding boxes aren't equal, the geometries themselves can't be equal!
4102 if ( d->geometry->boundingBox() != g.d->geometry->boundingBox() )
4103 return false;
4104
4105 QgsGeos geos( d->geometry.get() );
4106 return geos.isEqual( g.d->geometry.get(), &mLastError );
4107 }
4108
4110 throw QgsNotSupportedException( u"Geometry backend '%1' is not supported by this function."_s.arg( qgsEnumValueToKey( backend ) ) );
4111 }
4113}
4114
4115bool QgsGeometry::isFuzzyEqual( const QgsGeometry &g, double epsilon, Qgis::GeometryBackend backend ) const
4116{
4117 if ( !d->geometry || g.isNull() )
4118 {
4119 return false;
4120 }
4121
4122 // fast check - are they shared copies of the same underlying geometry?
4123 if ( d == g.d )
4124 return true;
4125
4126 // fast check - distinct geometry types?
4127 if ( type() != g.type() )
4128 return false;
4129
4130 mLastError.clear();
4131 switch ( backend )
4132 {
4134 {
4135 QgsGeos geos( d->geometry.get() );
4136 return geos.isFuzzyEqual( g.d->geometry.get(), epsilon, &mLastError );
4137 }
4138
4140 {
4141 // slower check - actually test the geometries
4142 return d->geometry->fuzzyEqual( *g.d->geometry, epsilon );
4143 }
4144 }
4146}
4147
4148QgsGeometry QgsGeometry::unaryUnion( const QVector<QgsGeometry> &geometries, const QgsGeometryParameters &parameters, QgsFeedback *feedback )
4149{
4150 QgsGeos geos( nullptr );
4151
4152 QString error;
4153 std::unique_ptr< QgsAbstractGeometry > geom( geos.combine( geometries, &error, parameters, feedback ) );
4154 QgsGeometry result( std::move( geom ) );
4155 result.mLastError = error;
4156 return result;
4157}
4158
4159QgsGeometry QgsGeometry::polygonize( const QVector<QgsGeometry> &geometryList )
4160{
4161 QVector<const QgsAbstractGeometry *> geomV2List;
4162 for ( const QgsGeometry &g : geometryList )
4163 {
4164 if ( !( g.isNull() ) )
4165 {
4166 geomV2List.append( g.constGet() );
4167 }
4168 }
4169
4170 QString error;
4171 QgsGeometry result = QgsGeos::polygonize( geomV2List, &error );
4172 result.mLastError = error;
4173 return result;
4174}
4175
4177{
4178 if ( !d->geometry || !requiresConversionToStraightSegments() )
4179 {
4180 return;
4181 }
4182
4183 std::unique_ptr< QgsAbstractGeometry > straightGeom( d->geometry->segmentize( tolerance, toleranceType ) );
4184 reset( std::move( straightGeom ) );
4185}
4186
4188{
4189 if ( !d->geometry )
4190 {
4191 return false;
4192 }
4193
4194 return d->geometry->hasCurvedSegments();
4195}
4196
4198{
4199 if ( !d->geometry )
4200 {
4202 }
4203
4204 detach();
4205 d->geometry->transform( ct, direction, transformZ );
4207}
4208
4209Qgis::GeometryOperationResult QgsGeometry::transform( const QTransform &ct, double zTranslate, double zScale, double mTranslate, double mScale )
4210{
4211 if ( !d->geometry )
4212 {
4214 }
4215
4216 detach();
4217 d->geometry->transform( ct, zTranslate, zScale, mTranslate, mScale );
4219}
4220
4222{
4223 if ( d->geometry )
4224 {
4225 detach();
4226 d->geometry->transform( mtp.transform() );
4227 }
4228}
4229
4231{
4232 if ( !d->geometry || rectangle.isNull() || rectangle.isEmpty() )
4233 {
4234 return QgsGeometry();
4235 }
4236
4237 QgsGeos geos( d->geometry.get() );
4238 mLastError.clear();
4239 std::unique_ptr< QgsAbstractGeometry > resultGeom = geos.clip( rectangle, &mLastError, feedback );
4240 if ( !resultGeom )
4241 {
4242 QgsGeometry result;
4243 result.mLastError = mLastError;
4244 return result;
4245 }
4246 return QgsGeometry( std::move( resultGeom ) );
4247}
4248
4249void QgsGeometry::draw( QPainter &p ) const
4250{
4251 if ( d->geometry )
4252 {
4253 d->geometry->draw( p );
4254 }
4255}
4256
4257static bool vertexIndexInfo( const QgsAbstractGeometry *g, int vertexIndex, int &partIndex, int &ringIndex, int &vertex )
4258{
4259 if ( vertexIndex < 0 )
4260 return false; // clearly something wrong
4261
4263 {
4264 partIndex = 0;
4265 for ( int i = 0; i < geomCollection->numGeometries(); ++i )
4266 {
4267 const QgsAbstractGeometry *part = geomCollection->geometryN( i );
4268
4269 // count total number of vertices in the part
4270 int numPoints = 0;
4271 for ( int k = 0; k < part->ringCount(); ++k )
4272 numPoints += part->vertexCount( 0, k );
4273
4274 if ( vertexIndex < numPoints )
4275 {
4276 int nothing;
4277 return vertexIndexInfo( part, vertexIndex, nothing, ringIndex, vertex ); // set ring_index + index
4278 }
4279 vertexIndex -= numPoints;
4280 partIndex++;
4281 }
4282 }
4283 else if ( const QgsPolyhedralSurface *polySurface = qgsgeometry_cast<const QgsPolyhedralSurface *>( g ) )
4284 {
4285 // PolyhedralSurface: patches are the parts
4286 partIndex = 0;
4287 for ( int i = 0; i < polySurface->numPatches(); ++i )
4288 {
4289 const QgsPolygon *patch = polySurface->patchN( i );
4290 // count total number of vertices in the patch
4291 int numPoints = 0;
4292 for ( int k = 0; k < patch->ringCount(); ++k )
4293 numPoints += patch->vertexCount( 0, k );
4294
4295 if ( vertexIndex < numPoints )
4296 {
4297 int nothing;
4298 return vertexIndexInfo( patch, vertexIndex, nothing, ringIndex, vertex );
4299 }
4300 vertexIndex -= numPoints;
4301 partIndex++;
4302 }
4303 }
4304 else if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast<const QgsCurvePolygon *>( g ) )
4305 {
4306 const QgsCurve *ring = curvePolygon->exteriorRing();
4307 if ( vertexIndex < ring->numPoints() )
4308 {
4309 partIndex = 0;
4310 ringIndex = 0;
4311 vertex = vertexIndex;
4312 return true;
4313 }
4314 vertexIndex -= ring->numPoints();
4315 ringIndex = 1;
4316 for ( int i = 0; i < curvePolygon->numInteriorRings(); ++i )
4317 {
4318 const QgsCurve *ring = curvePolygon->interiorRing( i );
4319 if ( vertexIndex < ring->numPoints() )
4320 {
4321 partIndex = 0;
4322 vertex = vertexIndex;
4323 return true;
4324 }
4325 vertexIndex -= ring->numPoints();
4326 ringIndex += 1;
4327 }
4328 }
4329 else if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
4330 {
4331 if ( vertexIndex < curve->numPoints() )
4332 {
4333 partIndex = 0;
4334 ringIndex = 0;
4335 vertex = vertexIndex;
4336 return true;
4337 }
4338 }
4339 else if ( qgsgeometry_cast<const QgsPoint *>( g ) )
4340 {
4341 if ( vertexIndex == 0 )
4342 {
4343 partIndex = 0;
4344 ringIndex = 0;
4345 vertex = 0;
4346 return true;
4347 }
4348 }
4349
4350 return false;
4351}
4352
4354{
4355 if ( !d->geometry )
4356 {
4357 return false;
4358 }
4359
4360 id.type = Qgis::VertexType::Segment;
4361
4362 bool res = vertexIndexInfo( d->geometry.get(), nr, id.part, id.ring, id.vertex );
4363 if ( !res )
4364 return false;
4365
4366 // now let's find out if it is a straight or circular segment
4367 const QgsAbstractGeometry *g = d->geometry.get();
4369 {
4370 g = geomCollection->geometryN( id.part );
4371 }
4372 else if ( const QgsPolyhedralSurface *polySurface = qgsgeometry_cast<const QgsPolyhedralSurface *>( g ) )
4373 {
4374 g = polySurface->patchN( id.part );
4375 }
4376
4377 if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast<const QgsCurvePolygon *>( g ) )
4378 {
4379 g = id.ring == 0 ? curvePolygon->exteriorRing() : curvePolygon->interiorRing( id.ring - 1 );
4380 }
4381
4382 if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
4383 {
4384 QgsPoint p;
4385 res = curve->pointAt( id.vertex, p, id.type );
4386 if ( !res )
4387 return false;
4388 }
4389
4390 return true;
4391}
4392
4394{
4395 if ( !d->geometry )
4396 {
4397 return -1;
4398 }
4399 return d->geometry->vertexNumberFromVertexId( id );
4400}
4401
4403{
4404 return mLastError;
4405}
4406
4407void QgsGeometry::filterVertices( const std::function<bool( const QgsPoint & )> &filter )
4408{
4409 if ( !d->geometry )
4410 return;
4411
4412 detach();
4413
4414 d->geometry->filterVertices( filter );
4415}
4416
4417void QgsGeometry::transformVertices( const std::function<QgsPoint( const QgsPoint & )> &transform )
4418{
4419 if ( !d->geometry )
4420 return;
4421
4422 detach();
4423
4424 d->geometry->transformVertices( transform );
4425}
4426
4427void QgsGeometry::convertPointList( const QVector<QgsPointXY> &input, QgsPointSequence &output )
4428{
4429 output.clear();
4430 for ( const QgsPointXY &p : input )
4431 {
4432 output.append( QgsPoint( p ) );
4433 }
4434}
4435
4436void QgsGeometry::convertPointList( const QgsPointSequence &input, QVector<QgsPointXY> &output )
4437{
4438 output.clear();
4439 for ( const QgsPoint &p : input )
4440 {
4441 output.append( QgsPointXY( p.x(), p.y() ) );
4442 }
4443}
4444
4445void QgsGeometry::convertPolygon( const QgsPolygon &input, QgsPolygonXY &output )
4446{
4447 output.clear();
4448
4449 auto convertRing = []( const QgsCurve *ring ) -> QgsPolylineXY {
4450 QgsPolylineXY res;
4452 std::unique_ptr< QgsLineString > segmentizedLine;
4453 const QgsLineString *line = nullptr;
4454 if ( doSegmentation )
4455 {
4456 segmentizedLine.reset( ring->curveToLine() );
4457 line = segmentizedLine.get();
4458 }
4459 else
4460 {
4462 if ( !line )
4463 {
4464 return res;
4465 }
4466 }
4467
4468 int nVertices = line->numPoints();
4469 res.resize( nVertices );
4470 QgsPointXY *data = res.data();
4471 const double *xData = line->xData();
4472 const double *yData = line->yData();
4473 for ( int i = 0; i < nVertices; ++i )
4474 {
4475 data->setX( *xData++ );
4476 data->setY( *yData++ );
4477 data++;
4478 }
4479 return res;
4480 };
4481
4482 if ( const QgsCurve *exterior = input.exteriorRing() )
4483 {
4484 output.push_back( convertRing( exterior ) );
4485 }
4486
4487 const int interiorRingCount = input.numInteriorRings();
4488 output.reserve( output.size() + interiorRingCount );
4489 for ( int n = 0; n < interiorRingCount; ++n )
4490 {
4491 output.push_back( convertRing( input.interiorRing( n ) ) );
4492 }
4493}
4494
4496{
4497 return QgsGeometry( std::make_unique< QgsPoint >( point.x(), point.y() ) );
4498}
4499
4500QgsGeometry QgsGeometry::fromQPolygonF( const QPolygonF &polygon )
4501{
4502 std::unique_ptr< QgsLineString > ring( QgsLineString::fromQPolygonF( polygon ) );
4503
4504 if ( polygon.isClosed() )
4505 {
4506 auto poly = std::make_unique< QgsPolygon >();
4507 poly->setExteriorRing( ring.release() );
4508 return QgsGeometry( std::move( poly ) );
4509 }
4510 else
4511 {
4512 return QgsGeometry( std::move( ring ) );
4513 }
4514}
4515
4517{
4519 QgsPolygonXY result;
4520 result << createPolylineFromQPolygonF( polygon );
4521 return result;
4523}
4524
4526{
4527 QgsPolylineXY result;
4528 result.reserve( polygon.count() );
4529 for ( const QPointF &p : polygon )
4530 {
4531 result.append( QgsPointXY( p ) );
4532 }
4533 return result;
4534}
4535
4536bool QgsGeometry::compare( const QgsPolylineXY &p1, const QgsPolylineXY &p2, double epsilon )
4537{
4538 if ( p1.count() != p2.count() )
4539 return false;
4540
4541 for ( int i = 0; i < p1.count(); ++i )
4542 {
4543 if ( !p1.at( i ).compare( p2.at( i ), epsilon ) )
4544 return false;
4545 }
4546 return true;
4547}
4548
4549bool QgsGeometry::compare( const QgsPolygonXY &p1, const QgsPolygonXY &p2, double epsilon )
4550{
4551 if ( p1.count() != p2.count() )
4552 return false;
4553
4554 for ( int i = 0; i < p1.count(); ++i )
4555 {
4556 if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) )
4557 return false;
4558 }
4559 return true;
4560}
4561
4562
4563bool QgsGeometry::compare( const QgsMultiPolygonXY &p1, const QgsMultiPolygonXY &p2, double epsilon )
4564{
4565 if ( p1.count() != p2.count() )
4566 return false;
4567
4568 for ( int i = 0; i < p1.count(); ++i )
4569 {
4570 if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) )
4571 return false;
4572 }
4573 return true;
4574}
4575
4576QgsGeometry QgsGeometry::smooth( const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
4577{
4578 if ( !d->geometry || d->geometry->isEmpty() )
4579 return QgsGeometry();
4580
4581 QgsGeometry geom = *this;
4583 geom = QgsGeometry( d->geometry->segmentize() );
4584
4585 switch ( QgsWkbTypes::flatType( geom.wkbType() ) )
4586 {
4589 //can't smooth a point based geometry
4590 return geom;
4591
4593 {
4595 return QgsGeometry( smoothLine( *lineString, iterations, offset, minimumDistance, maxAngle ) );
4596 }
4597
4599 {
4601
4602 auto resultMultiline = std::make_unique< QgsMultiLineString>();
4603 resultMultiline->reserve( inputMultiLine->numGeometries() );
4604 for ( int i = 0; i < inputMultiLine->numGeometries(); ++i )
4605 {
4606 resultMultiline->addGeometry( smoothLine( *( inputMultiLine->lineStringN( i ) ), iterations, offset, minimumDistance, maxAngle ).release() );
4607 }
4608 return QgsGeometry( std::move( resultMultiline ) );
4609 }
4610
4612 {
4614 return QgsGeometry( smoothPolygon( *poly, iterations, offset, minimumDistance, maxAngle ) );
4615 }
4616
4618 {
4620
4621 auto resultMultiPoly = std::make_unique< QgsMultiPolygon >();
4622 resultMultiPoly->reserve( inputMultiPoly->numGeometries() );
4623 for ( int i = 0; i < inputMultiPoly->numGeometries(); ++i )
4624 {
4625 resultMultiPoly->addGeometry( smoothPolygon( *( inputMultiPoly->polygonN( i ) ), iterations, offset, minimumDistance, maxAngle ).release() );
4626 }
4627 return QgsGeometry( std::move( resultMultiPoly ) );
4628 }
4629
4631 default:
4632 return QgsGeometry( *this );
4633 }
4634}
4635
4636std::unique_ptr< QgsLineString > smoothCurve( const QgsLineString &line, const unsigned int iterations, const double offset, double squareDistThreshold, double maxAngleRads, bool isRing )
4637{
4638 auto result = std::make_unique< QgsLineString >( line );
4639 QgsPointSequence outputLine;
4640 for ( unsigned int iteration = 0; iteration < iterations; ++iteration )
4641 {
4642 outputLine.resize( 0 );
4643 outputLine.reserve( 2 * ( result->numPoints() - 1 ) );
4644 bool skipFirst = false;
4645 bool skipLast = false;
4646 if ( isRing )
4647 {
4648 QgsPoint p1 = result->pointN( result->numPoints() - 2 );
4649 QgsPoint p2 = result->pointN( 0 );
4650 QgsPoint p3 = result->pointN( 1 );
4651 double angle = QgsGeometryUtilsBase::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(), p3.x(), p3.y() );
4652 angle = std::fabs( M_PI - angle );
4653 skipFirst = angle > maxAngleRads;
4654 }
4655 for ( int i = 0; i < result->numPoints() - 1; i++ )
4656 {
4657 QgsPoint p1 = result->pointN( i );
4658 QgsPoint p2 = result->pointN( i + 1 );
4659
4660 double angle = M_PI;
4661 if ( i == 0 && isRing )
4662 {
4663 QgsPoint p3 = result->pointN( result->numPoints() - 2 );
4664 angle = QgsGeometryUtilsBase::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(), p3.x(), p3.y() );
4665 }
4666 else if ( i < result->numPoints() - 2 )
4667 {
4668 QgsPoint p3 = result->pointN( i + 2 );
4669 angle = QgsGeometryUtilsBase::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(), p3.x(), p3.y() );
4670 }
4671 else if ( i == result->numPoints() - 2 && isRing )
4672 {
4673 QgsPoint p3 = result->pointN( 1 );
4674 angle = QgsGeometryUtilsBase::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(), p3.x(), p3.y() );
4675 }
4676
4677 skipLast = angle < M_PI - maxAngleRads || angle > M_PI + maxAngleRads;
4678
4679 // don't apply distance threshold to first or last segment
4680 if ( i == 0 || i >= result->numPoints() - 2 || QgsGeometryUtils::sqrDistance2D( p1, p2 ) > squareDistThreshold )
4681 {
4682 if ( !isRing )
4683 {
4684 if ( !skipFirst )
4685 outputLine << ( i == 0 ? result->pointN( i ) : QgsGeometryUtils::interpolatePointOnLine( p1, p2, offset ) );
4686 if ( !skipLast )
4687 outputLine << ( i == result->numPoints() - 2 ? result->pointN( i + 1 ) : QgsGeometryUtils::interpolatePointOnLine( p1, p2, 1.0 - offset ) );
4688 else
4689 outputLine << p2;
4690 }
4691 else
4692 {
4693 // ring
4694 if ( !skipFirst )
4695 outputLine << QgsGeometryUtils::interpolatePointOnLine( p1, p2, offset );
4696 else if ( i == 0 )
4697 outputLine << p1;
4698 if ( !skipLast )
4699 outputLine << QgsGeometryUtils::interpolatePointOnLine( p1, p2, 1.0 - offset );
4700 else
4701 outputLine << p2;
4702 }
4703 }
4704 skipFirst = skipLast;
4705 }
4706
4707 if ( isRing && outputLine.at( 0 ) != outputLine.at( outputLine.count() - 1 ) )
4708 outputLine << outputLine.at( 0 );
4709
4710 result->setPoints( outputLine );
4711 }
4712 return result;
4713}
4714
4715std::unique_ptr<QgsLineString> QgsGeometry::smoothLine( const QgsLineString &line, const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
4716{
4717 double maxAngleRads = maxAngle * M_PI / 180.0;
4718 double squareDistThreshold = minimumDistance > 0 ? minimumDistance * minimumDistance : -1;
4719 return smoothCurve( line, iterations, offset, squareDistThreshold, maxAngleRads, false );
4720}
4721
4722std::unique_ptr<QgsPolygon> QgsGeometry::smoothPolygon( const QgsPolygon &polygon, const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
4723{
4724 double maxAngleRads = maxAngle * M_PI / 180.0;
4725 double squareDistThreshold = minimumDistance > 0 ? minimumDistance * minimumDistance : -1;
4726 auto resultPoly = std::make_unique< QgsPolygon >();
4727
4728 resultPoly->setExteriorRing( smoothCurve( *( static_cast< const QgsLineString *>( polygon.exteriorRing() ) ), iterations, offset, squareDistThreshold, maxAngleRads, true ).release() );
4729
4730 for ( int i = 0; i < polygon.numInteriorRings(); ++i )
4731 {
4732 resultPoly->addInteriorRing( smoothCurve( *( static_cast< const QgsLineString *>( polygon.interiorRing( i ) ) ), iterations, offset, squareDistThreshold, maxAngleRads, true ).release() );
4733 }
4734 return resultPoly;
4735}
4736
4737QgsGeometry QgsGeometry::convertToPoint( bool destMultipart ) const
4738{
4739 switch ( type() )
4740 {
4742 {
4743 bool srcIsMultipart = isMultipart();
4744
4745 if ( ( destMultipart && srcIsMultipart ) || ( !destMultipart && !srcIsMultipart ) )
4746 {
4747 // return a copy of the same geom
4748 return QgsGeometry( *this );
4749 }
4750 if ( destMultipart )
4751 {
4752 // layer is multipart => make a multipoint with a single point
4753 return fromMultiPointXY( QgsMultiPointXY() << asPoint() );
4754 }
4755 else
4756 {
4757 // destination is singlepart => make a single part if possible
4758 QgsMultiPointXY multiPoint = asMultiPoint();
4759 if ( multiPoint.count() == 1 )
4760 {
4761 return fromPointXY( multiPoint[0] );
4762 }
4763 }
4764 return QgsGeometry();
4765 }
4766
4768 {
4769 // only possible if destination is multipart
4770 if ( !destMultipart )
4771 return QgsGeometry();
4772
4773 // input geometry is multipart
4774 if ( isMultipart() )
4775 {
4776 const QgsMultiPolylineXY inputMultiLine = asMultiPolyline();
4777 QgsMultiPointXY multiPoint;
4778 for ( const QgsPolylineXY &l : inputMultiLine )
4779 for ( const QgsPointXY &p : l )
4780 multiPoint << p;
4781 return fromMultiPointXY( multiPoint );
4782 }
4783 // input geometry is not multipart: copy directly the line into a multipoint
4784 else
4785 {
4786 QgsPolylineXY line = asPolyline();
4787 if ( !line.isEmpty() )
4788 return fromMultiPointXY( line );
4789 }
4790 return QgsGeometry();
4791 }
4792
4794 {
4795 // can only transform if destination is multipoint
4796 if ( !destMultipart )
4797 return QgsGeometry();
4798
4799 // input geometry is multipart: make a multipoint from multipolygon
4800 if ( isMultipart() )
4801 {
4802 const QgsMultiPolygonXY multiPolygon = asMultiPolygon();
4803 QgsMultiPointXY multiPoint;
4804 for ( const QgsPolygonXY &poly : multiPolygon )
4805 for ( const QgsPolylineXY &line : poly )
4806 for ( const QgsPointXY &pt : line )
4807 multiPoint << pt;
4808 return fromMultiPointXY( multiPoint );
4809 }
4810 // input geometry is not multipart: make a multipoint from polygon
4811 else
4812 {
4813 const QgsPolygonXY polygon = asPolygon();
4814 QgsMultiPointXY multiPoint;
4815 for ( const QgsPolylineXY &line : polygon )
4816 for ( const QgsPointXY &pt : line )
4817 multiPoint << pt;
4818 return fromMultiPointXY( multiPoint );
4819 }
4820 }
4821
4822 default:
4823 return QgsGeometry();
4824 }
4825}
4826
4827QgsGeometry QgsGeometry::convertToLine( bool destMultipart ) const
4828{
4829 switch ( type() )
4830 {
4832 {
4833 if ( !isMultipart() )
4834 return QgsGeometry();
4835
4836 QgsMultiPointXY multiPoint = asMultiPoint();
4837 if ( multiPoint.count() < 2 )
4838 return QgsGeometry();
4839
4840 if ( destMultipart )
4841 return fromMultiPolylineXY( QgsMultiPolylineXY() << multiPoint );
4842 else
4843 return fromPolylineXY( multiPoint );
4844 }
4845
4847 {
4848 bool srcIsMultipart = isMultipart();
4849
4850 if ( ( destMultipart && srcIsMultipart ) || ( !destMultipart && !srcIsMultipart ) )
4851 {
4852 // return a copy of the same geom
4853 return QgsGeometry( *this );
4854 }
4855 if ( destMultipart )
4856 {
4857 // destination is multipart => makes a multipoint with a single line
4858 QgsPolylineXY line = asPolyline();
4859 if ( !line.isEmpty() )
4860 return fromMultiPolylineXY( QgsMultiPolylineXY() << line );
4861 }
4862 else
4863 {
4864 // destination is singlepart => make a single part if possible
4865 QgsMultiPolylineXY inputMultiLine = asMultiPolyline();
4866 if ( inputMultiLine.count() == 1 )
4867 return fromPolylineXY( inputMultiLine[0] );
4868 }
4869 return QgsGeometry();
4870 }
4871
4873 {
4874 // input geometry is multipolygon
4875 if ( isMultipart() )
4876 {
4877 const QgsMultiPolygonXY multiPolygon = asMultiPolygon();
4878 QgsMultiPolylineXY inputMultiLine;
4879 for ( const QgsPolygonXY &poly : multiPolygon )
4880 for ( const QgsPolylineXY &line : poly )
4881 inputMultiLine << line;
4882
4883 if ( destMultipart )
4884 {
4885 // destination is multipart
4886 return fromMultiPolylineXY( inputMultiLine );
4887 }
4888 else if ( inputMultiLine.count() == 1 )
4889 {
4890 // destination is singlepart => make a single part if possible
4891 return fromPolylineXY( inputMultiLine[0] );
4892 }
4893 }
4894 // input geometry is single polygon
4895 else
4896 {
4897 QgsPolygonXY polygon = asPolygon();
4898 // if polygon has rings
4899 if ( polygon.count() > 1 )
4900 {
4901 // cannot fit a polygon with rings in a single line layer
4902 // TODO: would it be better to remove rings?
4903 if ( destMultipart )
4904 {
4905 const QgsPolygonXY polygon = asPolygon();
4906 QgsMultiPolylineXY inputMultiLine;
4907 inputMultiLine.reserve( polygon.count() );
4908 for ( const QgsPolylineXY &line : polygon )
4909 inputMultiLine << line;
4910 return fromMultiPolylineXY( inputMultiLine );
4911 }
4912 }
4913 // no rings
4914 else if ( polygon.count() == 1 )
4915 {
4916 if ( destMultipart )
4917 {
4918 return fromMultiPolylineXY( polygon );
4919 }
4920 else
4921 {
4922 return fromPolylineXY( polygon[0] );
4923 }
4924 }
4925 }
4926 return QgsGeometry();
4927 }
4928
4929 default:
4930 return QgsGeometry();
4931 }
4932}
4933
4934QgsGeometry QgsGeometry::convertToPolygon( bool destMultipart ) const
4935{
4936 switch ( type() )
4937 {
4939 {
4940 if ( !isMultipart() )
4941 return QgsGeometry();
4942
4943 QgsMultiPointXY multiPoint = asMultiPoint();
4944 if ( multiPoint.count() < 3 )
4945 return QgsGeometry();
4946
4947 if ( multiPoint.last() != multiPoint.first() )
4948 multiPoint << multiPoint.first();
4949
4950 QgsPolygonXY polygon = QgsPolygonXY() << multiPoint;
4951 if ( destMultipart )
4952 return fromMultiPolygonXY( QgsMultiPolygonXY() << polygon );
4953 else
4954 return fromPolygonXY( polygon );
4955 }
4956
4958 {
4959 // input geometry is multiline
4960 if ( isMultipart() )
4961 {
4962 QgsMultiPolylineXY inputMultiLine = asMultiPolyline();
4963 QgsMultiPolygonXY multiPolygon;
4964 for ( QgsMultiPolylineXY::iterator multiLineIt = inputMultiLine.begin(); multiLineIt != inputMultiLine.end(); ++multiLineIt )
4965 {
4966 // do not create polygon for a 1 segment line
4967 if ( ( *multiLineIt ).count() < 3 )
4968 return QgsGeometry();
4969 if ( ( *multiLineIt ).count() == 3 && ( *multiLineIt ).first() == ( *multiLineIt ).last() )
4970 return QgsGeometry();
4971
4972 // add closing node
4973 if ( ( *multiLineIt ).first() != ( *multiLineIt ).last() )
4974 *multiLineIt << ( *multiLineIt ).first();
4975 multiPolygon << ( QgsPolygonXY() << *multiLineIt );
4976 }
4977 // check that polygons were inserted
4978 if ( !multiPolygon.isEmpty() )
4979 {
4980 if ( destMultipart )
4981 {
4982 return fromMultiPolygonXY( multiPolygon );
4983 }
4984 else if ( multiPolygon.count() == 1 )
4985 {
4986 // destination is singlepart => make a single part if possible
4987 return fromPolygonXY( multiPolygon[0] );
4988 }
4989 }
4990 }
4991 // input geometry is single line
4992 else
4993 {
4994 QgsPolylineXY line = asPolyline();
4995
4996 // do not create polygon for a 1 segment line
4997 if ( line.count() < 3 )
4998 return QgsGeometry();
4999 if ( line.count() == 3 && line.first() == line.last() )
5000 return QgsGeometry();
5001
5002 // add closing node
5003 if ( line.first() != line.last() )
5004 line << line.first();
5005
5006 // destination is multipart
5007 if ( destMultipart )
5008 {
5009 return fromMultiPolygonXY( QgsMultiPolygonXY() << ( QgsPolygonXY() << line ) );
5010 }
5011 else
5012 {
5013 return fromPolygonXY( QgsPolygonXY() << line );
5014 }
5015 }
5016 return QgsGeometry();
5017 }
5018
5020 {
5021 bool srcIsMultipart = isMultipart();
5022
5023 if ( ( destMultipart && srcIsMultipart ) || ( !destMultipart && !srcIsMultipart ) )
5024 {
5025 // return a copy of the same geom
5026 return QgsGeometry( *this );
5027 }
5028 if ( destMultipart )
5029 {
5030 // destination is multipart => makes a multipoint with a single polygon
5031 QgsPolygonXY polygon = asPolygon();
5032 if ( !polygon.isEmpty() )
5033 return fromMultiPolygonXY( QgsMultiPolygonXY() << polygon );
5034 }
5035 else
5036 {
5037 QgsMultiPolygonXY multiPolygon = asMultiPolygon();
5038 if ( multiPolygon.count() == 1 )
5039 {
5040 // destination is singlepart => make a single part if possible
5041 return fromPolygonXY( multiPolygon[0] );
5042 }
5043 }
5044 return QgsGeometry();
5045 }
5046
5047 default:
5048 return QgsGeometry();
5049 }
5050}
5051
5052std::unique_ptr<QgsGeometryEngine> QgsGeometry::createGeometryEngine( const QgsAbstractGeometry *geometry, double precision, Qgis::GeosCreationFlags flags )
5053{
5054 return std::make_unique<QgsGeos>( geometry, precision, flags );
5055}
5056
5057QDataStream &operator<<( QDataStream &out, const QgsGeometry &geometry )
5058{
5059 out << geometry.asWkb();
5060 return out;
5061}
5062
5063QDataStream &operator>>( QDataStream &in, QgsGeometry &geometry )
5064{
5065 QByteArray byteArray;
5066 in >> byteArray;
5067 if ( byteArray.isEmpty() )
5068 {
5069 geometry.set( nullptr );
5070 return in;
5071 }
5072
5073 geometry.fromWkb( byteArray );
5074 return in;
5075}
5076
5077
5079{
5080 return mMessage;
5081}
5082
5084{
5085 return mLocation;
5086}
5087
5089{
5090 return mHasLocation;
5091}
5092
5093QgsGeometry QgsGeometry::doChamferFillet( ChamferFilletOperationType op, int vertexIndex, double distance1, double distance2, int segments ) const
5094{
5095 QgsDebugMsgLevel( u"%1 starts: %2"_s.arg( qgsEnumValueToKey( op ) ).arg( asWkt( 2 ) ), 3 );
5096 if ( isNull() )
5097 {
5098 mLastError = u"Operation '%1' needs non-null geometry."_s.arg( qgsEnumValueToKey( op ) );
5099 return QgsGeometry();
5100 }
5101
5102 QgsCurve *curve = nullptr;
5103
5104 int modifiedPart = -1;
5105 int modifiedRing = -1;
5106 QgsVertexId vertexId;
5107 if ( !vertexIdFromVertexNr( vertexIndex, vertexId ) )
5108 {
5109 mLastError = u"Invalid vertex index"_s;
5110 return QgsGeometry();
5111 }
5112 int resolvedVertexIndex = vertexId.vertex;
5113 QgsMultiCurve *inputMultiCurve = nullptr;
5114 QgsMultiSurface *inputMultiSurface = nullptr;
5116
5117 if ( geomType == Qgis::GeometryType::Line )
5118 {
5119 if ( isMultipart() )
5120 {
5121 modifiedPart = vertexId.part;
5122
5123 inputMultiCurve = qgsgeometry_cast<QgsMultiCurve *>( d->geometry.get() );
5124 curve = dynamic_cast<QgsCurve *>( inputMultiCurve->curveN( modifiedPart ) );
5125 }
5126 else
5127 {
5128 curve = dynamic_cast<QgsCurve *>( d->geometry.get() );
5129 }
5130 }
5131 else if ( geomType == Qgis::GeometryType::Polygon )
5132 {
5133 QgsCurvePolygon *poly = nullptr;
5134 if ( isMultipart() )
5135 {
5136 modifiedPart = vertexId.part;
5137 // get part, get ring
5138 inputMultiSurface = qgsgeometry_cast<QgsMultiSurface *>( d->geometry.get() );
5139 poly = dynamic_cast<QgsCurvePolygon *>( inputMultiSurface->surfaceN( modifiedPart ) );
5140 }
5141 else
5142 {
5143 poly = qgsgeometry_cast<QgsCurvePolygon *>( d->geometry.get() );
5144 }
5145 if ( !poly )
5146 {
5147 mLastError = u"Could not get polygon geometry."_s;
5148 return QgsGeometry();
5149 }
5150
5151 // if has rings
5152 modifiedRing = vertexId.ring;
5153 if ( modifiedRing == 0 )
5154 curve = qgsgeometry_cast<QgsCurve *>( poly->exteriorRing() );
5155 else
5156 curve = qgsgeometry_cast<QgsCurve *>( poly->interiorRing( modifiedRing - 1 ) );
5157 }
5158 else
5159 curve = nullptr;
5160
5161 if ( !curve )
5162 {
5163 mLastError = u"Operation '%1' needs curve geometry."_s.arg( qgsEnumValueToKey( op ) );
5164 return QgsGeometry();
5165 }
5166
5167 std::unique_ptr<QgsAbstractGeometry> result;
5168 try
5169 {
5171 result = QgsGeometryUtils::chamferVertex( curve, resolvedVertexIndex, distance1, distance2 );
5172 else
5173 result = QgsGeometryUtils::filletVertex( curve, resolvedVertexIndex, distance1, segments );
5174 }
5175 catch ( QgsInvalidArgumentException &e )
5176 {
5177 mLastError = u"%1 Requested vertex: %2 was resolved as: [part: %3, ring: %4, vertex: %5]"_s //
5178 .arg( e.what() )
5179 .arg( vertexIndex )
5180 .arg( modifiedPart )
5181 .arg( modifiedRing )
5182 .arg( resolvedVertexIndex );
5183 return QgsGeometry();
5184 }
5185
5186 if ( !result )
5187 {
5188 mLastError = u"Operation '%1' generates a null geometry."_s.arg( qgsEnumValueToKey( op ) );
5189 return QgsGeometry();
5190 }
5191
5192 if ( result->isEmpty() )
5193 return QgsGeometry( std::move( result ) );
5194
5195 // insert \a result geometry (obtain by the chamfer/fillet operation) back into original \a inputPoly polygon
5196 auto updatePolygon = []( const QgsCurvePolygon *inputPoly, QgsAbstractGeometry *result, int modifiedRing ) -> std::unique_ptr<QgsCurvePolygon> {
5197 auto newPoly = std::make_unique<QgsCurvePolygon>();
5198 if ( qgsgeometry_cast<const QgsPolygon *>( inputPoly ) )
5199 newPoly = std::make_unique<QgsPolygon>();
5200
5201 for ( int ringIndex = 0; ringIndex < inputPoly->numInteriorRings() + 1; ++ringIndex )
5202 {
5203 if ( ringIndex == modifiedRing )
5204 {
5205 for ( QgsAbstractGeometry::part_iterator resPartIte = result->parts_begin(); resPartIte != result->parts_end(); ++resPartIte )
5206 {
5207 if ( ringIndex == 0 && resPartIte == result->parts_begin() )
5208 newPoly->setExteriorRing( qgsgeometry_cast<QgsCurve *>( ( *resPartIte )->clone() ) );
5209 else
5210 newPoly->addInteriorRing( qgsgeometry_cast<QgsCurve *>( ( *resPartIte )->clone() ) );
5211 }
5212 }
5213 else
5214 {
5215 if ( ringIndex == 0 )
5216 newPoly->setExteriorRing( qgsgeometry_cast<QgsCurve *>( inputPoly->exteriorRing()->clone() ) );
5217 else
5218 newPoly->addInteriorRing( qgsgeometry_cast<QgsCurve *>( inputPoly->interiorRing( ringIndex - 1 )->clone() ) );
5219 }
5220 }
5221 return newPoly;
5222 };
5223
5224 std::unique_ptr<QgsAbstractGeometry> finalGeom;
5225 if ( geomType == Qgis::GeometryType::Line )
5226 {
5227 if ( modifiedPart >= 0 )
5228 {
5229 auto newMultiCurve = std::make_unique<QgsMultiCurve>();
5230 if ( qgsgeometry_cast<const QgsMultiLineString *>( inputMultiCurve ) )
5231 newMultiCurve = std::make_unique<QgsMultiLineString>();
5232
5233 int partIndex = 0;
5234 for ( QgsMultiCurve::part_iterator partIte = inputMultiCurve->parts_begin(); partIte != inputMultiCurve->parts_end(); ++partIte )
5235 {
5236 if ( partIndex == modifiedPart )
5237 {
5238 for ( QgsAbstractGeometry::part_iterator resPartIte = result->parts_begin(); resPartIte != result->parts_end(); ++resPartIte )
5239 {
5240 newMultiCurve->addGeometry( ( *resPartIte )->clone() );
5241 }
5242 }
5243 else
5244 {
5245 newMultiCurve->addGeometry( ( *partIte )->clone() );
5246 }
5247 partIndex++;
5248 }
5249 finalGeom = std::move( newMultiCurve );
5250 }
5251 else
5252 {
5253 // resultGeom is already the correct result!
5254 finalGeom = std::move( result );
5255 }
5256 }
5257 else
5258 {
5259 // geomType == Qgis::GeometryType::Polygon
5260 if ( modifiedPart >= 0 )
5261 {
5262 auto newMultiSurface = std::make_unique<QgsMultiSurface>();
5263 if ( qgsgeometry_cast<const QgsMultiPolygon *>( inputMultiSurface ) )
5264 newMultiSurface = std::make_unique<QgsMultiPolygon>();
5265
5266 int partIndex = 0;
5267 for ( QgsAbstractGeometry::part_iterator partIte = inputMultiSurface->parts_begin(); partIte != inputMultiSurface->parts_end(); ++partIte )
5268 {
5269 if ( partIndex == modifiedPart )
5270 {
5271 std::unique_ptr<QgsCurvePolygon> newCurvePoly = updatePolygon( qgsgeometry_cast<const QgsCurvePolygon *>( *partIte ), result.get(), modifiedRing );
5272 newMultiSurface->addGeometry( newCurvePoly.release() );
5273 }
5274 else
5275 {
5276 newMultiSurface->addGeometry( ( *partIte )->clone() );
5277 }
5278 partIndex++;
5279 }
5280 finalGeom = std::move( newMultiSurface );
5281 }
5282 else
5283 {
5284 std::unique_ptr<QgsCurvePolygon> newCurvePoly = updatePolygon( qgsgeometry_cast<const QgsCurvePolygon *>( d->geometry.get() ), result.get(), modifiedRing );
5285 finalGeom = std::move( newCurvePoly );
5286 }
5287 }
5288
5289 QgsGeometry finalResult( std::move( finalGeom ) );
5290
5291 QgsDebugMsgLevel( u"Final result Wkt: %1"_s.arg( finalResult.asWkt( 2 ) ), 3 );
5292
5293 return finalResult;
5294}
5295
5296
5297QgsGeometry QgsGeometry::chamfer( int vertexIndex, double distance1, double distance2 ) const
5298{
5299 return doChamferFillet( ChamferFilletOperationType::Chamfer, vertexIndex, distance1, distance2, 0 );
5300}
5301
5302QgsGeometry QgsGeometry::fillet( int vertexIndex, double radius, int segments ) const
5303{
5304 return doChamferFillet( ChamferFilletOperationType::Fillet, vertexIndex, radius, 0.0, segments );
5305}
5306
5307QgsGeometry QgsGeometry::chamfer( const QgsPoint &segment1Start, const QgsPoint &segment1End, const QgsPoint &segment2Start, const QgsPoint &segment2End, double distance1, double distance2 )
5308{
5309 std::unique_ptr<QgsLineString> result( QgsGeometryUtils::createChamferGeometry( segment1Start, segment1End, segment2Start, segment2End, distance1, distance2 ) );
5310
5311 if ( !result )
5312 {
5313 return QgsGeometry();
5314 }
5315
5316 return QgsGeometry( std::move( result ) );
5317}
5318
5319QgsGeometry QgsGeometry::fillet( const QgsPoint &segment1Start, const QgsPoint &segment1End, const QgsPoint &segment2Start, const QgsPoint &segment2End, double radius, int segments )
5320{
5321 std::unique_ptr<QgsAbstractGeometry> result( QgsGeometryUtils::createFilletGeometry( segment1Start, segment1End, segment2Start, segment2End, radius, segments ) );
5322
5323 if ( !result )
5324 {
5325 return QgsGeometry();
5326 }
5327
5328 return QgsGeometry( std::move( result ) );
5329}
5330
5331QVector< QgsGeometry > QgsGeometry::collectSplitFeatures( const QVector< QgsGeometry> newGeoms ) const
5332{
5333 QVector< QgsGeometry> collectedNewGeoms;
5334 QVector< QgsGeometry> unchangedParts;
5335
5336 for ( QgsGeometry newGeom : newGeoms )
5337 {
5338 bool inOriginalCollection = false;
5339 QVector< QgsGeometry > originalGeoms = this->asGeometryCollection();
5340 for ( QgsGeometry &originalPart : originalGeoms )
5341 {
5342 if ( newGeom.isExactlyEqual( originalPart ) )
5343 {
5344 inOriginalCollection = true;
5345 break;
5346 }
5347 }
5348 if ( inOriginalCollection )
5349 {
5350 unchangedParts.append( newGeom );
5351 }
5352 else
5353 {
5354 // Parts that were split are added to a single multi-part geometry.
5355 newGeom.convertToMultiType();
5356 collectedNewGeoms.append( newGeom );
5357 }
5358 }
5359
5360 // All unchanged parts are added to the same multi-geometry.
5361 if ( !unchangedParts.empty() )
5362 {
5363 collectedNewGeoms.prepend( QgsGeometry::collectGeometry( unchangedParts ) );
5364 }
5365 return collectedNewGeoms;
5366}
5367
5368QVector< QgsGeometry > QgsGeometry::collectSplitParts( const QVector< QgsGeometry> newGeoms ) const
5369{
5370 QVector< QgsGeometry> collectedNewGeoms;
5371 for ( const QgsGeometry &newGeom : newGeoms )
5372 {
5373 collectedNewGeoms.append( QgsGeometry::collectGeometry( QVector< QgsGeometry>() << newGeom ) );
5374 }
5375 return collectedNewGeoms;
5376}
5377
5378QVector< QgsGeometry > QgsGeometry::collectSplitGeometries( const QVector< QgsGeometry> newGeomsTemp, const bool splitFeature )
5379{
5380 QVector< QgsGeometry> newGeoms;
5381 if ( !newGeomsTemp.isEmpty() )
5382 {
5384 {
5385 newGeoms = splitFeature ? collectSplitFeatures( newGeomsTemp ) : collectSplitParts( newGeomsTemp );
5386 }
5387 else
5388 {
5389 newGeoms = newGeomsTemp;
5390 }
5391
5392 if ( splitFeature && !newGeoms.isEmpty() )
5393 {
5394 *this = newGeoms.takeAt( 0 );
5395 }
5396 }
5397 return newGeoms;
5398}
GeometryBackend
Geometry backend for QgsGeometry.
Definition qgis.h:2320
@ GEOS
Use GEOS implementation.
Definition qgis.h:2322
@ QGIS
Use internal implementation.
Definition qgis.h:2321
@ AllowSelfTouchingHoles
Indicates that self-touching holes are permitted. OGC validity states that self-touching holes are NO...
Definition qgis.h:2243
BufferSide
Side of line to buffer.
Definition qgis.h:2269
DashPatternSizeAdjustment
Dash pattern size adjustment options.
Definition qgis.h:3556
AngularDirection
Angular directions.
Definition qgis.h:3697
@ NoOrientation
Unknown orientation or sentinel value.
Definition qgis.h:3700
GeometryOperationResult
Success or failure of a geometry operation.
Definition qgis.h:2213
@ AddPartSelectedGeometryNotFound
The selected geometry cannot be found.
Definition qgis.h:2223
@ InvalidInputGeometryType
The input geometry (ring, part, split line, etc.) has not the correct geometry type.
Definition qgis.h:2217
@ Success
Operation succeeded.
Definition qgis.h:2214
@ SelectionIsEmpty
No features were selected.
Definition qgis.h:2218
@ GeometryTypeHasChanged
Operation has changed geometry type.
Definition qgis.h:2232
@ AddRingNotInExistingFeature
The input ring doesn't have any existing ring to fit into.
Definition qgis.h:2229
@ AddRingCrossesExistingRings
The input ring crosses existing rings (it is not disjoint).
Definition qgis.h:2228
@ AddPartNotMultiGeometry
The source geometry is not multi.
Definition qgis.h:2224
@ AddRingNotClosed
The input ring is not closed.
Definition qgis.h:2226
@ SelectionIsGreaterThanOne
More than one features were selected.
Definition qgis.h:2219
@ SplitCannotSplitPoint
Cannot split points.
Definition qgis.h:2231
@ GeometryEngineError
Geometry engine misses a method implemented or an error occurred in the geometry engine.
Definition qgis.h:2220
@ NothingHappened
Nothing happened, without any error.
Definition qgis.h:2215
@ InvalidBaseGeometry
The base geometry on which the operation is done is invalid or empty.
Definition qgis.h:2216
@ LayerNotEditable
Cannot edit layer.
Definition qgis.h:2221
@ AddRingNotValid
The input ring is not valid.
Definition qgis.h:2227
QFlags< GeometryValidityFlag > GeometryValidityFlags
Geometry validity flags.
Definition qgis.h:2247
@ Segment
The actual start or end point of a segment.
Definition qgis.h:3331
GeometryValidationEngine
Available engines for validating geometries.
Definition qgis.h:2256
@ QgisInternal
Use internal QgsGeometryValidator method.
Definition qgis.h:2257
@ Sfcgal
Use SFCGAL validation methods. Only available for QGIS builds with SFCGAL support enabled.
Definition qgis.h:2259
@ Geos
Use GEOS validation methods.
Definition qgis.h:2258
QFlags< GeosCreationFlag > GeosCreationFlags
Geos geometry creation behavior flags.
Definition qgis.h:2343
GeoJsonProfile
GeoJson export Profile according to OGC Features and Geometries JSON - Part 1: Core https://docs....
Definition qgis.h:5161
@ Rfc7946
GeoJson profile compliant with RFC7946 standard "http://www.opengis.net/def/profile/OGC/0/rfc7946".
Definition qgis.h:5163
CoverageEdgeType
Coverage edge types.
Definition qgis.h:2365
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:399
@ Point
Points.
Definition qgis.h:400
@ Line
Lines.
Definition qgis.h:401
@ Polygon
Polygons.
Definition qgis.h:402
@ Unknown
Unknown types.
Definition qgis.h:403
@ Null
No geometry.
Definition qgis.h:404
JoinStyle
Join styles for buffers.
Definition qgis.h:2294
EndCapStyle
End cap styles for buffers.
Definition qgis.h:2281
CoverageValidityResult
Coverage validity results.
Definition qgis.h:2352
@ Error
An exception occurred while determining validity.
Definition qgis.h:2355
DashPatternLineEndingRule
Dash pattern line ending rules.
Definition qgis.h:3541
MakeValidMethod
Algorithms to use when repairing invalid geometries.
Definition qgis.h:2378
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
@ Polygon
Polygon.
Definition qgis.h:318
@ MultiPolygon
MultiPolygon.
Definition qgis.h:322
@ Triangle
Triangle.
Definition qgis.h:319
@ NoGeometry
No geometry.
Definition qgis.h:332
@ MultiLineString
MultiLineString.
Definition qgis.h:321
@ Unknown
Unknown.
Definition qgis.h:315
@ CircularString
CircularString.
Definition qgis.h:324
@ GeometryCollection
GeometryCollection.
Definition qgis.h:323
@ MultiCurve
MultiCurve.
Definition qgis.h:327
@ CurvePolygon
CurvePolygon.
Definition qgis.h:326
@ PolyhedralSurface
PolyhedralSurface.
Definition qgis.h:329
@ MultiSurface
MultiSurface.
Definition qgis.h:328
TransformDirection
Indicates the direction (forward or inverse) of a transform.
Definition qgis.h:2897
The part_iterator class provides an STL-style iterator for const references to geometry parts.
The part_iterator class provides an STL-style iterator for geometry parts.
The vertex_iterator class provides an STL-style iterator for vertices.
Abstract base class for all geometries.
virtual int ringCount(int part=0) const =0
Returns the number of rings of which this geometry is built.
virtual bool addZValue(double zValue=0)=0
Adds a z-dimension to the geometry, initialized to a preset value.
virtual bool moveVertex(QgsVertexId position, const QgsPoint &newPos)=0
Moves a vertex within the geometry.
SegmentationToleranceType
Segmentation tolerance as maximum angle or maximum difference between approximation and circle.
virtual int vertexNumberFromVertexId(QgsVertexId id) const =0
Returns the vertex number corresponding to a vertex id.
virtual QgsAbstractGeometry * boundary() const =0
Returns the closure of the combinatorial boundary of the geometry (ie the topological boundary of the...
virtual bool dropMValue()=0
Drops any measure values which exist in the geometry.
virtual const QgsAbstractGeometry * simplifiedTypeRef() const
Returns a reference to the simplest lossless representation of this geometry, e.g.
virtual QgsAbstractGeometry * segmentize(double tolerance=M_PI/180., SegmentationToleranceType toleranceType=MaximumAngle) const
Returns a version of the geometry without curves.
virtual int vertexCount(int part=0, int ring=0) const =0
Returns the number of vertices of which this geometry is built.
bool isMeasure() const
Returns true if the geometry contains m values.
QFlags< WkbFlag > WkbFlags
virtual QgsRectangle boundingBox() const
Returns the minimal bounding box for the geometry.
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.
virtual QgsAbstractGeometry * toCurveType() const =0
Returns the geometry converted to the more generic curve type.
virtual void adjacentVertices(QgsVertexId vertex, QgsVertexId &previousVertex, QgsVertexId &nextVertex) const =0
Returns the vertices adjacent to a specified vertex within a geometry.
virtual bool addMValue(double mValue=0)=0
Adds a measure to the geometry, initialized to a preset value.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
virtual bool deleteVertex(QgsVertexId position)
Deletes a vertex within the geometry.
part_iterator parts_end()
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
virtual double length() const
Returns the planar, 2-dimensional length of the geometry.
virtual bool isEmpty() const
Returns true if the geometry is empty.
virtual bool dropZValue()=0
Drops any z-dimensions which exist in the geometry.
virtual int dimension() const =0
Returns the inherent dimension of the geometry.
part_iterator parts_begin()
Returns STL-style iterator pointing to the first part of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
A 3-dimensional box composed of x, y, z coordinates.
Definition qgsbox3d.h:45
double yMaximum() const
Returns the maximum y value.
Definition qgsbox3d.h:240
double xMinimum() const
Returns the minimum x value.
Definition qgsbox3d.h:205
double zMaximum() const
Returns the maximum z value.
Definition qgsbox3d.h:268
double xMaximum() const
Returns the maximum x value.
Definition qgsbox3d.h:212
QgsRectangle toRectangle() const
Converts the box to a 2D rectangle.
Definition qgsbox3d.h:388
bool is2d() const
Returns true if the box can be considered a 2-dimensional box, i.e.
Definition qgsbox3d.cpp:137
double zMinimum() const
Returns the minimum z value.
Definition qgsbox3d.h:261
double yMinimum() const
Returns the minimum y value.
Definition qgsbox3d.h:233
Circle geometry type.
Definition qgscircle.h:46
static QgsCircle from2Points(const QgsPoint &pt1, const QgsPoint &pt2)
Constructs a circle by 2 points on the circle.
Definition qgscircle.cpp:39
double radius() const
Returns the radius of the circle.
Definition qgscircle.h:303
std::unique_ptr< QgsCircularString > toCircularString(bool oriented=false) const
Returns a circular string from the circle.
bool contains(const QgsPoint &point, double epsilon=1E-8) const
Returns true if the circle contains the point.
static QgsCircle minimalCircleFrom3Points(const QgsPoint &pt1, const QgsPoint &pt2, const QgsPoint &pt3, double epsilon=1E-8)
Constructs the smallest circle from 3 points.
Circular string geometry type.
static QgsCircularString fromTwoPointsAndCenter(const QgsPoint &p1, const QgsPoint &p2, const QgsPoint &center, bool useShortestArc=true)
Creates a circular string with a single arc representing the curve from p1 to p2 with the specified c...
Compound curve geometry type.
bool toggleCircularAtVertex(QgsVertexId position)
Converts the vertex at the given position from/to circular.
void addCurve(QgsCurve *c, bool extendPrevious=false)
Adds a curve to the geometry (takes ownership).
A const WKB pointer.
Definition qgswkbptr.h:211
Handles coordinate transforms between two coordinate systems.
Encapsulates parameters for a coverage cleaning operation.
Curve polygon geometry type.
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.
int vertexCount(int part=0, int ring=0) const override
Returns the number of vertices of which this geometry is built.
virtual QgsPolygon * toPolygon(double tolerance=M_PI_2/90, SegmentationToleranceType toleranceType=MaximumAngle) const
Returns a new polygon geometry corresponding to a segmentized approximation of the curve.
const QgsCurve * interiorRing(int i) const
Retrieves an interior ring from the curve polygon.
virtual void setExteriorRing(QgsCurve *ring)
Sets the exterior ring of the polygon.
virtual void addInteriorRing(QgsCurve *ring)
Adds an interior ring to the geometry (takes ownership).
int ringCount(int part=0) const override
Returns the number of rings of which this geometry is built.
bool removeInteriorRing(int ringIndex)
Removes an interior ring from the polygon.
Abstract base class for curved geometry type.
Definition qgscurve.h:36
virtual int numPoints() const =0
Returns the number of points in the curve.
QgsCurve * segmentize(double tolerance=M_PI_2/90, SegmentationToleranceType toleranceType=MaximumAngle) const override
Returns a geometry without curves.
Definition qgscurve.cpp:175
virtual QgsPoint * interpolatePoint(double distance) const =0
Returns an interpolated point on the curve at the specified distance.
QgsCurve * clone() const override=0
Clones the geometry by performing a deep copy.
virtual void points(QgsPointSequence &pt) const =0
Returns a list of points within the curve.
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.
virtual QgsPolygon * toPolygon(unsigned int segments=36) const
Returns a segmented polygon.
QgsPoint center() const
Returns the center point.
Definition qgsellipse.h:122
QString what() const
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
virtual bool insertGeometry(QgsAbstractGeometry *g, int index)
Inserts a geometry before a specified index and takes ownership.
virtual bool removeGeometry(int nr)
Removes a geometry from the collection.
QgsGeometryCollection * createEmptyWithSameType() const override
Creates a new geometry with the same class and same WKB type as the original and transfers ownership.
virtual bool addGeometry(QgsAbstractGeometry *g)
Adds a geometry and takes ownership. Returns true in case of success.
int partCount() const override
Returns count of parts contained in the geometry.
int numGeometries() const
Returns the number of geometries within the collection.
const QgsAbstractGeometry * geometryN(int n) const
Returns a const reference to a geometry from within the collection.
Java-style iterator for const traversal of parts of a geometry.
static Qgis::GeometryOperationResult addRing(QgsAbstractGeometry *geometry, std::unique_ptr< QgsCurve > ring)
Add an interior ring to a geometry.
static std::unique_ptr< QgsAbstractGeometry > avoidIntersections(const QgsAbstractGeometry &geom, const QList< QgsVectorLayer * > &avoidIntersectionsLayers, bool &haveInvalidGeometry, const QHash< QgsVectorLayer *, QSet< QgsFeatureId > > &ignoreFeatures=(QHash< QgsVectorLayer *, QSet< QgsFeatureId > >()))
Alters a geometry so that it avoids intersections with features from all open vector layers.
static bool deletePart(QgsAbstractGeometry *geom, int partNum)
Deletes a part from a geometry.
static bool deleteRing(QgsAbstractGeometry *geom, int ringNum, int partNum=0)
Deletes a ring from a geometry.
static Qgis::GeometryOperationResult addPart(QgsAbstractGeometry *geometry, std::unique_ptr< QgsAbstractGeometry > part)
Add a part to multi type geometry.
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.
static std::unique_ptr< QgsMultiPolygon > fromMultiPolygonXY(const QgsMultiPolygonXY &multipoly)
Construct geometry from a multipolygon.
static std::unique_ptr< QgsAbstractGeometry > geomFromWkb(QgsConstWkbPtr &wkb)
Construct geometry from a WKB string.
static std::unique_ptr< QgsGeometryCollection > createCollectionOfType(Qgis::WkbType type)
Returns a new geometry collection matching a specified WKB type.
static std::unique_ptr< QgsAbstractGeometry > fromPolylineXY(const QgsPolylineXY &polyline)
Construct geometry from a polyline.
static std::unique_ptr< QgsMultiPoint > fromMultiPointXY(const QgsMultiPointXY &multipoint)
Construct geometry from a multipoint.
static std::unique_ptr< QgsAbstractGeometry > geomFromWkt(const QString &text)
Construct geometry from a WKT string.
static std::unique_ptr< QgsMultiLineString > fromMultiPolylineXY(const QgsMultiPolylineXY &multiline)
Construct geometry from a multipolyline.
static std::unique_ptr< QgsAbstractGeometry > fromPointXY(const QgsPointXY &point)
Construct geometry from a point.
static std::unique_ptr< QgsPolygon > fromPolygonXY(const QgsPolygonXY &polygon)
Construct geometry from a polygon.
static std::unique_ptr< QgsAbstractGeometry > geomFromWkbType(Qgis::WkbType t)
Returns empty geometry from wkb type.
Encapsulates parameters under which a geometry operation is performed.
Java-style iterator for traversal of parts of a geometry.
static double angleBetweenThreePoints(double x1, double y1, double x2, double y2, double x3, double y3)
Calculates the angle between the lines AB and BC, where AB and BC described by points a,...
static double lineAngle(double x1, double y1, double x2, double y2)
Calculates the direction of line joining two points in radians, clockwise from the north direction.
static double averageAngle(double x1, double y1, double x2, double y2, double x3, double y3)
Calculates the average angle (in radians) between the two linear segments from (x1,...
static double normalizedAngle(double angle)
Ensures that an angle is in the range 0 <= angle < 2 pi.
static std::unique_ptr< QgsLineString > createChamferGeometry(const QgsPoint &segment1Start, const QgsPoint &segment1End, const QgsPoint &segment2Start, const QgsPoint &segment2End, double distance1, double distance2)
Creates a complete chamfer geometry connecting two segments.
static QgsPointXY interpolatePointOnLine(double x1, double y1, double x2, double y2, double fraction)
Interpolates the position of a point a fraction of the way along the line from (x1,...
static std::unique_ptr< QgsAbstractGeometry > createFilletGeometry(const QgsPoint &segment1Start, const QgsPoint &segment1End, const QgsPoint &segment2Start, const QgsPoint &segment2End, double radius, int segments)
Creates a complete fillet geometry connecting two segments.
static QgsPoint interpolatePointOnSegment(double x, double y, const QgsPoint &segmentStart, const QgsPoint &segmentEnd)
Interpolates a point on a segment with proper Z and M value interpolation.
static bool verticesAtDistance(const QgsAbstractGeometry &geometry, double distance, QgsVertexId &previousVertex, QgsVertexId &nextVertex)
Retrieves the vertices which are before and after the interpolated point at a specified distance alon...
static double distanceToVertex(const QgsAbstractGeometry &geom, QgsVertexId id)
Returns the distance along a geometry from its first vertex to the specified vertex.
static QgsPoint closestVertex(const QgsAbstractGeometry &geom, const QgsPoint &pt, QgsVertexId &id)
Returns the closest vertex to a geometry for a specified point.
static Q_DECL_DEPRECATED double sqrDistance2D(double x1, double y1, double x2, double y2)
Returns the squared 2D distance between (x1, y1) and (x2, y2).
static std::unique_ptr< QgsAbstractGeometry > chamferVertex(const QgsCurve *curve, int vertexIndex, double distance1, double distance2)
Applies chamfer to a vertex in a curve geometry.
static std::unique_ptr< QgsAbstractGeometry > filletVertex(const QgsCurve *curve, int vertexIndex, double radius, int segments)
Applies fillet to a vertex in a curve geometry.
static void validateGeometry(const QgsGeometry &geometry, QVector< QgsGeometry::Error > &errors, Qgis::GeometryValidationEngine method=Qgis::GeometryValidationEngine::QgisInternal)
Validate geometry and produce a list of geometry errors.
A geometry error.
bool hasWhere() const
true if the location available from
QgsPointXY where() const
The coordinates at which the error is located and should be visualized.
QString what() const
A human readable error message containing details about the error.
A geometry is the spatial representation of a feature.
Q_DECL_DEPRECATED QgsGeometry makeDifference(const QgsGeometry &other, QgsFeedback *feedback=nullptr) const
Returns the geometry formed by modifying this geometry such that it does not intersect the other geom...
QPolygonF asQPolygonF() const
Returns contents of the geometry as a QPolygonF.
double closestSegmentWithContext(const QgsPointXY &point, QgsPointXY &minDistPoint, int &nextVertexIndex, int *leftOrRightOfSegment=nullptr, double epsilon=Qgis::DEFAULT_SEGMENT_EPSILON) const
Searches for the closest segment of geometry to the given point.
bool deleteRing(int ringNum, int partNum=0)
Deletes a ring in polygon or multipolygon.
QVector< QgsPointXY > randomPointsInPolygon(int count, const std::function< bool(const QgsPointXY &) > &acceptPoint, unsigned long seed=0, QgsFeedback *feedback=nullptr, int maxTriesPerPoint=0) const
Returns a list of count random points generated inside a (multi)polygon geometry (if acceptPoint is s...
double hausdorffDistanceDensify(const QgsGeometry &geom, double densifyFraction) const
Returns the Hausdorff distance between this geometry and geom.
QgsGeometry densifyByCount(int extraNodesPerSegment) const
Returns a copy of the geometry which has been densified by adding the specified number of extra nodes...
double area3D() const
Returns the 3-dimensional surface area of the geometry.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
double lineLocatePoint(const QgsGeometry &point) const
Returns a distance representing the location along this linestring of the closest point on this lines...
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points shared by this geometry and other.
void adjacentVertices(int atVertex, int &beforeVertex, int &afterVertex) const
Returns the indexes of the vertices before and after the given vertex index.
QgsMultiPolygonXY asMultiPolygon() const
Returns the contents of the geometry as a multi-polygon.
QgsGeometry concaveHullOfPolygons(double lengthRatio, bool allowHoles=false, bool isTight=false, QgsFeedback *feedback=nullptr) const
Constructs a concave hull of a set of polygons, respecting the polygons as constraints.
QgsGeometry chamfer(int vertexIndex, double distance1, double distance2=-1.0) const
Creates a chamfer (angled corner) at the specified vertex.
bool deleteVertex(int atVertex)
Deletes the vertex at the given position number and item (first number is index 0).
double length() const
Returns the planar, 2-dimensional length of geometry.
QgsGeometry offsetCurve(double distance, int segments, Qgis::JoinStyle joinStyle, double miterLimit) const
Returns an offset line at a given distance and side from an input line.
static bool compare(const QgsPolylineXY &p1, const QgsPolylineXY &p2, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compares two polylines for equality within a specified tolerance.
QgsVertexIterator vertices() const
Returns a read-only, Java-style iterator for traversal of vertices of all the geometry,...
QgsGeometry densifyByDistance(double distance) const
Densifies the geometry by adding regularly placed extra nodes inside each segment so that the maximum...
ChamferFilletOperationType
Privatly used in chamfer/fillet functions.
QgsGeometry poleOfInaccessibility(double precision, double *distanceToBoundary=nullptr) const
Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal ...
QgsAbstractGeometry::const_part_iterator const_parts_begin() const
Returns STL-style const iterator pointing to the first part of the geometry.
QgsGeometry squareWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs square waves along the boundary of the geometry, with the specified wavelength and amplitu...
QgsGeometry concaveHull(double targetPercent, bool allowHoles=false, QgsFeedback *feedback=nullptr) const
Returns a possibly concave polygon that contains all the points in the geometry.
static QgsGeometry fromQPointF(QPointF point)
Construct geometry from a QPointF.
static QgsGeometry collectTinPatches(const QVector< QgsGeometry > &geometries)
Collects all patches from a list of TIN or Triangle geometries into a single TIN geometry.
static QgsGeometry polygonize(const QVector< QgsGeometry > &geometries)
Creates a GeometryCollection geometry containing possible polygons formed from the constituent linewo...
bool addTopologicalPoint(const QgsPoint &point, double snappingTolerance=1e-8, double segmentSearchEpsilon=1e-12)
Adds a vertex to the segment which intersect point but don't already have a vertex there.
QgsGeometry triangularWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs triangular waves along the boundary of the geometry, with the specified wavelength and amp...
Q_INVOKABLE bool boundingBoxIntersects(const QgsRectangle &rectangle) const
Returns true if the bounding box of this geometry intersects with a rectangle.
bool vertexIdFromVertexNr(int number, QgsVertexId &id) const
Calculates the vertex ID from a vertex number.
QgsGeometry pointOnSurface() const
Returns a point guaranteed to lie on the surface of a geometry.
Q_INVOKABLE bool touches(const QgsGeometry &geometry) const
Returns true if the geometry touches another geometry.
Q_DECL_DEPRECATED int makeDifferenceInPlace(const QgsGeometry &other, QgsFeedback *feedback=nullptr)
Changes this geometry such that it does not intersect the other geometry.
void transformVertices(const std::function< QgsPoint(const QgsPoint &) > &transform)
Transforms the vertices from the geometry in place, applying the transform function to every vertex.
bool isExactlyEqual(const QgsGeometry &geometry, Qgis::GeometryBackend backend=Qgis::GeometryBackend::QGIS) const
Compares the geometry with another geometry using the specified backend.
QgsGeometry minimumWidth() const
Returns a linestring geometry which represents the minimum diameter of the geometry.
QgsGeometry applyDashPattern(const QVector< double > &pattern, Qgis::DashPatternLineEndingRule startRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternLineEndingRule endRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternSizeAdjustment adjustment=Qgis::DashPatternSizeAdjustment::ScaleBothDashAndGap, double patternOffset=0) const
Applies a dash pattern to a geometry, returning a MultiLineString geometry which is the input geometr...
Qgis::CoverageValidityResult validateCoverage(double gapWidth, QgsGeometry *invalidEdges=nullptr) const
Analyze a coverage (represented as a collection of polygonal geometry with exactly matching edge geom...
QgsGeometry roundWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs rounded (sine-like) waves along the boundary of the geometry, with the specified wavelengt...
QgsGeometry nearestPoint(const QgsGeometry &other) const
Returns the nearest (closest) point on this geometry to another geometry.
QgsGeometry simplifyCoverageVW(double tolerance, bool preserveBoundary) const
Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geomet...
static QgsGeometry collectGeometry(const QVector< QgsGeometry > &geometries)
Creates a new multipart geometry from a list of QgsGeometry objects.
QgsGeometry fillet(int vertexIndex, double radius, int segments=8) const
Creates a fillet (rounded corner) at the specified vertex.
QgsGeometry mergeLines(const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Merges any connected lines in a LineString/MultiLineString geometry and converts them to single line ...
static QgsGeometry fromMultiPolylineXY(const QgsMultiPolylineXY &multiline)
Creates a new geometry from a QgsMultiPolylineXY object.
double frechetDistance(const QgsGeometry &geom) const
Returns the Fréchet distance between this geometry and geom, restricted to discrete points for both g...
QString lastError() const
Returns an error string referring to the last error encountered either when this geometry was created...
QgsGeometry convertToType(Qgis::GeometryType destType, bool destMultipart=false) const
Try to convert the geometry to the requested type.
QgsGeometry clipped(const QgsRectangle &rectangle, QgsFeedback *feedback=nullptr)
Clips the geometry using the specified rectangle.
bool isAxisParallelRectangle(double maximumDeviation, bool simpleRectanglesOnly=false) const
Returns true if the geometry is a polygon that is almost an axis-parallel rectangle.
static QgsGeometry fromQPolygonF(const QPolygonF &polygon)
Construct geometry from a QPolygonF.
QgsGeometry variableWidthBufferByM(int segments) const
Calculates a variable width buffer for a (multi)linestring geometry, where the width at each node is ...
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
static QgsGeometry fromPolylineXY(const QgsPolylineXY &polyline)
Creates a new LineString geometry from a list of QgsPointXY points.
QgsMultiPointXY asMultiPoint() const
Returns the contents of the geometry as a multi-point.
QgsPoint vertexAt(int atVertex) const
Returns coordinates of a vertex.
QgsPointXY closestVertex(const QgsPointXY &point, int &closestVertexIndex, int &previousVertexIndex, int &nextVertexIndex, double &sqrDist) const
Returns the vertex closest to the given point, the corresponding vertex index, squared distance snap ...
void normalize()
Reorganizes the geometry into a normalized form (or "canonical" form).
int wkbSize(QgsAbstractGeometry::WkbFlags flags=QgsAbstractGeometry::WkbFlags()) const
Returns the length of the QByteArray returned by asWkb().
QgsPolygonXY asPolygon() const
Returns the contents of the geometry as a polygon.
Q_INVOKABLE bool disjoint(const QgsGeometry &geometry) const
Returns true if the geometry is disjoint of another geometry.
QVector< QgsGeometry > asGeometryCollection() const
Returns the contents of the geometry as a list of single-part geometries.
QgsGeometry roundWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized rounded (sine-like) waves along the boundary of the geometry,...
double distance(const QgsGeometry &geom) const
Returns the minimum distance between this geometry and another geometry.
QgsGeometry interpolate(double distance) const
Returns an interpolated point on the geometry at the specified distance.
QgsGeometry extrude(double x, double y)
Returns an extruded version of this geometry.
static Q_DECL_DEPRECATED QgsPolylineXY createPolylineFromQPolygonF(const QPolygonF &polygon)
Creates a QgsPolylineXY from a QPolygonF.
void mapToPixel(const QgsMapToPixel &mtp)
Transforms the geometry from map units to pixels in place.
static QgsGeometry fromMultiPointXY(const QgsMultiPointXY &multipoint)
Creates a new geometry from a QgsMultiPointXY object.
virtual json asJsonObject(int precision=17, Qgis::GeoJsonProfile profile=Qgis::GeoJsonProfile::Legacy) const
Exports the geometry to a json object with the give precision and following the specified GeoJSON pro...
QgsGeometry symDifference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points making up this geometry that do not make up other.
QgsGeometry singleSidedBuffer(double distance, int segments, Qgis::BufferSide side, Qgis::JoinStyle joinStyle=Qgis::JoinStyle::Round, double miterLimit=2.0) const
Returns a single sided buffer for a (multi)line geometry.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
QgsBox3D boundingBox3D() const
Returns the 3D bounding box of the geometry.
friend class QgsInternalGeometryEngine
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static Q_INVOKABLE QgsGeometry fromWkt(const QString &wkt)
Creates a new geometry from a WKT string.
bool contains(const QgsPointXY *p) const
Returns true if the geometry contains the point p.
QgsPolylineXY asPolyline() const
Returns the contents of the geometry as a polyline.
QgsAbstractGeometry::part_iterator parts_begin()
Returns STL-style iterator pointing to the first part of the geometry.
QgsGeometry forceRHR() const
Forces geometries to respect the Right-Hand-Rule, in which the area that is bounded by a polygon is t...
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
QgsGeometry snappedToGrid(double hSpacing, double vSpacing, double dSpacing=0, double mSpacing=0) const
Returns a new geometry with all points or vertices snapped to the closest point of the grid.
void filterVertices(const std::function< bool(const QgsPoint &) > &filter)
Filters the vertices from the geometry in place, removing any which do not return true for the filter...
Q_DECL_DEPRECATED bool equals(const QgsGeometry &geometry) const
Test if this geometry is exactly equal to another geometry.
bool isGeosValid(Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const
Checks validity of the geometry using GEOS.
bool insertVertex(double x, double y, int beforeVertex)
Insert a new vertex before the given vertex index, ring and item (first number is index 0) If the req...
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
QgsGeometry subdivide(int maxNodes=256, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Subdivides the geometry.
static Q_DECL_DEPRECATED QgsPolygonXY createPolygonFromQPolygonF(const QPolygonF &polygon)
Creates a QgsPolygonXYfrom a QPolygonF.
bool convertToSingleType()
Converts multi type geometry into single type geometry e.g.
Qgis::GeometryOperationResult addRing(const QVector< QgsPointXY > &ring)
Adds a new ring to this geometry.
Qgis::GeometryType type
QgsGeometry extendLine(double startDistance, double endDistance, double startDeflection=0, double endDeflection=0) const
Extends a (multi)line geometry by extrapolating out the start or end of the line by a specified dista...
bool requiresConversionToStraightSegments() const
Returns true if the geometry is a curved geometry type which requires conversion to display as straig...
bool isSimple() const
Determines whether the geometry is simple (according to OGC definition), i.e.
static QgsGeometry fromPolyline(const QgsPolyline &polyline)
Creates a new LineString geometry from a list of QgsPoint points.
void validateGeometry(QVector< QgsGeometry::Error > &errors, Qgis::GeometryValidationEngine method=Qgis::GeometryValidationEngine::QgisInternal, Qgis::GeometryValidityFlags flags=Qgis::GeometryValidityFlags()) const
Validates geometry and produces a list of geometry errors.
QgsMultiPolylineXY asMultiPolyline() const
Returns the contents of the geometry as a multi-linestring.
QgsGeometry taperedBuffer(double startWidth, double endWidth, int segments) const
Calculates a variable width buffer ("tapered buffer") for a (multi)curve geometry.
Qgis::GeometryOperationResult avoidIntersectionsV2(const QList< QgsVectorLayer * > &avoidIntersectionsLayers, const QHash< QgsVectorLayer *, QSet< QgsFeatureId > > &ignoreFeatures=(QHash< QgsVectorLayer *, QSet< QgsFeatureId > >()))
Modifies geometry to avoid intersections with the layers specified in project properties.
Q_INVOKABLE bool within(const QgsGeometry &geometry) const
Returns true if the geometry is completely within another geometry.
QPointF asQPointF() const
Returns contents of the geometry as a QPointF if wkbType is WKBPoint, otherwise returns a null QPoint...
QString asGeoJson(int precision=17, Qgis::GeoJsonProfile profile=Qgis::GeoJsonProfile::Legacy) const
Export the geometry to a GeoJSON string, with the given precision and following the specified GeoJSON...
void convertToStraightSegment(double tolerance=M_PI/180., QgsAbstractGeometry::SegmentationToleranceType toleranceType=QgsAbstractGeometry::MaximumAngle)
Converts the geometry to straight line segments, if it is a curved geometry type.
double area() const
Returns the planar, 2-dimensional area of the geometry.
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
Q_INVOKABLE bool crosses(const QgsGeometry &geometry) const
Returns true if the geometry crosses another geometry.
QgsGeometry & operator=(QgsGeometry const &rhs)
Creates a shallow copy of the geometry.
QgsGeometry orthogonalize(double tolerance=1.0E-8, int maxIterations=1000, double angleThreshold=15.0) const
Attempts to orthogonalize a line or polygon geometry by shifting vertices to make the geometries angl...
Qgis::AngularDirection polygonOrientation() const
Returns the orientation of the polygon.
double hausdorffDistance(const QgsGeometry &geom) const
Returns the Hausdorff distance between this geometry and geom.
QgsGeometry combine(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing all the points in this geometry and other (a union geometry operation...
bool deleteVertices(const QSet< int > &atVertices)
Deletes vertices at the given positions (first number is index 0).
QgsGeometry makeValid(Qgis::MakeValidMethod method=Qgis::MakeValidMethod::Linework, bool keepCollapsed=false, QgsFeedback *feedback=nullptr) const
Attempts to make an invalid geometry valid without losing vertices.
QgsGeometry largestEmptyCircle(double tolerance, const QgsGeometry &boundary=QgsGeometry()) const
Constructs the Largest Empty Circle for a set of obstacle geometries, up to a specified tolerance.
Q_DECL_DEPRECATED Qgis::GeometryOperationResult addPart(const QVector< QgsPointXY > &points, Qgis::GeometryType geomType=Qgis::GeometryType::Unknown)
Adds a new part to a the geometry.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr)
Compute the unary union on a list of geometries.
QgsGeometryPartIterator parts()
Returns Java-style iterator for traversal of parts of the geometry.
QgsGeometry convertToCurves(double distanceTolerance=1e-8, double angleTolerance=1e-8) const
Attempts to convert a non-curved geometry into a curved geometry type (e.g.
QgsGeometry voronoiDiagram(const QgsGeometry &extent=QgsGeometry(), double tolerance=0.0, bool edgesOnly=false) const
Creates a Voronoi diagram for the nodes contained within the geometry.
void set(QgsAbstractGeometry *geometry)
Sets the underlying geometry store.
QgsGeometry convexHull() const
Returns the smallest convex polygon that contains all the points in the geometry.
QgsGeometry minimumClearanceLine() const
Returns a LineString whose endpoints define the minimum clearance of a geometry.
QgsGeometry sharedPaths(const QgsGeometry &other) const
Find paths shared between the two given lineal geometries (this and other).
virtual ~QgsGeometry()
static QgsGeometry fromPolygonXY(const QgsPolygonXY &polygon)
Creates a new geometry from a QgsPolygonXY.
double sqrDistToVertexAt(QgsPointXY &point, int atVertex) const
Returns the squared Cartesian distance between the given point to the given vertex index (vertex at t...
void fromWkb(unsigned char *wkb, int length)
Set the geometry, feeding in the buffer containing OGC Well-Known Binary and the buffer's length.
QgsGeometry minimalEnclosingCircle(QgsPointXY &center, double &radius, unsigned int segments=36) const
Returns the minimal enclosing circle for the geometry.
static QgsGeometry fromMultiPolygonXY(const QgsMultiPolygonXY &multipoly)
Creates a new geometry from a QgsMultiPolygonXY.
QgsGeometry buffer(double distance, int segments, QgsFeedback *feedback=nullptr) const
Returns a buffer region around this geometry having the given width and with a specified number of se...
QVector< QgsGeometry > coerceToType(Qgis::WkbType type, double defaultZ=0, double defaultM=0, bool avoidDuplicates=true) const
Attempts to coerce this geometry into the specified destination type.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsGeometry node() const
Returns a (Multi)LineString representing the fully noded version of a collection of linestrings.
double distanceToVertex(int vertex) const
Returns the distance along this geometry from its first vertex to the specified vertex.
int vertexNrFromVertexId(QgsVertexId id) const
Returns the vertex number corresponding to a vertex id.
QgsAbstractGeometry::const_part_iterator const_parts_end() const
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
bool removeDuplicateNodes(double epsilon=4 *std::numeric_limits< double >::epsilon(), bool useZValues=false)
Removes duplicate nodes from the geometry, wherever removing the nodes does not result in a degenerat...
bool convertGeometryCollectionToSubclass(Qgis::GeometryType geomType)
Converts geometry collection to a the desired geometry type subclass (multi-point,...
QgsAbstractGeometry::part_iterator parts_end()
Returns STL-style iterator pointing to the imaginary part after the last part of the geometry.
QgsAbstractGeometry::vertex_iterator vertices_begin() const
Returns STL-style iterator pointing to the first vertex of the geometry.
bool isFuzzyEqual(const QgsGeometry &geometry, double epsilon=1e-4, Qgis::GeometryBackend backend=Qgis::GeometryBackend::QGIS) const
Compares the geometry with another geometry within the tolerance epsilon using the specified backend.
QgsGeometry forcePolygonClockwise() const
Forces geometries to respect the exterior ring is clockwise, interior rings are counter-clockwise con...
bool convertToMultiType()
Converts single type geometry into multitype geometry e.g.
QString asJson(int precision=17) const
Exports the geometry to a GeoJSON RFC7946 string.
static QgsGeometry createWedgeBuffer(const QgsPoint &center, double azimuth, double angularWidth, double outerRadius, double innerRadius=0)
Creates a wedge shaped buffer from a center point.
double frechetDistanceDensify(const QgsGeometry &geom, double densifyFraction) const
Returns the Fréchet distance between this geometry and geom, restricted to discrete points for both g...
QByteArray asWkb(QgsAbstractGeometry::WkbFlags flags=QgsAbstractGeometry::WkbFlags()) const
Export the geometry to WKB.
QgsGeometry unionCoverage() const
Optimized union algorithm for polygonal inputs that are correctly noded and do not overlap.
static std::unique_ptr< QgsGeometryEngine > createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
bool convertToCurvedMultiType()
Converts a geometry into a multitype geometry of curve kind (when there is a corresponding curve type...
static void convertPointList(const QVector< QgsPointXY > &input, QgsPointSequence &output)
Upgrades a point list from QgsPointXY to QgsPoint.
QgsGeometry extractCoverageEdges(Qgis::CoverageEdgeType edgeType=Qgis::CoverageEdgeType::AllEdges, QgsFeedback *feedback=nullptr) const
Operates on a coverage (represented as a list of polygonal geometry with exactly matching edge geomet...
QgsGeometry orientedMinimumBoundingBox() const
Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated r...
QgsGeometry triangularWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized triangular waves along the boundary of the geometry, with the specified wavelen...
QgsGeometry squareWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized square waves along the boundary of the geometry, with the specified wavelength ...
bool isTopologicallyEqual(const QgsGeometry &geometry, Qgis::GeometryBackend backend=Qgis::GeometryBackend::GEOS) const
Compares the geometry with another geometry using the specified backend.
QgsGeometryConstPartIterator constParts() const
Returns Java-style iterator for traversal of parts of the geometry.
QgsGeometry simplify(double tolerance, QgsFeedback *feedback=nullptr) const
Returns a simplified version of this geometry using a specified tolerance value.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Qgis::GeometryOperationResult addPartV2(const QVector< QgsPointXY > &points, Qgis::WkbType wkbType=Qgis::WkbType::Unknown)
Adds a new part to a the geometry.
double minimumClearance() const
Computes the minimum clearance of a geometry.
Qgis::GeometryOperationResult rotate(double rotation, const QgsPointXY &center)
Rotate this geometry around the Z axis.
Qgis::GeometryOperationResult translate(double dx, double dy, double dz=0.0, double dm=0.0)
Translates this geometry by dx, dy, dz and dm.
double interpolateAngle(double distance) const
Returns the angle parallel to the linestring or polygon boundary at the specified distance along the ...
double angleAtVertex(int vertex) const
Returns the bisector angle for this geometry at the specified vertex.
Qgis::GeometryOperationResult reshapeGeometry(const QgsLineString &reshapeLineString)
Replaces a part of this geometry with another line.
double closestVertexWithContext(const QgsPointXY &point, int &atVertex) const
Searches for the closest vertex in this geometry to the given point.
QgsGeometry delaunayTriangulation(double tolerance=0.0, bool edgesOnly=false) const
Returns the Delaunay triangulation for the vertices of the geometry.
void draw(QPainter &p) const
Draws the geometry onto a QPainter.
QgsGeometry smooth(unsigned int iterations=1, double offset=0.25, double minimumDistance=-1.0, double maxAngle=180.0) const
Smooths a geometry by rounding off corners using the Chaikin algorithm.
QgsGeometry forcePolygonCounterClockwise() const
Forces geometries to respect the exterior ring is counter-clockwise, interior rings are clockwise con...
Q_INVOKABLE QString asWkt(int precision=17) const
Exports the geometry to WKT.
QgsGeometry cleanCoverage(const QgsCoverageCleanParameters &parameters, QgsFeedback *feedback=nullptr) const
Operates on a coverage (represented as a list of polygonal geometry), to fix cases where the geometry...
Q_DECL_DEPRECATED Qgis::GeometryOperationResult splitGeometry(const QVector< QgsPointXY > &splitLine, QVector< QgsGeometry > &newGeometries, bool topological, QVector< QgsPointXY > &topologyTestPoints, bool splitFeature=true)
Splits this geometry according to a given line.
bool toggleCircularAtVertex(int atVertex)
Converts the vertex at the given position from/to circular.
Qgis::WkbType wkbType() const
Returns type of the geometry as a WKB type (point / linestring / polygon etc.).
bool moveVertex(double x, double y, int atVertex)
Moves the vertex at the given position number and item (first number is index 0) to the given coordin...
QgsGeometry constrainedDelaunayTriangulation() const
Returns a constrained Delaunay triangulation for the vertices of the geometry.
Q_DECL_DEPRECATED bool isGeosEqual(const QgsGeometry &) const
Compares the geometry with another geometry using GEOS.
Q_INVOKABLE bool intersects(const QgsRectangle &rectangle) const
Returns true if this geometry exactly intersects with a rectangle.
static QgsGeometry fromBox3D(const QgsBox3D &box)
Creates a new geometry from a QgsBox3D object Returns a 2D polygon geometry if the box is purely 2d,...
QgsAbstractGeometry::vertex_iterator vertices_end() const
Returns STL-style iterator pointing to the imaginary vertex after the last vertex of the geometry.
static QgsGeometry createWedgeBufferFromAngles(const QgsPoint &center, double startAngle, double endAngle, double outerRadius, double innerRadius=0)
Creates a wedge shaped buffer from a center point.
bool deletePart(int partNum)
Deletes part identified by the part number.
QgsGeometry removeInteriorRings(double minimumAllowedArea=-1) const
Removes the interior rings from a (multi)polygon geometry.
static QgsGeometry fromPoint(const QgsPoint &point)
Creates a new geometry from a QgsPoint object.
QgsGeometry difference(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points making up this geometry that do not make up other.
Q_INVOKABLE bool overlaps(const QgsGeometry &geometry) const
Returns true if the geometry overlaps another geometry.
Q_DECL_DEPRECATED int avoidIntersections(const QList< QgsVectorLayer * > &avoidIntersectionsLayers, const QHash< QgsVectorLayer *, QSet< QgsFeatureId > > &ignoreFeatures=(QHash< QgsVectorLayer *, QSet< QgsFeatureId > >()))
Modifies geometry to avoid intersections with the layers specified in project properties.
QgsGeometry shortestLine(const QgsGeometry &other) const
Returns the shortest line joining this geometry to another geometry.
Does vector analysis using the GEOS library and handles import, export, and exception handling.
Definition qgsgeos.h:192
double distance(const QgsAbstractGeometry *geom, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Calculates the distance between this and geom.
Definition qgsgeos.cpp:624
QgsAbstractGeometry * buffer(double distance, int segments, QString *errorMsg=nullptr, QgsFeedback *feedback=nullptr) const override
Buffers the geometry.
Definition qgsgeos.cpp:2432
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
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
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
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:3940
Offers geometry processing methods.
QgsGeometry triangularWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized triangular waves along the boundary of the geometry, with the specified wavelen...
QgsGeometry triangularWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs triangular waves along the boundary of the geometry, with the specified wavelength and amp...
QgsGeometry roundWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs rounded (sine-like) waves along the boundary of the geometry, with the specified wavelengt...
QgsGeometry poleOfInaccessibility(double precision, double *distanceFromBoundary=nullptr) const
Calculates the approximate pole of inaccessibility for a surface, which is the most distant internal ...
QgsGeometry squareWaves(double wavelength, double amplitude, bool strictWavelength=false) const
Constructs square waves along the boundary of the geometry, with the specified wavelength and amplitu...
QgsGeometry variableWidthBufferByM(int segments) const
Calculates a variable width buffer using the m-values from a (multi)line geometry.
QgsGeometry extrude(double x, double y) const
Will extrude a line or (segmentized) curve by a given offset and return a polygon representation of i...
QgsGeometry roundWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized rounded (sine-like) waves along the boundary of the geometry,...
QgsGeometry orthogonalize(double tolerance=1.0E-8, int maxIterations=1000, double angleThreshold=15.0) const
Attempts to orthogonalize a line or polygon geometry by shifting vertices to make the geometries angl...
QString lastError() const
Returns an error string referring to the last error encountered.
QgsGeometry orientedMinimumBoundingBox(double &area, double &angle, double &width, double &height) const
Returns the oriented minimum bounding box for the geometry, which is the smallest (by area) rotated r...
QgsGeometry densifyByDistance(double distance) const
Densifies the geometry by adding regularly placed extra nodes inside each segment so that the maximum...
QgsGeometry taperedBuffer(double startWidth, double endWidth, int segments) const
Calculates a tapered width buffer for a (multi)curve geometry.
QgsGeometry densifyByCount(int extraNodesPerSegment) const
Densifies the geometry by adding the specified number of extra nodes within each segment of the geome...
QgsGeometry applyDashPattern(const QVector< double > &pattern, Qgis::DashPatternLineEndingRule startRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternLineEndingRule endRule=Qgis::DashPatternLineEndingRule::NoRule, Qgis::DashPatternSizeAdjustment adjustment=Qgis::DashPatternSizeAdjustment::ScaleBothDashAndGap, double patternOffset=0) const
Applies a dash pattern to a geometry, returning a MultiLineString geometry which is the input geometr...
QgsGeometry squareWavesRandomized(double minimumWavelength, double maximumWavelength, double minimumAmplitude, double maximumAmplitude, unsigned long seed=0) const
Constructs randomized square waves along the boundary of the geometry, with the specified wavelength ...
QgsGeometry convertToCurves(double distanceTolerance, double angleTolerance) const
Attempts to convert a non-curved geometry into a curved geometry type (e.g.
bool isAxisParallelRectangle(double maximumDeviation, bool simpleRectanglesOnly=false) const
Returns true if the geometry is a polygon that is almost an axis-parallel rectangle.
Custom exception class when argument are invalid.
Line string geometry type, with support for z-dimension and m-values.
static std::unique_ptr< QgsLineString > fromQPolygonF(const QPolygonF &polygon)
Returns a new linestring from a QPolygonF polygon input.
QgsLineString * clone() const override
Clones the geometry by performing a deep copy.
Perform transforms between map coordinates and device coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transforms a point p from map (world) coordinates to device coordinates.
QgsCurve * curveN(int index)
Returns the curve with the specified index.
Multi line string geometry collection.
QgsLineString * lineStringN(int index)
Returns the line string with the specified index.
Multi point geometry collection.
QgsPoint * pointN(int index)
Returns the point with the specified index.
Multi polygon geometry collection.
QgsPolygon * polygonN(int index)
Returns the polygon with the specified index.
QgsSurface * surfaceN(int index)
Returns the surface with the specified index.
Custom exception class which is raised when an operation is not supported.
Represents a 2D point.
Definition qgspointxy.h:62
void setY(double y)
Sets the y value of the point.
Definition qgspointxy.h:132
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
void setX(double x)
Sets the x value of the point.
Definition qgspointxy.h:122
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:168
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 x
Definition qgspoint.h:56
QgsPoint project(double distance, double azimuth, double inclination=90.0) const
Returns a new point which corresponds to this point projected by a specified distance with specified ...
Definition qgspoint.cpp:743
double y
Definition qgspoint.h:57
Polygon geometry type.
Definition qgspolygon.h:37
Polyhedral surface geometry type.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum
bool dropZValue() override
Drops any z-dimensions which exist in the geometry.
bool dropMValue() override
Drops any measure values which exist in the geometry.
int numPoints() const override
Returns the number of points in the curve.
void points(QgsPointSequence &pts) const override
Returns a list of points within the curve.
const double * yData() const
Returns a const pointer to the y vertex data.
const double * xData() const
Returns a const pointer to the x vertex data.
Triangle geometry type.
Definition qgstriangle.h:33
Triangulated surface geometry type.
Represents a vector layer which manages a vector based dataset.
Java-style iterator for traversal of vertices of a geometry.
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 Q_INVOKABLE bool hasZ(Qgis::WkbType type)
Tests whether a WKB type contains the z-dimension.
static Qgis::WkbType singleType(Qgis::WkbType type)
Returns the single type for a WKB type.
Definition qgswkbtypes.h:53
static Q_INVOKABLE bool hasM(Qgis::WkbType type)
Tests whether a WKB type contains m values.
static Q_INVOKABLE bool isNurbsType(Qgis::WkbType type)
Returns true if the WKB type is a NURBS curve type.
static Q_INVOKABLE bool isCurvedType(Qgis::WkbType type)
Returns true if the WKB type is a curved type or can contain curved geometries.
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.
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.
static Qgis::WkbType curveType(Qgis::WkbType type)
Returns the curve type for a WKB type.
Contains geos related utilities and functions.
Definition qgsgeos.h:129
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
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:8462
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:8100
#define BUILTIN_UNREACHABLE
Definition qgis.h:8498
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:8461
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7826
T qgsgeometry_cast(QgsAbstractGeometry *geom)
QVector< QgsPoint > QgsPointSequence
Q_GLOBAL_STATIC_WITH_ARGS(PalPropertyList, palHiddenProperties,({ static_cast< int >(QgsPalLayerSettings::Property::PositionX), static_cast< int >(QgsPalLayerSettings::Property::PositionY), static_cast< int >(QgsPalLayerSettings::Property::Show), static_cast< int >(QgsPalLayerSettings::Property::LabelRotation), static_cast< int >(QgsPalLayerSettings::Property::Family), static_cast< int >(QgsPalLayerSettings::Property::FontStyle), static_cast< int >(QgsPalLayerSettings::Property::Size), static_cast< int >(QgsPalLayerSettings::Property::Bold), static_cast< int >(QgsPalLayerSettings::Property::Italic), static_cast< int >(QgsPalLayerSettings::Property::Underline), static_cast< int >(QgsPalLayerSettings::Property::Color), static_cast< int >(QgsPalLayerSettings::Property::Strikeout), static_cast< int >(QgsPalLayerSettings::Property::MultiLineAlignment), static_cast< int >(QgsPalLayerSettings::Property::BufferSize), static_cast< int >(QgsPalLayerSettings::Property::BufferDraw), static_cast< int >(QgsPalLayerSettings::Property::BufferColor), static_cast< int >(QgsPalLayerSettings::Property::LabelDistance), static_cast< int >(QgsPalLayerSettings::Property::Hali), static_cast< int >(QgsPalLayerSettings::Property::Vali), static_cast< int >(QgsPalLayerSettings::Property::ScaleVisibility), static_cast< int >(QgsPalLayerSettings::Property::MinScale), static_cast< int >(QgsPalLayerSettings::Property::MaxScale), static_cast< int >(QgsPalLayerSettings::Property::AlwaysShow), static_cast< int >(QgsPalLayerSettings::Property::CalloutDraw), static_cast< int >(QgsPalLayerSettings::Property::LabelAllParts) })) Q_GLOBAL_STATIC_WITH_ARGS(SymbolPropertyList
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
std::unique_ptr< QgsLineString > smoothCurve(const QgsLineString &line, const unsigned int iterations, const double offset, double squareDistThreshold, double maxAngleRads, bool isRing)
QCache< QString, QgsGeometry > WktCache
QVector< QgsPolylineXY > QgsPolygonXY
Polygon: first item of the list is outer ring, inner rings (if any) start from second item.
Definition qgsgeometry.h:92
CORE_EXPORT QDataStream & operator>>(QDataStream &in, QgsGeometry &geometry)
Reads a geometry from stream in into geometry. QGIS version compatibility is not guaranteed.
CORE_EXPORT QDataStream & operator<<(QDataStream &out, const QgsGeometry &geometry)
Writes the geometry to stream out. QGIS version compatibility is not guaranteed.
QVector< QgsPolylineXY > QgsMultiPolylineXY
A collection of QgsPolylines that share a common collection of attributes.
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition qgsgeometry.h:98
QVector< QgsPointXY > QgsPolylineXY
Polyline as represented as a vector of two-dimensional points.
Definition qgsgeometry.h:63
QVector< QgsPolygonXY > QgsMultiPolygonXY
A collection of QgsPolygons that share a common collection of attributes.
QgsPointSequence QgsPolyline
Polyline as represented as a vector of points.
Definition qgsgeometry.h:72
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71
std::unique_ptr< QgsAbstractGeometry > geometry
QgsGeometryPrivate(std::unique_ptr< QgsAbstractGeometry > geometry)
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:35
int vertex
Vertex number.
bool isValid() const
Returns true if the vertex id is valid.
Definition qgsvertexid.h:51
int part
Part number.
Definition qgsvertexid.h:96
int ring
Ring number.
Definition qgsvertexid.h:99