QGIS API Documentation 3.30.0-'s-Hertogenbosch (f186b8efe0)
qgsvectortilelayerrenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectortilelayerrenderer.cpp
3 --------------------------------------
4 Date : March 2020
5 Copyright : (C) 2020 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 <QElapsedTimer>
19
21#include "qgsfeedback.h"
22#include "qgslogger.h"
23
25#include "qgsvectortilelayer.h"
26#include "qgsvectortileloader.h"
27#include "qgsvectortileutils.h"
28
29#include "qgslabelingengine.h"
31#include "qgsmapclippingutils.h"
32#include "qgsrendercontext.h"
33
35 : QgsMapLayerRenderer( layer->id(), &context )
36 , mSourceType( layer->sourceType() )
37 , mSourcePath( layer->sourcePath() )
38 , mRenderer( layer->renderer()->clone() )
39 , mDrawTileBoundaries( layer->isTileBorderRenderingEnabled() )
40 , mFeedback( new QgsFeedback )
41 , mSelectedFeatures( layer->selectedFeatures() )
42 , mLayerOpacity( layer->opacity() )
43 , mTileMatrixSet( layer->tileMatrixSet() )
44{
45
46 QgsDataSourceUri dsUri;
47 dsUri.setEncodedUri( layer->source() );
48 mAuthCfg = dsUri.authConfigId();
49 mHeaders = dsUri.httpHeaders();
50
51 if ( QgsLabelingEngine *engine = context.labelingEngine() )
52 {
53 if ( layer->labeling() )
54 {
55 mLabelProvider = layer->labeling()->provider( layer );
56 if ( mLabelProvider )
57 {
58 engine->addProvider( mLabelProvider );
59 }
60 }
61 }
62
64}
65
67{
69
70 if ( ctx.renderingStopped() )
71 return false;
72
73 const QgsScopedQPainterState painterState( ctx.painter() );
74
75 if ( !mClippingRegions.empty() )
76 {
77 bool needsPainterClipPath = false;
78 const QPainterPath path = QgsMapClippingUtils::calculatePainterClipRegion( mClippingRegions, *renderContext(), Qgis::LayerType::VectorTile, needsPainterClipPath );
79 if ( needsPainterClipPath )
80 renderContext()->painter()->setClipPath( path, Qt::IntersectClip );
81 }
82
83 QElapsedTimer tTotal;
84 tTotal.start();
85
86 const double tileRenderScale = mTileMatrixSet.scaleForRenderContext( ctx );
87 QgsDebugMsgLevel( QStringLiteral( "Vector tiles rendering extent: " ) + ctx.extent().toString( -1 ), 2 );
88 QgsDebugMsgLevel( QStringLiteral( "Vector tiles map scale 1 : %1" ).arg( tileRenderScale ), 2 );
89
90 mTileZoom = mTileMatrixSet.scaleToZoomLevel( tileRenderScale );
91 QgsDebugMsgLevel( QStringLiteral( "Vector tiles zoom level: %1" ).arg( mTileZoom ), 2 );
92
93 mTileMatrix = mTileMatrixSet.tileMatrix( mTileZoom );
94
95 mTileRange = mTileMatrix.tileRangeFromExtent( ctx.extent() );
96 QgsDebugMsgLevel( QStringLiteral( "Vector tiles range X: %1 - %2 Y: %3 - %4" )
97 .arg( mTileRange.startColumn() ).arg( mTileRange.endColumn() )
98 .arg( mTileRange.startRow() ).arg( mTileRange.endRow() ), 2 );
99
100 // view center is used to sort the order of tiles for fetching and rendering
101 const QPointF viewCenter = mTileMatrix.mapToTileCoordinates( ctx.extent().center() );
102
103 if ( !mTileRange.isValid() )
104 {
105 QgsDebugMsgLevel( QStringLiteral( "Vector tiles - outside of range" ), 2 );
106 return true; // nothing to do
107 }
108
109 const bool isAsync = ( mSourceType == QLatin1String( "xyz" ) );
110
111 if ( mSourceType == QLatin1String( "xyz" ) && mSourcePath.contains( QLatin1String( "{usage}" ) ) )
112 {
113 switch ( renderContext()->rendererUsage() )
114 {
116 mSourcePath.replace( QLatin1String( "{usage}" ), QLatin1String( "view" ) );
117 break;
119 mSourcePath.replace( QLatin1String( "{usage}" ), QLatin1String( "export" ) );
120 break;
122 mSourcePath.replace( QLatin1String( "{usage}" ), QString() );
123 break;
124 }
125 }
126
127 std::unique_ptr<QgsVectorTileLoader> asyncLoader;
128 QList<QgsVectorTileRawData> rawTiles;
129 if ( !isAsync )
130 {
131 QElapsedTimer tFetch;
132 tFetch.start();
133 rawTiles = QgsVectorTileLoader::blockingFetchTileRawData( mSourceType, mSourcePath, mTileMatrix, viewCenter, mTileRange, mAuthCfg, mHeaders, mFeedback.get() );
134 QgsDebugMsgLevel( QStringLiteral( "Tile fetching time: %1" ).arg( tFetch.elapsed() / 1000. ), 2 );
135 QgsDebugMsgLevel( QStringLiteral( "Fetched tiles: %1" ).arg( rawTiles.count() ), 2 );
136 }
137 else
138 {
139 asyncLoader.reset( new QgsVectorTileLoader( mSourcePath, mTileMatrix, mTileRange, viewCenter, mAuthCfg, mHeaders, mFeedback.get() ) );
140 QObject::connect( asyncLoader.get(), &QgsVectorTileLoader::tileRequestFinished, asyncLoader.get(), [this]( const QgsVectorTileRawData & rawTile )
141 {
142 QgsDebugMsgLevel( QStringLiteral( "Got tile asynchronously: " ) + rawTile.id.toString(), 2 );
143 if ( !rawTile.data.isEmpty() )
144 decodeAndDrawTile( rawTile );
145 } );
146 }
147
148 if ( ctx.renderingStopped() )
149 return false;
150
151 // add @zoom_level variable which can be used in styling
152 QgsExpressionContextScope *scope = new QgsExpressionContextScope( QObject::tr( "Tiles" ) ); // will be deleted by popper
153 scope->setVariable( QStringLiteral( "zoom_level" ), mTileZoom, true );
154 scope->setVariable( QStringLiteral( "vector_tile_zoom" ), mTileMatrixSet.scaleToZoom( tileRenderScale ), true );
155 const QgsExpressionContextScopePopper popper( ctx.expressionContext(), scope );
156
157 mRenderer->startRender( *renderContext(), mTileZoom, mTileRange );
158
159 QMap<QString, QSet<QString> > requiredFields = mRenderer->usedAttributes( ctx );
160
161 if ( mLabelProvider )
162 {
163 const QMap<QString, QSet<QString> > requiredFieldsLabeling = mLabelProvider->usedAttributes( ctx, mTileZoom );
164 for ( auto it = requiredFieldsLabeling.begin(); it != requiredFieldsLabeling.end(); ++it )
165 {
166 requiredFields[it.key()].unite( it.value() );
167 }
168 }
169
170 for ( auto it = requiredFields.constBegin(); it != requiredFields.constEnd(); ++it )
171 mPerLayerFields[it.key()] = QgsVectorTileUtils::makeQgisFields( it.value() );
172
173 mRequiredLayers = mRenderer->requiredLayers( ctx, mTileZoom );
174
175 if ( mLabelProvider )
176 {
177 mLabelProvider->setFields( mPerLayerFields );
178 QSet<QString> attributeNames; // we don't need this - already got referenced columns in provider constructor
179 if ( !mLabelProvider->prepare( ctx, attributeNames ) )
180 {
181 ctx.labelingEngine()->removeProvider( mLabelProvider );
182 mLabelProvider = nullptr; // provider is deleted by the engine
183 }
184 else
185 {
186 mRequiredLayers.unite( mLabelProvider->requiredLayers( ctx, mTileZoom ) );
187 }
188 }
189
190 if ( !isAsync )
191 {
192 for ( const QgsVectorTileRawData &rawTile : std::as_const( rawTiles ) )
193 {
194 if ( ctx.renderingStopped() )
195 break;
196
197 decodeAndDrawTile( rawTile );
198 }
199 }
200 else
201 {
202 // Block until tiles are fetched and rendered. If the rendering gets canceled at some point,
203 // the async loader will catch the signal, abort requests and return from downloadBlocking()
204 asyncLoader->downloadBlocking();
205 if ( !asyncLoader->error().isEmpty() )
206 mErrors.append( asyncLoader->error() );
207 }
208
210 mRenderer->renderSelectedFeatures( mSelectedFeatures, ctx );
211
212 mRenderer->stopRender( ctx );
213
214 QgsDebugMsgLevel( QStringLiteral( "Total time for decoding: %1" ).arg( mTotalDecodeTime / 1000. ), 2 );
215 QgsDebugMsgLevel( QStringLiteral( "Drawing time: %1" ).arg( mTotalDrawTime / 1000. ), 2 );
216 QgsDebugMsgLevel( QStringLiteral( "Total time: %1" ).arg( tTotal.elapsed() / 1000. ), 2 );
217
218 return !ctx.renderingStopped();
219}
220
222{
223 return renderContext()->testFlag( Qgis::RenderContextFlag::UseAdvancedEffects ) && ( !qgsDoubleNear( mLayerOpacity, 1.0 ) );
224}
225
226void QgsVectorTileLayerRenderer::decodeAndDrawTile( const QgsVectorTileRawData &rawTile )
227{
229
230 QgsDebugMsgLevel( QStringLiteral( "Drawing tile " ) + rawTile.id.toString(), 2 );
231
232 QElapsedTimer tLoad;
233 tLoad.start();
234
235 // currently only MVT encoding supported
236 QgsVectorTileMVTDecoder decoder( mTileMatrixSet );
237 if ( !decoder.decode( rawTile.id, rawTile.data ) )
238 {
239 QgsDebugMsgLevel( QStringLiteral( "Failed to parse raw tile data! " ) + rawTile.id.toString(), 2 );
240 return;
241 }
242
243 if ( ctx.renderingStopped() )
244 return;
245
247
248 QgsVectorTileRendererData tile( rawTile.id );
249 tile.setFields( mPerLayerFields );
250 tile.setFeatures( decoder.layerFeatures( mPerLayerFields, ct, &mRequiredLayers ) );
251
252 try
253 {
254 tile.setTilePolygon( QgsVectorTileUtils::tilePolygon( rawTile.id, ct, mTileMatrix, ctx.mapToPixel() ) );
255 }
256 catch ( QgsCsException & )
257 {
258 QgsDebugMsgLevel( QStringLiteral( "Failed to generate tile polygon " ) + rawTile.id.toString(), 2 );
259 return;
260 }
261
262 mTotalDecodeTime += tLoad.elapsed();
263
264 // calculate tile polygon in screen coordinates
265
266 if ( ctx.renderingStopped() )
267 return;
268
269 {
270 // set up clipping so that rendering does not go behind tile's extent
271 const QgsScopedQPainterState savePainterState( ctx.painter() );
272 // we have to intersect with any existing painter clip regions, or we risk overwriting valid clip
273 // regions setup outside of the vector tile renderer (e.g. layout map clip region)
274 ctx.painter()->setClipRegion( QRegion( tile.tilePolygon() ), Qt::IntersectClip );
275
276 QElapsedTimer tDraw;
277 tDraw.start();
278
279 mRenderer->renderTile( tile, ctx );
280 mTotalDrawTime += tDraw.elapsed();
281 }
282
283 if ( mLabelProvider )
284 mLabelProvider->registerTileFeatures( tile, ctx );
285
286 if ( mDrawTileBoundaries )
287 {
288 const QgsScopedQPainterState savePainterState( ctx.painter() );
289 ctx.painter()->setClipping( false );
290
291 QPen pen( Qt::red );
292 pen.setWidth( 3 );
293 QBrush brush( QColor( 255, 0, 0, 40 ), Qt::BrushStyle::Dense3Pattern );
294
295 ctx.painter()->setPen( pen );
296 ctx.painter()->setBrush( brush );
297 ctx.painter()->drawPolygon( tile.tilePolygon() );
298#if 0
299 ctx.painter()->setBrush( QBrush( QColor( 255, 0, 0 ) ) );
300 ctx.painter()->drawText( tile.tilePolygon().boundingRect().center(), tile.id().toString() );
301#endif
302 }
303}
@ DrawSelection
Whether vector selections should be shown in the rendered map.
@ UseAdvancedEffects
Enable layer opacity and blending effects.
@ Export
Renderer used for printing or exporting to a file.
@ View
Renderer used for displaying on screen.
@ Unknown
Renderer used for unknown usage.
Class for doing transforms between two map coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
Class for storing the component parts of a RDBMS data source URI (e.g.
void setEncodedUri(const QByteArray &uri)
Sets the complete encoded uri.
QgsHttpHeaders httpHeaders() const
Returns http headers.
QString authConfigId() const
Returns any associated authentication configuration ID stored in the URI.
RAII class to pop scope from an expression context on destruction.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void setVariable(const QString &name, const QVariant &value, bool isStatic=false)
Convenience method for setting a variable in the context scope by name name and value.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition: qgsfeedback.h:45
The QgsLabelingEngine class provides map labeling functionality.
void removeProvider(QgsAbstractLabelProvider *provider)
Remove provider if the provider's initialization failed. Provider instance is deleted.
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.
Base class for utility classes that encapsulate information necessary for rendering of map layers.
QgsRenderContext * renderContext()
Returns the render context associated with the renderer.
QString source() const
Returns the source for the layer.
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
Definition: qgsrectangle.h:251
Contains information about the context of a rendering operation.
Qgis::RendererUsage rendererUsage() const
Returns the renderer usage.
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
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.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
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.
Qgis::RenderContextFlags flags() const
Returns combination of flags used for rendering.
Scoped object for saving and restoring a QPainter object's state.
double scaleForRenderContext(const QgsRenderContext &context) const
Calculates the correct scale to use for the tiles when rendered using the specified render context.
Definition: qgstiles.cpp:273
int scaleToZoomLevel(double scale) const
Finds the best fitting (integer) zoom level given a map scale denominator.
Definition: qgstiles.cpp:257
double scaleToZoom(double scale) const
Calculates a fractional zoom level given a map scale denominator.
Definition: qgstiles.cpp:215
QgsTileMatrix tileMatrix(int zoom) const
Returns the tile matrix corresponding to the specified zoom.
Definition: qgstiles.cpp:150
QPointF mapToTileCoordinates(const QgsPointXY &mapPoint) const
Returns row/column coordinates (floating point number) from the given point in map coordinates.
Definition: qgstiles.cpp:121
QgsTileRange tileRangeFromExtent(const QgsRectangle &mExtent) const
Returns tile range that fully covers the given extent.
Definition: qgstiles.cpp:97
int endColumn() const
Returns index of the last column in the range.
Definition: qgstiles.h:83
int endRow() const
Returns index of the last row in the range.
Definition: qgstiles.h:87
int startRow() const
Returns index of the first row in the range.
Definition: qgstiles.h:85
int startColumn() const
Returns index of the first column in the range.
Definition: qgstiles.h:81
bool isValid() const
Returns whether the range is valid (when all row/column numbers are not negative)
Definition: qgstiles.h:78
QString toString() const
Returns tile coordinates in a formatted string.
Definition: qgstiles.h:54
virtual bool prepare(QgsRenderContext &context, QSet< QString > &attributeNames)
Prepare for registration of features.
virtual QMap< QString, QSet< QString > > usedAttributes(const QgsRenderContext &context, int tileZoom) const =0
Returns field names for each sub-layer that are required for labeling.
virtual void setFields(const QMap< QString, QgsFields > &perLayerFields)=0
Sets fields for each sub-layer.
virtual QSet< QString > requiredLayers(QgsRenderContext &context, int tileZoom) const
Returns a list of the layers required for labeling.
virtual void registerTileFeatures(const QgsVectorTileRendererData &tile, QgsRenderContext &context)=0
Registers label features for given tile to the labeling engine.
virtual QgsVectorTileLabelProvider * provider(QgsVectorTileLayer *layer) const SIP_SKIP
Factory for label provider implementation.
bool forceRasterRender() const override
Returns true if the renderer must be rendered to a raster paint device (e.g.
QgsVectorTileLayerRenderer(QgsVectorTileLayer *layer, QgsRenderContext &context)
Creates the renderer. Always called from main thread, should copy whatever necessary from the layer.
virtual bool render() override
Do the rendering (based on data stored in the class).
Implements a map layer that is dedicated to rendering of vector tiles.
QgsVectorTileLabeling * labeling() const
Returns currently assigned labeling.
The loader class takes care of loading raw vector tile data from a tile source.
void tileRequestFinished(const QgsVectorTileRawData &rawTile)
Emitted when a tile request has finished. If a tile request has failed, the returned raw tile byte ar...
static QList< QgsVectorTileRawData > blockingFetchTileRawData(const QString &sourceType, const QString &sourcePath, const QgsTileMatrix &tileMatrix, const QPointF &viewCenter, const QgsTileRange &range, const QString &authid, const QgsHttpHeaders &headers, QgsFeedback *feedback=nullptr)
Returns raw tile data for the specified range of tiles. Blocks the caller until all tiles are fetched...
This class is responsible for decoding raw tile data written with Mapbox Vector Tiles encoding.
Keeps track of raw tile data that need to be decoded.
QByteArray data
Raw tile data.
QgsTileXYZ id
Tile position in tile matrix set.
Contains decoded features of a single vector tile and any other data necessary for rendering of it.
static QPolygon tilePolygon(QgsTileXYZ id, const QgsCoordinateTransform &ct, const QgsTileMatrix &tm, const QgsMapToPixel &mtp)
Returns polygon (made by four corners of the tile) in screen coordinates.
static QgsFields makeQgisFields(const QSet< QString > &flds)
Returns QgsFields instance based on the set of field names.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:3509
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39