QGIS API Documentation 3.34.0-Prizren (ffbdd678812)
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 "qgsmessagelog.h"
19#include "qgspallabeling.h"
20#include "qgsrenderer.h"
21#include "qgsrendercontext.h"
23#include "qgssymbollayer.h"
24#include "qgssymbol.h"
25#include "qgsvectorlayer.h"
30#include "qgspainteffect.h"
32#include "qgsexception.h"
33#include "qgslabelsink.h"
34#include "qgslogger.h"
40#include "qgsmapclippingutils.h"
43#include "qgsruntimeprofiler.h"
44#include "qgsapplication.h"
45
46#include <QPicture>
47#include <QTimer>
48
50 : QgsMapLayerRenderer( layer->id(), &context )
51 , mFeedback( std::make_unique< QgsFeedback >() )
52 , mLayer( layer )
53 , mLayerName( layer->name() )
54 , mFields( layer->fields() )
55 , mSource( std::make_unique< QgsVectorLayerFeatureSource >( layer ) )
56 , mNoSetLayerExpressionContext( layer->customProperty( QStringLiteral( "_noset_layer_expression_context" ) ).toBool() )
57 , mEnableProfile( context.flags() & Qgis::RenderContextFlag::RecordProfile )
58{
59 QElapsedTimer timer;
60 timer.start();
61 std::unique_ptr< QgsFeatureRenderer > mainRenderer( layer->renderer() ? layer->renderer()->clone() : nullptr );
62
63 QgsVectorLayerSelectionProperties *selectionProperties = qobject_cast< QgsVectorLayerSelectionProperties * >( layer->selectionProperties() );
64 switch ( selectionProperties->selectionRenderingMode() )
65 {
67 break;
68
70 {
71 // overwrite default selection color if layer has a specific selection color set
72 const QColor layerSelectionColor = selectionProperties->selectionColor();
73 if ( layerSelectionColor.isValid() )
74 context.setSelectionColor( layerSelectionColor );
75 break;
76 }
77
79 {
80 if ( QgsSymbol *selectionSymbol = qobject_cast< QgsVectorLayerSelectionProperties * >( layer->selectionProperties() )->selectionSymbol() )
81 mSelectionSymbol.reset( selectionSymbol->clone() );
82 break;
83 }
84 }
85
86 if ( !mainRenderer )
87 return;
88
89 QList< const QgsFeatureRendererGenerator * > generators = layer->featureRendererGenerators();
90 std::sort( generators.begin(), generators.end(), []( const QgsFeatureRendererGenerator * g1, const QgsFeatureRendererGenerator * g2 )
91 {
92 return g1->level() < g2->level();
93 } );
94
95 bool insertedMainRenderer = false;
96 double prevLevel = std::numeric_limits< double >::lowest();
97 // cppcheck-suppress danglingLifetime
98 mRenderer = mainRenderer.get();
99 for ( const QgsFeatureRendererGenerator *generator : std::as_const( generators ) )
100 {
101 if ( generator->level() >= 0 && prevLevel < 0 && !insertedMainRenderer )
102 {
103 // insert main renderer when level changes from <0 to >0
104 mRenderers.emplace_back( std::move( mainRenderer ) );
105 insertedMainRenderer = true;
106 }
107 mRenderers.emplace_back( generator->createRenderer() );
108 prevLevel = generator->level();
109 }
110 // cppcheck-suppress accessMoved
111 if ( mainRenderer )
112 {
113 // cppcheck-suppress accessMoved
114 mRenderers.emplace_back( std::move( mainRenderer ) );
115 }
116
117 mSelectedFeatureIds = layer->selectedFeatureIds();
118
119 mDrawVertexMarkers = nullptr != layer->editBuffer();
120
121 mGeometryType = layer->geometryType();
122
123 mFeatureBlendMode = layer->featureBlendMode();
124
125 if ( context.isTemporal() )
126 {
127 QgsVectorLayerTemporalContext temporalContext;
128 temporalContext.setLayer( layer );
129 mTemporalFilter = qobject_cast< const QgsVectorLayerTemporalProperties * >( layer->temporalProperties() )->createFilterString( temporalContext, context.temporalRange() );
130 QgsDebugMsgLevel( "Rendering with Temporal Filter: " + mTemporalFilter, 2 );
131 }
132
133 // if there's already a simplification method specified via the context, we respect that. Otherwise, we fall back
134 // to the layer's individual setting
135 if ( renderContext()->vectorSimplifyMethod().simplifyHints() != QgsVectorSimplifyMethod::NoSimplification )
136 {
137 mSimplifyMethod = renderContext()->vectorSimplifyMethod();
140 }
141 else
142 {
143 mSimplifyMethod = layer->simplifyMethod();
145 }
146
148
150 if ( markerTypeString == QLatin1String( "Cross" ) )
151 {
152 mVertexMarkerStyle = Qgis::VertexMarkerType::Cross;
153 }
154 else if ( markerTypeString == QLatin1String( "SemiTransparentCircle" ) )
155 {
157 }
158 else
159 {
160 mVertexMarkerStyle = Qgis::VertexMarkerType::NoMarker;
161 }
162
164
165 // cppcheck-suppress danglingLifetime
166 QgsDebugMsgLevel( "rendering v2:\n " + mRenderer->dump(), 2 );
167
168 if ( mDrawVertexMarkers )
169 {
170 // set editing vertex markers style (main renderer only)
171 mRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
172 }
173 if ( !mNoSetLayerExpressionContext )
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
200 ( ( layer->blendMode() != QPainter::CompositionMode_SourceOver )
201 || ( layer->featureBlendMode() != QPainter::CompositionMode_SourceOver )
202 || ( !qgsDoubleNear( layer->opacity(), 1.0 ) ) ) )
203 {
204 //layer properties require rasterization
205 mForceRasterRender = true;
206 }
207
208 mReadyToCompose = false;
209 mPreparationTime = timer.elapsed();
210}
211
213
215{
216 mRenderTimeHint = time;
217}
218
220{
221 return mFeedback.get();
222}
223
225{
226 return mForceRasterRender;
227}
228
230{
231 if ( mGeometryType == Qgis::GeometryType::Null || mGeometryType == Qgis::GeometryType::Unknown )
232 {
233 mReadyToCompose = true;
234 return true;
235 }
236
237 if ( mRenderers.empty() )
238 {
239 mReadyToCompose = true;
240 mErrors.append( QObject::tr( "No renderer for drawing." ) );
241 return false;
242 }
243
244 std::unique_ptr< QgsScopedRuntimeProfile > profile;
245 if ( mEnableProfile )
246 {
247 profile = std::make_unique< QgsScopedRuntimeProfile >( mLayerName, QStringLiteral( "rendering" ), layerId() );
248 if ( mPreparationTime > 0 )
249 QgsApplication::profiler()->record( QObject::tr( "Create renderer" ), mPreparationTime / 1000.0, QStringLiteral( "rendering" ) );
250 }
251
252 // if the previous layer render was relatively quick (e.g. less than 3 seconds), the we show any previously
253 // cached version of the layer during rendering instead of the usual progressive updates
254 if ( mRenderTimeHint > 0 && mRenderTimeHint <= MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
255 {
256 mBlockRenderUpdates = true;
257 mElapsedTimer.start();
258 }
259
260 bool res = true;
261 int rendererIndex = 0;
262 for ( const std::unique_ptr< QgsFeatureRenderer > &renderer : mRenderers )
263 {
264 res = renderInternal( renderer.get(), rendererIndex++ ) && res;
265 }
266
267 mReadyToCompose = true;
268 return res && !renderContext()->renderingStopped();
269}
270
271bool QgsVectorLayerRenderer::renderInternal( QgsFeatureRenderer *renderer, int rendererIndex )
272{
273 const bool isMainRenderer = renderer == mRenderer;
274
275 QgsRenderContext &context = *renderContext();
276 context.setSymbologyReferenceScale( renderer->referenceScale() );
277
278 if ( renderer->type() == QLatin1String( "nullSymbol" ) )
279 {
280 // a little shortcut for the null symbol renderer - most of the time it is not going to render anything
281 // so we can even skip the whole loop to fetch features
282 if ( !isMainRenderer ||
283 ( !mDrawVertexMarkers && !mLabelProvider && !mDiagramProvider && mSelectedFeatureIds.isEmpty() ) )
284 return true;
285 }
286
287 std::unique_ptr< QgsScopedRuntimeProfile > preparingProfile;
288 if ( mEnableProfile )
289 {
290 QString title;
291 if ( mRenderers.size() > 1 )
292 title = QObject::tr( "Preparing render %1" ).arg( rendererIndex + 1 );
293 else
294 title = QObject::tr( "Preparing render" );
295 preparingProfile = std::make_unique< QgsScopedRuntimeProfile >( title, QStringLiteral( "rendering" ) );
296 }
297
298 QgsScopedQPainterState painterState( context.painter() );
299
300 bool usingEffect = false;
301 if ( renderer->paintEffect() && renderer->paintEffect()->enabled() )
302 {
303 usingEffect = true;
304 renderer->paintEffect()->begin( context );
305 }
306
307 // Per feature blending mode
308 if ( context.useAdvancedEffects() && mFeatureBlendMode != QPainter::CompositionMode_SourceOver )
309 {
310 // set the painter to the feature blend mode, so that features drawn
311 // on this layer will interact and blend with each other
312 context.painter()->setCompositionMode( mFeatureBlendMode );
313 }
314
315 renderer->startRender( context, mFields );
316
317 if ( renderer->canSkipRender() )
318 {
319 // nothing to draw for now...
320 renderer->stopRender( context );
321 return true;
322 }
323
324 QString rendererFilter = renderer->filter( mFields );
325
326 QgsRectangle requestExtent = context.extent();
327 if ( !mClippingRegions.empty() )
328 {
329 mClipFilterGeom = QgsMapClippingUtils::calculateFeatureRequestGeometry( mClippingRegions, context, mApplyClipFilter );
330 requestExtent = requestExtent.intersect( mClipFilterGeom.boundingBox() );
331
332 mClipFeatureGeom = QgsMapClippingUtils::calculateFeatureIntersectionGeometry( mClippingRegions, context, mApplyClipGeometries );
333
334 bool needsPainterClipPath = false;
335 const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, context, Qgis::LayerType::Vector, needsPainterClipPath );
336 if ( needsPainterClipPath )
337 context.painter()->setClipPath( path, Qt::IntersectClip );
338
339 mLabelClipFeatureGeom = QgsMapClippingUtils::calculateLabelIntersectionGeometry( mClippingRegions, context, mApplyLabelClipGeometries );
340
341 if ( mDiagramProvider )
342 mDiagramProvider->setClipFeatureGeometry( mLabelClipFeatureGeom );
343 }
344 renderer->modifyRequestExtent( requestExtent, context );
345
346 QgsFeatureRequest featureRequest = QgsFeatureRequest()
347 .setFilterRect( requestExtent )
348 .setSubsetOfAttributes( mAttrNames, mFields )
350 if ( renderer->orderByEnabled() )
351 {
352 featureRequest.setOrderBy( renderer->orderBy() );
353 }
354
355 const QgsFeatureFilterProvider *featureFilterProvider = context.featureFilterProvider();
356 if ( featureFilterProvider )
357 {
358 featureFilterProvider->filterFeatures( mLayer, featureRequest );
359 }
360 if ( !rendererFilter.isEmpty() && rendererFilter != QLatin1String( "TRUE" ) )
361 {
362 featureRequest.combineFilterExpression( rendererFilter );
363 }
364 if ( !mTemporalFilter.isEmpty() )
365 {
366 featureRequest.combineFilterExpression( mTemporalFilter );
367 }
368
369 if ( renderer->usesEmbeddedSymbols() )
370 {
371 featureRequest.setFlags( featureRequest.flags() | QgsFeatureRequest::EmbeddedSymbols );
372 }
373
374 // enable the simplification of the geometries (Using the current map2pixel context) before send it to renderer engine.
375 if ( mSimplifyGeometry )
376 {
377 double map2pixelTol = mSimplifyMethod.threshold();
378 bool validTransform = true;
379
380 const QgsMapToPixel &mtp = context.mapToPixel();
381 map2pixelTol *= mtp.mapUnitsPerPixel();
382 const QgsCoordinateTransform ct = context.coordinateTransform();
383
384 // resize the tolerance using the change of size of an 1-BBOX from the source CoordinateSystem to the target CoordinateSystem
385 if ( ct.isValid() && !ct.isShortCircuited() )
386 {
387 try
388 {
389 QgsCoordinateTransform toleranceTransform = ct;
390 QgsPointXY center = context.extent().center();
391 double rectSize = toleranceTransform.sourceCrs().mapUnits() == Qgis::DistanceUnit::Degrees ? 0.0008983 /* ~100/(40075014/360=111319.4833) */ : 100;
392
393 QgsRectangle sourceRect = QgsRectangle( center.x(), center.y(), center.x() + rectSize, center.y() + rectSize );
394 toleranceTransform.setBallparkTransformsAreAppropriate( true );
395 QgsRectangle targetRect = toleranceTransform.transform( sourceRect );
396
397 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceTransformRect=%1" ).arg( sourceRect.toString( 16 ) ), 4 );
398 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetTransformRect=%1" ).arg( targetRect.toString( 16 ) ), 4 );
399
400 if ( !sourceRect.isEmpty() && sourceRect.isFinite() && !targetRect.isEmpty() && targetRect.isFinite() )
401 {
402 QgsPointXY minimumSrcPoint( sourceRect.xMinimum(), sourceRect.yMinimum() );
403 QgsPointXY maximumSrcPoint( sourceRect.xMaximum(), sourceRect.yMaximum() );
404 QgsPointXY minimumDstPoint( targetRect.xMinimum(), targetRect.yMinimum() );
405 QgsPointXY maximumDstPoint( targetRect.xMaximum(), targetRect.yMaximum() );
406
407 double sourceHypothenuse = std::sqrt( minimumSrcPoint.sqrDist( maximumSrcPoint ) );
408 double targetHypothenuse = std::sqrt( minimumDstPoint.sqrDist( maximumDstPoint ) );
409
410 QgsDebugMsgLevel( QStringLiteral( "Simplify - SourceHypothenuse=%1" ).arg( sourceHypothenuse ), 4 );
411 QgsDebugMsgLevel( QStringLiteral( "Simplify - TargetHypothenuse=%1" ).arg( targetHypothenuse ), 4 );
412
413 if ( !qgsDoubleNear( targetHypothenuse, 0.0 ) )
414 map2pixelTol *= ( sourceHypothenuse / targetHypothenuse );
415 }
416 }
417 catch ( QgsCsException &cse )
418 {
419 QgsMessageLog::logMessage( QObject::tr( "Simplify transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
420 validTransform = false;
421 }
422 }
423
424 if ( validTransform )
425 {
426 QgsSimplifyMethod simplifyMethod;
428 simplifyMethod.setTolerance( map2pixelTol );
429 simplifyMethod.setThreshold( mSimplifyMethod.threshold() );
430 simplifyMethod.setForceLocalOptimization( mSimplifyMethod.forceLocalOptimization() );
431 featureRequest.setSimplifyMethod( simplifyMethod );
432
433 QgsVectorSimplifyMethod vectorMethod = mSimplifyMethod;
434 vectorMethod.setTolerance( map2pixelTol );
435 context.setVectorSimplifyMethod( vectorMethod );
436 }
437 else
438 {
439 QgsVectorSimplifyMethod vectorMethod;
441 context.setVectorSimplifyMethod( vectorMethod );
442 }
443 }
444 else
445 {
446 QgsVectorSimplifyMethod vectorMethod;
448 context.setVectorSimplifyMethod( vectorMethod );
449 }
450
451 featureRequest.setFeedback( mFeedback.get() );
452 // also set the interruption checker for the expression context, in case the renderer uses some complex expression
453 // which could benefit from early exit paths...
454 context.expressionContext().setFeedback( mFeedback.get() );
455
456 std::unique_ptr< QgsScopedRuntimeProfile > preparingFeatureItProfile;
457 if ( mEnableProfile )
458 {
459 preparingFeatureItProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Prepare feature iteration" ), QStringLiteral( "rendering" ) );
460 }
461
462 QgsFeatureIterator fit = mSource->getFeatures( featureRequest );
463 // Attach an interruption checker so that iterators that have potentially
464 // slow fetchFeature() implementations, such as in the WFS provider, can
465 // check it, instead of relying on just the mContext.renderingStopped() check
466 // in drawRenderer()
467
468 fit.setInterruptionChecker( mFeedback.get() );
469
470 preparingFeatureItProfile.reset();
471 preparingProfile.reset();
472
473 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
474 if ( mEnableProfile )
475 {
476 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering" ), QStringLiteral( "rendering" ) );
477 }
478
479 if ( ( renderer->capabilities() & QgsFeatureRenderer::SymbolLevels ) && renderer->usingSymbolLevels() )
480 drawRendererLevels( renderer, fit );
481 else
482 drawRenderer( renderer, fit );
483
484 if ( !fit.isValid() )
485 {
486 mErrors.append( QStringLiteral( "Data source invalid" ) );
487 }
488
489 if ( usingEffect )
490 {
491 renderer->paintEffect()->end( context );
492 }
493
494 context.expressionContext().setFeedback( nullptr );
495 return true;
496}
497
498
499void QgsVectorLayerRenderer::drawRenderer( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
500{
501 QElapsedTimer timer;
502 timer.start();
503 quint64 totalLabelTime = 0;
504
505 const bool isMainRenderer = renderer == mRenderer;
506
508 QgsRenderContext &context = *renderContext();
509 context.expressionContext().appendScope( symbolScope );
510
511 std::unique_ptr< QgsGeometryEngine > clipEngine;
512 if ( mApplyClipFilter )
513 {
514 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
515 clipEngine->prepareGeometry();
516 }
517
518 if ( mSelectionSymbol && isMainRenderer )
519 mSelectionSymbol->startRender( context, mFields );
520
521 QgsFeature fet;
522 while ( fit.nextFeature( fet ) )
523 {
524 try
525 {
526 if ( context.renderingStopped() )
527 {
528 QgsDebugMsgLevel( QStringLiteral( "Drawing of vector layer %1 canceled." ).arg( layerId() ), 2 );
529 break;
530 }
531
532 if ( !fet.hasGeometry() || fet.geometry().isEmpty() )
533 continue; // skip features without geometry
534
535 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
536 continue; // skip features outside of clipping region
537
538 if ( mApplyClipGeometries )
539 context.setFeatureClipGeometry( mClipFeatureGeom );
540
541 if ( ! mNoSetLayerExpressionContext )
542 context.expressionContext().setFeature( fet );
543
544 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( fet.id() );
545 bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
546
547 // render feature
548 bool rendered = false;
550 {
551 if ( featureIsSelected && mSelectionSymbol )
552 {
553 // note: here we pass "false" for the selected argument, as we don't want to change
554 // the user's defined selection symbol colors or settings in any way
555 mSelectionSymbol->renderFeature( fet, context, -1, false, drawMarker );
556 rendered = renderer->willRenderFeature( fet, context );
557 }
558 else
559 {
560 rendered = renderer->renderFeature( fet, context, -1, featureIsSelected, drawMarker );
561 }
562 }
563 else
564 {
565 rendered = renderer->willRenderFeature( fet, context );
566 }
567
568 // labeling - register feature
569 if ( rendered )
570 {
571 // as soon as first feature is rendered, we can start showing layer updates.
572 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
573 // at most e.g. 3 seconds before we start forcing progressive updates.
574 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
575 {
576 mReadyToCompose = true;
577 }
578
579 // new labeling engine
580 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
581 {
582 const quint64 startLabelTime = timer.elapsed();
583 QgsGeometry obstacleGeometry;
584 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
585 QgsSymbol *symbol = nullptr;
586 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
587 {
588 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
589 }
590
591 if ( !symbols.isEmpty() )
592 {
593 symbol = symbols.at( 0 );
595 }
596
597 if ( mApplyLabelClipGeometries )
598 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
599
600 if ( mLabelProvider )
601 {
602 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
603 }
604 if ( mDiagramProvider )
605 {
606 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
607 }
608
609 if ( mApplyLabelClipGeometries )
611
612 totalLabelTime += ( timer.elapsed() - startLabelTime );
613 }
614 }
615 }
616 catch ( const QgsCsException &cse )
617 {
618 Q_UNUSED( cse )
619 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
620 .arg( fet.id() ).arg( cse.what() ) );
621 }
622 }
623
624 delete context.expressionContext().popScope();
625
626 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
627 if ( mEnableProfile )
628 {
629 QgsApplication::profiler()->record( QObject::tr( "Rendering features" ), ( timer.elapsed() - totalLabelTime ) / 1000.0, QStringLiteral( "rendering" ) );
630 if ( totalLabelTime > 0 )
631 {
632 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
633 }
634 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
635 }
636
637 if ( mSelectionSymbol && isMainRenderer )
638 mSelectionSymbol->stopRender( context );
639
640 stopRenderer( renderer, nullptr );
641}
642
643void QgsVectorLayerRenderer::drawRendererLevels( QgsFeatureRenderer *renderer, QgsFeatureIterator &fit )
644{
645 const bool isMainRenderer = renderer == mRenderer;
646
647 // We need to figure out in which order all the features should be rendered.
648 // Ordering is based on (a) a "level" which is determined by the configured
649 // feature rendering order" and (b) the symbol level. The "level" is
650 // determined by the values of the attributes defined in the feature
651 // rendering order settings. Each time the attribute(s) have a new distinct
652 // value, a new empty QHash is added to the "features" list. This QHash is
653 // then filled by mappings from the symbol to a list of all the features
654 // that should be rendered by that symbol.
655 //
656 // If orderBy is not enabled, this list will only ever contain a single
657 // element.
658 QList<QHash< QgsSymbol *, QList<QgsFeature> >> features;
659
660 // We have at least one "level" for the features.
661 features.push_back( {} );
662
663 QSet<int> orderByAttributeIdx;
664 if ( renderer->orderByEnabled() )
665 {
666 orderByAttributeIdx = renderer->orderBy().usedAttributeIndices( mSource->fields() );
667 }
668
669 QgsRenderContext &context = *renderContext();
670
671 QgsSingleSymbolRenderer *selRenderer = nullptr;
672 if ( !mSelectedFeatureIds.isEmpty() )
673 {
674 selRenderer = new QgsSingleSymbolRenderer( QgsSymbol::defaultSymbol( mGeometryType ) );
675 selRenderer->symbol()->setColor( context.selectionColor() );
676 selRenderer->setVertexMarkerAppearance( mVertexMarkerStyle, mVertexMarkerSize );
677 selRenderer->startRender( context, mFields );
678 }
679
681 std::unique_ptr< QgsExpressionContextScopePopper > scopePopper = std::make_unique< QgsExpressionContextScopePopper >( context.expressionContext(), symbolScope );
682
683
684 std::unique_ptr< QgsGeometryEngine > clipEngine;
685 if ( mApplyClipFilter )
686 {
687 clipEngine.reset( QgsGeometry::createGeometryEngine( mClipFilterGeom.constGet() ) );
688 clipEngine->prepareGeometry();
689 }
690
691 if ( mApplyLabelClipGeometries )
692 context.setFeatureClipGeometry( mLabelClipFeatureGeom );
693
694 std::unique_ptr< QgsScopedRuntimeProfile > fetchFeaturesProfile;
695 if ( mEnableProfile )
696 {
697 fetchFeaturesProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Fetching features" ), QStringLiteral( "rendering" ) );
698 }
699
700 QElapsedTimer timer;
701 timer.start();
702 quint64 totalLabelTime = 0;
703
704 // 1. fetch features
705 QgsFeature fet;
706 QVector<QVariant> prevValues; // previous values of ORDER BY attributes
707 while ( fit.nextFeature( fet ) )
708 {
709 if ( context.renderingStopped() )
710 {
711 qDebug( "rendering stop!" );
712 stopRenderer( renderer, selRenderer );
713 return;
714 }
715
716 if ( !fet.hasGeometry() )
717 continue; // skip features without geometry
718
719 if ( clipEngine && !clipEngine->intersects( fet.geometry().constGet() ) )
720 continue; // skip features outside of clipping region
721
722 if ( ! mNoSetLayerExpressionContext )
723 context.expressionContext().setFeature( fet );
724 QgsSymbol *sym = renderer->symbolForFeature( fet, context );
725 if ( !sym )
726 {
727 continue;
728 }
729
730 if ( renderer->orderByEnabled() )
731 {
732 QVector<QVariant> currentValues;
733 for ( const int idx : std::as_const( orderByAttributeIdx ) )
734 {
735 currentValues.push_back( fet.attribute( idx ) );
736 }
737 if ( prevValues.empty() )
738 {
739 prevValues = std::move( currentValues );
740 }
741 else if ( currentValues != prevValues )
742 {
743 // Current values of ORDER BY attributes are different than previous
744 // values of these attributes. Start a new level.
745 prevValues = std::move( currentValues );
746 features.push_back( {} );
747 }
748 }
749
751 {
752 QHash<QgsSymbol *, QList<QgsFeature> > &featuresBack = features.back();
753 auto featuresBackIt = featuresBack.find( sym );
754 if ( featuresBackIt == featuresBack.end() )
755 {
756 featuresBackIt = featuresBack.insert( sym, QList<QgsFeature>() );
757 }
758 featuresBackIt->append( fet );
759 }
760
761 // new labeling engine
762 if ( isMainRenderer && context.labelingEngine() && ( mLabelProvider || mDiagramProvider ) )
763 {
764 const quint64 startLabelTime = timer.elapsed();
765
766 QgsGeometry obstacleGeometry;
767 QgsSymbolList symbols = renderer->originalSymbolsForFeature( fet, context );
768 QgsSymbol *symbol = nullptr;
769 if ( !symbols.isEmpty() && fet.geometry().type() == Qgis::GeometryType::Point )
770 {
771 obstacleGeometry = QgsVectorLayerLabelProvider::getPointObstacleGeometry( fet, context, symbols );
772 }
773
774 if ( !symbols.isEmpty() )
775 {
776 symbol = symbols.at( 0 );
778 }
779
780 if ( mLabelProvider )
781 {
782 mLabelProvider->registerFeature( fet, context, obstacleGeometry, symbol );
783 }
784 if ( mDiagramProvider )
785 {
786 mDiagramProvider->registerFeature( fet, context, obstacleGeometry );
787 }
788
789 totalLabelTime += ( timer.elapsed() - startLabelTime );
790 }
791 }
792
793 fetchFeaturesProfile.reset();
794 if ( mEnableProfile )
795 {
796 if ( totalLabelTime > 0 )
797 {
798 QgsApplication::profiler()->record( QObject::tr( "Registering labels" ), totalLabelTime / 1000.0, QStringLiteral( "rendering" ) );
799 }
800 }
801
802 if ( mApplyLabelClipGeometries )
804
805 scopePopper.reset();
806
807 if ( features.back().empty() )
808 {
809 // nothing to draw
810 stopRenderer( renderer, selRenderer );
811 return;
812 }
813
814
815 std::unique_ptr< QgsScopedRuntimeProfile > sortingProfile;
816 if ( mEnableProfile )
817 {
818 sortingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Sorting features" ), QStringLiteral( "rendering" ) );
819 }
820 // find out the order
821 QgsSymbolLevelOrder levels;
822 QgsSymbolList symbols = renderer->symbols( context );
823 for ( int i = 0; i < symbols.count(); i++ )
824 {
825 QgsSymbol *sym = symbols[i];
826 for ( int j = 0; j < sym->symbolLayerCount(); j++ )
827 {
828 int level = sym->symbolLayer( j )->renderingPass();
829 if ( level < 0 || level >= 1000 ) // ignore invalid levels
830 continue;
831 QgsSymbolLevelItem item( sym, j );
832 while ( level >= levels.count() ) // append new empty levels
833 levels.append( QgsSymbolLevel() );
834 levels[level].append( item );
835 }
836 }
837 sortingProfile.reset();
838
839 if ( mApplyClipGeometries )
840 context.setFeatureClipGeometry( mClipFeatureGeom );
841
842 // 2. draw features in correct order
843 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
844 {
845 for ( int l = 0; l < levels.count(); l++ )
846 {
847 const QgsSymbolLevel &level = levels[l];
848 std::unique_ptr< QgsScopedRuntimeProfile > renderingProfile;
849 if ( mEnableProfile )
850 {
851 renderingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Rendering symbol level %1" ).arg( l + 1 ), QStringLiteral( "rendering" ) );
852 }
853
854 for ( int i = 0; i < level.count(); i++ )
855 {
856 const QgsSymbolLevelItem &item = level[i];
857 if ( !featureLists.contains( item.symbol() ) )
858 {
859 QgsDebugError( QStringLiteral( "level item's symbol not found!" ) );
860 continue;
861 }
862 const int layer = item.layer();
863 const QList<QgsFeature> &lst = featureLists[item.symbol()];
864 for ( const QgsFeature &feature : lst )
865 {
866 if ( context.renderingStopped() )
867 {
868 stopRenderer( renderer, selRenderer );
869 return;
870 }
871
872 const bool featureIsSelected = isMainRenderer && context.showSelection() && mSelectedFeatureIds.contains( feature.id() );
873 if ( featureIsSelected && mSelectionSymbol )
874 continue; // defer rendering of selected symbols
875
876 // maybe vertex markers should be drawn only during the last pass...
877 const bool drawMarker = isMainRenderer && ( mDrawVertexMarkers && context.drawEditingInformation() && ( !mVertexMarkerOnlyForSelection || featureIsSelected ) );
878
879 if ( ! mNoSetLayerExpressionContext )
880 context.expressionContext().setFeature( feature );
881
882 try
883 {
884 renderer->renderFeature( feature, context, layer, featureIsSelected, drawMarker );
885
886 // as soon as first feature is rendered, we can start showing layer updates.
887 // but if we are blocking render updates (so that a previously cached image is being shown), we wait
888 // at most e.g. 3 seconds before we start forcing progressive updates.
889 if ( !mBlockRenderUpdates || mElapsedTimer.elapsed() > MAX_TIME_TO_USE_CACHED_PREVIEW_IMAGE )
890 {
891 mReadyToCompose = true;
892 }
893 }
894 catch ( const QgsCsException &cse )
895 {
896 Q_UNUSED( cse )
897 QgsDebugError( QStringLiteral( "Failed to transform a point while drawing a feature with ID '%1'. Ignoring this feature. %2" )
898 .arg( fet.id() ).arg( cse.what() ) );
899 }
900 }
901 }
902 }
903 }
904
905 if ( mSelectionSymbol && !mSelectedFeatureIds.empty() && isMainRenderer && context.showSelection() )
906 {
907 mSelectionSymbol->startRender( context, mFields );
908
909 for ( const QHash< QgsSymbol *, QList<QgsFeature> > &featureLists : features )
910 {
911 for ( auto it = featureLists.constBegin(); it != featureLists.constEnd(); ++it )
912 {
913 const QList<QgsFeature> &lst = it.value();
914 for ( const QgsFeature &feature : lst )
915 {
916 if ( context.renderingStopped() )
917 {
918 break;
919 }
920
921 const bool featureIsSelected = mSelectedFeatureIds.contains( feature.id() );
922 if ( !featureIsSelected )
923 continue;
924
925 const bool drawMarker = mDrawVertexMarkers && context.drawEditingInformation();
926 // note: here we pass "false" for the selected argument, as we don't want to change
927 // the user's defined selection symbol colors or settings in any way
928 mSelectionSymbol->renderFeature( feature, context, -1, false, drawMarker );
929 }
930 }
931 }
932
933 mSelectionSymbol->stopRender( context );
934 }
935
936 std::unique_ptr< QgsScopedRuntimeProfile > cleanupProfile;
937 if ( mEnableProfile )
938 {
939 cleanupProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "Finalizing" ), QStringLiteral( "rendering" ) );
940 }
941
942 stopRenderer( renderer, selRenderer );
943}
944
945void QgsVectorLayerRenderer::stopRenderer( QgsFeatureRenderer *renderer, QgsSingleSymbolRenderer *selRenderer )
946{
947 QgsRenderContext &context = *renderContext();
948 renderer->stopRender( context );
949 if ( selRenderer )
950 {
951 selRenderer->stopRender( context );
952 delete selRenderer;
953 }
954}
955
956void QgsVectorLayerRenderer::prepareLabeling( QgsVectorLayer *layer, QSet<QString> &attributeNames )
957{
958 QgsRenderContext &context = *renderContext();
959 // TODO: add attributes for geometry generator
960 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
961 {
962 if ( layer->labelsEnabled() )
963 {
964 if ( context.labelSink() )
965 {
966 if ( const QgsRuleBasedLabeling *rbl = dynamic_cast<const QgsRuleBasedLabeling *>( layer->labeling() ) )
967 {
968 mLabelProvider = new QgsRuleBasedLabelSinkProvider( *rbl, layer, context.labelSink() );
969 }
970 else
971 {
972 QgsPalLayerSettings settings = layer->labeling()->settings();
973 mLabelProvider = new QgsLabelSinkProvider( layer, QString(), context.labelSink(), &settings );
974 }
975 }
976 else
977 {
978 mLabelProvider = layer->labeling()->provider( layer );
979 }
980 if ( mLabelProvider )
981 {
982 engine2->addProvider( mLabelProvider );
983 if ( !mLabelProvider->prepare( context, attributeNames ) )
984 {
985 engine2->removeProvider( mLabelProvider );
986 mLabelProvider = nullptr; // deleted by engine
987 }
988 }
989 }
990 }
991
992#if 0 // TODO: limit of labels, font not found
993 QgsPalLayerSettings &palyr = mContext.labelingEngine()->layer( mLayerID );
994
995 // see if feature count limit is set for labeling
996 if ( palyr.limitNumLabels && palyr.maxNumLabels > 0 )
997 {
998 QgsFeatureIterator fit = getFeatures( QgsFeatureRequest()
999 .setFilterRect( mContext.extent() )
1000 .setNoAttributes() );
1001
1002 // total number of features that may be labeled
1003 QgsFeature f;
1004 int nFeatsToLabel = 0;
1005 while ( fit.nextFeature( f ) )
1006 {
1007 nFeatsToLabel++;
1008 }
1009 palyr.mFeaturesToLabel = nFeatsToLabel;
1010 }
1011
1012 // notify user about any font substitution
1013 if ( !palyr.mTextFontFound && !mLabelFontNotFoundNotified )
1014 {
1015 emit labelingFontNotFound( this, palyr.mTextFontFamily );
1016 mLabelFontNotFoundNotified = true;
1017 }
1018#endif
1019}
1020
1021void QgsVectorLayerRenderer::prepareDiagrams( QgsVectorLayer *layer, QSet<QString> &attributeNames )
1022{
1023 QgsRenderContext &context = *renderContext();
1024 if ( QgsLabelingEngine *engine2 = context.labelingEngine() )
1025 {
1026 if ( layer->diagramsEnabled() )
1027 {
1028 mDiagramProvider = new QgsVectorLayerDiagramProvider( layer );
1029 // need to be added before calling prepare() - uses map settings from engine
1030 engine2->addProvider( mDiagramProvider );
1031 if ( !mDiagramProvider->prepare( context, attributeNames ) )
1032 {
1033 engine2->removeProvider( mDiagramProvider );
1034 mDiagramProvider = nullptr; // deleted by engine
1035 }
1036 }
1037 }
1038}
1039
The Qgis class provides global constants for use throughout the application.
Definition qgis.h:54
@ Degrees
Degrees, for planar geographic CRS distance measurements.
@ Unknown
Unknown types.
@ Null
No geometry.
@ Vector
Vector layer.
@ SkipSymbolRendering
Disable symbol rendering while still drawing labels if enabled (since QGIS 3.24)
@ UseAdvancedEffects
Enable layer opacity and blending effects.
@ SemiTransparentCircle
Semi-transparent circle marker.
@ Cross
Cross marker.
@ CustomColor
Use default symbol with a custom selection color.
@ CustomSymbol
Use a custom symbol.
@ Default
Use default symbol and selection colors.
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.
Class for doing transforms between two map coordinate systems.
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...
Custom exception class for Coordinate Reference System related exceptions.
QString what() const
Single scope for storing variables and functions for use within a QgsExpressionContext.
static QgsExpressionContextScope * updateSymbolScope(const QgsSymbol *symbol, QgsExpressionContextScope *symbolScope=nullptr)
Updates a symbol scope related to a QgsSymbol to an expression context.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
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.
Abstract interface for use by classes that filter the features or attributes of a layer.
virtual void filterFeatures(const QgsVectorLayer *layer, QgsFeatureRequest &featureRequest) const =0
Add additional filters to the feature request to further restrict the features returned by the reques...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
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.
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 QString dump() const
Returns debug information about this renderer.
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.
This class wraps a request for features to a vector layer (or directly its vector data provider).
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.
QgsFeatureRequest & setFlags(QgsFeatureRequest::Flags flags)
Sets flags that affect how features will be fetched.
Flags flags() const
Returns the flags which affect how features are fetched.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the iterator to check if it should be cance...
@ EmbeddedSymbols
Retrieve any embedded feature symbology (since QGIS 3.20)
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
QgsFeatureRequest & setOrderBy(const OrderBy &orderBy)
Set a list of order by clauses.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:56
QgsFeatureId id
Definition qgsfeature.h:64
QgsGeometry geometry
Definition qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
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:45
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
Qgis::GeometryType type
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine representing the specified geometry.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
Implements a derived label provider for use with QgsLabelSink.
The QgsLabelingEngine class provides map labeling functionality.
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.
Base class for utility classes that encapsulate information necessary for rendering of map layers.
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.
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
double opacity
Definition qgsmaplayer.h:83
Perform transforms between map coordinates and device coordinates.
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)
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.
Contains settings for how a map layer will be labeled.
A class to represent a 2D point.
Definition qgspointxy.h:59
double y
Definition qgspointxy.h:63
double x
Definition qgspointxy.h:62
A rectangle specified with double values.
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() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double xMaximum() const
Returns the x maximum value (right side of rectangle).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
QgsPointXY center() const
Returns the center point of the rectangle.
bool isEmpty() const
Returns true if the rectangle has no area.
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 useAdvancedEffects() const
Returns true if advanced effects such as blend modes such be used.
bool hasRenderedFeatureHandlers() const
Returns true if the context has any rendered feature handlers.
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 QgsVectorSimplifyMethod & vectorSimplifyMethod() const
Returns the simplification settings to use when rendering vector layers.
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.
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 provider custom handlers for features rendered as part of a map render...
Implements a derived label provider for rule based labels for use with QgsLabelSink.
Rule based labeling for a vector layer.
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 saving and restoring a QPainter object's state.
T value(const QString &dynamicKeyPart=QString()) const
Returns settings value.
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.
This class contains information about how to simplify geometries fetched from a QgsFeatureIterator.
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.
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:94
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:216
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...
The QgsVectorLayerDiagramProvider class implements support for diagrams within the labeling engine.
virtual bool prepare(const QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
virtual void registerFeature(QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry())
Register a feature for labeling as one or more QgsLabelFeature objects stored into mFeatures.
void setClipFeatureGeometry(const QgsGeometry &geometry)
Sets a geometry to use to clip features to when registering them as diagrams.
Partial snapshot of vector layer's state (only the members necessary for access to features)
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of 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.
virtual QList< QgsLabelFeature * > registerFeature(const QgsFeature &feature, QgsRenderContext &context, const QgsGeometry &obstacleGeometry=QgsGeometry(), const QgsSymbol *symbol=nullptr)
Register a feature for labeling as one or more QgsLabelFeature objects stored into mLabels.
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 data sets.
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.
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.
bool simplifyDrawingCanbeApplied(const QgsRenderContext &renderContext, QgsVectorSimplifyMethod::SimplifyHint simplifyHint) const
Returns whether the VectorLayer can apply the specified simplification hint.
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.
This class contains information how to simplify geometries fetched from a vector layer.
bool forceLocalOptimization() const
Gets where the simplification executes, after fetch the geometries from provider, or when supported,...
void setSimplifyHints(SimplifyHints simplifyHints)
Sets the simplification hints of the vector layer managed.
SimplifyHints simplifyHints() const
Gets 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...
float threshold() const
Gets the simplification threshold of the vector layer managed.
@ GeometrySimplification
The geometries can be simplified using the current map2pixel context state.
@ FullSimplification
All simplification hints can be applied ( Geometry + AA-disabling )
@ NoSimplification
No simplification can be applied.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:4332
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
#define QgsDebugError(str)
Definition qgslogger.h:38
QList< QgsSymbolLevel > QgsSymbolLevelOrder
Definition qgsrenderer.h:88
QList< QgsSymbolLevelItem > QgsSymbolLevel
Definition qgsrenderer.h:84
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:44