QGIS API Documentation 4.1.0-Master (60fea48833c)
Loading...
Searching...
No Matches
qgsvectortilemvtdecoder.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectortilemvtdecoder.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 <string>
19
20#include "qgslinestring.h"
21#include "qgslogger.h"
22#include "qgsmultilinestring.h"
23#include "qgsmultipoint.h"
24#include "qgsmultipolygon.h"
25#include "qgspolygon.h"
26#include "qgsvectortileloader.h"
28#include "qgsvectortileutils.h"
29#include "qgsziputils.h"
30
31#include <QNetworkRequest>
32#include <QPointer>
33#include <QString>
34
35using namespace Qt::StringLiterals;
36
38 : mStructure( structure )
39{}
40
42
44{
45 mLayerNameToIndex.clear();
46
47 for ( auto it = rawTileData.data.constBegin(); it != rawTileData.data.constEnd(); ++it )
48 {
49 const QString sourceId = it.key();
50 const QByteArray &raw = it.value();
51
52 QByteArray pbf;
53 const bool isGzip = raw.size() >= 2 && static_cast<uchar>( raw[0] ) == 0x1f && static_cast<uchar>( raw[1] ) == 0x8b;
54
55 if ( isGzip )
56 {
57 if ( !QgsZipUtils::decodeGzip( raw, pbf ) )
58 {
59 QgsDebugMsgLevel( u"Failed to gunzip tile data"_s, 2 );
60 return false;
61 }
62 }
63 else
64 {
65 pbf = raw;
66 }
67
68 vector_tile::Tile tile;
69 if ( !tile.ParseFromArray( pbf.constData(), static_cast<int>( pbf.size() ) ) )
70 return false;
71
72 for ( int layerNum = 0; layerNum < tile.layers_size(); ++layerNum )
73 {
74 const ::vector_tile::Tile_Layer &layer = tile.layers( layerNum );
75 mLayerNameToIndex[sourceId][QString::fromStdString( layer.name() )] = layerNum;
76 }
77
78 tiles[sourceId] = std::move( tile );
79 }
80
81 mTileID = rawTileData.tileGeometryId;
82 return true;
83}
84
86{
87 QStringList layerNames;
88 const int layerSize = std::accumulate( tiles.constBegin(), tiles.constEnd(), 0, []( int count, const vector_tile::Tile &tile ) { return count + tile.layers_size(); } );
89 layerNames.reserve( layerSize );
90
91 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
92 for ( ; it != tiles.constEnd(); ++it )
93 {
94 for ( int layerNum = 0; layerNum < layerSize; layerNum++ )
95 {
96 const ::vector_tile::Tile_Layer &layer = it.value().layers( layerNum );
97 const QString layerName = layer.name().c_str();
98 layerNames << layerName;
99 }
100 }
101 return layerNames;
102}
103
104QStringList QgsVectorTileMVTDecoder::layerFieldNames( const QString &layerName ) const
105{
106 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
107 for ( ; it != tiles.constEnd(); ++it )
108 {
109 if ( !mLayerNameToIndex[it.key()].contains( layerName ) )
110 continue;
111
112 const ::vector_tile::Tile_Layer &layer = it.value().layers( mLayerNameToIndex[it.key()][layerName] );
113 QStringList fieldNames;
114 const int size = layer.keys_size();
115 fieldNames.reserve( size );
116 for ( int i = 0; i < size; ++i )
117 {
118 const QString fieldName = layer.keys( i ).c_str();
119 fieldNames << fieldName;
120 }
121 return fieldNames;
122 }
123 return QStringList();
124}
125
126QgsVectorTileFeatures QgsVectorTileMVTDecoder::layerFeatures( const QMap<QString, QgsFields> &perLayerFields, const QgsCoordinateTransform &ct, const QSet<QString> *layerSubset ) const
127{
128 QgsVectorTileFeatures features;
129
130 const int numTiles = static_cast<int>( pow( 2, mTileID.zoomLevel() ) ); // assuming we won't ever go over 30 zoom levels
131 const QgsTileMatrix &rootMatrix = mStructure.rootMatrix();
132 const double z0Width = rootMatrix.extent().width();
133 const double z0Height = rootMatrix.extent().height();
134 const double z0xMinimum = rootMatrix.extent().xMinimum();
135 const double z0yMaximum = rootMatrix.extent().yMaximum();
136
137 const double tileDX = z0Width / numTiles;
138 const double tileDY = z0Height / numTiles;
139 const double tileXMin = z0xMinimum + mTileID.column() * tileDX;
140 const double tileYMax = z0yMaximum - mTileID.row() * tileDY;
141
142 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
143 for ( ; it != tiles.constEnd(); ++it )
144 {
145 vector_tile::Tile tile = it.value();
146
147 for ( int layerNum = 0; layerNum < tile.layers_size(); layerNum++ )
148 {
149 const ::vector_tile::Tile_Layer &layer = tile.layers( layerNum );
150
151 const QString layerName = layer.name().c_str();
152 if ( layerSubset && !layerSubset->contains( QString() ) && !layerSubset->contains( layerName ) )
153 continue;
154
155 QVector<QgsFeature> layerFeatures;
156 QgsFields layerFields = perLayerFields[layerName];
157
158 const auto allLayerFields = perLayerFields.find( QString() );
159 if ( allLayerFields != perLayerFields.end() )
160 {
161 // need to add the fields from any "all layer" rules to every layer
162 for ( const QgsField &field : allLayerFields.value() )
163 {
164 if ( layerFields.lookupField( field.name() ) == -1 )
165 {
166 layerFields.append( field );
167 }
168 }
169 }
170
171 // figure out how field indexes in MVT encoding map to field indexes in QgsFields (we may not use all available fields)
172 QHash<int, int> tagKeyIndexToFieldIndex;
173 for ( int i = 0; i < layer.keys_size(); ++i )
174 {
175 const int fieldIndex = layerFields.indexOf( layer.keys( i ).c_str() );
176 if ( fieldIndex != -1 )
177 tagKeyIndexToFieldIndex.insert( i, fieldIndex );
178 }
179
180 // go through features of a layer
181 for ( int featureNum = 0; featureNum < layer.features_size(); featureNum++ )
182 {
183 const ::vector_tile::Tile_Feature &feature = layer.features( featureNum );
184
185 QgsFeatureId fid;
186 {
187 // There is no assigned ID, but some parts of QGIS do not work correctly if all IDs are zero
188 // (e.g. labeling will not register two features with the same FID within a single layer),
189 // so let's generate some pseudo-unique FIDs to keep those bits happy
190 fid = featureNum;
191 fid |= ( layerNum & 0xff ) << 24;
192 fid |= ( static_cast<QgsFeatureId>( mTileID.row() ) & 0xff ) << 32;
193 fid |= ( static_cast<QgsFeatureId>( mTileID.column() ) & 0xff ) << 40;
194 }
195
196 QgsFeature f( layerFields, fid );
197
198 //
199 // parse attributes
200 //
201
202 for ( int tagNum = 0; tagNum + 1 < feature.tags_size(); tagNum += 2 )
203 {
204 const int keyIndex = static_cast<int>( feature.tags( tagNum ) );
205 const int fieldIndex = tagKeyIndexToFieldIndex.value( keyIndex, -1 );
206 if ( fieldIndex == -1 )
207 continue;
208
209 const int valueIndex = static_cast<int>( feature.tags( tagNum + 1 ) );
210 if ( valueIndex >= layer.values_size() )
211 {
212 QgsDebugError( u"Invalid value index for attribute"_s );
213 continue;
214 }
215 const ::vector_tile::Tile_Value &value = layer.values( valueIndex );
216
217 if ( value.has_string_value() )
218 f.setAttribute( fieldIndex, QString::fromStdString( value.string_value() ) );
219 else if ( value.has_float_value() )
220 f.setAttribute( fieldIndex, static_cast<double>( value.float_value() ) );
221 else if ( value.has_double_value() )
222 f.setAttribute( fieldIndex, value.double_value() );
223 else if ( value.has_int_value() )
224 f.setAttribute( fieldIndex, static_cast<long long>( value.int_value() ) );
225 else if ( value.has_uint_value() )
226 f.setAttribute( fieldIndex, static_cast<long long>( value.uint_value() ) );
227 else if ( value.has_sint_value() )
228 f.setAttribute( fieldIndex, static_cast<long long>( value.sint_value() ) );
229 else if ( value.has_bool_value() )
230 f.setAttribute( fieldIndex, static_cast<bool>( value.bool_value() ) );
231 else
232 {
233 QgsDebugError( u"Unexpected attribute value"_s );
234 }
235 }
236
237 //
238 // parse geometry
239 //
240
241 const int extent = static_cast<int>( layer.extent() );
242 int cursorx = 0, cursory = 0;
243
244 QVector<QgsPoint *> outputPoints; // for point/multi-point
245 QVector<QgsLineString *> outputLinestrings; // for linestring/multi-linestring
246 QVector<QgsPolygon *> outputPolygons;
247 QVector<QgsPoint> tmpPoints;
248
249 for ( int i = 0; i < feature.geometry_size(); i++ )
250 {
251 const unsigned g = feature.geometry( i );
252 const unsigned cmdId = g & 0x7;
253 const int cmdCount = static_cast<int>( g >> 3 );
254 if ( cmdId == 1 ) // MoveTo
255 {
256 if ( i + static_cast<int>( cmdCount ) * 2 >= feature.geometry_size() )
257 {
258 QgsDebugError( u"Malformed geometry: invalid cmdCount"_s );
259 break;
260 }
261
262 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
263 outputPoints.reserve( static_cast<int>( outputPoints.size() ) + cmdCount );
264 else
265 tmpPoints.reserve( static_cast<int>( tmpPoints.size() ) + cmdCount );
266
267 for ( int j = 0; j < cmdCount; j++ )
268 {
269 const int v = static_cast<int>( feature.geometry( i + 1 ) );
270 const int w = static_cast<int>( feature.geometry( i + 2 ) );
271 const int dx = ( ( v >> 1 ) ^ ( -( v & 1 ) ) );
272 const int dy = ( ( w >> 1 ) ^ ( -( w & 1 ) ) );
273 cursorx += dx;
274 cursory += dy;
275 const double px = tileXMin + tileDX * double( cursorx ) / double( extent );
276 const double py = tileYMax - tileDY * double( cursory ) / double( extent );
277
278 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
279 {
280 outputPoints.append( new QgsPoint( px, py ) );
281 }
282 else if ( feature.type() == vector_tile::Tile_GeomType_LINESTRING )
283 {
284 if ( tmpPoints.size() > 0 )
285 {
286 outputLinestrings.append( new QgsLineString( tmpPoints ) );
287 tmpPoints.clear();
288 }
289 tmpPoints.append( QgsPoint( px, py ) );
290 }
291 else if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
292 {
293 tmpPoints.append( QgsPoint( px, py ) );
294 }
295 i += 2;
296 }
297 }
298 else if ( cmdId == 2 ) // LineTo
299 {
300 if ( i + static_cast<int>( cmdCount ) * 2 >= feature.geometry_size() )
301 {
302 QgsDebugError( u"Malformed geometry: invalid cmdCount"_s );
303 break;
304 }
305 tmpPoints.reserve( tmpPoints.size() + cmdCount );
306 for ( int j = 0; j < cmdCount; j++ )
307 {
308 const int v = static_cast<int>( feature.geometry( i + 1 ) );
309 const int w = static_cast<int>( feature.geometry( i + 2 ) );
310 const int dx = ( v >> 1 ) ^ ( -( v & 1 ) );
311 const int dy = ( w >> 1 ) ^ ( -( w & 1 ) );
312 cursorx += dx;
313 cursory += dy;
314 const double px = tileXMin + tileDX * double( cursorx ) / double( extent );
315 const double py = tileYMax - tileDY * double( cursory ) / double( extent );
316
317 tmpPoints.push_back( QgsPoint( px, py ) );
318 i += 2;
319 }
320 }
321 else if ( cmdId == 7 ) // ClosePath
322 {
323 if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
324 {
325 tmpPoints.append( tmpPoints.first() ); // close the ring
326
327 auto ring = std::make_unique<QgsLineString>( tmpPoints );
328 tmpPoints.clear();
329
330 if ( QgsVectorTileMVTUtils::isExteriorRing( ring.get() ) )
331 {
332 // start a new polygon
333 QgsPolygon *p = new QgsPolygon;
334 p->setExteriorRing( ring.release() );
335 outputPolygons.append( p );
336 }
337 else
338 {
339 // interior ring (hole)
340 if ( outputPolygons.count() != 0 )
341 {
342 outputPolygons[outputPolygons.count() - 1]->addInteriorRing( ring.release() );
343 }
344 else
345 {
346 QgsDebugError( u"Malformed geometry: first ring of a polygon is interior ring"_s );
347 }
348 }
349 }
350 }
351 else
352 {
353 QgsDebugError( u"Unexpected command ID: %1"_s.arg( cmdId ) );
354 }
355 }
356
357 QString geomType;
358 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
359 {
360 geomType = u"Point"_s;
361 if ( outputPoints.count() == 1 )
362 f.setGeometry( QgsGeometry( outputPoints.at( 0 ) ) );
363 else
364 {
366 mp->reserve( outputPoints.count() );
367 for ( int k = 0; k < outputPoints.count(); ++k )
368 mp->addGeometry( outputPoints[k] );
369 f.setGeometry( QgsGeometry( mp ) );
370 }
371 }
372 else if ( feature.type() == vector_tile::Tile_GeomType_LINESTRING )
373 {
374 geomType = u"LineString"_s;
375
376 // finish the linestring we have started
377 outputLinestrings.append( new QgsLineString( tmpPoints ) );
378
379 if ( outputLinestrings.count() == 1 )
380 f.setGeometry( QgsGeometry( outputLinestrings.at( 0 ) ) );
381 else
382 {
384 mls->reserve( outputLinestrings.size() );
385 for ( int k = 0; k < outputLinestrings.count(); ++k )
386 mls->addGeometry( outputLinestrings[k] );
387 f.setGeometry( QgsGeometry( mls ) );
388 }
389 }
390 else if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
391 {
392 geomType = u"Polygon"_s;
393
394 if ( outputPolygons.count() == 1 )
395 f.setGeometry( QgsGeometry( outputPolygons.at( 0 ) ) );
396 else
397 {
399 mpl->reserve( outputPolygons.size() );
400 for ( int k = 0; k < outputPolygons.count(); ++k )
401 mpl->addGeometry( outputPolygons[k] );
402 f.setGeometry( QgsGeometry( mpl ) );
403 }
404 }
405
406 f.setAttribute( u"_geom_type"_s, geomType );
407 f.geometry().transform( ct );
408
409 layerFeatures.append( f );
410 }
411
412 features[layerName] = layerFeatures;
413 }
414 }
415 return features;
416}
Handles coordinate transforms between two coordinate systems.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
Q_INVOKABLE bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
QgsGeometry geometry
Definition qgsfeature.h:71
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
Q_INVOKABLE int indexOf(const QString &fieldName) const
Gets the field index from the field name.
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
void reserve(int size)
Attempts to allocate memory for at least size geometries.
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
Line string geometry type, with support for z-dimension and m-values.
Multi line string geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Multi point geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Multi polygon geometry collection.
bool addGeometry(QgsAbstractGeometry *g) override
Adds a geometry and takes ownership. Returns true in case of success.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
Polygon geometry type.
Definition qgspolygon.h:37
void setExteriorRing(QgsCurve *ring) override
Sets the exterior ring of the polygon.
double xMinimum
double yMaximum
Defines a matrix of tiles for a single zoom level: it is defined by its size (width *.
Definition qgstiles.h:171
QgsRectangle extent() const
Returns extent of the tile matrix.
Definition qgstiles.h:223
QStringList layerFieldNames(const QString &layerName) const
Returns a list of all field names in a tile. It can only be called after a successful decode().
QStringList layers() const
Returns a list of sub-layer names in a tile. It can only be called after a successful decode().
bool decode(const QgsVectorTileRawData &rawTileData)
Tries to decode raw tile data, returns true on success.
QgsVectorTileMVTDecoder(const QgsVectorTileMatrixSet &structure)
Constructor for QgsVectorTileMVTDecoder, using the specified tile structure.
QgsVectorTileFeatures layerFeatures(const QMap< QString, QgsFields > &perLayerFields, const QgsCoordinateTransform &ct, const QSet< QString > *layerSubset=nullptr) const
Returns decoded features grouped by sub-layers.
static bool isExteriorRing(const QgsLineString *lineString)
Returns whether this linear ring forms an exterior ring according to MVT spec (depending on the orien...
Encapsulates properties of a vector tile matrix set, including tile origins and scaling information.
Keeps track of raw tile data from one or more sources that need to be decoded.
QMap< QString, QByteArray > data
Raw tile data by source ID.
QgsTileXYZ tileGeometryId
Tile id associated with the raw tile data.
static bool decodeGzip(const QByteArray &bytesIn, QByteArray &bytesOut)
Decodes gzip byte stream, returns true on success.
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
QMap< QString, QVector< QgsFeature > > QgsVectorTileFeatures
Features of a vector tile, grouped by sub-layer names (key of the map).