QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsvectorlayerrenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectorlayerrenderer.cpp
3 --------------------------------------
4 Date : December 2013
5 Copyright : (C) 2013 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
17
18#include "qgsapplication.h"
19#include "qgsexception.h"
23#include "qgslabelsink.h"
24#include "qgslogger.h"
25#include "qgsmapclippingutils.h"
26#include "qgsmessagelog.h"
27#include "qgspainteffect.h"
28#include "qgspallabeling.h"
29#include "qgsrendercontext.h"
31#include "qgsrenderer.h"
32#include "qgsruntimeprofiler.h"
36#include "qgssymbol.h"
37#include "qgssymbollayer.h"
38#include "qgsthreadingutils.h"
39#include "qgsvectorlayer.h"
46
47#include <QPicture>
48#include <QThread>
49#include <QTimer>
50
52 : QgsMapLayerRenderer( layer->id(), &context )
53 , mFeedback( std::make_unique< QgsFeedback >() )
54 , mLayer( layer )
55 , mLayerName( layer->name() )
56 , mFields( layer->fields() )
57 , mSource( std::make_unique< QgsVectorLayerFeatureSource >( layer ) )
58 , mNoSetLayerExpressionContext( layer->customProperty( QStringLiteral( "_noset_layer_expression_context" ) ).toBool() )
59 , mEnableProfile( context.flags() & Qgis::RenderContextFlag::RecordProfile )
60{
61 QElapsedTimer timer;
62 timer.start();
63 std::unique_ptr< QgsFeatureRenderer > mainRenderer( layer->renderer() ? layer->renderer()->clone() : nullptr );
64
65 QgsVectorLayerSelectionProperties *selectionProperties = qobject_cast< QgsVectorLayerSelectionProperties * >( layer->selectionProperties() );
66 switch ( selectionProperties->selectionRenderingMode() )
67 {
69 break;
70
72 {
73 // overwrite default selection color if layer has a specific selection color set
74 const QColor layerSelectionColor = selectionProperties->selectionColor();
75 if ( layerSelectionColor.isValid() )
76 context.setSelectionColor( layerSelectionColor );
77 break;
78 }
79
81 {
82 if ( QgsSymbol *selectionSymbol = qobject_cast< QgsVectorLayerSelectionProperties * >( layer->selectionProperties() )->selectionSymbol() )
83 mSelectionSymbol.reset( selectionSymbol->clone() );
84 break;
85 }
86 }
87
88 if ( !mainRenderer )
89 return;
90
91 QList< const QgsFeatureRendererGenerator * > generators = layer->featureRendererGenerators();
92 std::sort( generators.begin(), generators.end(), []( const QgsFeatureRendererGenerator * g1, const QgsFeatureRendererGenerator * g2 )
93 {
94 return g1->level() < g2->level();
95 } );
96
97 bool insertedMainRenderer = false;
98 double prevLevel = std::numeric_limits< double >::lowest();
99 // cppcheck-suppress danglingLifetime
100 mRenderer = mainRenderer.get();
101 for ( const QgsFeatureRendererGenerator *generator : std::as_const( generators ) )
102 {
103 if ( generator->level() >= 0 && prevLevel < 0 && !insertedMainRenderer )
104 {
105 // insert main renderer when level changes from <0 to >0
106 mRenderers.emplace_back( std::move( mainRenderer ) );
107 insertedMainRenderer = true;
108 }
109 mRenderers.emplace_back( generator->createRenderer() );
110 prevLevel = generator->level();
111 }
112 // cppcheck-suppress accessMoved
113 if ( mainRenderer )
114 {
115 // cppcheck-suppress accessMoved
116 mRenderers.emplace_back( std::move( mainRenderer ) );
117 }
118
119 mSelectedFeatureIds = layer->selectedFeatureIds();
120
121 mDrawVertexMarkers = nullptr != layer->editBuffer();
122
123 mGeometryType = layer->geometryType();
124
125 mFeatureBlendMode = layer->featureBlendMode();
126
127 if ( context.isTemporal() )
128 {
129 QgsVectorLayerTemporalContext temporalContext;
130 temporalContext.setLayer( layer );
131 mTemporalFilter = qobject_cast< const QgsVectorLayerTemporalProperties * >( layer->temporalProperties() )->createFilterString( temporalContext, context.temporalRange() );
132 QgsDebugMsgLevel( "Rendering with Temporal Filter: " + mTemporalFilter, 2 );
133 }
134
135 // if there's already a simplification method specified via the context, we respect that. Otherwise, we fall back
136 // to the layer's individual setting
138 {
139 mSimplifyMethod = renderContext()->vectorSimplifyMethod();
142 }
143 else
144 {
145 mSimplifyMethod = layer->simplifyMethod();
147 }
148
149 mVertexMarkerOnlyForSelection = QgsSettingsRegistryCore::settingsDigitizingMarkerOnlyForSelected->value();
150
151 QString markerTypeString = QgsSettingsRegistryCore::settingsDigitizingMarkerStyle->value();
152 if ( markerTypeString == QLatin1String( "Cross" ) )
153 {
154 mVertexMarkerStyle = Qgis::VertexMarkerType::Cross;
155 }
156 else if ( markerTypeString == QLatin1String( "SemiTransparentCircle" ) )
157 {
159 }
160 else
161 {
162 mVertexMarkerStyle = Qgis::VertexMarkerType::NoMarker;
163 }
164
166
167 // cppcheck-suppress danglingLifetime
168 QgsDebugMsgLevel( "rendering v2:\n " + mRenderer->dump(), 2 );
169
170 if ( mDrawVertexMarkers )
171 {
172 // set editing vertex markers style (main renderer only)
173 mRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
174 }
175
176 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
177 {
178 mAttrNames.unite( renderer->usedAttributes( context ) );
179 }
180 if ( context.hasRenderedFeatureHandlers() )
181 {
182 const QList< QgsRenderedFeatureHandlerInterface * > handlers = context.renderedFeatureHandlers();
183 for ( QgsRenderedFeatureHandlerInterface *handler : handlers )
184 mAttrNames.unite( handler->usedAttributes( layer, context ) );
185 }
186
187 //register label and diagram layer to the labeling engine
188 prepareLabeling( layer, mAttrNames );
189 prepareDiagrams( layer, mAttrNames );
190
191 mClippingRegions = QgsMapClippingUtils::collectClippingRegionsForLayer( context, layer );
192
193 if ( std::any_of( mRenderers.begin(), mRenderers.end(), []( const auto & renderer ) { return renderer->forceRasterRender(); } ) )
194 {
195 //raster rendering is forced for this layer
196 mForceRasterRender = true;
197 }
198
199 const bool allowFlattening = context.rasterizedRenderingPolicy() != Qgis::RasterizedRenderingPolicy::ForceVector;
200 if ( allowFlattening &&
201 ( ( layer->blendMode() != QPainter::CompositionMode_SourceOver )
202 || ( layer->featureBlendMode() != QPainter::CompositionMode_SourceOver )
203 || ( !qgsDoubleNear( layer->opacity(), 1.0 ) ) ) )
204 {
205 //layer properties require rasterization
206 mForceRasterRender = true;
207 }
208
209 mReadyToCompose = false;
210 mPreparationTime = timer.elapsed();
211}
212
214
216{
217 mRenderTimeHint = time;
218}
219
221{
222 return mFeedback.get();
223}
224
226{
227 return mForceRasterRender;
228}
229
231{
233 if ( mRenderer && mRenderer->flags().testFlag( Qgis::FeatureRendererFlag::AffectsLabeling ) )
235 return res;
236}
237
239{
240 QgsScopedThreadName threadName( QStringLiteral( "render:%1" ).arg( mLayerName ) );
241
242 if ( mGeometryType == Qgis::GeometryType::Null || mGeometryType == Qgis::GeometryType::Unknown )
243 {
244 mReadyToCompose = true;
245 return true;
246 }
247
248 if ( mRenderers.empty() )
249 {
250 mReadyToCompose = true;
251 mErrors.append( QObject::tr( "No renderer for drawing." ) );
252 return false;
253 }
254
255 std::unique_ptr< QgsScopedRuntimeProfile > profile;
256 if ( mEnableProfile )
257 {
258 profile = std::make_unique< QgsScopedRuntimeProfile >( mLayerName, QStringLiteral( "rendering" ), layerId() );
259 if ( mPreparationTime > 0 )
260 QgsApplication::profiler()->record( QObject::tr( "Create renderer" ), mPreparationTime / 1000.0, QStringLiteral( "rendering" ) );
261 }
262
263 // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
264 // cached version of the layer during rendering instead of the usual progressive updates
265 if ( mRenderTimeHint > 0 && mRenderTimeHint <= MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
266 {
267 mBlockRenderUpdates = true;
268 mElapsedTimer.start();
269 }
270
271 bool res = true;
272 int rendererIndex = 0;
273 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
274 {
275 if ( mFeedback->isCanceled() || !res )
276 {
277 break;
278 }
279 res = renderInternal( renderer.get(), rendererIndex++ ) && res;
280 }
281
282 mReadyToCompose = true;
283 return res && !renderContext()->renderingStopped();
284}
285
286bool QgsVectorLayerRenderer::renderInternal( QgsFeatureRenderer *renderer, int rendererIndex )
287{
288 const bool isMainRenderer = renderer == mRenderer;
289
290 QgsRenderContext &context = *renderContext();
291 context.setSymbologyReferenceScale( renderer->referenceScale() );
292
293 if ( renderer->type() == QLatin1String( "nullSymbol" ) )
294 {
295 // a little shortcut for the null symbol renderer - most of the time it is not going to render anything
296 // so we can even skip the whole loop to fetch features
297 if ( !isMainRenderer ||
298 ( !mDrawVertexMarkers && !mLabelProvider && !mDiagramProvider && mSelectedFeatureIds.isEmpty() ) )
299 return true;
300 }
301
302 std::unique_ptr< QgsScopedRuntimeProfile > preparingProfile;
303 if ( mEnableProfile )
304 {
305 QString title;
306 if ( mRenderers.size() > 1 )
307 title = QObject::tr( "Preparing render %1" ).arg( rendererIndex + 1 );
308 else
309 title = QObject::tr( "Preparing render" );
310 preparingProfile = std::make_unique< QgsScopedRuntimeProfile >( title, QStringLiteral( "rendering" ) );
311 }
312
313 QgsScopedQPainterState painterState( context.painter() );
314
315 bool usingEffect = false;
316 if ( renderer->paintEffect() && renderer->paintEffect()->enabled() )
317 {
318 usingEffect = true;
319 renderer->paintEffect()->begin( context );
320 }
321
322 // Per feature blending mode
324 && mFeatureBlendMode != QPainter::CompositionMode_SourceOver )
325 {
326 // set the painter to the feature blend mode, so that features drawn
327 // on this layer will interact and blend with each other
328 context.painter()->setCompositionMode( mFeatureBlendMode );
329 }
330
331 renderer->startRender( context, mFields );
332
333 if ( renderer->canSkipRender() )
334 {
335 // nothing to draw for now...
336 renderer->stopRender( context );
337 return true;
338 }
339
340 QString rendererFilter = renderer->filter( mFields );
341
342 QgsRectangle requestExtent = context.extent();
343 if ( !mClippingRegions.empty() )
344 {
345 mClipFilterGeom = QgsMapClippingUtils::calculateFeatureRequestGeometry( mClippingRegions, context, mApplyClipFilter );
346 requestExtent = requestExtent.intersect( mClipFilterGeom.boundingBox() );
347
348 mClipFeatureGeom = QgsMapClippingUtils::calculateFeatureIntersectionGeometry( mClippingRegions, context, mApplyClipGeometries );
349
350 bool needsPainterClipPath = false;
351 const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, context, Qgis::LayerType::Vector, needsPainterClipPath );
352 if ( needsPainterClipPath )
353 context.painter()->setClipPath( path, Qt::IntersectClip );
354
355 mLabelClipFeatureGeom = QgsMapClippingUtils::calculateLabelIntersectionGeometry( mClippingRegions, context, mApplyLabelClipGeometries );
356
357 if ( mDiagramProvider )
358 mDiagramProvider->setClipFeatureGeometry( mLabelClipFeatureGeom );
359 }
360
361 renderer->modifyRequestExtent( requestExtent, context );
362
363 QgsFeatureRequest featureRequest = QgsFeatureRequest()
364 .setFilterRect( requestExtent )
365 .setSubsetOfAttributes( mAttrNames, mFields )
366 .setExpressionContext( context.expressionContext() );
367 if ( renderer->orderByEnabled() )
368 {
369 featureRequest.setOrderBy( renderer->orderBy() );
370 }
371
372 const QgsFeatureFilterProvider *featureFilterProvider = context.featureFilterProvider();
373 if ( featureFilterProvider )
374 {
376 if ( featureFilterProvider->isFilterThreadSafe() )
377 {
378 featureFilterProvider->filterFeatures( layerId(), featureRequest );
379 }
380 else
381 {
382 featureFilterProvider->filterFeatures( mLayer, featureRequest );
383 }
385 }
386 if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) )
387 {
388 featureRequest.combineFilterExpression( rendererFilter );
389 }
390 if ( !mTemporalFilter.isEmpty() )
391 {
392 featureRequest.combineFilterExpression( mTemporalFilter );
393 }
394
395 if ( renderer->usesEmbeddedSymbols() )
396 {
397 featureRequest.setFlags( featureRequest.flags() | Qgis::FeatureRequestFlag::EmbeddedSymbols );
398 }
399
400 // enable the simplification of the geometries (Using the current map2pixel context) before send it to renderer engine.
401 if ( mSimplifyGeometry )
402 {
403 double map2pixelTol = mSimplifyMethod.threshold();
404 bool validTransform = true;
405
406 const QgsMapToPixel &mtp = context.mapToPixel();
407 map2pixelTol *= mtp.mapUnitsPerPixel();
408 const QgsCoordinateTransform ct = context.coordinateTransform();
409
410 // resize the tolerance using the change of size of an 1-BBOX from the source CoordinateSystem to the target CoordinateSystem
411 if ( ct.isValid() && !ct.isShortCircuited() )
412 {
413 try
414 {
415 QgsCoordinateTransform toleranceTransform = ct;
416 QgsPointXY center = context.extent().center();
417 double rectSize = toleranceTransform.sourceCrs().mapUnits() == Qgis::DistanceUnit::Degrees ? 0.0008983 /* ~100/(40075014/360=111319.4833) */ : 100;
418
419 QgsRectangle sourceRect = QgsRectangle( center.x(), center.y(), center.x() + rectSize, center.y() + rectSize );
420 toleranceTransform.setBallparkTransformsAreAppropriate( true );
421 QgsRectangle targetRect = toleranceTransform.transform( sourceRect );
422
423 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceTransformRect=%1" ).arg( sourceRect.toString( 16 ) ), 4 );
424 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetTransformRect=%1" ).arg( targetRect.toString( 16 ) ), 4 );
425
426 if ( !sourceRect.isEmpty() && sourceRect.isFinite() && !targetRect.isEmpty() && targetRect.isFinite() )
427 {
428 QgsPointXY minimumSrcPoint( sourceRect.xMinimum(), sourceRect.yMinimum() );
429 QgsPointXY maximumSrcPoint( sourceRect.xMaximum(), sourceRect.yMaximum() );
430 QgsPointXY minimumDstPoint( targetRect.xMinimum(), targetRect.yMinimum() );
431 QgsPointXY maximumDstPoint( targetRect.xMaximum(), targetRect.yMaximum() );
432
433 double sourceHypothenuse = std::sqrt( minimumSrcPoint.sqrDist( maximumSrcPoint ) );
434 double targetHypothenuse = std::sqrt( minimumDstPoint.sqrDist( maximumDstPoint ) );
435
436 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceHypothenuse=%1" ).arg( sourceHypothenuse ), 4 );
437 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetHypothenuse=%1" ).arg( targetHypothenuse ), 4 );
438
439 if ( !qgsDoubleNear( targetHypothenuse, 0.0 ) )
440 map2pixelTol *= ( sourceHypothenuse / targetHypothenuse );
441 }
442 }
443 catch ( QgsCsException &cse )
444 {
445 QgsMessageLog::logMessage( QObject::tr( "Simplify transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
446 validTransform = false;
447 }
448 }
449
450 if ( validTransform )
451 {
452 QgsSimplifyMethod simplifyMethod;
454 simplifyMethod.setTolerance( map2pixelTol );
455 simplifyMethod.setThreshold( mSimplifyMethod.threshold() );
456 simplifyMethod.setForceLocalOptimization( mSimplifyMethod.forceLocalOptimization() );
457 featureRequest.setSimplifyMethod( simplifyMethod );
458
459 QgsVectorSimplifyMethod vectorMethod = mSimplifyMethod;
460 vectorMethod.setTolerance( map2pixelTol );
461 context.setVectorSimplifyMethod( vectorMethod );
462 }
463 else
464 {
465 QgsVectorSimplifyMethod vectorMethod;
467 context.setVectorSimplifyMethod( vectorMethod );
468 }
469 }
470 else
471 {
472 QgsVectorSimplifyMethod vectorMethod;
474 context.setVectorSimplifyMethod( vectorMethod );
475 }
476
477 featureRequest.setFeedback( mFeedback.get() );
478 // also set the interruption checker for the expression context, in case the renderer uses some complex expression
479 // which could benefit from early exit paths...
480 context.expressionContext().setFeedback( mFeedback.get() );
481
482 std::unique_ptr< QgsScopedRuntimeProfile > preparingFeatureItProfile;
483 if ( mEnableProfile )
484 {
485 preparingFeatureItProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Prepare feature iteration" ), QStringLiteral( "rendering" ) );
486 }
487
488 QgsFeatureIterator fit = mSource->getFeatures( featureRequest );
489 // Attach an interruption checker so that iterators that have potentially
490 // slow fetchFeature() implementations, such as in the WFS provider, can
491 // check it, instead of relying on just the mContext.renderingStopped() check
492 // in drawRenderer()
493
494 fit.setInterruptionChecker( mFeedback.get() );
495
496 preparingFeatureItProfile.reset();
497 preparingProfile.reset();
498
499 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
500 if ( mEnableProfile )
501 {
502 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering" ), QStringLiteral( "rendering" ) );
503 }
504
505 if ( ( renderer->capabilities() & QgsFeatureRenderer::SymbolLevels ) && renderer->usingSymbolLevels() )
506 drawRendererLevels( renderer, fit );
507 else
508 drawRenderer( renderer, fit );
509
510 if ( !fit.isValid() )
511 {
512 mErrors.append( QStringLiteral( "Data source invalid" ) );
513 }
514
515 if ( usingEffect )
516 {
517 renderer->paintEffect()->end( context );
518 }
519
520 context.expressionContext().setFeedback( nullptr );
521 return true;
522}
523
524
525void QgsVectorLayerRenderer::drawRenderer( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
526{
527 QElapsedTimer timer;
528 timer.start();
529 quint64 totalLabelTime = 0;
530
531 const bool isMainRenderer = renderer == mRenderer;
532
533 QgsExpressionContextScope *symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() );
534 QgsRenderContext &context = *renderContext();
535 context.expressionContext().appendScope( symbolScope );
536
537 std::unique_ptr< QgsGeometryEngine > clipEngine;
538 if ( mApplyClipFilter )
539 {
540 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
541 clipEngine->prepareGeometry();
542 }
543
544 if ( mSelectionSymbol && isMainRenderer )
545 mSelectionSymbol->startRender( context, mFields );
546
547 QgsFeature fet;
548 while ( fit.nextFeature( fet ) )
549 {
550 try
551 {
552 if ( context.renderingStopped() )
553 {
554 QgsDebugMsgLevel( QStringLiteral( "Drawing of vector layer %1 canceled." ).arg( layerId() ), 2 );
555 break;
556 }
557
558 if ( !fet.hasGeometry() || fet.geometry().isEmpty() )
559 continue; // skip features without geometry
560
561 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
562 continue; // skip features outside of clipping region
563
564 if ( mApplyClipGeometries )
565 context.setFeatureClipGeometry( mClipFeatureGeom );
566
567 if ( ! mNoSetLayerExpressionContext )
568 context.expressionContext().setFeature( fet );
569
570 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fet.id() );
571 bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
572
573 // render feature
574 bool rendered = false;
576 {
577 if ( featureIsSelected && mSelectionSymbol )
578 {
579 // note: here we pass "false" for the selected argument, as we don't want to change
580 // the user's defined selection symbol colors or settings in any way
581 mSelectionSymbol->renderFeature( fet, context, -1, false, drawMarker );
582 rendered = renderer->willRenderFeature( fet, context );
583 }
584 else
585 {
586 rendered = renderer->renderFeature( fet, context, -1, featureIsSelected, drawMarker );
587 }
588 }
589 else
590 {
591 rendered = renderer->willRenderFeature( fet, context );
592 }
593
594 // labeling - register feature
595 if ( rendered )
596 {
597 // as soon as first feature is rendered, we can start showing layer updates.
598 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
599 // at most e.g. 3 seconds before we start forcing progressive updates.
600 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
601 {
602 mReadyToCompose = true;
603 }
604
605 // new labeling engine
606 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
607 {
608 const quint64 startLabelTime = timer.elapsed();
609 QgsGeometry obstacleGeometry;
610 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
611 QgsSymbol *symbol = nullptr;
612 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
613 {
614 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
615 }
616
617 if ( !symbols.isEmpty() )
618 {
619 symbol = symbols.at( 0 );
621 }
622
623 if ( mApplyLabelClipGeometries )
624 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
625
626 if ( mLabelProvider )
627 {
628 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
629 }
630 if ( mDiagramProvider )
631 {
632 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
633 }
634
635 if ( mApplyLabelClipGeometries )
636 context.setFeatureClipGeometry( QgsGeometry() );
637
638 totalLabelTime += ( timer.elapsed() - startLabelTime );
639 }
640 }
641 }
642 catch ( const QgsCsException &cse )
643 {
644 Q_UNUSED( cse )
645 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
646 .arg( fet.id() ).arg( cse.what() ) );
647 }
648 }
649
650 delete context.expressionContext().popScope();
651
652 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
653 if ( mEnableProfile )
654 {
655 QgsApplication::profiler()->record( QObject::tr( "Rendering features" ), ( timer.elapsed() - totalLabelTime ) / 1000.0, QStringLiteral( "rendering" ) );
656 if ( totalLabelTime > 0 )
657 {
658 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
659 }
660 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
661 }
662
663 if ( mSelectionSymbol && isMainRenderer )
664 mSelectionSymbol->stopRender( context );
665
666 stopRenderer( renderer, nullptr );
667}
668
669void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
670{
671 const bool isMainRenderer = renderer == mRenderer;
672
673 // We need to figure out in which order all the features should be rendered.
674 // Ordering is based on (a) a "level" which is determined by the configured
675 // feature rendering order" and (b) the symbol level. The "level" is
676 // determined by the values of the attributes defined in the feature
677 // rendering order settings. Each time the attribute(s) have a new distinct
678 // value, a new empty QHash is added to the "features" list. This QHash is
679 // then filled by mappings from the symbol to a list of all the features
680 // that should be rendered by that symbol.
681 //
682 // If orderBy is not enabled, this list will only ever contain a single
683 // element.
684 QList<QHash< QgsSymbol *, QList<QgsFeature> >> features;
685
686 // We have at least one "level" for the features.
687 features.push_back( {} );
688
689 QSet<int> orderByAttributeIdx;
690 if ( renderer->orderByEnabled() )
691 {
692 orderByAttributeIdx = renderer->orderBy().usedAttributeIndices( mSource->fields() );
693 }
694
695 QgsRenderContext &context = *renderContext();
696
697 QgsSingleSymbolRenderer *selRenderer = nullptr;
698 if ( !mSelectedFeatureIds.isEmpty() )
699 {
700 selRenderer = new QgsSingleSymbolRenderer( QgsSymbol::defaultSymbol( mGeometryType ) );
701 selRenderer->symbol()->setColor( context.selectionColor() );
702 selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
703 selRenderer->startRender( context, mFields );
704 }
705
706 QgsExpressionContextScope *symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() );
707 auto scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
708
709
710 std::unique_ptr< QgsGeometryEngine > clipEngine;
711 if ( mApplyClipFilter )
712 {
713 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
714 clipEngine->prepareGeometry();
715 }
716
717 if ( mApplyLabelClipGeometries )
718 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
719
720 std::unique_ptr< QgsScopedRuntimeProfile > fetchFeaturesProfile;
721 if ( mEnableProfile )
722 {
723 fetchFeaturesProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Fetching features" ), QStringLiteral( "rendering" ) );
724 }
725
726 QElapsedTimer timer;
727 timer.start();
728 quint64 totalLabelTime = 0;
729
730 // 1. fetch features
731 QgsFeature fet;
732 QVector<QVariant> prevValues; // previous values of ORDER BY attributes
733 while ( fit.nextFeature( fet ) )
734 {
735 if ( context.renderingStopped() )
736 {
737 qDebug( "rendering stop!" );
738 stopRenderer( renderer, selRenderer );
739 return;
740 }
741
742 if ( !fet.hasGeometry() )
743 continue; // skip features without geometry
744
745 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
746 continue; // skip features outside of clipping region
747
748 if ( ! mNoSetLayerExpressionContext )
749 context.expressionContext().setFeature( fet );
750 QgsSymbol *sym = renderer->symbolForFeature( fet, context );
751 if ( !sym )
752 {
753 continue;
754 }
755
756 if ( renderer->orderByEnabled() )
757 {
758 QVector<QVariant> currentValues;
759 for ( const int idx : std::as_const( orderByAttributeIdx ) )
760 {
761 currentValues.push_back( fet.attribute( idx ) );
762 }
763 if ( prevValues.empty() )
764 {
765 prevValues = std::move( currentValues );
766 }
767 else if ( currentValues != prevValues )
768 {
769 // Current values of ORDER BY attributes are different than previous
770 // values of these attributes. Start a new level.
771 prevValues = std::move( currentValues );
772 features.push_back( {} );
773 }
774 }
775
777 {
778 QHash<QgsSymbol *, QList<QgsFeature> > &featuresBack = features.back();
779 auto featuresBackIt = featuresBack.find( sym );
780 if ( featuresBackIt == featuresBack.end() )
781 {
782 featuresBackIt = featuresBack.insert( sym, QList<QgsFeature>() );
783 }
784 featuresBackIt->append( fet );
785 }
786
787 // new labeling engine
788 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
789 {
790 const quint64 startLabelTime = timer.elapsed();
791
792 QgsGeometry obstacleGeometry;
793 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
794 QgsSymbol *symbol = nullptr;
795 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
796 {
797 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
798 }
799
800 if ( !symbols.isEmpty() )
801 {
802 symbol = symbols.at( 0 );
804 }
805
806 if ( mLabelProvider )
807 {
808 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
809 }
810 if ( mDiagramProvider )
811 {
812 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
813 }
814
815 totalLabelTime += ( timer.elapsed() - startLabelTime );
816 }
817 }
818
819 fetchFeaturesProfile.reset();
820 if ( mEnableProfile )
821 {
822 if ( totalLabelTime > 0 )
823 {
824 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
825 }
826 }
827
828 if ( mApplyLabelClipGeometries )
829 context.setFeatureClipGeometry( QgsGeometry() );
830
831 scopePopper.reset();
832
833 if ( features.back().empty() )
834 {
835 // nothing to draw
836 stopRenderer( renderer, selRenderer );
837 return;
838 }
839
840
841 std::unique_ptr< QgsScopedRuntimeProfile > sortingProfile;
842 if ( mEnableProfile )
843 {
844 sortingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Sorting features" ), QStringLiteral( "rendering" ) );
845 }
846 // find out the order
847 QgsSymbolLevelOrder levels;
848 QgsSymbolList symbols = renderer->symbols( context );
849 for ( int i = 0; i < symbols.count(); i++ )
850 {
851 QgsSymbol *sym = symbols[i];
852 for ( int j = 0; j < sym->symbolLayerCount(); j++ )
853 {
854 int level = sym->symbolLayer( j )->renderingPass();
855 if ( level < 0 || level >= 1000 ) // ignore invalid levels
856 continue;
857 QgsSymbolLevelItem item( sym, j );
858 while ( level >= levels.count() ) // append new empty levels
859 levels.append( QgsSymbolLevel() );
860 levels[level].append( item );
861 }
862 }
863 sortingProfile.reset();
864
865 if ( mApplyClipGeometries )
866 context.setFeatureClipGeometry( mClipFeatureGeom );
867
868 // 2. draw features in correct order
869 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
870 {
871 for ( int l = 0; l < levels.count(); l++ )
872 {
873 const QgsSymbolLevel &level = levels[l];
874 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
875 if ( mEnableProfile )
876 {
877 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering symbol level %1" ).arg( l + 1 ), QStringLiteral( "rendering" ) );
878 }
879
880 for ( int i = 0; i < level.count(); i++ )
881 {
882 const QgsSymbolLevelItem &item = level[i];
883 if ( !featureLists.contains( item.symbol() ) )
884 {
885 QgsDebugError( QStringLiteral( "level item's symbol not found!" ) );
886 continue;
887 }
888 const int layer = item.layer();
889 const QList<QgsFeature> &lst = featureLists[item.symbol()];
890 for ( const QgsFeature &feature : lst )
891 {
892 if ( context.renderingStopped() )
893 {
894 stopRenderer( renderer, selRenderer );
895 return;
896 }
897
898 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( feature.id() );
899 if ( featureIsSelected && mSelectionSymbol )
900 continue; // defer rendering of selected symbols
901
902 // maybe vertex markers should be drawn only during the last pass...
903 const bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
904
905 if ( ! mNoSetLayerExpressionContext )
906 context.expressionContext().setFeature( feature );
907
908 try
909 {
910 renderer->renderFeature( feature, context, layer, featureIsSelected, drawMarker );
911
912 // as soon as first feature is rendered, we can start showing layer updates.
913 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
914 // at most e.g. 3 seconds before we start forcing progressive updates.
915 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
916 {
917 mReadyToCompose = true;
918 }
919 }
920 catch ( const QgsCsException &cse )
921 {
922 Q_UNUSED( cse )
923 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
924 .arg( fet.id() ).arg( cse.what() ) );
925 }
926 }
927 }
928 }
929 }
930
931 if ( mSelectionSymbol && !mSelectedFeatureIds.empty() && isMainRenderer && context.showSelection() )
932 {
933 mSelectionSymbol->startRender( context, mFields );
934
935 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
936 {
937 for ( auto it = featureLists.constBegin(); it != featureLists.constEnd(); ++it )
938 {
939 const QList<QgsFeature> &lst = it.value();
940 for ( const QgsFeature &feature : lst )
941 {
942 if ( context.renderingStopped() )
943 {
944 break;
945 }
946
947 const bool featureIsSelected = mSelectedFeatureIds.contains( feature.id() );
948 if ( !featureIsSelected )
949 continue;
950
951 const bool drawMarker = mDrawVertexMarkers && context.drawEditingInformation();
952 // note: here we pass "false" for the selected argument, as we don't want to change
953 // the user's defined selection symbol colors or settings in any way
954 mSelectionSymbol->renderFeature( feature, context, -1, false, drawMarker );
955 }
956 }
957 }
958
959 mSelectionSymbol->stopRender( context );
960 }
961
962 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
963 if ( mEnableProfile )
964 {
965 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
966 }
967
968 stopRenderer( renderer, selRenderer );
969}
970
971void QgsVectorLayerRenderer::stopRenderer( QgsFeatureRenderer *renderer, QgsSingleSymbolRenderer *selRenderer )
972{
973 QgsRenderContext &context = *renderContext();
974 renderer->stopRender( context );
975 if ( selRenderer )
976 {
977 selRenderer->stopRender( context );
978 delete selRenderer;
979 }
980}
981
982void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer *layer, QSet<QString> &attributeNames )
983{
984 QgsRenderContext &context = *renderContext();
985 // TODO: add attributes for geometry generator
986 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
987 {
988 if ( layer->labelsEnabled() )
989 {
990 if ( context.labelSink() )
991 {
992 if ( const QgsRuleBasedLabeling *rbl = dynamic_cast<const QgsRuleBasedLabeling *>( layer->labeling() ) )
993 {
994 mLabelProvider = new QgsRuleBasedLabelSinkProvider( *rbl, layer, context.labelSink() );
995 }
996 else
997 {
998 QgsPalLayerSettings settings = layer->labeling()->settings();
999 mLabelProvider = new QgsLabelSinkProvider( layer, QString(), context.labelSink(), &settings );
1000 }
1001 }
1002 else
1003 {
1004 mLabelProvider = layer->labeling()->provider( layer );
1005 }
1006 if ( mLabelProvider )
1007 {
1008 engine2->addProvider( mLabelProvider );
1009 if ( !mLabelProvider->prepare( context, attributeNames ) )
1010 {
1011 engine2->removeProvider( mLabelProvider );
1012 mLabelProvider = nullptr; // deleted by engine
1013 }
1014 }
1015 }
1016 }
1017
1018#if 0 // TODO: limit of labels, font not found
1019 QgsPalLayerSettings &palyr = mContext.labelingEngine()->layer( mLayerID );
1020
1021 // see if feature count limit is set for labeling
1022 if ( palyr.limitNumLabels && palyr.maxNumLabels > 0 )
1023 {
1024 QgsFeatureIterator fit = getFeatures( QgsFeatureRequest()
1025 .setFilterRect( mContext.extent() )
1026 .setNoAttributes() );
1027
1028 // total number of features that may be labeled
1029 QgsFeature f;
1030 int nFeatsToLabel = 0;
1031 while ( fit.nextFeature( f ) )
1032 {
1033 nFeatsToLabel++;
1034 }
1035 palyr.mFeaturesToLabel = nFeatsToLabel;
1036 }
1037
1038 // notify user about any font substitution
1039 if ( !palyr.mTextFontFound && !mLabelFontNotFoundNotified )
1040 {
1041 emit labelingFontNotFound( this, palyr.mTextFontFamily );
1042 mLabelFontNotFoundNotified = true;
1043 }
1044#endif
1045}
1046
1047void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer *layer, QSet<QString> &attributeNames )
1048{
1049 QgsRenderContext &context = *renderContext();
1050 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
1051 {
1052 if ( layer->diagramsEnabled() )
1053 {
1054 mDiagramProvider = new QgsVectorLayerDiagramProvider( layer );
1055 // need to be added before calling prepare() - uses map settings from engine
1056 engine2->addProvider( mDiagramProvider );
1057 if ( !mDiagramProvider->prepare( context, attributeNames ) )
1058 {
1059 engine2->removeProvider( mDiagramProvider );
1060 mDiagramProvider = nullptr; // deleted by engine
1061 }
1062 }
1063 }
1064}
1065
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:56
@ ForceVector
Always force vector-based rendering, even when the result will be visually different to a raster-base...
Definition qgis.h:2706
QFlags< MapLayerRendererFlag > MapLayerRendererFlags
Flags which control how map layer renderers behave.
Definition qgis.h:2796
QFlags< VectorRenderingSimplificationFlag > VectorRenderingSimplificationFlags
Simplification flags for vector feature rendering.
Definition qgis.h:3044
@ NoSimplification
No simplification can be applied.
Definition qgis.h:3030
@ FullSimplification
All simplification hints can be applied ( Geometry + AA-disabling ).
Definition qgis.h:3033
@ GeometrySimplification
The geometries can be simplified using the current map2pixel context state.
Definition qgis.h:3031
@ Degrees
Degrees, for planar geographic CRS distance measurements.
Definition qgis.h:5020
@ EmbeddedSymbols
Retrieve any embedded feature symbology.
Definition qgis.h:2200
@ AffectsLabeling
If present, indicates that the renderer will participate in the map labeling problem.
Definition qgis.h:829
@ Point
Points.
Definition qgis.h:359
@ Unknown
Unknown types.
Definition qgis.h:362
@ Null
No geometry.
Definition qgis.h:363
@ Vector
Vector layer.
Definition qgis.h:191
@ AffectsLabeling
The layer rendering will interact with the map labeling.
Definition qgis.h:2787
@ SkipSymbolRendering
Disable symbol rendering while still drawing labels if enabled.
Definition qgis.h:2767
@ NoMarker
No marker.
Definition qgis.h:1836
@ SemiTransparentCircle
Semi-transparent circle marker.
Definition qgis.h:1834
@ Cross
Cross marker.
Definition qgis.h:1835
@ CustomColor
Use default symbol with a custom selection color.
Definition qgis.h:1760
@ CustomSymbol
Use a custom symbol.
Definition qgis.h:1761
@ Default
Use default symbol and selection colors.
Definition qgis.h:1759
virtual QgsPalLayerSettings settings(const QString &providerId=QString()) const =0
Gets associated label settings.
virtual QgsVectorLayerLabelProvider * provider(QgsVectorLayer *layer) const
Factory for label provider implementation.
static QgsRuntimeProfiler * profiler()
Returns the application runtime profiler.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source coordinate reference system, which the transform will transform coordinates from.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
bool isShortCircuited() const
Returns true if the transform short circuits because the source and destination are equivalent.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
QString what() const
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
QgsExpressionContextScope * popScope()
Removes the last scope from the expression context and return it.
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the expression engine to check if expressio...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
virtual Q_DECL_DEPRECATED void filterFeatures(const QgsVectorLayer *layer, QgsFeatureRequest &featureRequest) const
Add additional filters to the feature request to further restrict the features returned by the reques...
virtual Q_DECL_DEPRECATED bool isFilterThreadSafe() const
Returns true if the filterFeature function is thread safe, which will lead to reliance on layer ID in...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
void setInterruptionChecker(QgsFeedback *interruptionChecker)
Attach an object that can be queried regularly by the iterator to check if it must stopped.
bool isValid() const
Will return if this iterator is valid.
An interface for objects which generate feature renderers for vector layers.
Abstract base class for all 2D vector feature renderers.
virtual bool canSkipRender()
Returns true if the renderer can be entirely skipped, i.e.
virtual void modifyRequestExtent(QgsRectangle &extent, QgsRenderContext &context)
Allows for a renderer to modify the extent of a feature request prior to rendering.
virtual QString filter(const QgsFields &fields=QgsFields())
If a renderer does not require all the features this method may be overridden and return an expressio...
QgsPaintEffect * paintEffect() const
Returns the current paint effect for the renderer.
virtual QgsSymbolList symbols(QgsRenderContext &context) const
Returns list of symbols used by the renderer.
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
QString type() const
virtual bool usesEmbeddedSymbols() const
Returns true if the renderer uses embedded symbols for features.
virtual bool renderFeature(const QgsFeature &feature, QgsRenderContext &context, int layer=-1, bool selected=false, bool drawVertexMarker=false)
Render a feature using this renderer in the given context.
double referenceScale() const
Returns the symbology reference scale.
bool usingSymbolLevels() const
virtual QgsFeatureRenderer::Capabilities capabilities()
Returns details about internals of this renderer.
virtual QgsSymbol * symbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const =0
To be overridden.
@ SymbolLevels
Rendering with symbol levels (i.e. implements symbols(), symbolForFeature()).
bool orderByEnabled() const
Returns whether custom ordering will be applied before features are processed by this renderer.
virtual bool willRenderFeature(const QgsFeature &feature, QgsRenderContext &context) const
Returns whether the renderer will render a feature or not.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
void setVertexMarkerAppearance(Qgis::VertexMarkerType type, double size)
Sets type and size of editing vertex markers for subsequent rendering.
QgsFeatureRequest::OrderBy orderBy() const
Gets the order in which features shall be processed by this renderer.
virtual QgsSymbolList originalSymbolsForFeature(const QgsFeature &feature, QgsRenderContext &context) const
Equivalent of originalSymbolsForFeature() call extended to support renderers that may use more symbol...
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
QSet< int > CORE_EXPORT usedAttributeIndices(const QgsFields &fields) const
Returns a set of used, validated attribute indices.
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setSimplifyMethod(const QgsSimplifyMethod &simplifyMethod)
Set a simplification method for geometries that will be fetched.
QgsFeatureRequest & combineFilterExpression(const QString &expression)
Modifies the existing filter expression to add an additional expression filter.
Qgis::FeatureRequestFlags flags() const
Returns the flags which affect how features are fetched.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the iterator to check if it should be cance...
QgsFeatureRequest & setOrderBy(const OrderBy &orderBy)
Set a list of order by clauses.
QgsFeatureId id
Definition qgsfeature.h:66
QgsGeometry geometry
Definition qgsfeature.h:69
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::GeometryType type
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
static 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...
static QPainterPath calculatePainterClipRegion(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, Qgis::LayerType layerType, bool &shouldClip)
Returns a QPainterPath representing the intersection of clipping regions from context which should be...
static QList< QgsMapClippingRegion > collectClippingRegionsForLayer(const QgsRenderContext &context, const QgsMapLayer *layer)
Collects the list of map clipping regions from a context which apply to a map layer.
static QgsGeometry calculateLabelIntersectionGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldClip)
Returns the geometry representing the intersection of clipping regions from context which should be u...
static QgsGeometry calculateFeatureIntersectionGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldClip)
Returns the geometry representing the intersection of clipping regions from context which should be u...
static QgsGeometry calculateFeatureRequestGeometry(const QList< QgsMapClippingRegion > &regions, const QgsRenderContext &context, bool &shouldFilter)
Returns the geometry representing the intersection of clipping regions from context.
bool mReadyToCompose
The flag must be set to false in renderer's constructor if wants to use the smarter map redraws funct...
static constexpr int MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE
Maximum time (in ms) to allow display of a previously cached preview image while rendering layers,...
QString layerId() const
Gets access to the ID of the layer rendered by this class.
QgsRenderContext * renderContext()
Returns the render context associated with the renderer.
QgsMapLayerRenderer(const QString &layerID, QgsRenderContext *context=nullptr)
Constructor for QgsMapLayerRenderer, with the associated layerID and render context.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
double opacity
Definition qgsmaplayer.h:92
double mapUnitsPerPixel() const
Returns the current map units per pixel.
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())
Adds a message to the log instance (and creates it if necessary).
virtual void begin(QgsRenderContext &context)
Begins intercepting paint operations to a render context.
virtual void end(QgsRenderContext &context)
Ends interception of paint operations to a render context, and draws the result to the render context...
bool enabled() const
Returns whether the effect is enabled.
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
Q_INVOKABLE QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
double xMinimum
double yMinimum
double xMaximum
double yMaximum
QgsPointXY center
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Contains information about the context of a rendering operation.
bool hasRenderedFeatureHandlers() const
Returns true if the context has any rendered feature handlers.
QgsVectorSimplifyMethod & vectorSimplifyMethod()
Returns the simplification settings to use when rendering vector layers.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
void setVectorSimplifyMethod(const QgsVectorSimplifyMethod &simplifyMethod)
Sets the simplification setting to use when rendering vector layers.
QgsLabelSink * labelSink() const
Returns the associated label sink, or nullptr if not set.
const QgsRectangle & extent() const
When rendering a map layer, calling this method returns the "clipping" extent for the layer (in the l...
bool testFlag(Qgis::RenderContextFlag flag) const
Check whether a particular flag is enabled.
void setFeatureClipGeometry(const QgsGeometry &geometry)
Sets a geometry to use to clip features at render time.
const QgsFeatureFilterProvider * featureFilterProvider() const
Gets the filter feature provider used for additional filtering of rendered features.
QList< QgsRenderedFeatureHandlerInterface * > renderedFeatureHandlers() const
Returns the list of rendered feature handlers to use while rendering map layers.
void setSymbologyReferenceScale(double scale)
Sets the symbology reference scale.
bool showSelection() const
Returns true if vector selections should be shown in the rendered map.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
QColor selectionColor() const
Returns the color to use when rendering selected features.
Qgis::RasterizedRenderingPolicy rasterizedRenderingPolicy() const
Returns the policy controlling when rasterisation of content during renders is permitted.
bool drawEditingInformation() const
Returns true if edit markers should be drawn during the render operation.
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
QgsLabelingEngine * labelingEngine() const
Gets access to new labeling engine (may be nullptr).
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
void setSelectionColor(const QColor &color)
Sets the color to use when rendering selected features.
An interface for classes which provide custom handlers for features rendered as part of a map render ...
void record(const QString &name, double time, const QString &group="startup", const QString &id=QString())
Manually adds a profile event with the given name and total time (in seconds).
Scoped object for setting the current thread name.
static const QgsSettingsEntryDouble * settingsDigitizingMarkerSizeMm
Settings entry digitizing marker size mm.
static const QgsSettingsEntryBool * settingsDigitizingMarkerOnlyForSelected
Settings entry digitizing marker only for selected.
static const QgsSettingsEntryString * settingsDigitizingMarkerStyle
Settings entry digitizing marker style.
void setTolerance(double tolerance)
Sets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
void setThreshold(float threshold)
Sets the simplification threshold in pixels. Represents the maximum distance in pixels between two co...
void setForceLocalOptimization(bool localOptimization)
Sets whether the simplification executes after fetch the geometries from provider,...
void setMethodType(MethodType methodType)
Sets the simplification type.
@ OptimizeForRendering
Simplify using the map2pixel data to optimize the rendering of geometries.
A feature renderer which renders all features with the same symbol.
QgsSymbol * symbol() const
Returns the symbol which will be rendered for every feature.
void stopRender(QgsRenderContext &context) override
Must be called when a render cycle has finished, to allow the renderer to clean up.
void startRender(QgsRenderContext &context, const QgsFields &fields) override
Must be called when a new render cycle is started.
int renderingPass() const
Specifies the rendering pass in which this symbol layer should be rendered.
int layer() const
The layer of this symbol level.
QgsSymbol * symbol() const
The symbol of this symbol level.
Abstract base class for all rendered symbols.
Definition qgssymbol.h:231
QgsSymbolLayer * symbolLayer(int layer)
Returns the symbol layer at the specified index.
void setColor(const QColor &color) const
Sets the color for the symbol.
int symbolLayerCount() const
Returns the total number of symbol layers contained in the symbol.
Definition qgssymbol.h:353
static QgsSymbol * defaultSymbol(Qgis::GeometryType geomType)
Returns a new default symbol for the specified geometry type.
const QgsDateTimeRange & temporalRange() const
Returns the datetime range for the object.
bool isTemporal() const
Returns true if the object's temporal range is enabled, and the object will be filtered when renderin...
Partial snapshot of vector layer's state (only the members necessary for access to features).
static QgsGeometry getPointObstacleGeometry(QgsFeature &fet, QgsRenderContext &context, const QgsSymbolList &symbols)
Returns the geometry for a point feature which should be used as an obstacle for labels.
Qgis::MapLayerRendererFlags flags() const override
Returns flags which control how the map layer rendering behaves.
bool forceRasterRender() const override
Returns true if the renderer must be rendered to a raster paint device (e.g.
QgsVectorLayerRenderer(QgsVectorLayer *layer, QgsRenderContext &context)
~QgsVectorLayerRenderer() override
void setLayerRenderingTimeHint(int time) override
Sets approximate render time (in ms) for the layer to render.
bool render() override
Do the rendering (based on data stored in the class).
QgsFeedback * feedback() const override
Access to feedback object of the layer renderer (may be nullptr).
Implementation of layer selection properties for vector layers.
Encapsulates the context in which a QgsVectorLayer's temporal capabilities will be applied.
void setLayer(QgsVectorLayer *layer)
Sets the associated layer.
Represents a vector layer which manages a vector based dataset.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
QgsMapLayerTemporalProperties * temporalProperties() override
Returns the layer's temporal properties.
QPainter::CompositionMode featureBlendMode() const
Returns the current blending mode for features.
bool diagramsEnabled() const
Returns whether the layer contains diagrams which are enabled and should be drawn.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
bool simplifyDrawingCanbeApplied(const QgsRenderContext &renderContext, Qgis::VectorRenderingSimplificationFlag simplifyHint) const
Returns whether the VectorLayer can apply the specified simplification hint.
QgsFeatureRenderer * renderer()
Returns the feature renderer used for rendering the features in the layer in 2D map views.
Q_INVOKABLE QgsVectorLayerEditBuffer * editBuffer()
Buffer with uncommitted editing operations. Only valid after editing has been turned on.
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
const QgsVectorSimplifyMethod & simplifyMethod() const
Returns the simplification settings for fast rendering of features.
QList< const QgsFeatureRendererGenerator * > featureRendererGenerators() const
Returns a list of the feature renderer generators owned by the layer.
QgsMapLayerSelectionProperties * selectionProperties() override
Returns the layer's selection properties.
Qgis::VectorRenderingSimplificationFlags simplifyHints() const
Gets the simplification hints of the vector layer managed.
void setSimplifyHints(Qgis::VectorRenderingSimplificationFlags simplifyHints)
Sets the simplification hints of the vector layer managed.
void setTolerance(double tolerance)
Sets the tolerance of simplification in map units. Represents the maximum distance in map units betwe...
#define Q_NOWARN_DEPRECATED_POP
Definition qgis.h:7170
#define Q_NOWARN_DEPRECATED_PUSH
Definition qgis.h:7169
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6607
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:61
#define QgsDebugError(str)
Definition qgslogger.h:57
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition qgsrenderer.h:94
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition qgsrenderer.h:90
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:49