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