-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathqgspointlocator.cpp
1490 lines (1247 loc) · 46.2 KB
/
qgspointlocator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgspointlocator.cpp
--------------------------------------
Date : November 2014
Copyright : (C) 2014 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgspointlocator.h"
#include "qgsfeatureiterator.h"
#include "qgsgeometry.h"
#include "qgsvectorlayer.h"
#include "qgswkbptr.h"
#include "qgis.h"
#include "qgslogger.h"
#include "qgsrenderer.h"
#include "qgsapplication.h"
#include "qgsvectorlayerfeatureiterator.h"
#include "qgsexpressioncontextutils.h"
#include "qgslinestring.h"
#include "qgscurvepolygon.h"
#include "qgsrendercontext.h"
#include "qgspointlocatorinittask.h"
#include <spatialindex/SpatialIndex.h>
#include <QLinkedListIterator>
#include <QtConcurrent>
using namespace SpatialIndex;
static SpatialIndex::Point point2point( const QgsPointXY &point )
{
double plow[2] = { point.x(), point.y() };
return Point( plow, 2 );
}
static SpatialIndex::Region rect2region( const QgsRectangle &rect )
{
double pLow[2] = { rect.xMinimum(), rect.yMinimum() };
double pHigh[2] = { rect.xMaximum(), rect.yMaximum() };
return SpatialIndex::Region( pLow, pHigh, 2 );
}
// Ahh.... another magic number. Taken from QgsVectorLayer::snapToGeometry() call to closestSegmentWithContext().
// The default epsilon used for sqrDistToSegment (1e-8) is too high when working with lat/lon coordinates
// I still do not fully understand why the sqrDistToSegment() code uses epsilon and if the square distance
// is lower than epsilon it will have a special logic...
static const double POINT_LOC_EPSILON = 1e-12;
////////////////////////////////////////////////////////////////////////////
/**
* \ingroup core
* \brief Helper class for bulk loading of R-trees.
* \note not available in Python bindings
*/
class QgsPointLocator_Stream : public IDataStream
{
public:
explicit QgsPointLocator_Stream( const QLinkedList<RTree::Data *> &dataList )
: mDataList( dataList )
, mIt( mDataList )
{ }
IData *getNext() override { return mIt.next(); }
bool hasNext() override { return mIt.hasNext(); }
uint32_t size() override { Q_ASSERT( false && "not available" ); return 0; }
void rewind() override { Q_ASSERT( false && "not available" ); }
private:
QLinkedList<RTree::Data *> mDataList;
QLinkedListIterator<RTree::Data *> mIt;
};
////////////////////////////////////////////////////////////////////////////
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for vertices - builds a list of matches.
* \note not available in Python bindings
*/
class QgsPointLocator_VisitorNearestVertex : public IVisitor
{
public:
QgsPointLocator_VisitorNearestVertex( QgsPointLocator *pl, QgsPointLocator::Match &m, const QgsPointXY &srcPoint, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mBest( m )
, mSrcPoint( srcPoint )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
int vertexIndex, beforeVertex, afterVertex;
double sqrDist;
const QgsPointXY pt = geom->closestVertex( mSrcPoint, vertexIndex, beforeVertex, afterVertex, sqrDist );
if ( sqrDist < 0 )
return; // probably empty geometry
const QgsPointLocator::Match m( QgsPointLocator::Vertex, mLocator->mLayer, id, std::sqrt( sqrDist ), pt, vertexIndex );
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
return;
if ( !mBest.isValid() || m.distance() < mBest.distance() )
mBest = m;
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::Match &mBest;
QgsPointXY mSrcPoint;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for centroid - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.12
*/
class QgsPointLocator_VisitorNearestCentroid : public IVisitor
{
public:
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for centroid - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.12
*/
QgsPointLocator_VisitorNearestCentroid( QgsPointLocator *pl, QgsPointLocator::Match &m, const QgsPointXY &srcPoint, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mBest( m )
, mSrcPoint( srcPoint )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
const QgsPointXY pt = geom->centroid().asPoint();
const QgsPointLocator::Match m( QgsPointLocator::Centroid, mLocator->mLayer, id, std::sqrt( mSrcPoint.sqrDist( pt ) ), pt, -1 );
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
return;
if ( !mBest.isValid() || m.distance() < mBest.distance() )
mBest = m;
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::Match &mBest;
QgsPointXY mSrcPoint;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
////////////////////////////////////////////////////////////////////////////
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for middle segment - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.12
*/
class QgsPointLocator_VisitorNearestMiddleOfSegment: public IVisitor
{
public:
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for middle segment - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.12
*/
QgsPointLocator_VisitorNearestMiddleOfSegment( QgsPointLocator *pl, QgsPointLocator::Match &m, const QgsPointXY &srcPoint, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mBest( m )
, mSrcPoint( srcPoint )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
QgsPointXY pt;
int afterVertex;
const double sqrDist = geom->closestSegmentWithContext( mSrcPoint, pt, afterVertex, nullptr, POINT_LOC_EPSILON );
if ( sqrDist < 0 )
return;
QgsPointXY edgePoints[2];
edgePoints[0] = geom->vertexAt( afterVertex - 1 );
edgePoints[1] = geom->vertexAt( afterVertex );
pt = QgsPointXY( ( edgePoints[0].x() + edgePoints[1].x() ) / 2.0, ( edgePoints[0].y() + edgePoints[1].y() ) / 2.0 );
const QgsPointLocator::Match m( QgsPointLocator::MiddleOfSegment, mLocator->mLayer, id, std::sqrt( mSrcPoint.sqrDist( pt ) ), pt, afterVertex - 1 );
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
return;
if ( !mBest.isValid() || m.distance() < mBest.distance() )
mBest = m;
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::Match &mBest;
QgsPointXY mSrcPoint;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
////////////////////////////////////////////////////////////////////////////
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for line endpoints (start or end vertex) - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.20
*/
class QgsPointLocator_VisitorNearestLineEndpoint : public IVisitor
{
public:
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for line endpoints (start or end vertex) - builds a list of matches.
*/
QgsPointLocator_VisitorNearestLineEndpoint( QgsPointLocator *pl, QgsPointLocator::Match &m, const QgsPointXY &srcPoint, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mBest( m )
, mSrcPoint( srcPoint )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
const QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
QgsPointXY bestPoint;
int bestVertexNumber = -1;
auto replaceIfBetter = [this, &bestPoint, &bestVertexNumber]( const QgsPoint & candidate, int vertexNumber )
{
if ( bestPoint.isEmpty() || candidate.distanceSquared( mSrcPoint.x(), mSrcPoint.y() ) < bestPoint.sqrDist( mSrcPoint ) )
{
bestPoint = QgsPointXY( candidate );
bestVertexNumber = vertexNumber;
}
};
switch ( QgsWkbTypes::geometryType( geom->wkbType() ) )
{
case Qgis::GeometryType::Point:
case Qgis::GeometryType::Unknown:
case Qgis::GeometryType::Null:
return;
case Qgis::GeometryType::Line:
{
int partStartVertexNum = 0;
for ( auto partIt = geom->const_parts_begin(); partIt != geom->const_parts_end(); ++partIt )
{
if ( const QgsCurve *curve = qgsgeometry_cast< const QgsCurve * >( *partIt ) )
{
replaceIfBetter( curve->startPoint(), partStartVertexNum );
replaceIfBetter( curve->endPoint(), partStartVertexNum + curve->numPoints() - 1 );
partStartVertexNum += curve->numPoints();
}
}
break;
}
case Qgis::GeometryType::Polygon:
{
int partStartVertexNum = 0;
for ( auto partIt = geom->const_parts_begin(); partIt != geom->const_parts_end(); ++partIt )
{
if ( const QgsCurvePolygon *polygon = qgsgeometry_cast< const QgsCurvePolygon * >( *partIt ) )
{
if ( polygon->exteriorRing() )
{
replaceIfBetter( polygon->exteriorRing()->startPoint(), partStartVertexNum );
partStartVertexNum += polygon->exteriorRing()->numPoints();
}
for ( int i = 0; i < polygon->numInteriorRings(); ++i )
{
const QgsCurve *ring = polygon->interiorRing( i );
replaceIfBetter( ring->startPoint(), partStartVertexNum );
partStartVertexNum += ring->numPoints();
}
}
}
break;
}
}
const QgsPointLocator::Match m( QgsPointLocator::LineEndpoint, mLocator->mLayer, id, std::sqrt( mSrcPoint.sqrDist( bestPoint ) ), bestPoint, bestVertexNumber );
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
return;
if ( !mBest.isValid() || m.distance() < mBest.distance() )
mBest = m;
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::Match &mBest;
QgsPointXY mSrcPoint;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
////////////////////////////////////////////////////////////////////////////
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for edges - builds a list of matches.
* \note not available in Python bindings
*/
class QgsPointLocator_VisitorNearestEdge : public IVisitor
{
public:
QgsPointLocator_VisitorNearestEdge( QgsPointLocator *pl, QgsPointLocator::Match &m, const QgsPointXY &srcPoint, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mBest( m )
, mSrcPoint( srcPoint )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
QgsPointXY pt;
int afterVertex;
const double sqrDist = geom->closestSegmentWithContext( mSrcPoint, pt, afterVertex, nullptr, POINT_LOC_EPSILON );
if ( sqrDist < 0 )
return;
QgsPointXY edgePoints[2];
edgePoints[0] = geom->vertexAt( afterVertex - 1 );
edgePoints[1] = geom->vertexAt( afterVertex );
const QgsPointLocator::Match m( QgsPointLocator::Edge, mLocator->mLayer, id, std::sqrt( sqrDist ), pt, afterVertex - 1, edgePoints );
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
return;
if ( !mBest.isValid() || m.distance() < mBest.distance() )
mBest = m;
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::Match &mBest;
QgsPointXY mSrcPoint;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
////////////////////////////////////////////////////////////////////////////
/**
* \ingroup core
* \brief Helper class used when traversing the index with areas - builds a list of matches.
* \note not available in Python bindings
*/
class QgsPointLocator_VisitorArea : public IVisitor
{
public:
//! constructor
QgsPointLocator_VisitorArea( QgsPointLocator *pl, const QgsPointXY &origPt, QgsPointLocator::MatchList &list, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mList( list )
, mFilter( filter )
, mGeomPt( QgsGeometry::fromPointXY( origPt ) )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
QgsGeometry *g = mLocator->mGeoms.value( id );
if ( !g )
return; // should not happen, but be safe
if ( g->intersects( mGeomPt ) )
{
const QgsPointLocator::Match m( QgsPointLocator::Area, mLocator->mLayer, id, 0, mGeomPt.asPoint() );
if ( mFilter && !mFilter->acceptMatch( m ) )
return;
mList << m;
}
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::MatchList &mList;
QgsPointLocator::MatchFilter *mFilter = nullptr;
QgsGeometry mGeomPt;
};
////////////////////////////////////////////////////////////////////////////
// code adapted from
// http://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm
struct _CohenSutherland
{
explicit _CohenSutherland( const QgsRectangle &rect ) : mRect( rect ) {}
typedef int OutCode;
static const int INSIDE = 0; // 0000
static const int LEFT = 1; // 0001
static const int RIGHT = 2; // 0010
static const int BOTTOM = 4; // 0100
static const int TOP = 8; // 1000
QgsRectangle mRect;
OutCode computeOutCode( double x, double y )
{
OutCode code = INSIDE; // initialized as being inside of clip window
if ( x < mRect.xMinimum() ) // to the left of clip window
code |= LEFT;
else if ( x > mRect.xMaximum() ) // to the right of clip window
code |= RIGHT;
if ( y < mRect.yMinimum() ) // below the clip window
code |= BOTTOM;
else if ( y > mRect.yMaximum() ) // above the clip window
code |= TOP;
return code;
}
bool isSegmentInRect( double x0, double y0, double x1, double y1 )
{
// compute outcodes for P0, P1, and whatever point lies outside the clip rectangle
OutCode outcode0 = computeOutCode( x0, y0 );
OutCode outcode1 = computeOutCode( x1, y1 );
bool accept = false;
while ( true )
{
if ( !( outcode0 | outcode1 ) )
{
// Bitwise OR is 0. Trivially accept and get out of loop
accept = true;
break;
}
else if ( outcode0 & outcode1 )
{
// Bitwise AND is not 0. Trivially reject and get out of loop
break;
}
else
{
// failed both tests, so calculate the line segment to clip
// from an outside point to an intersection with clip edge
double x, y;
// At least one endpoint is outside the clip rectangle; pick it.
const OutCode outcodeOut = outcode0 ? outcode0 : outcode1;
// Now find the intersection point;
// use formulas y = y0 + slope * (x - x0), x = x0 + (1 / slope) * (y - y0)
if ( outcodeOut & TOP )
{
// point is above the clip rectangle
x = x0 + ( x1 - x0 ) * ( mRect.yMaximum() - y0 ) / ( y1 - y0 );
y = mRect.yMaximum();
}
else if ( outcodeOut & BOTTOM )
{
// point is below the clip rectangle
x = x0 + ( x1 - x0 ) * ( mRect.yMinimum() - y0 ) / ( y1 - y0 );
y = mRect.yMinimum();
}
else if ( outcodeOut & RIGHT )
{
// point is to the right of clip rectangle
y = y0 + ( y1 - y0 ) * ( mRect.xMaximum() - x0 ) / ( x1 - x0 );
x = mRect.xMaximum();
}
else if ( outcodeOut & LEFT )
{
// point is to the left of clip rectangle
y = y0 + ( y1 - y0 ) * ( mRect.xMinimum() - x0 ) / ( x1 - x0 );
x = mRect.xMinimum();
}
else
break;
// Now we move outside point to intersection point to clip
// and get ready for next pass.
if ( outcodeOut == outcode0 )
{
x0 = x;
y0 = y;
outcode0 = computeOutCode( x0, y0 );
}
else
{
x1 = x;
y1 = y;
outcode1 = computeOutCode( x1, y1 );
}
}
}
return accept;
}
};
static QgsPointLocator::MatchList _geometrySegmentsInRect( QgsGeometry *geom, const QgsRectangle &rect, QgsVectorLayer *vl, QgsFeatureId fid )
{
// this code is stupidly based on QgsGeometry::closestSegmentWithContext
// we need iterator for segments...
QgsPointLocator::MatchList lst;
// geom is converted to a MultiCurve
QgsGeometry straightGeom = geom->convertToType( Qgis::GeometryType::Line, true );
// and convert to straight segemnt / converts curve to linestring
straightGeom.convertToStraightSegment();
// so, you must have multilinestring
//
// Special case: Intersections cannot be done on an empty linestring like
// QgsGeometry(QgsLineString()) or QgsGeometry::fromWkt("LINESTRING EMPTY")
if ( straightGeom.isEmpty() || ( ( straightGeom.type() != Qgis::GeometryType::Line ) && ( !straightGeom.isMultipart() ) ) )
return lst;
_CohenSutherland cs( rect );
int pointIndex = 0;
for ( auto part = straightGeom.const_parts_begin(); part != straightGeom.const_parts_end(); ++part )
{
// Checking for invalid linestrings
// A linestring should/(must?) have at least two points.
QgsCurve *curve = qgsgeometry_cast<QgsCurve *>( *part );
Q_ASSERT( !curve->hasCurvedSegments() );
if ( curve->numPoints() < 2 )
continue;
QgsAbstractGeometry::vertex_iterator it = ( *part )->vertices_begin();
QgsPointXY prevPoint( *it );
it++;
while ( it != ( *part )->vertices_end() )
{
const QgsPointXY thisPoint( *it );
if ( cs.isSegmentInRect( prevPoint.x(), prevPoint.y(), thisPoint.x(), thisPoint.y() ) )
{
QgsPointXY edgePoints[2];
edgePoints[0] = prevPoint;
edgePoints[1] = thisPoint;
lst << QgsPointLocator::Match( QgsPointLocator::Edge, vl, fid, 0, QgsPointXY(), pointIndex - 1, edgePoints );
}
prevPoint = QgsPointXY( *it );
it++;
pointIndex += 1;
}
}
return lst;
}
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for edges - builds a list of matches.
* \note not available in Python bindings
*/
class QgsPointLocator_VisitorEdgesInRect : public IVisitor
{
public:
QgsPointLocator_VisitorEdgesInRect( QgsPointLocator *pl, QgsPointLocator::MatchList &lst, const QgsRectangle &srcRect, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mList( lst )
, mSrcRect( srcRect )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
const auto segmentsInRect {_geometrySegmentsInRect( geom, mSrcRect, mLocator->mLayer, id )};
for ( const QgsPointLocator::Match &m : segmentsInRect )
{
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
continue;
mList << m;
}
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::MatchList &mList;
QgsRectangle mSrcRect;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
////////////////////////////////////////////////////////////////////////////
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for vertices - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.6
*/
class QgsPointLocator_VisitorVerticesInRect : public IVisitor
{
public:
//! Constructs the visitor
QgsPointLocator_VisitorVerticesInRect( QgsPointLocator *pl, QgsPointLocator::MatchList &lst, const QgsRectangle &srcRect, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mList( lst )
, mSrcRect( srcRect )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ) }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ) }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
const QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
for ( QgsAbstractGeometry::vertex_iterator it = geom->vertices_begin(); it != geom->vertices_end(); ++it )
{
if ( mSrcRect.contains( *it ) )
{
const QgsPointLocator::Match m( QgsPointLocator::Vertex, mLocator->mLayer, id, 0, *it, geom->vertexNrFromVertexId( it.vertexId() ) );
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
continue;
mList << m;
}
}
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::MatchList &mList;
QgsRectangle mSrcRect;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for centroid - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.10
*/
class QgsPointLocator_VisitorCentroidsInRect : public IVisitor
{
public:
//! Constructs the visitor
QgsPointLocator_VisitorCentroidsInRect( QgsPointLocator *pl, QgsPointLocator::MatchList &lst, const QgsRectangle &srcRect, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mList( lst )
, mSrcRect( srcRect )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ); }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ); }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
const QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
const QgsPointXY centroid = geom->centroid().asPoint();
if ( mSrcRect.contains( centroid ) )
{
const QgsPointLocator::Match m( QgsPointLocator::Centroid, mLocator->mLayer, id, 0, centroid, -1 );
// in range queries the filter may reject some matches
if ( !( mFilter && !mFilter->acceptMatch( m ) ) )
mList << m;
}
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::MatchList &mList;
QgsRectangle mSrcRect;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
/**
* \ingroup core
* \brief Helper class used when traversing the index looking for middle segment - builds a list of matches.
* \note not available in Python bindings
* \since QGIS 3.10
*/
class QgsPointLocator_VisitorMiddlesInRect : public IVisitor
{
public:
//! Constructs the visitor
QgsPointLocator_VisitorMiddlesInRect( QgsPointLocator *pl, QgsPointLocator::MatchList &lst, const QgsRectangle &srcRect, QgsPointLocator::MatchFilter *filter = nullptr )
: mLocator( pl )
, mList( lst )
, mSrcRect( srcRect )
, mFilter( filter )
{}
void visitNode( const INode &n ) override { Q_UNUSED( n ); }
void visitData( std::vector<const IData *> &v ) override { Q_UNUSED( v ); }
void visitData( const IData &d ) override
{
const QgsFeatureId id = d.getIdentifier();
const QgsGeometry *geom = mLocator->mGeoms.value( id );
if ( !geom )
return; // should not happen, but be safe
for ( QgsAbstractGeometry::const_part_iterator itPart = geom->const_parts_begin() ; itPart != geom->const_parts_end() ; ++itPart )
{
QgsAbstractGeometry::vertex_iterator it = ( *itPart )->vertices_begin();
QgsAbstractGeometry::vertex_iterator itPrevious = ( *itPart )->vertices_begin();
it++;
for ( ; it != geom->vertices_end(); ++it, ++itPrevious )
{
const QgsPointXY pt( ( ( *itPrevious ).x() + ( *it ).x() ) / 2.0, ( ( *itPrevious ).y() + ( *it ).y() ) / 2.0 );
if ( mSrcRect.contains( pt ) )
{
const QgsPointLocator::Match m( QgsPointLocator::MiddleOfSegment, mLocator->mLayer, id, 0, pt, geom->vertexNrFromVertexId( it.vertexId() ) );
// in range queries the filter may reject some matches
if ( mFilter && !mFilter->acceptMatch( m ) )
continue;
mList << m;
}
}
}
}
private:
QgsPointLocator *mLocator = nullptr;
QgsPointLocator::MatchList &mList;
QgsRectangle mSrcRect;
QgsPointLocator::MatchFilter *mFilter = nullptr;
};
////////////////////////////////////////////////////////////////////////////
#include <QStack>
/**
* \ingroup core
* \brief Helper class to dump the R-index nodes and their content
* \note not available in Python bindings
*/
class QgsPointLocator_DumpTree : public SpatialIndex::IQueryStrategy
{
private:
QStack<id_type> ids;
public:
void getNextEntry( const IEntry &entry, id_type &nextEntry, bool &hasNext ) override
{
const INode *n = dynamic_cast<const INode *>( &entry );
if ( !n )
return;
QgsDebugMsgLevel( QStringLiteral( "NODE: %1" ).arg( n->getIdentifier() ), 4 );
if ( n->getLevel() > 0 )
{
// inner nodes
for ( uint32_t cChild = 0; cChild < n->getChildrenCount(); cChild++ )
{
QgsDebugMsgLevel( QStringLiteral( "- CH: %1" ).arg( n->getChildIdentifier( cChild ) ), 4 );
ids.push( n->getChildIdentifier( cChild ) );
}
}
else
{
// leaves
for ( uint32_t cChild = 0; cChild < n->getChildrenCount(); cChild++ )
{
QgsDebugMsgLevel( QStringLiteral( "- L: %1" ).arg( n->getChildIdentifier( cChild ) ), 4 );
}
}
if ( ! ids.empty() )
{
nextEntry = ids.back();
ids.pop();
hasNext = true;
}
else
hasNext = false;
}
};
////////////////////////////////////////////////////////////////////////////
QgsPointLocator::QgsPointLocator( QgsVectorLayer *layer, const QgsCoordinateReferenceSystem &destCRS, const QgsCoordinateTransformContext &transformContext, const QgsRectangle *extent )
: mLayer( layer )
{
if ( destCRS.isValid() )
{
mTransform = QgsCoordinateTransform( layer->crs(), destCRS, transformContext );
}
setExtent( extent );
mStorage.reset( StorageManager::createNewMemoryStorageManager() );
connect( mLayer, &QgsVectorLayer::featureAdded, this, &QgsPointLocator::onFeatureAdded );
connect( mLayer, &QgsVectorLayer::featureDeleted, this, &QgsPointLocator::onFeatureDeleted );
connect( mLayer, &QgsVectorLayer::geometryChanged, this, &QgsPointLocator::onGeometryChanged );
connect( mLayer, &QgsVectorLayer::attributeValueChanged, this, &QgsPointLocator::onAttributeValueChanged );
connect( mLayer, &QgsVectorLayer::dataChanged, this, &QgsPointLocator::destroyIndex );
}
QgsPointLocator::~QgsPointLocator()
{
// don't delete a locator if there is an indexing task running on it
mIsDestroying = true;
if ( mIsIndexing )
waitForIndexingFinished();
destroyIndex();
}
QgsCoordinateReferenceSystem QgsPointLocator::destinationCrs() const
{
return mTransform.isValid() ? mTransform.destinationCrs() : QgsCoordinateReferenceSystem();
}
void QgsPointLocator::setExtent( const QgsRectangle *extent )
{
if ( mIsIndexing )
// already indexing, return!
return;
mExtent.reset( extent ? new QgsRectangle( *extent ) : nullptr );
destroyIndex();
}
void QgsPointLocator::setRenderContext( const QgsRenderContext *context )
{
if ( mIsIndexing )
// already indexing, return!
return;
disconnect( mLayer, &QgsVectorLayer::styleChanged, this, &QgsPointLocator::destroyIndex );
destroyIndex();
mContext.reset( nullptr );
if ( context )
{
mContext = std::unique_ptr<QgsRenderContext>( new QgsRenderContext( *context ) );
connect( mLayer, &QgsVectorLayer::styleChanged, this, &QgsPointLocator::destroyIndex );
}
}
void QgsPointLocator::onInitTaskFinished()
{
Q_ASSERT_X( QThread::currentThread() == qApp->thread(), "QgsPointLocator::onInitTaskFinished", "was not called on main thread" );
// Check that we don't call this method twice, when calling waitForFinished
// for instance (because of taskCompleted signal)
if ( !mIsIndexing )
return;
if ( mIsDestroying )
return;
mIsIndexing = false;
mRenderer.reset();
mSource.reset();
// treat added and deleted feature while indexing
for ( const QgsFeatureId fid : std::as_const( mAddedFeatures ) )
onFeatureAdded( fid );
mAddedFeatures.clear();
for ( const QgsFeatureId fid : std::as_const( mDeletedFeatures ) )
onFeatureDeleted( fid );
mDeletedFeatures.clear();
emit initFinished( mInitTask->isBuildOK() );
}
bool QgsPointLocator::init( int maxFeaturesToIndex, bool relaxed )
{
const Qgis::GeometryType geomType = mLayer->geometryType();
if ( geomType == Qgis::GeometryType::Null // nothing to index
|| hasIndex()
|| mIsIndexing ) // already indexing, return!
return true;
if ( !mLayer->dataProvider()
|| !mLayer->dataProvider()->isValid() )
return false;
mSource.reset( new QgsVectorLayerFeatureSource( mLayer ) );
if ( mContext )
{
mRenderer.reset( mLayer->renderer() ? mLayer->renderer()->clone() : nullptr );
mContext->expressionContext() << QgsExpressionContextUtils::layerScope( mLayer );
}
mIsIndexing = true;
if ( relaxed )
{
mInitTask = new QgsPointLocatorInitTask( this );
connect( mInitTask, &QgsPointLocatorInitTask::taskTerminated, this, &QgsPointLocator::onInitTaskFinished );
connect( mInitTask, &QgsPointLocatorInitTask::taskCompleted, this, &QgsPointLocator::onInitTaskFinished );
QgsApplication::taskManager()->addTask( mInitTask );
return true;
}
else
{
const bool ok = rebuildIndex( maxFeaturesToIndex );