QGIS API Documentation 4.3.0-Master (0cef2469b72)
Loading...
Searching...
No Matches
qgsmaprendererjob.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmaprendererjob.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
16#include "qgsmaprendererjob.h"
17
18#include <memory>
19
20#include "qgselevationmap.h"
21#include "qgsexception.h"
24#include "qgsgeos.h"
25#include "qgslabelingengine.h"
26#include "qgslogger.h"
27#include "qgsmaplayer.h"
30#include "qgsmaplayerrenderer.h"
31#include "qgsmaplayerstyle.h"
33#include "qgsmaprenderercache.h"
34#include "qgsmeshlayer.h"
36#include "qgsmessagelog.h"
37#include "qgspainting.h"
38#include "qgspallabeling.h"
39#include "qgsrasterlabeling.h"
40#include "qgsrasterlayer.h"
41#include "qgsrasterrenderer.h"
42#include "qgsrendercontext.h"
44#include "qgsruntimeprofiler.h"
46#include "qgssettingstree.h"
49#include "qgsvectorlayerutils.h"
50
51#include <QElapsedTimer>
52#include <QPainter>
53#include <QPicture>
54#include <QString>
55#include <QTimer>
56
57#include "moc_qgsmaprendererjob.cpp"
58
59using namespace Qt::StringLiterals;
60
62const QgsSettingsEntryString *QgsMapRendererJob::settingsMaskBackend = new QgsSettingsEntryString( u"mask-backend"_s, QgsSettingsTree::sTreeMap, QString(), u"Backend engine to use for selective masking"_s );
63
65
66const QString QgsMapRendererJob::LABEL_CACHE_ID = u"_labels_"_s;
67const QString QgsMapRendererJob::ELEVATION_MAP_CACHE_PREFIX = u"_elevation_map_"_s;
68const QString QgsMapRendererJob::LABEL_PREVIEW_CACHE_ID = u"_preview_labels_"_s;
69
70LayerRenderJob &LayerRenderJob::operator=( LayerRenderJob &&other )
71{
72 if ( &other == this )
73 return *this;
74
75 mContext = std::move( other.mContext );
76 destinationImage = std::move( other.destinationImage );
77 destinationPainter = std::move( other.destinationPainter );
78 renderer = std::move( other.renderer );
79 previewRenderImage = std::move( other.previewRenderImage );
80 previewRenderPainter = std::move( other.previewRenderPainter );
81
82 imageInitialized = other.imageInitialized;
83 previewRenderImageInitialized = other.previewRenderImageInitialized;
84
85 blendMode = other.blendMode;
86 opacity = other.opacity;
87 cached = other.cached;
88 layer = other.layer;
89 renderAboveLabels = other.renderAboveLabels;
90 completed = other.completed;
91 renderingTime = other.renderingTime;
92 estimatedRenderingTime = other.estimatedRenderingTime;
93 errors = other.errors;
94 layerId = other.layerId;
95
96 maskPaintDevice = std::move( other.maskPaintDevice );
97 maskRenderFormat = other.maskRenderFormat;
98
99 firstPassJob = other.firstPassJob;
100 other.firstPassJob = nullptr;
101
102 picture = std::move( other.picture );
103
104 maskJobs = other.maskJobs;
105
106 elevationMap = std::move( other.elevationMap );
107 maskPainter = std::move( other.maskPainter );
108
109 return *this;
110}
111
112LayerRenderJob::LayerRenderJob( LayerRenderJob &&other )
113 : imageInitialized( other.imageInitialized )
114 , previewRenderImageInitialized( other.previewRenderImageInitialized )
115 , blendMode( other.blendMode )
116 , opacity( other.opacity )
117 , cached( other.cached )
118 , renderAboveLabels( other.renderAboveLabels )
119 , layer( other.layer )
120 , completed( other.completed )
121 , renderingTime( other.renderingTime )
122 , estimatedRenderingTime( other.estimatedRenderingTime )
123 , errors( other.errors )
124 , layerId( other.layerId )
125 , maskRenderFormat( other.maskRenderFormat )
126 , maskPainter( std::move( other.maskPainter ) )
127 , maskJobs( other.maskJobs )
128{
129 mContext = std::move( other.mContext );
130 destinationImage = std::move( other.destinationImage );
131 destinationPainter = std::move( other.destinationPainter );
132 previewRenderImage = std::move( other.previewRenderImage );
133 previewRenderPainter = std::move( other.previewRenderPainter );
134 renderer = std::move( other.renderer );
135 elevationMap = std::move( other.elevationMap );
136 maskPaintDevice = std::move( other.maskPaintDevice );
137
138 firstPassJob = other.firstPassJob;
139 other.firstPassJob = nullptr;
140
141 picture = std::move( other.picture );
142}
143
144bool LayerRenderJob::imageCanBeComposed() const
145{
146 if ( imageInitialized )
147 {
148 if ( renderer )
149 {
150 return renderer->isReadyToCompose();
151 }
152 else
153 {
154 return true;
155 }
156 }
157 else
158 {
159 return false;
160 }
161}
162
164 : mSettings( settings )
165 , mRenderedItemResults( std::make_unique< QgsRenderedItemResults >( settings.extent() ) )
166 , mLabelingEngineFeedback( new QgsLabelingEngineFeedback( this ) )
167{}
168
170
172{
173 if ( mSettings.hasValidSettings() )
174 startPrivate();
175 else
176 {
177 mErrors.append( QgsMapRendererJob::Error( QString(), tr( "Invalid map settings" ) ) );
178 emit finished();
179 }
180}
181
183{
185}
186
188{
189 return mRenderedItemResults.release();
190}
191
193 : QgsMapRendererJob( settings )
194{}
195
196
198{
199 return mErrors;
200}
201
203{
204 mCache = cache;
205}
206
208{
209 return mLabelingEngineFeedback;
210}
211
212QHash<QgsMapLayer *, int> QgsMapRendererJob::perLayerRenderingTime() const
213{
214 QHash<QgsMapLayer *, int> result;
215 for ( auto it = mPerLayerRenderingTime.constBegin(); it != mPerLayerRenderingTime.constEnd(); ++it )
216 {
217 if ( auto &&lKey = it.key() )
218 result.insert( lKey, it.value() );
219 }
220 return result;
221}
222
223void QgsMapRendererJob::setLayerRenderingTimeHints( const QHash<QString, int> &hints )
224{
226}
227
229{
230 return mSettings;
231}
232
234{
235 bool canCache = mCache;
236
237 // calculate which layers will be labeled
238 QSet< QgsMapLayer * > labeledLayers;
239 const QList<QgsMapLayer *> layers = mSettings.layers();
240 for ( QgsMapLayer *ml : layers )
241 {
243 labeledLayers << ml;
244
245 switch ( ml->type() )
246 {
248 {
249 QgsVectorLayer *vl = qobject_cast< QgsVectorLayer *>( ml );
250 if ( vl->labelsEnabled() && vl->labeling()->requiresAdvancedEffects() )
251 {
252 canCache = false;
253 }
254 break;
255 }
256
258 {
259 QgsMeshLayer *l = qobject_cast< QgsMeshLayer *>( ml );
260 if ( l->labelsEnabled() && l->labeling()->requiresAdvancedEffects() )
261 {
262 canCache = false;
263 }
264 break;
265 }
266
268 {
269 QgsRasterLayer *l = qobject_cast< QgsRasterLayer *>( ml );
270 if ( l->labelsEnabled() && l->labeling()->requiresAdvancedEffects() )
271 {
272 canCache = false;
273 }
274 break;
275 }
276
278 {
279 // TODO -- add detection of advanced labeling effects for vector tile layers
280 break;
281 }
282
288 break;
289 }
290
291 if ( !canCache )
292 break;
293 }
294
295 if ( mCache && mCache->hasCacheImage( LABEL_CACHE_ID ) )
296 {
297 // we may need to clear label cache and re-register labeled features - check for that here
298
299 // can we reuse the cached label solution?
300 const QList< QgsMapLayer * > labelDependentLayers = mCache->dependentLayers( LABEL_CACHE_ID );
301 bool canUseCache = canCache && QSet< QgsMapLayer * >( labelDependentLayers.begin(), labelDependentLayers.end() ) == labeledLayers;
302 if ( !canUseCache )
303 {
304 // no - participating layers have changed
305 mCache->clearCacheImage( LABEL_CACHE_ID );
306 }
307 }
308 return canCache;
309}
310
312{
313 const QList<QgsMapLayer *> layers = mSettings.layers();
314 for ( QgsMapLayer *ml : layers )
315 {
317 continue;
318
319 switch ( ml->type() )
320 {
322 {
323 QgsVectorLayer *vl = qobject_cast< QgsVectorLayer *>( ml );
325 {
326 return true;
327 }
328 break;
329 }
330
332 {
333 QgsMeshLayer *l = qobject_cast< QgsMeshLayer *>( ml );
335 {
336 return true;
337 }
338 break;
339 }
340
342 {
343 QgsRasterLayer *l = qobject_cast< QgsRasterLayer *>( ml );
345 {
346 return true;
347 }
348 break;
349 }
350
352 {
353 // TODO -- add detection of advanced labeling effects for vector tile layers
354 break;
355 }
356
362 break;
363 }
364 }
365
366 return false;
367}
368
369bool QgsMapRendererJob::reprojectToLayerExtent( const QgsMapLayer *ml, const QgsCoordinateTransform &ct, QgsRectangle &extent, QgsRectangle &r2 )
370{
371 bool res = true;
372 // we can safely use ballpark transforms without bothering the user here -- at the likely scale of layer extents there
373 // won't be an appreciable difference, and we aren't actually transforming any rendered points here anyway (just the layer extent)
374 QgsCoordinateTransform approxTransform = ct;
375 approxTransform.setBallparkTransformsAreAppropriate( true );
376
377 try
378 {
379#ifdef QGISDEBUG
380 // QgsLogger::debug<QgsRectangle>("Getting extent of canvas in layers CS. Canvas is ", extent, __FILE__, __FUNCTION__, __LINE__);
381#endif
382 // Split the extent into two if the source CRS is
383 // geographic and the extent crosses the split in
384 // geographic coordinates (usually +/- 180 degrees,
385 // and is assumed to be so here), and draw each
386 // extent separately.
387 static const double SPLIT_COORD = 180.0;
388
389 if ( ml->crs().isGeographic() )
390 {
391 if ( ml->type() == Qgis::LayerType::Vector && !approxTransform.destinationCrs().isGeographic() )
392 {
393 // if we transform from a projected coordinate system check
394 // check if transforming back roughly returns the input
395 // extend - otherwise render the world.
396 QgsRectangle extent1 = approxTransform.transformBoundingBox( extent, Qgis::TransformDirection::Reverse );
397 QgsRectangle extent2 = approxTransform.transformBoundingBox( extent1, Qgis::TransformDirection::Forward );
398
400 u"\n0:%1 %2x%3\n1:%4\n2:%5 %6x%7 (w:%8 h:%9)"_s.arg( extent.toString() )
401 .arg( extent.width() )
402 .arg( extent.height() )
403 .arg( extent1.toString(), extent2.toString() )
404 .arg( extent2.width() )
405 .arg( extent2.height() )
406 .arg( std::fabs( 1.0 - extent2.width() / extent.width() ) )
407 .arg( std::fabs( 1.0 - extent2.height() / extent.height() ) ),
408 3
409 );
410
411 // can differ by a maximum of up to 20% of height/width
412 if ( qgsDoubleNear( extent2.xMinimum(), extent.xMinimum(), extent.width() * 0.2 )
413 && qgsDoubleNear( extent2.xMaximum(), extent.xMaximum(), extent.width() * 0.2 )
414 && qgsDoubleNear( extent2.yMinimum(), extent.yMinimum(), extent.height() * 0.2 )
415 && qgsDoubleNear( extent2.yMaximum(), extent.yMaximum(), extent.height() * 0.2 ) )
416 {
417 extent = extent1;
418 }
419 else
420 {
421 extent = QgsRectangle( -180.0, -90.0, 180.0, 90.0 );
422 res = false;
423 }
424 }
425 else
426 {
427 // Note: ll = lower left point
428 QgsPointXY ll = approxTransform.transform( extent.xMinimum(), extent.yMinimum(), Qgis::TransformDirection::Reverse );
429
430 // and ur = upper right point
431 QgsPointXY ur = approxTransform.transform( extent.xMaximum(), extent.yMaximum(), Qgis::TransformDirection::Reverse );
432
433 QgsDebugMsgLevel( u"in:%1 (ll:%2 ur:%3)"_s.arg( extent.toString(), ll.toString(), ur.toString() ), 4 );
434
435 extent = approxTransform.transformBoundingBox( extent, Qgis::TransformDirection::Reverse );
436
437 QgsDebugMsgLevel( u"out:%1 (w:%2 h:%3)"_s.arg( extent.toString() ).arg( extent.width() ).arg( extent.height() ), 4 );
438
439 if ( ll.x() > ur.x() )
440 {
441 // the coordinates projected in reverse order than what one would expect.
442 // we are probably looking at an area that includes longitude of 180 degrees.
443 // we need to take into account coordinates from two intervals: (-180,x1) and (x2,180)
444 // so let's use (-180,180). This hopefully does not add too much overhead. It is
445 // more straightforward than rendering with two separate extents and more consistent
446 // for rendering, labeling and caching as everything is rendered just in one go
447 extent.setXMinimum( -SPLIT_COORD );
448 extent.setXMaximum( SPLIT_COORD );
449 res = false;
450 }
451 }
452
453 // TODO: the above rule still does not help if using a projection that covers the whole
454 // world. E.g. with EPSG:3857 the longitude spectrum -180 to +180 is mapped to approx.
455 // -2e7 to +2e7. Converting extent from -5e7 to +5e7 is transformed as -90 to +90,
456 // but in fact the extent should cover the whole world.
457 }
458 else // can't cross 180
459 {
460 if ( approxTransform.destinationCrs().isGeographic() && ( extent.xMinimum() <= -180 || extent.xMaximum() >= 180 || extent.yMinimum() <= -90 || extent.yMaximum() >= 90 ) )
461 // Use unlimited rectangle because otherwise we may end up transforming wrong coordinates.
462 // E.g. longitude -200 to +160 would be understood as +40 to +160 due to periodicity.
463 // We could try to clamp coords to (-180,180) for lon resp. (-90,90) for lat,
464 // but this seems like a safer choice.
465 {
466 extent = QgsRectangle( std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max() );
467 res = false;
468 }
469 else
470 extent = approxTransform.transformBoundingBox( extent, Qgis::TransformDirection::Reverse );
471 }
472 }
473 catch ( QgsCsException &e )
474 {
475 QgsDebugError( u"Transform error caught: %1"_s.arg( e.what() ) );
476 extent = QgsRectangle( std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max() );
477 r2 = QgsRectangle( std::numeric_limits<double>::lowest(), std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(), std::numeric_limits<double>::max() );
478 res = false;
479 }
480
481 return res;
482}
483
484std::unique_ptr<QImage> QgsMapRendererJob::allocateImage( const QString &layerId )
485{
486 auto image = std::make_unique< QImage >( mSettings.deviceOutputSize(), mSettings.outputImageFormat() );
487 image->setDevicePixelRatio( static_cast<qreal>( mSettings.devicePixelRatio() ) );
488 image->setDotsPerMeterX( static_cast< int >( 1000 * mSettings.outputDpi() / 25.4 ) );
489 image->setDotsPerMeterY( static_cast< int >( 1000 * mSettings.outputDpi() / 25.4 ) );
490 if ( image->isNull() )
491 {
492 QgsDebugError( u"Insufficient memory for image %1x%2"_s.arg( mSettings.outputSize().width() ).arg( mSettings.outputSize().height() ) );
493 mErrors.append( Error( layerId, tr( "Insufficient memory for image %1x%2" ).arg( mSettings.outputSize().width() ).arg( mSettings.outputSize().height() ) ) );
494 return {};
495 }
496 return image;
497}
498
499std::unique_ptr<QgsElevationMap> QgsMapRendererJob::allocateElevationMap( const QString &layerId )
500{
501 auto elevationMap = std::make_unique<QgsElevationMap>( mSettings.deviceOutputSize(), mSettings.devicePixelRatio() );
502 if ( !elevationMap->isValid() )
503 {
504 QgsDebugError( u"Insufficient memory for elevation map %1x%2"_s.arg( mSettings.outputSize().width() ).arg( mSettings.outputSize().height() ) );
505 mErrors.append( Error( layerId, tr( "Insufficient memory for elevation map %1x%2" ).arg( mSettings.outputSize().width() ).arg( mSettings.outputSize().height() ) ) );
506 return nullptr;
507 }
508 return elevationMap;
509}
510
511std::tuple< std::unique_ptr< QImage >, std::unique_ptr< QPainter > > QgsMapRendererJob::allocateImageAndPainter( const QString &layerId, const QgsRenderContext &context )
512{
513 std::unique_ptr< QPainter > painter;
514 std::unique_ptr< QImage > image = allocateImage( layerId );
515 if ( image )
516 {
517 painter = std::make_unique< QPainter >( image.get() );
518 context.setPainterFlagsUsingContext( painter.get() );
519 }
520 return { std::move( image ), std::move( painter ) };
521}
522
523std::tuple<std::unique_ptr<QPicture>, std::unique_ptr< QPainter > > QgsMapRendererJob::allocatePictureAndPainter( const QgsRenderContext &context )
524{
525 auto picture = std::make_unique<QPicture>();
526 auto painter = std::make_unique< QPainter >( picture.get() );
527 context.setPainterFlagsUsingContext( painter.get() );
528 return { std::move( picture ), std::move( painter ) };
529}
530
531std::vector<LayerRenderJob> QgsMapRendererJob::prepareJobs( QPainter *painter, QgsLabelingEngine *labelingEngine2, bool deferredPainterSet )
532{
533 std::vector< LayerRenderJob > layerJobs;
534
535 // render all layers in the stack, starting at the base
536 QListIterator<QgsMapLayer *> li( mSettings.layers() );
537 li.toBack();
538
539 if ( mCache )
540 {
541 bool cacheValid = mCache->updateParameters( mSettings.visibleExtent(), mSettings.mapToPixel() );
542 Q_UNUSED( cacheValid )
543 QgsDebugMsgLevel( u"CACHE VALID: %1"_s.arg( cacheValid ), 4 );
544 }
545
546 bool requiresLabelRedraw = !( mCache && mCache->hasCacheImage( LABEL_CACHE_ID ) );
547
548 while ( li.hasPrevious() )
549 {
550 QgsMapLayer *ml = li.previous();
551
553 u"layer %1: minscale:%2 maxscale:%3 scaledepvis:%4 blendmode:%5 isValid:%6"_s.arg( ml->name() )
554 .arg( ml->minimumScale() )
555 .arg( ml->maximumScale() )
556 .arg( ml->hasScaleBasedVisibility() )
557 .arg( ml->blendMode() )
558 .arg( ml->isValid() ),
559 3
560 );
561
562 if ( !ml->isValid() )
563 {
564 QgsDebugMsgLevel( u"Invalid Layer skipped"_s, 3 );
565 mErrors.append( Error( ml->id(), QString( "Layer %1 is invalid, skipped" ).arg( ml->name() ) ) );
566 continue;
567 }
568
569 if ( !ml->isInScaleRange( mSettings.scale() ) ) //|| mOverview )
570 {
571 QgsDebugMsgLevel( u"Layer not rendered because it is not within the defined visibility scale range"_s, 3 );
572 continue;
573 }
574
575 if ( mSettings.isTemporal() && ml->temporalProperties() && !ml->temporalProperties()->isVisibleInTemporalRange( mSettings.temporalRange() ) )
576 {
577 QgsDebugMsgLevel( u"Layer not rendered because it is not visible within the map's time range"_s, 3 );
578 continue;
579 }
580
581 if ( mPerLayerTemporalRange.contains( ml ) && ml->temporalProperties() && !ml->temporalProperties()->isVisibleInTemporalRange( mPerLayerTemporalRange[ml] ) )
582 {
583 QgsDebugMsgLevel( u"Layer not rendered because it is not visible within the layer's time range"_s, 3 );
584 continue;
585 }
586
587 if ( !mSettings.zRange().isInfinite() && ml->elevationProperties() && !ml->elevationProperties()->isVisibleInZRange( mSettings.zRange(), ml ) )
588 {
589 QgsDebugMsgLevel( u"Layer not rendered because it is not visible within the map's z range"_s, 3 );
590 continue;
591 }
592
593 QgsRectangle r1 = mSettings.visibleExtent(), r2;
594 r1.grow( mSettings.extentBuffer() );
595 QgsCoordinateTransform ct;
596
597 ct = mSettings.layerTransform( ml );
598 bool haveExtentInLayerCrs = true;
599 if ( ct.isValid() )
600 {
601 haveExtentInLayerCrs = reprojectToLayerExtent( ml, ct, r1, r2 );
602 }
603 QgsDebugMsgLevel( "extent: " + r1.toString(), 3 );
604 if ( !r1.isFinite() || !r2.isFinite() )
605 {
606 mErrors.append( Error( ml->id(), tr( "There was a problem transforming the layer's extent. Layer skipped." ) ) );
607 continue;
608 }
609
610 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( ml );
611
612 // Force render of layers that are being edited
613 // or if there's a labeling engine that needs the layer to register features
614 if ( mCache )
615 {
616 const bool requiresLabeling = ( labelingEngine2 && QgsPalLabeling::staticWillUseLayer( ml ) ) && requiresLabelRedraw;
617 if ( ( vl && vl->isEditable() ) || requiresLabeling )
618 {
619 mCache->clearCacheImage( ml->id() );
620 }
621 }
622
623 layerJobs.emplace_back( LayerRenderJob() );
624 LayerRenderJob &job = layerJobs.back();
625 job.layer = ml;
626 job.layerId = ml->id();
627 job.renderAboveLabels = ml->customProperty( u"rendering/renderAboveLabels"_s ).toBool();
628 job.estimatedRenderingTime = mLayerRenderingTimeHints.value( ml->id(), 0 );
629
630 job.setContext( std::make_unique< QgsRenderContext >( QgsRenderContext::fromMapSettings( mSettings ) ) );
631 if ( !ml->customProperty( u"_noset_layer_expression_context"_s ).toBool() )
632 job.context()->expressionContext().appendScope( QgsExpressionContextUtils::layerScope( ml ) );
633 job.context()->setPainter( painter );
634 job.context()->setLabelingEngine( labelingEngine2 );
635 job.context()->setLabelSink( labelSink() );
636 job.context()->setCoordinateTransform( ct );
637 job.context()->setExtent( r1 );
638
639 // Also check geographic, see: https://github.com/qgis/QGIS/issues/45200
640 if ( !haveExtentInLayerCrs || ( ct.isValid() && ( ct.sourceCrs().isGeographic() != ct.destinationCrs().isGeographic() ) ) )
641 job.context()->setFlag( Qgis::RenderContextFlag::ApplyClipAfterReprojection, true );
642
643 if ( mFeatureFilterProvider )
644 {
645 job.context()->setFeatureFilterProvider( mFeatureFilterProvider );
646 }
647
648 if ( mPerLayerTemporalRange.contains( ml ) )
649 {
650 job.context()->setTemporalRange( mPerLayerTemporalRange.value( ml ) );
651 }
652
653 QgsMapLayerStyleOverride styleOverride( ml );
654 if ( mSettings.layerStyleOverrides().contains( ml->id() ) )
655 styleOverride.setOverrideStyle( mSettings.layerStyleOverrides().value( ml->id() ) );
656
657 job.blendMode = ml->blendMode();
658
659 if ( ml->type() == Qgis::LayerType::Raster )
660 {
661 // raster layers are abnormal wrt opacity handling -- opacity is sometimes handled directly within the raster layer renderer
662 QgsRasterLayer *rl = qobject_cast< QgsRasterLayer * >( ml );
664 {
665 job.opacity = 1.0;
666 }
667 else
668 {
669 job.opacity = ml->opacity();
670 }
671 }
672 else
673 {
674 job.opacity = ml->opacity();
675 }
676
677 const QgsElevationShadingRenderer shadingRenderer = mSettings.elevationShadingRenderer();
678
679 // if we can use the cache, let's do it and avoid rendering!
680 const bool canUseCache = mSettings.rasterizedRenderingPolicy() == Qgis::RasterizedRenderingPolicy::Default && mCache;
681 if ( canUseCache && mCache->hasCacheImage( ml->id() ) )
682 {
683 job.cached = true;
684 job.imageInitialized = true;
685 job.destinationImage = std::make_unique< QImage >( mCache->cacheImage( ml->id() ) );
686 if ( shadingRenderer.isActive() && ml->elevationProperties() && ml->elevationProperties()->hasElevation() && mCache->hasCacheImage( ELEVATION_MAP_CACHE_PREFIX + ml->id() ) )
687 job.elevationMap = std::make_unique< QgsElevationMap >( mCache->cacheImage( ELEVATION_MAP_CACHE_PREFIX + ml->id() ) );
688 job.destinationImage->setDevicePixelRatio( static_cast<qreal>( mSettings.devicePixelRatio() ) );
689 job.renderer.reset();
690 job.context()->setPainter( nullptr );
691 mLayersRedrawnFromCache.append( ml->id() );
692 continue;
693 }
694
695 QElapsedTimer layerTime;
696 layerTime.start();
697 job.renderer.reset( ml->createMapRenderer( *( job.context() ) ) );
698 if ( job.renderer )
699 {
700 job.renderer->setLayerRenderingTimeHint( job.estimatedRenderingTime );
701 job.context()->setFeedback( job.renderer->feedback() );
702
703 if ( job.renderer->flags().testFlag( Qgis::MapLayerRendererFlag::AffectsLabeling ) )
704 {
705 mAdditionalLabelLayers.append( ml );
706 }
707 }
708
709 // If we are drawing with an alternative blending mode then we need to render to a separate image
710 // before compositing this on the map. This effectively flattens the layer and prevents
711 // blending occurring between objects on the layer
712 if ( canUseCache || ( !painter && !deferredPainterSet ) || ( job.renderer && job.renderer->forceRasterRender() ) )
713 {
714 // Flattened image for drawing when a blending mode is set
715 auto [image, painter] = allocateImageAndPainter( ml->id(), *job.context() );
716 job.destinationImage = std::move( image );
717 job.destinationPainter = std::move( painter );
718 job.context()->setPainter( job.destinationPainter.get() );
719 if ( !job.destinationImage )
720 {
721 job.renderer.reset();
722 layerJobs.pop_back();
723 continue;
724 }
725 }
726
727 if ( shadingRenderer.isActive() && ml->elevationProperties() && ml->elevationProperties()->hasElevation() )
728 {
729 job.elevationMap = allocateElevationMap( ml->id() );
730 job.context()->setElevationMap( job.elevationMap.get() );
731 }
732
733 if ( job.renderer && ( job.renderer->flags() & Qgis::MapLayerRendererFlag::RenderPartialOutputs ) && ( mSettings.flags() & Qgis::MapSettingsFlag::RenderPartialOutput ) )
734 {
735 if ( canUseCache && ( job.renderer->flags() & Qgis::MapLayerRendererFlag::RenderPartialOutputOverPreviousCachedImage ) && mCache->hasAnyCacheImage( job.layerId + u"_preview"_s ) )
736 {
737 const QImage cachedImage = mCache->transformedCacheImage( job.layerId + u"_preview"_s, mSettings.mapToPixel() );
738 if ( !cachedImage.isNull() )
739 {
740 job.previewRenderImage = std::make_unique< QImage >( cachedImage );
741 job.previewRenderImageInitialized = true;
742 job.context()->setPreviewRenderPainter( new QPainter( job.previewRenderImage.get() ) );
743 job.context()->setPainterFlagsUsingContext( painter );
744 }
745 }
746 if ( !job.previewRenderImage )
747 {
748 auto [image, painter] = allocateImageAndPainter( ml->id(), *job.context() );
749 job.previewRenderImage = std::move( image );
750 job.previewRenderPainter = std::move( painter );
751 job.previewRenderImageInitialized = false;
752 job.context()->setPreviewRenderPainter( job.previewRenderPainter.get() );
753 }
754
755 if ( !job.previewRenderImage )
756 {
757 job.context()->setPreviewRenderPainter( nullptr );
758 job.previewRenderPainter.reset();
759 }
760 }
761
762 job.renderingTime = static_cast< int >( layerTime.elapsed() ); // include job preparation time in layer rendering time
763 }
764
765 return layerJobs;
766}
767
768std::vector< LayerRenderJob > QgsMapRendererJob::prepareSecondPassJobs( std::vector< LayerRenderJob > &firstPassJobs, LabelRenderJob &labelJob )
769{
770 std::vector< LayerRenderJob > secondPassJobs;
771
772 // We will need to quickly access the associated rendering job of a layer
773 QHash<QString, LayerRenderJob *> layerJobMapping;
774
775 // ... and layer that contains a mask (and whether there is effects implied or not)
776 QMap<QString, bool> maskLayerHasEffects;
777 QMap<int, bool> labelHasEffects;
778
779 struct MaskSource
780 {
781 QString layerId;
782 QString labelRuleId;
783 int labelMaskId;
784 bool hasEffects;
785 MaskSource( const QString &layerId_, const QString &labelRuleId_, int labelMaskId_, bool hasEffects_ )
786 : layerId( layerId_ )
787 , labelRuleId( labelRuleId_ )
788 , labelMaskId( labelMaskId_ )
789 , hasEffects( hasEffects_ )
790 {}
791 };
792
793 struct MaskedSymbolLayers
794 {
795 QSet<QString> maskedSymbolLayerIds;
796 QList<MaskSource> maskSourceList;
797 };
798
799 // We collect for each layer, the set of symbol layers that will be "masked"
800 // and the list of source layers that have a mask
801 // Hash keys are the layer ID of the layer that WILL be masked
802 QHash<QString, MaskedSymbolLayers> maskedSymbolLayers;
803
804 // First up, create a mapping of layer id to jobs. We need this to filter out any masking
805 // which refers to layers which we aren't rendering as part of this map render
806 for ( LayerRenderJob &job : firstPassJobs )
807 {
808 layerJobMapping[job.layerId] = &job;
809 }
810
811 const QHash<QString, QgsSelectiveMaskingSourceSet> selectiveMaskingSourceSets = mapSettings().selectiveMaskingSourceSets();
812
813 QVector< QgsVectorLayer * > allRenderedVectorLayers;
814 for ( LayerRenderJob &job : firstPassJobs )
815 {
816 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( job.layer );
817 if ( !vl )
818 continue;
819
820 allRenderedVectorLayers << vl;
821 }
822
823 // next, collate a master list of masked layers, skipping over any which refer to layers
824 // which don't have a corresponding render job
825 for ( LayerRenderJob &job : firstPassJobs )
826 {
827 QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( job.layer );
828 if ( !vl )
829 continue;
830
831 // lambda function to factor code for both labels and symbol layers
832 auto collectMasks = [&maskedSymbolLayers,
833 &maskLayerHasEffects]( const QgsMaskedLayers &objectsToBeMaskedByLayer, const QString &idOfLayerCreatingMask, const QString &ruleId = QString(), int labelMaskId = -1 ) {
834 bool hasEffects = false;
835 for ( auto it = objectsToBeMaskedByLayer.begin(); it != objectsToBeMaskedByLayer.end(); ++it )
836 {
837 const QString maskedLayerId = it.key();
838 auto lit = maskedSymbolLayers.find( maskedLayerId );
839 if ( lit == maskedSymbolLayers.end() )
840 {
841 MaskedSymbolLayers maskedObjects;
842 maskedObjects.maskedSymbolLayerIds = it.value().symbolLayerIdsToMask;
843 maskedObjects.maskSourceList = QList<MaskSource>() << MaskSource( idOfLayerCreatingMask, ruleId, labelMaskId, it.value().hasEffects );
844 maskedSymbolLayers[maskedLayerId] = maskedObjects;
845 }
846 else
847 {
848 if ( lit->maskedSymbolLayerIds != it.value().symbolLayerIdsToMask )
849 {
850 QgsLogger::warning( u"Layer %1 : Different sets of symbol layers are masked by different sources ! Only one (arbitrary) set will be retained !"_s.arg( it.key() ) );
851 continue;
852 }
853 lit->maskSourceList.push_back( MaskSource( idOfLayerCreatingMask, ruleId, labelMaskId, hasEffects ) );
854 }
855 hasEffects |= it.value().hasEffects;
856 }
857 if ( !objectsToBeMaskedByLayer.isEmpty() && labelMaskId == -1 )
858 maskLayerHasEffects[idOfLayerCreatingMask] = hasEffects;
859 };
860
861 // collect label masks
862 QHash<QString, QgsMaskedLayers> labelMasks = QgsVectorLayerUtils::collectObjectsMaskedByLabelsFromLayer( vl, selectiveMaskingSourceSets, allRenderedVectorLayers );
863 for ( auto it = labelMasks.begin(); it != labelMasks.end(); it++ )
864 {
865 QString labelRule = it.key();
866 // this is a hash of layer id to masks
867 QgsMaskedLayers masks = it.value();
868
869 // filter out masks to those which we are actually rendering
870 QgsMaskedLayers usableMasks;
871 for ( auto mit = masks.begin(); mit != masks.end(); mit++ )
872 {
873 const QString sourceLayerId = mit.key();
874 // if we aren't rendering the source layer as part of this render, we can't process this mask
875 if ( !layerJobMapping.contains( sourceLayerId ) )
876 continue;
877 else
878 usableMasks.insert( sourceLayerId, mit.value() );
879 }
880
881 if ( usableMasks.empty() )
882 continue;
883
884 // group layers by QSet<QgsSymbolLayerReference>
885 QSet<QgsSymbolLayerReference> slRefs;
886 bool hasEffects = false;
887 for ( auto mit = usableMasks.begin(); mit != usableMasks.end(); mit++ )
888 {
889 const QString sourceLayerId = mit.key();
890 // if we aren't rendering the source layer as part of this render, we can't process this mask
891 if ( !layerJobMapping.contains( sourceLayerId ) )
892 continue;
893
894 for ( const QString &symbolLayerId : std::as_const( mit.value().symbolLayerIdsToMask ) )
895 slRefs.insert( QgsSymbolLayerReference( sourceLayerId, symbolLayerId ) );
896
897 hasEffects |= mit.value().hasEffects;
898 }
899 // generate a new mask id for this set
900 int labelMaskId = labelJob.maskIdProvider.insertLabelLayer( vl->id(), it.key(), slRefs );
901 labelHasEffects[labelMaskId] = hasEffects;
902
903 // now collect masks
904 collectMasks( usableMasks, vl->id(), labelRule, labelMaskId );
905 }
906
907 // collect symbol layer masks
908 const QgsMaskedLayers objectsToBeMaskedByLayer = QgsVectorLayerUtils::collectObjectsMaskedBySymbolLayersFromLayer( vl, selectiveMaskingSourceSets, allRenderedVectorLayers );
909 collectMasks( objectsToBeMaskedByLayer, vl->id() );
910 }
911
912 if ( maskedSymbolLayers.isEmpty() )
913 return secondPassJobs;
914
915 // determine upfront if a label mask requires raster rendering
916 QMap<int, bool> labelMaskRequiresRaster;
917 QMap<QString, bool> layerMaskRequiresRaster;
918 for ( auto it = maskedSymbolLayers.constBegin(); it != maskedSymbolLayers.constEnd(); ++it )
919 {
920 const QString maskedLayerId = it.key();
921 LayerRenderJob *targetJob = layerJobMapping.value( maskedLayerId );
922
923 // check if target layer itself forces rasterization
924 const bool targetForcesRaster = !targetJob || ( targetJob->renderer && targetJob->renderer->forceRasterRender() ) || ( targetJob->blendMode != QPainter::CompositionMode_SourceOver );
925 for ( const MaskSource &source : it->maskSourceList )
926 {
927 bool sourceRequiresRaster = source.hasEffects || targetForcesRaster;
928 if ( source.labelMaskId != -1 )
929 {
930 if ( labelHasEffects[source.labelMaskId] || sourceRequiresRaster )
931 labelMaskRequiresRaster[source.labelMaskId] = true;
932 }
933 else
934 {
935 if ( maskLayerHasEffects.value( source.layerId, false ) || sourceRequiresRaster )
936 layerMaskRequiresRaster[source.layerId] = true;
937 }
938 }
939 }
940
941 // Prepare label mask images
942 for ( int maskId = 0; maskId < labelJob.maskIdProvider.size(); maskId++ )
943 {
944 std::unique_ptr< QPaintDevice > maskPaintDevice;
945 std::unique_ptr< QPainter > maskPainter;
946
948 switch ( mapSettings().rasterizedRenderingPolicy() )
949 {
951 renderFormat = Qgis::RenderFormat::Raster;
952 break;
954 renderFormat = !mapSettings().testFlag( Qgis::MapSettingsFlag::ForceRasterMasks ) && !labelMaskRequiresRaster.value( maskId, false ) ? Qgis::RenderFormat::Vector : Qgis::RenderFormat::Raster;
955 break;
958 break;
959 }
960
961 switch ( renderFormat )
962 {
964 {
965 // set a painter to get all masking instruction in order to later clip masked symbol layer
966 auto geomPaintDevice = std::make_unique< QgsGeometryPaintDevice >( true );
967 geomPaintDevice->setStrokedPathSegments( 4 );
968 geomPaintDevice->setSimplificationTolerance( labelJob.context.maskSettings().simplifyTolerance() );
969 maskPaintDevice = std::move( geomPaintDevice );
970 maskPainter = std::make_unique< QPainter >( maskPaintDevice.get() );
971 break;
972 }
974 {
975 // Note: we only need an alpha channel here, rather than a full RGBA image
976 auto [maskImage, painter] = allocateImageAndPainter( u"label mask"_s, labelJob.context );
977
978 // FIXME ? when maskImage is let to nullptr in case of out-of-memory
979 // cppcheck-suppress nullPointer
980 maskImage->fill( 0 );
981 maskPaintDevice = std::move( maskImage );
982 maskPainter = std::move( painter );
983 break;
984 }
985 }
986
987 labelJob.context.setMaskPainter( maskPainter.get(), maskId );
988 labelJob.maskPainters.emplace_back( std::move( maskPainter ) );
989 labelJob.maskPaintDevices.emplace_back( std::move( maskPaintDevice ) );
990 }
991 labelJob.context.setMaskIdProvider( &labelJob.maskIdProvider );
992
993 const bool hasNonDefaultComposition = labelingHasNonDefaultCompositionModes();
994
995 // Prepare second pass jobs
996 // - For raster rendering or vector rendering if effects are involved
997 // 1st pass, 2nd pass and mask are rendered in QImage and composed in composeSecondPass
998 // - For vector rendering if no effects are involved
999 // 1st pass is rendered in QImage, clip paths are generated according to mask and used during
1000 // masked symbol layer rendering during second pass, which is rendered in QPicture, second
1001 // pass job picture
1002
1003 // Allocate an image or picture for labels, as suitable.
1004 // If we have some non-default label composition modes, we CAN'T render to an image as that
1005 // "flattens" composition modes and prevents them interacting with underlying layers.
1006
1007 Qgis::RenderFormat labelJobRenderFormat = Qgis::RenderFormat::Raster;
1008 switch ( mapSettings().rasterizedRenderingPolicy() )
1009 {
1011 labelJobRenderFormat = hasNonDefaultComposition ? Qgis::RenderFormat::Vector : Qgis::RenderFormat::Raster;
1012 break;
1013
1017 break;
1018 }
1019
1020 switch ( labelJobRenderFormat )
1021 {
1023 {
1024 if ( !labelJob.img )
1025 {
1026 labelJob.img = allocateImage( u"labels"_s );
1027 }
1028 break;
1029 }
1030
1032 {
1033 if ( !labelJob.picture )
1034 {
1035 labelJob.picture = std::make_unique<QPicture>();
1036 }
1037 break;
1038 }
1039 }
1040
1041 // first we initialize painter and mask painter for all jobs
1042 for ( LayerRenderJob &job : firstPassJobs )
1043 {
1044 bool maskRequiresLayerRasterization = false;
1045
1046 auto it = maskedSymbolLayers.find( job.layerId );
1047 if ( it != maskedSymbolLayers.end() )
1048 {
1049 const QList<MaskSource> &sourceList = it->maskSourceList;
1050 for ( const MaskSource &source : sourceList )
1051 {
1052 maskRequiresLayerRasterization |= source.hasEffects;
1053 }
1054 }
1055
1056 // update first pass job painter and device if needed
1057 job.maskRenderFormat = Qgis::RenderFormat::Raster;
1058 switch ( mapSettings().rasterizedRenderingPolicy() )
1059 {
1061 job.maskRenderFormat = Qgis::RenderFormat::Raster;
1062 break;
1064 {
1066 || maskRequiresLayerRasterization
1067 || ( job.renderer && job.renderer->forceRasterRender() )
1068 || ( job.blendMode != QPainter::CompositionMode_SourceOver ) )
1069 job.maskRenderFormat = Qgis::RenderFormat::Raster;
1070 else
1071 job.maskRenderFormat = Qgis::RenderFormat::Vector;
1072 break;
1073 }
1076 break;
1077 }
1078
1079 switch ( job.maskRenderFormat )
1080 {
1082 {
1083 if ( !job.destinationImage )
1084 {
1085 auto [img, painter] = allocateImageAndPainter( job.layerId, *job.context() );
1086 Q_ASSERT( !job.destinationPainter );
1087 job.destinationPainter = std::move( painter );
1088 job.context()->setPainter( job.destinationPainter.get() );
1089 job.destinationImage = std::move( img );
1090 }
1091 break;
1092 }
1093
1095 {
1096 if ( !job.picture )
1097 {
1098 auto [picture, painter] = allocatePictureAndPainter( *job.context() );
1099 job.picture = std::move( picture );
1100 if ( job.context()->painter()->hasClipping() )
1101 {
1102 // need to copy clipping paths from original painter, so that e.g. the layout map bounds clipping path is respected
1103 painter->setClipping( true );
1104 painter->setClipPath( job.context()->painter()->clipPath() );
1105 }
1106 Q_ASSERT( !job.destinationPainter );
1107 job.destinationPainter = std::move( painter );
1108 job.context()->setPainter( job.destinationPainter.get() );
1109 // force recreation of layer renderer so it initialize correctly the renderer
1110 // especially the RasterLayerRender that need logicalDpiX from painting device
1111 job.context()->setFeedback( nullptr );
1112 job.renderer.reset( job.layer->createMapRenderer( *( job.context() ) ) );
1113 if ( job.renderer )
1114 {
1115 job.context()->setFeedback( job.renderer->feedback() );
1116 }
1117 }
1118 break;
1119 }
1120 }
1121
1122 // for layer that mask, generate mask in first pass job
1123 if ( maskLayerHasEffects.contains( job.layerId ) )
1124 {
1125 std::unique_ptr< QPaintDevice > maskPaintDevice;
1126 std::unique_ptr< QPainter > maskPainter;
1127 switch ( mapSettings().rasterizedRenderingPolicy() )
1128 {
1130 job.maskRenderFormat = Qgis::RenderFormat::Raster;
1131 break;
1133 job.maskRenderFormat = mapSettings().testFlag( Qgis::MapSettingsFlag::ForceRasterMasks ) || layerMaskRequiresRaster.value( job.layerId, false ) ? Qgis::RenderFormat::Raster
1135 break;
1138 break;
1139 }
1140
1141 switch ( job.maskRenderFormat )
1142 {
1144 {
1145 // set a painter to get all masking instruction in order to later clip masked symbol layer
1146 auto geomPaintDevice = std::make_unique< QgsGeometryPaintDevice >();
1147 geomPaintDevice->setStrokedPathSegments( 4 );
1148 geomPaintDevice->setSimplificationTolerance( job.context()->maskSettings().simplifyTolerance() );
1149 maskPaintDevice = std::move( geomPaintDevice );
1150 maskPainter = std::make_unique< QPainter >( maskPaintDevice.get() );
1151 break;
1152 }
1153
1155 {
1156 // Note: we only need an alpha channel here, rather than a full RGBA image
1157 auto [maskImage, painter] = allocateImageAndPainter( job.layerId, *job.context() );
1158 maskImage->fill( 0 );
1159 maskPaintDevice = std::move( maskImage );
1160 maskPainter = std::move( painter );
1161 break;
1162 }
1163 }
1164
1165 job.context()->setMaskPainter( maskPainter.get() );
1166 job.maskPainter = std::move( maskPainter );
1167 job.maskPaintDevice = std::move( maskPaintDevice );
1168 }
1169 }
1170
1171 for ( LayerRenderJob &job : firstPassJobs )
1172 {
1173 QgsMapLayer *ml = job.layer;
1174
1175 auto it = maskedSymbolLayers.find( job.layerId );
1176 if ( it == maskedSymbolLayers.end() )
1177 continue;
1178
1179 const QList<MaskSource> maskedSourceList = it->maskSourceList;
1180 const QSet<QString> maskedSymbolLayerIds = it->maskedSymbolLayerIds;
1181
1182 secondPassJobs.emplace_back( LayerRenderJob() );
1183 LayerRenderJob &job2 = secondPassJobs.back();
1184
1185 job2.maskRenderFormat = job.maskRenderFormat;
1186
1187 // Points to the masking jobs. This will be needed during the second pass composition.
1188 for ( const MaskSource &source : maskedSourceList )
1189 {
1190 LayerRenderJob::MaskJob maskJob;
1191
1192 if ( source.labelMaskId != -1 )
1193 {
1194 maskJob.maskPaintDeviceId = source.labelMaskId;
1195 }
1196 else
1197 {
1198 maskJob.layerRenderJob = layerJobMapping[source.layerId];
1199 }
1200 job2.maskJobs.emplace_back( maskJob );
1201 }
1202
1203 // copy the context from the initial job
1204 job2.setContext( std::make_unique< QgsRenderContext >( *job.context() ) );
1205 // also assign layer to match initial job
1206 job2.layer = job.layer;
1207 job2.renderAboveLabels = job.renderAboveLabels;
1208 job2.layerId = job.layerId;
1209
1210 // associate first pass job with second pass job
1211 job2.firstPassJob = &job;
1212
1213 switch ( job2.maskRenderFormat )
1214 {
1216 {
1217 Q_ASSERT( !job2.destinationImage );
1218 Q_ASSERT( !job2.destinationPainter );
1219 auto [img, painter] = allocateImageAndPainter( job.layerId, *job2.context() );
1220 job2.context()->setPainter( painter.get() );
1221 job2.destinationImage = std::move( img );
1222 job2.destinationPainter = std::move( painter );
1223 break;
1224 }
1225
1227 {
1228 auto [picture, painter] = allocatePictureAndPainter( *job2.context() );
1229 if ( job.context()->painter()->hasClipping() )
1230 {
1231 // need to copy clipping paths from original painter, so that e.g. the layout map bounds clipping path is respected
1232 painter->setClipping( true );
1233 painter->setClipPath( job.context()->painter()->clipPath() );
1234 }
1235 job2.picture = std::move( picture );
1236 Q_ASSERT( !job2.destinationPainter );
1237 job2.destinationPainter = std::move( painter );
1238 job2.context()->setPainter( job2.destinationPainter.get() );
1239 break;
1240 }
1241 }
1242
1243 if ( !job2.destinationImage && !job2.picture )
1244 {
1245 secondPassJobs.pop_back();
1246 continue;
1247 }
1248
1249 // FIXME: another possibility here, to avoid allocating a new map renderer and reuse the one from
1250 // the first pass job, would be to be able to call QgsMapLayerRenderer::render() with a QgsRenderContext.
1251 job2.context()->setFeedback( nullptr );
1252 job2.renderer.reset( ml->createMapRenderer( *job2.context() ) );
1253 if ( job2.renderer )
1254 {
1255 job2.context()->setFeedback( job2.renderer->feedback() );
1256 }
1257
1258 // Render only the non masked symbol layer and we will compose 2nd pass with mask and first pass rendering in composeSecondPass
1259 // If vector output is enabled, disabled symbol layers would be actually rendered and masked with clipping path set in QgsMapRendererJob::initSecondPassJobs
1260 job2.context()->setDisabledSymbolLayersV2( maskedSymbolLayerIds );
1261 }
1262
1263 return secondPassJobs;
1264}
1265
1266QList<QPointer<QgsMapLayer> > QgsMapRendererJob::participatingLabelLayers( QgsLabelingEngine *engine )
1267{
1268 QList<QPointer<QgsMapLayer> > res = _qgis_listRawToQPointer( engine->participatingLayers() );
1269
1270 for ( const QPointer<QgsMapLayer> &it : std::as_const( mAdditionalLabelLayers ) )
1271 {
1272 if ( !res.contains( it ) )
1273 res.append( it );
1274 }
1275
1276 return res;
1277}
1278
1279void QgsMapRendererJob::initSecondPassJobs( std::vector< LayerRenderJob > &secondPassJobs, LabelRenderJob &labelJob ) const
1280{
1281 for ( LayerRenderJob &job : secondPassJobs )
1282 {
1283 switch ( job.maskRenderFormat )
1284 {
1286 break;
1287
1289 {
1290 // we draw disabled symbol layer but me mask them with clipping path produced during first pass job
1291 // Resulting 2nd pass job picture will be the final rendering
1292
1293 for ( const LayerRenderJob::MaskJob &p : std::as_const( job.maskJobs ) )
1294 {
1295 QPainter *maskPainter = p.layerRenderJob ? p.layerRenderJob->maskPainter.get() : labelJob.maskPainters[p.maskPaintDeviceId].get();
1296
1297 const QSet<QString> layers = job.context()->disabledSymbolLayersV2();
1298 if ( QgsGeometryPaintDevice *geometryDevice = dynamic_cast<QgsGeometryPaintDevice *>( maskPainter->device() ) )
1299 {
1300 QgsGeometry geometry( geometryDevice->geometry().clone() );
1301
1302#if GEOS_VERSION_NUM < GEOS_COMPUTE_VERSION( 3, 10, 0 )
1303 // structure would be better, but too old GEOS
1304 geometry = geometry.makeValid( Qgis::MakeValidMethod::Linework );
1305#else
1306 geometry = geometry.makeValid( Qgis::MakeValidMethod::Structure );
1307#endif
1308
1309 for ( const QString &symbolLayerId : layers )
1310 {
1311 job.context()->addSymbolLayerClipGeometry( symbolLayerId, geometry );
1312 }
1313 }
1314 }
1315
1316 job.context()->setDisabledSymbolLayersV2( QSet<QString>() );
1317 break;
1318 }
1319 }
1320 }
1321}
1322
1323LabelRenderJob QgsMapRendererJob::prepareLabelingJob( QPainter *painter, QgsLabelingEngine *labelingEngine2, bool canUseLabelCache )
1324{
1325 LabelRenderJob job;
1327 job.context.setPainter( painter );
1328 job.context.setLabelingEngine( labelingEngine2 );
1329 job.context.setFeedback( mLabelingEngineFeedback );
1330 if ( labelingEngine2 )
1331 job.context.labelingEngine()->prepare( job.context );
1332
1333 QgsRectangle r1 = mSettings.visibleExtent();
1334 r1.grow( mSettings.extentBuffer() );
1335 job.context.setExtent( r1 );
1336
1337 job.context.setFeatureFilterProvider( mFeatureFilterProvider );
1338 QgsCoordinateTransform ct;
1339 ct.setDestinationCrs( mSettings.destinationCrs() );
1340 job.context.setCoordinateTransform( ct );
1341
1342 // no cache, no image allocation
1343 if ( mSettings.rasterizedRenderingPolicy() != Qgis::RasterizedRenderingPolicy::Default )
1344 return job;
1345
1346 // if we can use the cache, let's do it and avoid rendering!
1347 bool hasCache = canUseLabelCache && mCache && mCache->hasCacheImage( LABEL_CACHE_ID ) && mCache->cacheImage( LABEL_CACHE_ID ).devicePixelRatio() == mSettings.devicePixelRatio();
1348 if ( hasCache )
1349 {
1350 job.cached = true;
1351 job.complete = true;
1352 job.img = std::make_unique< QImage >( mCache->cacheImage( LABEL_CACHE_ID ) );
1353 job.context.setPainter( nullptr );
1354 }
1355 else
1356 {
1357 if ( canUseLabelCache && ( mCache || !painter ) )
1358 {
1359 job.img = allocateImage( u"labels"_s );
1360 }
1361 }
1362
1363 return job;
1364}
1365
1366
1367void QgsMapRendererJob::cleanupJobs( std::vector<LayerRenderJob> &jobs )
1368{
1369 for ( LayerRenderJob &job : jobs )
1370 {
1371 if ( job.destinationImage )
1372 {
1373 job.context()->setPainter( nullptr );
1374 job.destinationPainter.reset();
1375
1376 if ( mCache && !job.cached && job.completed && job.layer )
1377 {
1378 QgsDebugMsgLevel( u"caching image for %1"_s.arg( job.layerId ), 2 );
1379 mCache->setCacheImageWithParameters( job.layerId, *job.destinationImage, mSettings.visibleExtent(), mSettings.mapToPixel(), QList< QgsMapLayer * >() << job.layer );
1380 mCache->setCacheImageWithParameters( job.layerId + u"_preview"_s, *job.destinationImage, mSettings.visibleExtent(), mSettings.mapToPixel(), QList< QgsMapLayer * >() << job.layer );
1381 }
1382
1383 job.destinationImage.reset();
1384 }
1385
1386 if ( job.previewRenderImage )
1387 {
1388 job.context()->setPreviewRenderPainter( nullptr );
1389 job.previewRenderPainter.reset();
1390 job.previewRenderImage.reset();
1391 }
1392
1393 if ( job.elevationMap )
1394 {
1395 job.context()->setElevationMap( nullptr );
1396 if ( mCache && !job.cached && job.completed && job.layer )
1397 {
1398 QgsDebugMsgLevel( u"caching elevation map for %1"_s.arg( job.layerId ), 2 );
1399 mCache->setCacheImageWithParameters(
1400 ELEVATION_MAP_CACHE_PREFIX + job.layerId, job.elevationMap->rawElevationImage(), mSettings.visibleExtent(), mSettings.mapToPixel(), QList< QgsMapLayer * >() << job.layer
1401 );
1402 mCache->setCacheImageWithParameters(
1403 ELEVATION_MAP_CACHE_PREFIX + job.layerId + u"_preview"_s, job.elevationMap->rawElevationImage(), mSettings.visibleExtent(), mSettings.mapToPixel(), QList< QgsMapLayer * >() << job.layer
1404 );
1405 }
1406
1407 job.elevationMap.reset();
1408 }
1409
1410 if ( job.picture )
1411 {
1412 job.context()->setPainter( nullptr );
1413 job.destinationPainter.reset();
1414 job.picture.reset( nullptr );
1415 }
1416
1417 if ( job.renderer )
1418 {
1419 const QStringList errors = job.renderer->errors();
1420 for ( const QString &message : errors )
1421 mErrors.append( Error( job.renderer->layerId(), message ) );
1422
1423 mRenderedItemResults->appendResults( job.renderer->takeRenderedItemDetails(), *job.context() );
1424
1425 job.context()->setFeedback( nullptr );
1426 job.renderer.reset();
1427 }
1428
1429 if ( job.layer )
1430 mPerLayerRenderingTime.insert( job.layer, job.renderingTime );
1431
1432 job.maskPainter.reset( nullptr );
1433 job.maskPaintDevice.reset( nullptr );
1434 }
1435
1436 jobs.clear();
1437}
1438
1439void QgsMapRendererJob::cleanupSecondPassJobs( std::vector< LayerRenderJob > &jobs )
1440{
1441 for ( LayerRenderJob &job : jobs )
1442 {
1443 if ( job.destinationImage )
1444 {
1445 job.context()->setPainter( nullptr );
1446 job.destinationPainter.reset();
1447 job.destinationImage.reset();
1448 }
1449
1450 if ( job.previewRenderImage )
1451 {
1452 job.context()->setPreviewRenderPainter( nullptr );
1453 job.previewRenderPainter.reset();
1454 job.previewRenderImage.reset();
1455 }
1456
1457 if ( job.picture )
1458 {
1459 job.context()->setPainter( nullptr );
1460 job.destinationPainter.reset();
1461 }
1462
1463 if ( job.renderer )
1464 {
1465 job.context()->setFeedback( nullptr );
1466 job.renderer.reset();
1467 }
1468
1469 if ( job.layer )
1470 mPerLayerRenderingTime.insert( job.layer, job.renderingTime );
1471 }
1472
1473 jobs.clear();
1474}
1475
1476void QgsMapRendererJob::cleanupLabelJob( LabelRenderJob &job )
1477{
1478 if ( job.img )
1479 {
1480 if ( mCache && !job.cached && !job.context.renderingStopped() )
1481 {
1482 QgsDebugMsgLevel( u"caching label result image"_s, 2 );
1483 mCache->setCacheImageWithParameters( LABEL_CACHE_ID, *job.img, mSettings.visibleExtent(), mSettings.mapToPixel(), _qgis_listQPointerToRaw( job.participatingLayers ) );
1484 mCache->setCacheImageWithParameters( LABEL_PREVIEW_CACHE_ID, *job.img, mSettings.visibleExtent(), mSettings.mapToPixel(), _qgis_listQPointerToRaw( job.participatingLayers ) );
1485 }
1486
1487 job.img.reset();
1488 }
1489
1490 job.picture.reset( nullptr );
1491 job.maskPainters.clear();
1492 job.maskPaintDevices.clear();
1493}
1494
1495
1496#define DEBUG_RENDERING 0
1497
1498QImage QgsMapRendererJob::composeImage( const QgsMapSettings &settings, const std::vector<LayerRenderJob> &jobs, const LabelRenderJob &labelJob, const QgsMapRendererCache *cache )
1499{
1500 QImage image( settings.deviceOutputSize(), settings.outputImageFormat() );
1501 image.setDevicePixelRatio( settings.devicePixelRatio() );
1502 image.setDotsPerMeterX( static_cast<int>( settings.outputDpi() * 39.37 ) );
1503 image.setDotsPerMeterY( static_cast<int>( settings.outputDpi() * 39.37 ) );
1504 image.fill( settings.backgroundColor() );
1505
1506 const QgsElevationShadingRenderer mapShadingRenderer = settings.elevationShadingRenderer();
1507 std::unique_ptr<QgsElevationMap> mainElevationMap;
1508 if ( mapShadingRenderer.isActive() )
1509 mainElevationMap = std::make_unique<QgsElevationMap>( settings.deviceOutputSize(), settings.devicePixelRatio() );
1510
1511 QPainter painter( &image );
1512
1513#if DEBUG_RENDERING
1514 int i = 0;
1515#endif
1516 for ( const LayerRenderJob &job : jobs )
1517 {
1518 if ( job.renderAboveLabels )
1519 continue; // skip layer for now, it will be rendered after labels
1520
1521 QImage img = layerImageToBeComposed( settings, job, cache );
1522 if ( img.isNull() )
1523 continue; // image is not prepared and not even in cache
1524
1525 painter.setCompositionMode( job.blendMode );
1526 painter.setOpacity( job.opacity );
1527
1528 if ( mainElevationMap )
1529 {
1530 QgsElevationMap layerElevationMap = layerElevationToBeComposed( settings, job, cache );
1531 if ( layerElevationMap.isValid() )
1532 mainElevationMap->combine( layerElevationMap, mapShadingRenderer.combinedElevationMethod() );
1533 }
1534
1535
1536#if DEBUG_RENDERING
1537 img.save( QString( "/tmp/final_%1.png" ).arg( i ) );
1538 i++;
1539#endif
1540
1541 painter.drawImage( 0, 0, img );
1542 }
1543
1544 if ( mapShadingRenderer.isActive() && mainElevationMap )
1545 {
1546 mapShadingRenderer.renderShading( *mainElevationMap.get(), image, QgsRenderContext::fromMapSettings( settings ) );
1547 }
1548
1549 // IMPORTANT - don't draw labelJob img before the label job is complete,
1550 // as the image is uninitialized and full of garbage before the label job
1551 // commences
1552 if ( labelJob.img && labelJob.complete )
1553 {
1554 painter.setCompositionMode( QPainter::CompositionMode_SourceOver );
1555 painter.setOpacity( 1.0 );
1556 painter.drawImage( 0, 0, *labelJob.img );
1557 }
1558 else if ( labelJob.picture && labelJob.complete )
1559 {
1560 painter.setCompositionMode( QPainter::CompositionMode_SourceOver );
1561 painter.setOpacity( 1.0 );
1562 QgsPainting::drawPicture( &painter, QPointF( 0, 0 ), *labelJob.picture );
1563 }
1564 // when checking for a label cache image, we only look for those which would be drawn between 30% and 300% of the
1565 // original size. We don't want to draw massive pixelated labels on top of everything else, and we also don't need
1566 // to draw tiny unreadable labels... better to draw nothing in this case and wait till the updated label results are ready!
1567 else if ( cache && cache->hasAnyCacheImage( LABEL_PREVIEW_CACHE_ID, 0.3, 3 ) )
1568 {
1569 const QImage labelCacheImage = cache->transformedCacheImage( LABEL_PREVIEW_CACHE_ID, settings.mapToPixel() );
1570 painter.setCompositionMode( QPainter::CompositionMode_SourceOver );
1571 painter.setOpacity( 1.0 );
1572 painter.drawImage( 0, 0, labelCacheImage );
1573 }
1574
1575 // render any layers with the renderAboveLabels flag now
1576 for ( const LayerRenderJob &job : jobs )
1577 {
1578 if ( !job.renderAboveLabels )
1579 continue;
1580
1581 QImage img = layerImageToBeComposed( settings, job, cache );
1582 if ( img.isNull() )
1583 continue; // image is not prepared and not even in cache
1584
1585 painter.setCompositionMode( job.blendMode );
1586 painter.setOpacity( job.opacity );
1587
1588 painter.drawImage( 0, 0, img );
1589 }
1590
1591 painter.end();
1592#if DEBUG_RENDERING
1593 image.save( "/tmp/final.png" );
1594#endif
1595 return image;
1596}
1597
1598QImage QgsMapRendererJob::layerImageToBeComposed( const QgsMapSettings &settings, const LayerRenderJob &job, const QgsMapRendererCache *cache )
1599{
1600 if ( job.imageCanBeComposed() )
1601 {
1602 if ( job.previewRenderImage && !job.completed )
1603 return *job.previewRenderImage;
1604
1605 Q_ASSERT( job.destinationImage );
1606 return *job.destinationImage;
1607 }
1608 else
1609 {
1610 if ( cache && cache->hasAnyCacheImage( job.layerId + u"_preview"_s ) )
1611 {
1612 return cache->transformedCacheImage( job.layerId + u"_preview"_s, settings.mapToPixel() );
1613 }
1614 else
1615 return QImage();
1616 }
1617}
1618
1619QgsElevationMap QgsMapRendererJob::layerElevationToBeComposed( const QgsMapSettings &settings, const LayerRenderJob &job, const QgsMapRendererCache *cache )
1620{
1621 if ( job.imageCanBeComposed() && job.elevationMap )
1622 {
1623 return *job.elevationMap;
1624 }
1625 else
1626 {
1627 if ( cache && cache->hasAnyCacheImage( ELEVATION_MAP_CACHE_PREFIX + job.layerId + u"_preview"_s ) )
1628 return QgsElevationMap( cache->transformedCacheImage( ELEVATION_MAP_CACHE_PREFIX + job.layerId + u"_preview"_s, settings.mapToPixel() ) );
1629 else
1630 return QgsElevationMap();
1631 }
1632}
1633
1634void QgsMapRendererJob::composeSecondPass( std::vector<LayerRenderJob> &secondPassJobs, LabelRenderJob &labelJob )
1635{
1636 // compose the second pass with the mask
1637 for ( LayerRenderJob &job : secondPassJobs )
1638 {
1639 if ( job.maskJobs.empty() )
1640 continue;
1641
1642 switch ( job.maskRenderFormat )
1643 {
1645 {
1646 // First find the primary mask image
1647 LayerRenderJob::MaskJob firstJob = *job.maskJobs.begin();
1648 QPaintDevice *firstMaskPaintDevice = nullptr;
1649 QPainter *firstMaskPainter = nullptr;
1650 if ( firstJob.layerRenderJob )
1651 {
1652 firstMaskPaintDevice = firstJob.layerRenderJob->maskPaintDevice.get();
1653 firstMaskPainter = firstJob.layerRenderJob->maskPainter.get();
1654 }
1655 else
1656 {
1657 Q_ASSERT( firstJob.maskPaintDeviceId >= 0 && firstJob.maskPaintDeviceId < static_cast< int >( labelJob.maskPaintDevices.size() ) );
1658 firstMaskPaintDevice = labelJob.maskPaintDevices[firstJob.maskPaintDeviceId].get();
1659 firstMaskPainter = labelJob.maskPainters[firstJob.maskPaintDeviceId].get();
1660 }
1661
1662 QImage *firstMaskImage = dynamic_cast<QImage *>( firstMaskPaintDevice );
1663 if ( !firstMaskImage )
1664 {
1665 QgsDebugError( u"FORMAT MISMATCH -- expected a raster mask format, but mask paint device is not a QImage!!"_s );
1666 continue;
1667 }
1668
1669 // Merge all mask images into the first one if we have more than one mask image
1670 for ( size_t i = 1; i < job.maskJobs.size(); ++i )
1671 {
1672 const LayerRenderJob::MaskJob &nextJob = job.maskJobs[i];
1673 QPaintDevice *nextJobPaintDevice = nullptr;
1674 if ( nextJob.layerRenderJob )
1675 {
1676 nextJobPaintDevice = nextJob.layerRenderJob->maskPaintDevice.get();
1677 }
1678 else
1679 {
1680 Q_ASSERT( nextJob.maskPaintDeviceId >= 0 && nextJob.maskPaintDeviceId < static_cast< int >( labelJob.maskPaintDevices.size() ) );
1681 nextJobPaintDevice = labelJob.maskPaintDevices[nextJob.maskPaintDeviceId].get();
1682 }
1683 Q_ASSERT( nextJobPaintDevice );
1684
1685 QImage *nextJobImage = dynamic_cast<QImage *>( nextJobPaintDevice );
1686 if ( !nextJobImage )
1687 {
1688 QgsDebugError( u"FORMAT MISMATCH -- expected a raster mask format, but mask paint device is not a QImage!!"_s );
1689 continue;
1690 }
1691
1692 firstMaskPainter->drawImage( 0, 0, *nextJobImage );
1693 }
1694
1695 // Only retain parts of the second rendering that are "inside" the mask image
1696 QPainter *painter = job.context()->painter();
1697
1698 painter->setCompositionMode( QPainter::CompositionMode_DestinationIn );
1699
1700 //Create an "alpha binarized" image of the maskImage to :
1701 //* Eliminate antialiasing artifact
1702 //* Avoid applying mask opacity to elements under the mask but not masked
1703 QImage maskBinAlpha = firstMaskImage->createMaskFromColor( 0 );
1704 QVector<QRgb> mswTable;
1705 mswTable.push_back( qRgba( 0, 0, 0, 255 ) );
1706 mswTable.push_back( qRgba( 0, 0, 0, 0 ) );
1707 maskBinAlpha.setColorTable( mswTable );
1708 painter->drawImage( 0, 0, maskBinAlpha );
1709
1710 // Modify the first pass' image ...
1711 {
1712 QPainter tempPainter;
1713
1714 // reuse the first pass painter, if available
1715 QPainter *painter1 = job.firstPassJob->context()->painter();
1716 if ( !painter1 )
1717 {
1718 tempPainter.begin( job.firstPassJob->destinationImage.get() );
1719 painter1 = &tempPainter;
1720 }
1721
1722 // ... first retain parts that are "outside" the mask image
1723 painter1->setCompositionMode( QPainter::CompositionMode_DestinationOut );
1724 painter1->drawImage( 0, 0, *firstMaskImage );
1725
1726 // ... and overpaint the second pass' image on it
1727 painter1->setCompositionMode( QPainter::CompositionMode_DestinationOver );
1728 painter1->drawImage( 0, 0, *job.destinationImage );
1729 }
1730 break;
1731 }
1732
1734 {
1735 job.firstPassJob->picture = std::move( job.picture );
1736 job.picture = nullptr;
1737 break;
1738 }
1739 }
1740 }
1741}
1742
1743void QgsMapRendererJob::logRenderingTime( const std::vector< LayerRenderJob > &jobs, const std::vector< LayerRenderJob > &secondPassJobs, const LabelRenderJob &labelJob )
1744{
1745 if ( !settingsLogCanvasRefreshEvent->value() )
1746 return;
1747
1748 QMultiMap<int, QString> elapsed;
1749 for ( const LayerRenderJob &job : jobs )
1750 elapsed.insert( job.renderingTime, job.layerId );
1751 for ( const LayerRenderJob &job : secondPassJobs )
1752 elapsed.insert( job.renderingTime, job.layerId + QString( " (second pass)" ) );
1753
1754 elapsed.insert( labelJob.renderingTime, tr( "Labeling" ) );
1755
1756 QList<int> tt( elapsed.uniqueKeys() );
1757 std::sort( tt.begin(), tt.end(), std::greater<int>() );
1758 for ( int t : std::as_const( tt ) )
1759 {
1760 QgsMessageLog::logMessage( tr( "%1 ms: %2" ).arg( t ).arg( QStringList( elapsed.values( t ) ).join( ", "_L1 ) ), tr( "Rendering" ) );
1761 }
1762 QgsMessageLog::logMessage( u"---"_s, tr( "Rendering" ) );
1763}
1764
1765void QgsMapRendererJob::drawLabeling( QgsRenderContext &renderContext, QgsLabelingEngine *labelingEngine2, QPainter *painter )
1766{
1767 QgsDebugMsgLevel( u"Draw labeling start"_s, 5 );
1768
1769 std::unique_ptr< QgsScopedRuntimeProfile > labelingProfile;
1770 if ( renderContext.flags() & Qgis::RenderContextFlag::RecordProfile )
1771 {
1772 labelingProfile = std::make_unique< QgsScopedRuntimeProfile >( QObject::tr( "(labeling)" ), u"rendering"_s );
1773 }
1774
1775 QElapsedTimer t;
1776 t.start();
1777
1778 // Reset the composition mode before rendering the labels
1779 painter->setCompositionMode( QPainter::CompositionMode_SourceOver );
1780
1781 renderContext.setPainter( painter );
1782
1783 if ( labelingEngine2 )
1784 {
1785 labelingEngine2->run( renderContext );
1786 }
1787
1788 QgsDebugMsgLevel( u"Draw labeling took (seconds): %1"_s.arg( t.elapsed() / 1000. ), 2 );
1789}
1790
1791void QgsMapRendererJob::drawLabeling( const QgsMapSettings &settings, QgsRenderContext &renderContext, QgsLabelingEngine *labelingEngine2, QPainter *painter )
1792{
1793 Q_UNUSED( settings )
1794
1795 drawLabeling( renderContext, labelingEngine2, painter );
1796}
1797
@ Default
Allow raster-based rendering in situations where it is required for correct rendering or where it wil...
Definition qgis.h:2917
@ PreferVector
Prefer vector-based rendering, when the result will still be visually near-identical to a raster-base...
Definition qgis.h:2918
@ ForceVector
Always force vector-based rendering, even when the result will be visually different to a raster-base...
Definition qgis.h:2919
@ InternalLayerOpacityHandling
The renderer internally handles the raster layer's opacity, so the default layer level opacity handli...
Definition qgis.h:1672
RenderFormat
Rendering formats.
Definition qgis.h:2929
@ Vector
Vector-based rendering.
Definition qgis.h:2931
@ Raster
Raster-based rendering.
Definition qgis.h:2930
@ Group
Composite group layer. Added in QGIS 3.24.
Definition qgis.h:214
@ Plugin
Plugin based layer.
Definition qgis.h:209
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
Definition qgis.h:215
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
Definition qgis.h:212
@ Vector
Vector layer.
Definition qgis.h:207
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
Definition qgis.h:211
@ Mesh
Mesh layer. Added in QGIS 3.2.
Definition qgis.h:210
@ Raster
Raster layer.
Definition qgis.h:208
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
Definition qgis.h:213
@ AffectsLabeling
The layer rendering will interact with the map labeling.
Definition qgis.h:3016
@ RenderPartialOutputOverPreviousCachedImage
When rendering temporary in-progress preview renders, these preview renders can be drawn over any pre...
Definition qgis.h:3015
@ RenderPartialOutputs
The renderer benefits from rendering temporary in-progress preview renders. These are temporary resul...
Definition qgis.h:3014
@ ApplyClipAfterReprojection
Feature geometry clipping to mapExtent() must be performed after the geometries are transformed using...
Definition qgis.h:2992
@ RecordProfile
Enable run-time profiling while rendering.
Definition qgis.h:2996
@ Linework
Combines all rings into a set of noded lines and then extracts valid polygons from that linework.
Definition qgis.h:2365
@ Structure
Structured method, first makes all rings valid and then merges shells and subtracts holes from shells...
Definition qgis.h:2366
@ Forward
Forward transform (from source to destination).
Definition qgis.h:2883
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2884
@ RenderPartialOutput
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
Definition qgis.h:2951
@ ForceRasterMasks
Force symbol masking to be applied using a raster method. This is considerably faster when compared t...
Definition qgis.h:2959
virtual bool hasNonDefaultCompositionMode() const =0
Returns true the labeling requires a non-default composition mode.
virtual bool requiresAdvancedEffects() const =0
Returns true if drawing labels requires advanced effects like composition modes, which could prevent ...
virtual bool hasNonDefaultCompositionMode() const =0
Returns true the labeling requires a non-default composition mode.
virtual bool requiresAdvancedEffects() const =0
Returns true if drawing labels requires advanced effects like composition modes, which could prevent ...
virtual bool hasNonDefaultCompositionMode() const =0
Returns true the labeling requires a non-default composition mode.
virtual bool requiresAdvancedEffects() const =0
Returns true if drawing labels requires advanced effects like composition modes, which could prevent ...
Handles coordinate transforms between two 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.
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets the destination coordinate reference system.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system, which the transform will transform coordinates t...
Stores a digital elevation model in a raster image which may get updated as a part of the map layer r...
bool isValid() const
Returns whether the elevation map is valid.
Qgis::ElevationMapCombineMethod combinedElevationMethod() const
Returns the method used when conbining different elevation sources.
bool isActive() const
Returns whether this shading renderer is active.
void renderShading(const QgsElevationMap &elevation, QImage &image, const QgsRenderContext &context) const
Render shading on image condidering the elevation map elevation and the renderer context context If e...
QString what() const
static std::unique_ptr< QgsExpressionContextScope > layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
QgsFeedback subclass for granular reporting of labeling engine progress.
Provides map labeling functionality.
virtual void run(QgsRenderContext &context)=0
Runs the labeling job.
QList< QgsMapLayer * > participatingLayers() const
Returns a list of layers with providers in the engine.
static void warning(const QString &msg)
Goes to qWarning.
virtual bool isVisibleInTemporalRange(const QgsDateTimeRange &range) const
Returns true if the layer should be visible and rendered for the specified time range.
Base class for all map layer types.
Definition qgsmaplayer.h:84
QString name
Definition qgsmaplayer.h:88
bool isInScaleRange(double scale) const
Tests whether the layer should be visible at the specified scale.
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:91
QString id
Definition qgsmaplayer.h:87
Qgis::LayerType type
Definition qgsmaplayer.h:94
QPainter::CompositionMode blendMode() const
Returns the current blending mode for a layer.
bool hasScaleBasedVisibility() const
Returns whether scale based visibility is enabled for the layer.
virtual QgsMapLayerTemporalProperties * temporalProperties()
Returns the layer's temporal properties.
virtual QgsMapLayerRenderer * createMapRenderer(QgsRenderContext &rendererContext)=0
Returns new instance of QgsMapLayerRenderer that will be used for rendering of given context.
double minimumScale() const
Returns the minimum map scale (i.e.
double maximumScale() const
Returns the maximum map scale (i.e.
Responsible for keeping a cache of rendered images resulting from a map rendering job.
bool hasAnyCacheImage(const QString &cacheKey, double minimumScaleThreshold=0, double maximumScaleThreshold=0) const
Returns true if the cache contains an image with the specified cacheKey with any cache's parameters (...
QImage transformedCacheImage(const QString &cacheKey, const QgsMapToPixel &mtp) const
Returns the cached image for the specified cacheKey transformed to the particular extent and scale.
Abstract base class for map rendering implementations.
void logRenderingTime(const std::vector< LayerRenderJob > &jobs, const std::vector< LayerRenderJob > &secondPassJobs, const LabelRenderJob &labelJob)
static void composeSecondPass(std::vector< LayerRenderJob > &secondPassJobs, LabelRenderJob &labelJob)
Compose second pass images into first pass images.
QList< QPointer< QgsMapLayer > > participatingLabelLayers(QgsLabelingEngine *engine)
Returns a list of the layers participating in the map labeling.
static QgsElevationMap layerElevationToBeComposed(const QgsMapSettings &settings, const LayerRenderJob &job, const QgsMapRendererCache *cache)
static QImage composeImage(const QgsMapSettings &settings, const std::vector< LayerRenderJob > &jobs, const LabelRenderJob &labelJob, const QgsMapRendererCache *cache=nullptr)
void cleanupSecondPassJobs(std::vector< LayerRenderJob > &jobs)
void setCache(QgsMapRendererCache *cache)
Assign a cache to be used for reading and storing rendered images of individual layers.
QHash< QgsMapLayer *, int > perLayerRenderingTime() const
Returns the render time (in ms) per layer.
void initSecondPassJobs(std::vector< LayerRenderJob > &secondPassJobs, LabelRenderJob &labelJob) const
Initialize secondPassJobs according to what have been rendered (mask clipping path e....
static QImage layerImageToBeComposed(const QgsMapSettings &settings, const LayerRenderJob &job, const QgsMapRendererCache *cache)
QHash< QString, int > mLayerRenderingTimeHints
Approximate expected layer rendering time per layer, by layer ID.
std::unique_ptr< QgsRenderedItemResults > mRenderedItemResults
Errors errors() const
List of errors that happened during the rendering job - available when the rendering has been finishe...
static Q_DECL_DEPRECATED void drawLabeling(const QgsMapSettings &settings, QgsRenderContext &renderContext, QgsLabelingEngine *labelingEngine2, QPainter *painter)
static const QString LABEL_PREVIEW_CACHE_ID
QgsMapRendererCache ID string for cached label image during preview compositions only.
QList< QPointer< QgsMapLayer > > mAdditionalLabelLayers
Additional layers participating in labeling problem.
std::vector< LayerRenderJob > prepareJobs(QPainter *painter, QgsLabelingEngine *labelingEngine2, bool deferredPainterSet=false)
Creates a list of layer rendering jobs and prepares them for later render.
void cleanupJobs(std::vector< LayerRenderJob > &jobs)
const QgsMapSettings & mapSettings() const
Returns map settings with which this job was started.
QgsMapRendererCache * mCache
void finished()
emitted when asynchronous rendering is finished (or canceled).
bool labelingHasNonDefaultCompositionModes() const
Returns true if any component of the map labeling requires non-default composition modes.
QgsMapSettings mSettings
static const QgsSettingsEntryBool * settingsLogCanvasRefreshEvent
Settings entry log canvas refresh event.
QgsMapRendererJob(const QgsMapSettings &settings)
~QgsMapRendererJob() override
void start()
Start the rendering job and immediately return.
QStringList mLayersRedrawnFromCache
QStringList layersRedrawnFromCache() const
Returns a list of the layer IDs for all layers which were redrawn from cached images.
QList< QgsMapRendererJob::Error > Errors
static const QString LABEL_CACHE_ID
QgsMapRendererCache ID string for cached label image.
static const QString ELEVATION_MAP_CACHE_PREFIX
QgsMapRendererCache prefix string for cached elevation map image.
QHash< QgsWeakMapLayerPointer, int > mPerLayerRenderingTime
Render time (in ms) per layer, by layer ID.
QgsRenderedItemResults * takeRenderedItemResults()
Takes the rendered item results from the map render job and returns them.
QgsLabelingEngineFeedback * labelingEngineFeedback()
Returns the associated labeling engine feedback object.
std::vector< LayerRenderJob > prepareSecondPassJobs(std::vector< LayerRenderJob > &firstPassJobs, LabelRenderJob &labelJob)
Prepares jobs for a second pass, if selective masks exist (from labels or symbol layers).
static const QgsSettingsEntryString * settingsMaskBackend
Settings entry for mask painting backend engine.
LabelRenderJob prepareLabelingJob(QPainter *painter, QgsLabelingEngine *labelingEngine2, bool canUseLabelCache=true)
Prepares a labeling job.
void setLayerRenderingTimeHints(const QHash< QString, int > &hints)
Sets approximate render times (in ms) for map layers.
void cleanupLabelJob(LabelRenderJob &job)
Handles clean up tasks for a label job, including deletion of images and storing cached label results...
QgsLabelSink * labelSink() const
Returns the label sink associated to this rendering job.
bool prepareLabelCache() const
Prepares the cache for storing the result of labeling.
QgsMapRendererQImageJob(const QgsMapSettings &settings)
Contains configuration for rendering maps.
QSize deviceOutputSize() const
Returns the device output size of the map render.
QColor backgroundColor() const
Returns the background color of the map.
const QgsMapToPixel & mapToPixel() const
float devicePixelRatio() const
Returns the device pixel ratio.
QImage::Format outputImageFormat() const
format of internal QImage, default QImage::Format_ARGB32_Premultiplied
const QgsElevationShadingRenderer & elevationShadingRenderer() const
Returns the shading renderer used to render shading on the entire map.
QHash< QString, QgsSelectiveMaskingSourceSet > selectiveMaskingSourceSets() const
Returns a hash of all selective masking source sets defined for the map.
double outputDpi() const
Returns the DPI (dots per inch) used for conversion between real world units (e.g.
bool testFlag(Qgis::MapSettingsFlag flag) const
Check whether a particular flag is enabled.
const QgsAbstractMeshLayerLabeling * labeling() const
Access to const labeling configuration.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
static void drawPicture(QPainter *painter, const QPointF &point, const QPicture &picture)
Draws a picture onto a painter, correctly applying workarounds to avoid issues with incorrect scaling...
static bool staticWillUseLayer(const QgsMapLayer *layer)
Called to find out whether a specified layer is used for labeling.
QString toString(int precision=-1) const
Returns a string representation of the point (x, y) with a preset precision.
double x
Definition qgspointxy.h:65
const QgsAbstractRasterLayerLabeling * labeling() const
Access to const labeling configuration.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
QgsRasterRenderer * renderer() const
Returns the raster's renderer.
virtual Qgis::RasterRendererFlags flags() const
Returns flags which dictate renderer behavior.
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 rounded to the spec...
double xMinimum
double yMinimum
double xMaximum
void setXMinimum(double x)
Set the minimum x value.
void setXMaximum(double x)
Set the maximum x value.
void grow(double delta)
Grows the rectangle in place by the specified amount.
double yMaximum
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Contains information about the context of a rendering operation.
void setPainterFlagsUsingContext(QPainter *painter=nullptr) const
Sets relevant flags on a destination painter, using the flags and settings currently defined for the ...
void setPainter(QPainter *p)
Sets the destination QPainter for the render operation.
static QgsRenderContext fromMapSettings(const QgsMapSettings &mapSettings)
create initialized QgsRenderContext instance from given QgsMapSettings
Qgis::RenderContextFlags flags() const
Returns combination of flags used for rendering.
Stores collated details of rendered items during a map rendering operation.
A boolean settings entry.
A string settings entry.
static QgsSettingsTreeNode * sTreeMap
static QgsMaskedLayers collectObjectsMaskedBySymbolLayersFromLayer(const QgsVectorLayer *layer, const QHash< QString, QgsSelectiveMaskingSourceSet > &selectiveMaskingSourceSets, const QVector< QgsVectorLayer * > &allRenderedVectorLayers)
Returns all objects that will be masked by the symbol layers for a given vector layer.
static QHash< QString, QgsMaskedLayers > collectObjectsMaskedByLabelsFromLayer(const QgsVectorLayer *layer, const QHash< QString, QgsSelectiveMaskingSourceSet > &selectiveMaskingSourceSets, const QVector< QgsVectorLayer * > &allRenderedVectorLayers)
Returns all objects that will be masked by the labels for a given vector layer.
bool labelsEnabled() const
Returns whether the layer contains labels which are enabled and should be drawn.
bool isEditable() const final
Returns true if the provider is in editing mode.
const QgsAbstractVectorLayerLabeling * labeling() const
Access to const labeling configuration.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:7811
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:80
#define QgsDebugError(str)
Definition qgslogger.h:71
QHash< QString, QgsMaskedLayer > QgsMaskedLayers
masked layers where key is the layer id of the layer that WILL be masked