QGIS API Documentation 4.3.0-Master (16eddb2670e)
Loading...
Searching...
No Matches
pal.cpp
Go to the documentation of this file.
1/*
2 * libpal - Automated Placement of Labels Library
3 *
4 * Copyright (C) 2008 Maxence Laurent, MIS-TIC, HEIG-VD
5 * University of Applied Sciences, Western Switzerland
6 * http://www.hes-so.ch
7 *
8 * Contact:
9 * maxence.laurent <at> heig-vd <dot> ch
10 * or
11 * eric.taillard <at> heig-vd <dot> ch
12 *
13 * This file is part of libpal.
14 *
15 * libpal is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * libpal is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with libpal. If not, see <http://www.gnu.org/licenses/>.
27 *
28 */
29
30#include "pal.h"
31
32#include "costcalculator.h"
33#include "feature.h"
34#include "geomfunction.h"
35#include "internalexception.h"
36#include "labelposition.h"
37#include "layer.h"
38#include "palrtree.h"
39#include "pointset.h"
40#include "problem.h"
41#include "qgsgeometry.h"
42#include "qgsgeos.h"
43#include "qgslabelingengine.h"
45#include "qgsrendercontext.h"
46#include "qgsruntimeprofiler.h"
48#include "util.h"
49
50#include <QString>
51
52using namespace Qt::StringLiterals;
53
54#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 10, 0 )
55#include "qgsmessagelog.h"
56#endif
57#include <cfloat>
58#include <list>
59
60
61using namespace pal;
62
63const QgsSettingsEntryInteger *Pal::settingsRenderingLabelCandidatesLimitPoints = new QgsSettingsEntryInteger( u"label-candidates-limit-points"_s, sTreePal, 0 );
64const QgsSettingsEntryInteger *Pal::settingsRenderingLabelCandidatesLimitLines = new QgsSettingsEntryInteger( u"label-candidates-limit-lines"_s, sTreePal, 0 );
65const QgsSettingsEntryInteger *Pal::settingsRenderingLabelCandidatesLimitPolygons = new QgsSettingsEntryInteger( u"label-candidates-limit-polygons"_s, sTreePal, 0 );
66
67
69 : mFlags( flags )
70{
71 mGlobalCandidatesLimitPoint = Pal::settingsRenderingLabelCandidatesLimitPoints->value();
72 mGlobalCandidatesLimitLine = Pal::settingsRenderingLabelCandidatesLimitLines->value();
73 mGlobalCandidatesLimitPolygon = Pal::settingsRenderingLabelCandidatesLimitPolygons->value();
74}
75
76Pal::~Pal() = default;
77
78void Pal::removeLayer( Layer *layer )
79{
80 if ( !layer )
81 return;
82
83 mMutex.lock();
84
85 for ( auto it = mLayers.begin(); it != mLayers.end(); ++it )
86 {
87 if ( it->second.get() == layer )
88 {
89 mLayers.erase( it );
90 break;
91 }
92 }
93 mMutex.unlock();
94}
95
96Layer *Pal::addLayer( QgsAbstractLabelProvider *provider, const QString &layerName, Qgis::LabelPlacement arrangement, double defaultPriority, bool active, bool toLabel )
97{
98 mMutex.lock();
99
100#ifdef QGISDEBUG
101 for ( const auto &it : mLayers )
102 {
103 Q_ASSERT( it.first != provider );
104 }
105#endif
106
107 auto layer = std::make_unique< Layer >( provider, layerName, arrangement, defaultPriority, active, toLabel, this );
108 Layer *res = layer.get();
109 mLayers.emplace_back( std::make_pair( provider, std::move( layer ) ) );
110 mMutex.unlock();
111
112 // cppcheck-suppress returnDanglingLifetime
113 return res;
114}
115
116std::unique_ptr<Problem> Pal::extractProblem( const QgsRectangle &extent, const QgsGeometry &mapBoundary, QgsRenderContext &context )
117{
118 QgsLabelingEngineFeedback *feedback = qobject_cast< QgsLabelingEngineFeedback * >( context.feedback() );
119 QgsLabelingEngineContext labelContext( context );
120 labelContext.setExtent( extent );
121 labelContext.setMapBoundaryGeometry( mapBoundary );
122
123 std::unique_ptr< QgsScopedRuntimeProfile > extractionProfile;
125 {
126 extractionProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Placing labels" ), u"rendering"_s );
127 }
128
129 // expand out the incoming buffer by 1000x -- that's the visible map extent, yet we may be getting features which exceed this extent
130 // (while 1000x may seem excessive here, this value is only used for scaling coordinates in the spatial indexes
131 // and the consequence of inserting coordinates outside this extent is worse than the consequence of setting this value too large.)
132 const QgsRectangle maxCoordinateExtentForSpatialIndices = extent.buffered( std::max( extent.width(), extent.height() ) * 1000 );
133
134 // to store obstacles
135 PalRtree< FeaturePart > obstacles( maxCoordinateExtentForSpatialIndices );
136 PalRtree< LabelPosition > allCandidatesFirstRound( maxCoordinateExtentForSpatialIndices );
137 std::vector< FeaturePart * > allObstacleParts;
138 auto prob = std::make_unique< Problem >( maxCoordinateExtentForSpatialIndices );
139
140 double bbx[4];
141 double bby[4];
142
143 bbx[0] = bbx[3] = prob->mMapExtentBounds[0] = extent.xMinimum();
144 bby[0] = bby[1] = prob->mMapExtentBounds[1] = extent.yMinimum();
145 bbx[1] = bbx[2] = prob->mMapExtentBounds[2] = extent.xMaximum();
146 bby[2] = bby[3] = prob->mMapExtentBounds[3] = extent.yMaximum();
147
148 prob->pal = this;
149
150 std::list< std::unique_ptr< Feats > > features;
151
152 // prepare map boundary
153 geos::unique_ptr mapBoundaryGeos( QgsGeos::asGeos( mapBoundary ) );
154 geos::prepared_unique_ptr mapBoundaryPrepared( GEOSPrepare_r( QgsGeosContext::get(), mapBoundaryGeos.get() ) );
155
156 int obstacleCount = 0;
157
158 // first step : extract features from layers
159
160 std::size_t previousFeatureCount = 0;
161 int previousObstacleCount = 0;
162
163 QStringList layersWithFeaturesInBBox;
164
165 QMutexLocker palLocker( &mMutex );
166
167 double step = !mLayers.empty() ? 100.0 / mLayers.size() : 1;
168 int index = -1;
169 std::unique_ptr< QgsScopedRuntimeProfile > candidateProfile;
171 {
172 candidateProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Generating label candidates" ), u"rendering"_s );
173 }
174
175 for ( auto it = mLayers.rbegin(); it != mLayers.rend(); ++it )
176 {
177 index++;
178 if ( feedback )
179 feedback->setProgress( index * step );
180
181 Layer *layer = it->second.get();
182 if ( !layer )
183 {
184 // invalid layer name
185 continue;
186 }
187
188 // only select those who are active
189 if ( !layer->active() )
190 continue;
191
192 if ( feedback )
193 feedback->emit candidateCreationAboutToBegin( it->first );
194
195 std::unique_ptr< QgsScopedRuntimeProfile > layerProfile;
197 {
198 layerProfile = std::make_unique< QgsScopedRuntimeProfile >( it->first->providerId(), u"rendering"_s );
199 }
200
201 // check for connected features with the same label text and join them
202 if ( layer->mergeConnectedLines() )
203 layer->joinConnectedFeatures();
204
205 if ( isCanceled() )
206 return nullptr;
207
209
210 if ( isCanceled() )
211 return nullptr;
212
213 QMutexLocker locker( &layer->mMutex );
214
215 const double featureStep = !layer->mFeatureParts.empty() ? step / layer->mFeatureParts.size() : 1;
216 std::size_t featureIndex = 0;
217 // generate candidates for all features
218 for ( const std::unique_ptr< FeaturePart > &featurePart : std::as_const( layer->mFeatureParts ) )
219 {
220 if ( feedback )
221 feedback->setProgress( index * step + featureIndex * featureStep );
222 featureIndex++;
223
224 if ( isCanceled() )
225 break;
226
227 // Holes of the feature are obstacles
228 for ( int i = 0; i < featurePart->getNumSelfObstacles(); i++ )
229 {
230 FeaturePart *selfObstacle = featurePart->getSelfObstacle( i );
231 obstacles.insert( selfObstacle, selfObstacle->boundingBox() );
232 allObstacleParts.emplace_back( selfObstacle );
233
234 if ( !featurePart->getSelfObstacle( i )->getHoleOf() )
235 {
236 //ERROR: SHOULD HAVE A PARENT!!!!!
237 }
238 }
239
240 // generate candidates for the feature part
241 std::vector< std::unique_ptr< LabelPosition > > candidates = featurePart->createCandidates( this );
242
243 if ( isCanceled() )
244 break;
245
246 // purge candidates that violate known constraints, eg
247 // - they are outside the bbox
248 // - they violate a labeling rule
249 candidates.erase(
250 std::remove_if(
251 candidates.begin(),
252 candidates.end(),
253 [&mapBoundaryPrepared, &labelContext, this]( std::unique_ptr< LabelPosition > &candidate ) {
254 if ( showPartialLabels() )
255 {
256 if ( !candidate->intersects( mapBoundaryPrepared.get() ) )
257 return true;
258 }
259 else
260 {
261 if ( !candidate->within( mapBoundaryPrepared.get() ) )
262 return true;
263 }
264
265 for ( QgsAbstractLabelingEngineRule *rule : std::as_const( mRules ) )
266 {
267 if ( rule->candidateIsIllegal( candidate.get(), labelContext ) )
268 {
269 return true;
270 }
271 }
272 return false;
273 }
274 ),
275 candidates.end()
276 );
277
278 if ( isCanceled() )
279 break;
280
281 if ( !candidates.empty() )
282 {
283 for ( std::unique_ptr< LabelPosition > &candidate : candidates )
284 {
285 candidate->insertIntoIndex( allCandidatesFirstRound, this );
286 candidate->setGlobalId( mNextCandidateId++ );
287 }
288
289 std::sort( candidates.begin(), candidates.end(), CostCalculator::candidateSortGrow );
290
291 // valid features are added to fFeats
292 auto ft = std::make_unique< Feats >();
293 ft->feature = featurePart.get();
294 ft->shape = nullptr;
295 ft->candidates = std::move( candidates );
296 ft->priority = featurePart->calculatePriority();
297 features.emplace_back( std::move( ft ) );
298 }
299 else
300 {
301 // no candidates, so generate a default "point on surface" one
302 std::unique_ptr< LabelPosition > unplacedPosition = featurePart->createCandidatePointOnSurface( featurePart.get() );
303 if ( !unplacedPosition )
304 continue;
305
306 if ( featurePart->feature()->allowDegradedPlacement() )
307 {
308 // if we are allowing degraded placements, we throw the default candidate in too
309 unplacedPosition->insertIntoIndex( allCandidatesFirstRound, this );
310 unplacedPosition->setGlobalId( mNextCandidateId++ );
311 candidates.emplace_back( std::move( unplacedPosition ) );
312
313 // valid features are added to fFeats
314 auto ft = std::make_unique< Feats >();
315 ft->feature = featurePart.get();
316 ft->shape = nullptr;
317 ft->candidates = std::move( candidates );
318 ft->priority = featurePart->calculatePriority();
319 features.emplace_back( std::move( ft ) );
320 }
321 else
322 {
323 // not displaying all labels for this layer, so it goes into the unlabeled feature list
324 prob->positionsWithNoCandidates()->emplace_back( std::move( unplacedPosition ) );
325 }
326 }
327 }
328 if ( isCanceled() )
329 return nullptr;
330
331 if ( !mFlags.testFlag( Qgis::LabelingFlag::IgnoreObstacles ) )
332 {
333 // collate all layer obstacles
334 for ( FeaturePart *obstaclePart : std::as_const( layer->mObstacleParts ) )
335 {
336 if ( isCanceled() )
337 break; // do not continue searching
338
339 // insert into obstacles
340 obstacles.insert( obstaclePart, obstaclePart->boundingBox() );
341 allObstacleParts.emplace_back( obstaclePart );
342 obstacleCount++;
343 }
344 }
345
346 if ( isCanceled() )
347 return nullptr;
348
349 locker.unlock();
350
351 if ( features.size() - previousFeatureCount > 0 || obstacleCount > previousObstacleCount )
352 {
353 layersWithFeaturesInBBox << layer->name();
354 }
355 previousFeatureCount = features.size();
356 previousObstacleCount = obstacleCount;
357
358 if ( feedback )
359 feedback->emit candidateCreationFinished( it->first );
360 }
361
362 candidateProfile.reset();
363
364 palLocker.unlock();
365
366 if ( isCanceled() )
367 return nullptr;
368
369 prob->mLayerCount = layersWithFeaturesInBBox.size();
370 prob->labelledLayersName = layersWithFeaturesInBBox;
371
372 prob->mFeatureCount = features.size();
373 prob->mTotalCandidates = 0;
374 prob->mCandidateCountForFeature.resize( prob->mFeatureCount );
375 prob->mFirstCandidateIndexForFeature.resize( prob->mFeatureCount );
376 prob->mUnlabeledCostForFeature.resize( prob->mFeatureCount );
377
378 if ( !features.empty() )
379 {
380 if ( !mFlags.testFlag( Qgis::LabelingFlag::IgnoreObstacles ) )
381 {
382 if ( feedback )
383 feedback->emit obstacleCostingAboutToBegin();
384
385 std::unique_ptr< QgsScopedRuntimeProfile > costingProfile;
386 if ( context.flags() & Qgis::RenderContextFlag::RecordProfile )
387 {
388 costingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Assigning label costs" ), u"rendering"_s );
389 }
390
391 // allow rules to alter candidate costs
392 for ( const auto &feature : features )
393 {
394 for ( auto &candidate : feature->candidates )
395 {
396 for ( QgsAbstractLabelingEngineRule *rule : std::as_const( mRules ) )
397 {
398 rule->alterCandidateCost( candidate.get(), labelContext );
399 }
400 }
401 }
402
403 // Filtering label positions against obstacles
404 index = -1;
405 step = !allObstacleParts.empty() ? 100.0 / allObstacleParts.size() : 1;
406
407 for ( FeaturePart *obstaclePart : allObstacleParts )
408 {
409 index++;
410 if ( feedback )
411 feedback->setProgress( step * index );
412
413 if ( isCanceled() )
414 break; // do not continue searching
415
416 allCandidatesFirstRound.intersects( obstaclePart->boundingBox(), [obstaclePart, this]( const LabelPosition *candidatePosition ) -> bool {
417 // test whether we should ignore this obstacle for the candidate. We do this if:
418 // 1. it's not a hole, and the obstacle belongs to the same label feature as the candidate (e.g.,
419 // features aren't obstacles for their own labels)
420 // 2. it IS a hole, and the hole belongs to a different label feature to the candidate (e.g., holes
421 // are ONLY obstacles for the labels of the feature they belong to)
422 // 3. The label is set to "Always Allow" overlap mode
423 if ( candidatePosition->getFeaturePart()->feature()->overlapHandling() == Qgis::LabelOverlapHandling::AllowOverlapAtNoCost
424 || ( !obstaclePart->getHoleOf() && candidatePosition->getFeaturePart()->hasSameLabelFeatureAs( obstaclePart ) )
425 || ( obstaclePart->getHoleOf() && !candidatePosition->getFeaturePart()->hasSameLabelFeatureAs( dynamic_cast< FeaturePart * >( obstaclePart->getHoleOf() ) ) ) )
426 {
427 return true;
428 }
429
430 CostCalculator::addObstacleCostPenalty( const_cast< LabelPosition * >( candidatePosition ), obstaclePart, this );
431 return true;
432 } );
433 }
434
435 if ( feedback )
436 feedback->emit obstacleCostingFinished();
437 }
438
439 if ( isCanceled() )
440 {
441 return nullptr;
442 }
443
444 step = prob->mFeatureCount != 0 ? 100.0 / prob->mFeatureCount : 1;
445 if ( feedback )
446 feedback->emit calculatingConflictsAboutToBegin();
447
448 std::unique_ptr< QgsScopedRuntimeProfile > conflictProfile;
449 if ( context.flags() & Qgis::RenderContextFlag::RecordProfile )
450 {
451 conflictProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Calculating conflicts" ), u"rendering"_s );
452 }
453
454 int currentLabelPositionIndex = 0;
455 // loop through all the features registered in the problem
456 for ( std::size_t featureIndex = 0; featureIndex < prob->mFeatureCount; featureIndex++ )
457 {
458 if ( feedback )
459 feedback->setProgress( static_cast< double >( featureIndex ) * step );
460
461 std::unique_ptr< Feats > feat = std::move( features.front() );
462 features.pop_front();
463
464 prob->mFirstCandidateIndexForFeature[featureIndex] = currentLabelPositionIndex;
465 prob->mUnlabeledCostForFeature[featureIndex] = std::pow( 2, 10 - 10 * feat->priority );
466
467 std::size_t maxCandidates = 0;
468 switch ( feat->feature->getGeosType() )
469 {
470 case GEOS_POINT:
471 // this is usually 0, i.e. no maximum
472 maxCandidates = feat->feature->maximumPointCandidates();
473 break;
474
475 case GEOS_LINESTRING:
476 maxCandidates = feat->feature->maximumLineCandidates();
477 break;
478
479 case GEOS_POLYGON:
480 maxCandidates = std::max( static_cast< std::size_t >( 16 ), feat->feature->maximumPolygonCandidates() );
481 break;
482 }
483
484 if ( isCanceled() )
485 return nullptr;
486
487 auto pruneHardConflicts = [&] {
488 switch ( mPlacementVersion )
489 {
491 break;
492
494 {
495 // v2 placement rips out candidates where the candidate cost is too high when compared to
496 // their inactive cost
497
498 // note, we start this at the SECOND candidate (you'll see why after this loop)
499 feat->candidates.erase(
500 std::remove_if(
501 feat->candidates.begin() + 1,
502 feat->candidates.end(),
503 [&]( std::unique_ptr< LabelPosition > &candidate ) {
504 if ( candidate->hasHardObstacleConflict() )
505 {
506 return true;
507 }
508 return false;
509 }
510 ),
511 feat->candidates.end()
512 );
513
514 if ( feat->candidates.size() == 1 && feat->candidates[0]->hasHardObstacleConflict() )
515 {
516 switch ( feat->feature->feature()->overlapHandling() )
517 {
519 {
520 // we're going to end up removing ALL candidates for this label. Oh well, that's allowed. We just need to
521 // make sure we move this last candidate to the unplaced labels list
522 prob->positionsWithNoCandidates()->emplace_back( std::move( feat->candidates.front() ) );
523 feat->candidates.clear();
524 break;
525 }
526
529 // we can't avoid overlaps for this label, but in this mode we are allowing overlaps as a last resort.
530 // => don't discard this last remaining candidate.
531 break;
532 }
533 }
534 }
535 }
536 };
537
538 // if we're not showing all labels (including conflicts) for this layer, then we prune the candidates
539 // upfront to avoid extra work...
540 switch ( feat->feature->feature()->overlapHandling() )
541 {
543 if ( !mFlags.testFlag( Qgis::LabelingFlag::IgnoreOverlaps ) )
544 {
545 pruneHardConflicts();
546 }
547 break;
548
551 break;
552 }
553
554 if ( feat->candidates.empty() )
555 continue;
556
557 // calculate final costs
558 CostCalculator::finalizeCandidatesCosts( feat.get(), bbx, bby );
559
560 // sort candidates list, best label to worst
561 std::sort( feat->candidates.begin(), feat->candidates.end(), CostCalculator::candidateSortGrow );
562
563 // but if we ARE showing all labels (including conflicts), let's go ahead and prune them now.
564 // Since we've calculated all their costs and sorted them, if we've hit the situation that ALL
565 // candidates have conflicts, then at least when we pick the first candidate to display it will be
566 // the lowest cost (i.e. best possible) overlapping candidate...
567 switch ( feat->feature->feature()->overlapHandling() )
568 {
570 break;
573 if ( !mFlags.testFlag( Qgis::LabelingFlag::IgnoreOverlaps ) )
574 {
575 pruneHardConflicts();
576 }
577 break;
578 }
579
580 // only keep the 'maxCandidates' best candidates
581 if ( maxCandidates > 0 && feat->candidates.size() > maxCandidates )
582 {
583 feat->candidates.resize( maxCandidates );
584 }
585
586 if ( isCanceled() )
587 return nullptr;
588
589 // update problem's # candidate
590 prob->mCandidateCountForFeature[featureIndex] = static_cast< int >( feat->candidates.size() );
591 prob->mTotalCandidates += static_cast< int >( feat->candidates.size() );
592
593 // add all candidates into a rtree (to speed up conflicts searching)
594 for ( std::unique_ptr< LabelPosition > &candidate : feat->candidates )
595 {
596 candidate->insertIntoIndex( prob->allCandidatesIndex(), this );
597 candidate->setProblemIds( static_cast< int >( featureIndex ), currentLabelPositionIndex++ );
598 }
599 features.emplace_back( std::move( feat ) );
600 }
601
602 if ( feedback )
603 feedback->emit calculatingConflictsFinished();
604
605 conflictProfile.reset();
606
607 int nbOverlaps = 0;
608
609 if ( feedback )
610 feedback->emit finalizingCandidatesAboutToBegin();
611
612 std::unique_ptr< QgsScopedRuntimeProfile > finalizingProfile;
613 if ( context.flags() & Qgis::RenderContextFlag::RecordProfile )
614 {
615 finalizingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing labels" ), u"rendering"_s );
616 }
617
618 index = -1;
619 step = !features.empty() ? 100.0 / features.size() : 1;
620 while ( !features.empty() ) // for each feature
621 {
622 index++;
623 if ( feedback )
624 feedback->setProgress( step * index );
625
626 if ( isCanceled() )
627 return nullptr;
628
629 std::unique_ptr< Feats > feat = std::move( features.front() );
630 features.pop_front();
631
632 for ( std::unique_ptr< LabelPosition > &candidate : feat->candidates )
633 {
634 std::unique_ptr< LabelPosition > lp = std::move( candidate );
635
636 lp->resetNumOverlaps();
637
638 // make sure that candidate's cost is less than 1
639 lp->validateCost();
640
641 //prob->feat[idlp] = j;
642
643 // lookup for overlapping candidate
644 if ( !mFlags.testFlag( Qgis::LabelingFlag::IgnoreOverlaps ) )
645 {
646 const QgsRectangle searchBounds = lp->boundingBoxForCandidateConflicts( this );
647 prob->allCandidatesIndex().intersects( searchBounds, [&lp, this]( const LabelPosition *lp2 ) -> bool {
648 if ( candidatesAreConflicting( lp.get(), lp2 ) )
649 {
650 lp->incrementNumOverlaps();
651 }
652
653 return true;
654 } );
655
656 nbOverlaps += lp->getNumOverlaps();
657 }
658
659 prob->addCandidatePosition( std::move( lp ) );
660
661 if ( isCanceled() )
662 return nullptr;
663 }
664 }
665
666 if ( feedback )
667 feedback->emit finalizingCandidatesFinished();
668
669 finalizingProfile.reset();
670
671 nbOverlaps /= 2;
672 prob->mAllNblp = prob->mTotalCandidates;
673 prob->mNbOverlap = nbOverlaps;
674 }
675
676 return prob;
677}
678
680{
681 fnIsCanceled = fnCanceled;
682 fnIsCanceledContext = context;
683}
684
685
686QList<LabelPosition *> Pal::solveProblem( Problem *prob, QgsRenderContext &context, bool displayAll, QList<LabelPosition *> *unlabeled )
687{
688 QgsLabelingEngineFeedback *feedback = qobject_cast< QgsLabelingEngineFeedback * >( context.feedback() );
689
690 if ( !prob )
691 return QList<LabelPosition *>();
692
693 std::unique_ptr< QgsScopedRuntimeProfile > calculatingProfile;
695 {
696 calculatingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Calculating optimal labeling" ), u"rendering"_s );
697 }
698
699 if ( feedback )
700 feedback->emit reductionAboutToBegin();
701
702 {
703 std::unique_ptr< QgsScopedRuntimeProfile > reductionProfile;
705 {
706 reductionProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Reducing labeling" ), u"rendering"_s );
707 }
708
709 prob->reduce();
710 }
711
712 if ( feedback )
713 feedback->emit reductionFinished();
714
715 if ( feedback )
716 feedback->emit solvingPlacementAboutToBegin();
717
718 {
719 std::unique_ptr< QgsScopedRuntimeProfile > solvingProfile;
721 {
722 solvingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Solving labeling" ), u"rendering"_s );
723 }
724 try
725 {
726 prob->chainSearch( context );
727 }
728 catch ( InternalException::Empty & )
729 {
730 return QList<LabelPosition *>();
731 }
732 }
733
734 if ( feedback )
735 feedback->emit solvingPlacementFinished();
736
737 return prob->getSolution( displayAll, unlabeled );
738}
739
740void Pal::setMinIt( int min_it )
741{
742 if ( min_it >= 0 )
743 mTabuMinIt = min_it;
744}
745
746void Pal::setMaxIt( int max_it )
747{
748 if ( max_it > 0 )
749 mTabuMaxIt = max_it;
750}
751
752void Pal::setPopmusicR( int r )
753{
754 if ( r > 0 )
755 mPopmusicR = r;
756}
757
758void Pal::setEjChainDeg( int degree )
759{
760 this->mEjChainDeg = degree;
761}
762
763void Pal::setTenure( int tenure )
764{
765 this->mTenure = tenure;
766}
767
768void Pal::setCandListSize( double fact )
769{
770 this->mCandListSize = fact;
771}
772
774{
775 this->mShowPartialLabels = show;
776}
777
779{
780 return mPlacementVersion;
781}
782
787
789{
790 // we cache the value -- this can be costly to calculate, and we check this multiple times
791 // per candidate during the labeling problem solving
792
793 if ( lp1->getProblemFeatureId() == lp2->getProblemFeatureId() )
794 return false;
795
796 // conflicts are commutative - so we always store them in the cache using the smaller id as the first element of the key pair
797 auto key = qMakePair( std::min( lp1->globalId(), lp2->globalId() ), std::max( lp1->globalId(), lp2->globalId() ) );
798 auto it = mCandidateConflicts.constFind( key );
799 if ( it != mCandidateConflicts.constEnd() )
800 return *it;
801
802 bool res = false;
803
804 const double labelMarginDistance = std::max( lp1->getFeaturePart()->feature()->thinningSettings().labelMarginDistance(), lp2->getFeaturePart()->feature()->thinningSettings().labelMarginDistance() );
805
806 if ( labelMarginDistance > 0 )
807 {
808 GEOSContextHandle_t geosctxt = QgsGeosContext::get();
809 try
810 {
811#if GEOS_VERSION_NUM >= GEOS_COMPUTE_VERSION( 3, 10, 0 )
812 if ( GEOSPreparedDistanceWithin_r( geosctxt, lp1->preparedMultiPartGeom(), lp2->multiPartGeom(), labelMarginDistance ) )
813 {
814 res = true;
815 }
816#else
817 QgsMessageLog::logMessage( u"label margin distance requires GEOS 3.10+"_s );
818#endif
819 }
820 catch ( QgsGeosException &e )
821 {
822 QgsDebugError( u"GEOS exception: %1"_s.arg( e.what() ) );
823 }
824 }
825
826 if ( !res )
827 {
828 for ( QgsAbstractLabelingEngineRule *rule : mRules )
829 {
830 if ( rule->candidatesAreConflicting( lp1, lp2 ) )
831 {
832 res = true;
833 break;
834 }
835 }
836 }
837
838 res |= lp1->isInConflict( lp2 );
839
840 mCandidateConflicts.insert( key, res );
841 return res;
842}
843
844void Pal::setRules( const QList<QgsAbstractLabelingEngineRule *> &rules )
845{
846 mRules = rules;
847}
848
849int Pal::getMinIt() const
850{
851 return mTabuMaxIt;
852}
853
854int Pal::getMaxIt() const
855{
856 return mTabuMinIt;
857}
858
860{
861 return mShowPartialLabels;
862}
A rtree spatial index for use in the pal labeling engine.
Definition palrtree.h:37
void insert(T *data, const QgsRectangle &bounds)
Inserts new data into the spatial index, with the specified bounds.
Definition palrtree.h:57
LabelPlacement
Placement modes which determine how label candidates are generated for a feature.
Definition qgis.h:1307
@ IgnoreObstacles
Disable obstacle handling.
Definition qgis.h:3072
@ IgnoreOverlaps
Disable overlap detection and search solver, immediately returning lowest cost candidate per feature.
Definition qgis.h:3074
QFlags< LabelingFlag > LabelingFlags
Flags that affect drawing and placement of labels.
Definition qgis.h:3086
@ RecordProfile
Enable run-time profiling while rendering.
Definition qgis.h:2984
LabelPlacementEngineVersion
Labeling placement engine version.
Definition qgis.h:3097
@ Version2
Version 2 (default for new projects since QGIS 3.12).
Definition qgis.h:3099
@ Version1
Version 1, matches placement from QGIS <= 3.10.1.
Definition qgis.h:3098
@ AllowOverlapAtNoCost
Labels may freely overlap other labels, at no cost.
Definition qgis.h:1271
@ AllowOverlapIfRequired
Avoids overlapping labels when possible, but permit overlaps if labels for features cannot otherwise ...
Definition qgis.h:1270
@ PreventOverlap
Do not allow labels to overlap other labels.
Definition qgis.h:1269
An abstract interface class for label providers.
Abstract base class for labeling engine rules.
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
A geometry is the spatial representation of a feature.
static GEOSContextHandle_t get()
Returns a thread local instance of a GEOS context, safe for use in the current thread.
static geos::unique_ptr asGeos(const QgsGeometry &geometry, double precision=0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlags())
Returns a geos geometry - caller takes ownership of the object (should be deleted with GEOSGeom_destr...
Definition qgsgeos.cpp:284
double labelMarginDistance() const
Returns the minimum distance (in label units) between labels for this feature and other labels.
const QgsLabelFeatureThinningSettings & thinningSettings() const
Returns the thinning settings for this label.
Encapsulates the context for a labeling engine run.
void setMapBoundaryGeometry(const QgsGeometry &geometry)
Sets the map label boundary geometry, which defines the limits within which labels may be placed in t...
void setExtent(const QgsRectangle &extent)
Sets the map extent defining the limits for labeling.
QgsFeedback subclass for granular reporting of labeling engine progress.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum
QgsRectangle buffered(double width) const
Gets rectangle enlarged by buffer.
Contains information about the context of a rendering operation.
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly during rendering to check if rendering shou...
Qgis::RenderContextFlags flags() const
Returns combination of flags used for rendering.
An integer settings entry.
static void addObstacleCostPenalty(pal::LabelPosition *lp, pal::FeaturePart *obstacle, Pal *pal)
Increase candidate's cost according to its collision with passed feature.
static void finalizeCandidatesCosts(Feats *feat, double bbx[4], double bby[4])
Sort candidates by costs, skip the worse ones, evaluate polygon candidates.
static bool candidateSortGrow(const std::unique_ptr< pal::LabelPosition > &c1, const std::unique_ptr< pal::LabelPosition > &c2)
Sorts label candidates in ascending order of cost.
Represents a part of a label feature.
Definition feature.h:60
QgsLabelFeature * feature()
Returns the parent feature.
Definition feature.h:87
Thrown when trying to access an empty data set.
LabelPosition is a candidate feature label position.
bool isInConflict(const LabelPosition *ls) const
Check whether or not this overlap with another labelPosition.
const GEOSGeometry * multiPartGeom() const
Returns a GEOS representation of all label parts as a multipolygon.
unsigned int globalId() const
Returns the global ID for the candidate, which is unique for a single run of the pal labelling engine...
FeaturePart * getFeaturePart() const
Returns the feature corresponding to this labelposition.
const GEOSPreparedGeometry * preparedMultiPartGeom() const
Returns a prepared GEOS representation of all label parts as a multipolygon.
int getProblemFeatureId() const
QMutex mMutex
Definition layer.h:344
std::deque< std::unique_ptr< FeaturePart > > mFeatureParts
List of feature parts.
Definition layer.h:315
bool active() const
Returns whether the layer is currently active.
Definition layer.h:197
bool mergeConnectedLines() const
Returns whether connected lines will be merged before labeling.
Definition layer.h:255
void joinConnectedFeatures()
Join connected features with the same label text.
Definition layer.cpp:308
void chopFeaturesAtRepeatDistance()
Chop layer features at the repeat distance.
Definition layer.cpp:379
void setPlacementVersion(Qgis::LabelPlacementEngineVersion placementVersion)
Sets the placement engine version, which dictates how the label placement problem is solved.
Definition pal.cpp:783
void setShowPartialLabels(bool show)
Sets whether partial labels show be allowed.
Definition pal.cpp:773
std::unique_ptr< Problem > extractProblem(const QgsRectangle &extent, const QgsGeometry &mapBoundary, QgsRenderContext &context)
Extracts the labeling problem for the specified map extent - only features within this extent will be...
Definition pal.cpp:116
Qgis::LabelPlacementEngineVersion placementVersion() const
Returns the placement engine version, which dictates how the label placement problem is solved.
Definition pal.cpp:778
Qgis::LabelingFlags flags() const
Returns labeling flags.
Definition pal.h:111
void setRules(const QList< QgsAbstractLabelingEngineRule * > &rules)
Sets rules which the labeling solution must satisfy.
Definition pal.cpp:844
void removeLayer(Layer *layer)
remove a layer
Definition pal.cpp:78
bool candidatesAreConflicting(const LabelPosition *lp1, const LabelPosition *lp2) const
Returns true if a labelling candidate lp1 conflicts with lp2.
Definition pal.cpp:788
friend class Layer
Definition pal.h:90
bool(* FnIsCanceled)(void *ctx)
Cancellation check callback function.
Definition pal.h:135
bool showPartialLabels() const
Returns whether partial labels should be allowed.
Definition pal.cpp:859
static const QgsSettingsEntryInteger * settingsRenderingLabelCandidatesLimitLines
Definition pal.h:96
static const QgsSettingsEntryInteger * settingsRenderingLabelCandidatesLimitPoints
Definition pal.h:95
static const QgsSettingsEntryInteger * settingsRenderingLabelCandidatesLimitPolygons
Definition pal.h:97
friend class Problem
Definition pal.h:88
bool isCanceled()
Check whether the job has been canceled.
Definition pal.h:141
QList< LabelPosition * > solveProblem(Problem *prob, QgsRenderContext &context, bool displayAll, QList< pal::LabelPosition * > *unlabeled=nullptr)
Solves the labeling problem, selecting the best candidate locations for all labels and returns a list...
Definition pal.cpp:686
friend class FeaturePart
Definition pal.h:89
Pal(Qgis::LabelingFlags flags)
Constructor for pal labeling engine.
Definition pal.cpp:68
void registerCancellationCallback(FnIsCanceled fnCanceled, void *context)
Register a function that returns whether this job has been canceled - PAL calls it during the computa...
Definition pal.cpp:679
QList< QgsAbstractLabelingEngineRule * > rules() const
Returns the rules which the labeling solution must satisfy.
Definition pal.h:293
Layer * addLayer(QgsAbstractLabelProvider *provider, const QString &layerName, Qgis::LabelPlacement arrangement, double defaultPriority, bool active, bool toLabel)
add a new layer
Definition pal.cpp:96
QgsRectangle boundingBox() const
Returns the point set bounding box.
Definition pointset.h:162
QList< LabelPosition * > getSolution(bool returnInactive, QList< LabelPosition * > *unlabeled=nullptr)
Solves the labeling problem, selecting the best candidate locations for all labels and returns a list...
Definition problem.cpp:609
void chainSearch(QgsRenderContext &context)
Test with very-large scale neighborhood.
Definition problem.cpp:535
void reduce()
Gets called AFTER extractProblem.
Definition problem.cpp:58
std::unique_ptr< GEOSGeometry, GeosDeleter > unique_ptr
Scoped GEOS pointer.
Definition qgsgeos.h:165
std::unique_ptr< const GEOSPreparedGeometry, GeosDeleter > prepared_unique_ptr
Scoped GEOS prepared geometry pointer.
Definition qgsgeos.h:170
#define QgsDebugError(str)
Definition qgslogger.h:71