QGIS API Documentation 3.99.0-Master (a8882ad4560)
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
35 : mStructure( structure )
36{}
37
39
41{
42 mLayerNameToIndex.clear();
43
44 for ( auto it = rawTileData.data.constBegin(); it != rawTileData.data.constEnd(); ++it )
45 {
46 const QString sourceId = it.key();
47 const QByteArray &raw = it.value();
48
49 QByteArray pbf;
50 const bool isGzip = raw.size() >= 2
51 && static_cast<uchar>( raw[0] ) == 0x1f
52 && static_cast<uchar>( raw[1] ) == 0x8b;
53
54 if ( isGzip )
55 {
56 if ( !QgsZipUtils::decodeGzip( raw, pbf ) )
57 {
58 QgsDebugMsgLevel( u"Failed to gunzip tile data"_s, 2 );
59 return false;
60 }
61 }
62 else
63 {
64 pbf = raw;
65 }
66
67 vector_tile::Tile tile;
68 if ( !tile.ParseFromArray( pbf.constData(), static_cast<int>( pbf.size() ) ) )
69 return false;
70
71 for ( int layerNum = 0; layerNum < tile.layers_size(); ++layerNum )
72 {
73 const ::vector_tile::Tile_Layer &layer = tile.layers( layerNum );
74 mLayerNameToIndex[sourceId][ QString::fromStdString( layer.name() ) ] = layerNum;
75 }
76
77 tiles[sourceId] = std::move( tile );
78 }
79
80 mTileID = rawTileData.tileGeometryId;
81 return true;
82}
83
85{
86 QStringList layerNames;
87 const int layerSize = std::accumulate( tiles.constBegin(), tiles.constEnd(), 0, []( int count, const vector_tile::Tile & tile ) {return count + tile.layers_size();} );
88 layerNames.reserve( layerSize );
89
90 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
91 for ( ; it != tiles.constEnd(); ++it )
92 {
93 for ( int layerNum = 0; layerNum < layerSize; layerNum++ )
94 {
95 const ::vector_tile::Tile_Layer &layer = it.value().layers( layerNum );
96 const QString layerName = layer.name().c_str();
97 layerNames << layerName;
98 }
99 }
100 return layerNames;
101}
102
103QStringList QgsVectorTileMVTDecoder::layerFieldNames( const QString &layerName ) const
104{
105 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
106 for ( ; it != tiles.constEnd(); ++it )
107 {
108 if ( !mLayerNameToIndex[it.key()].contains( layerName ) )
109 continue;
110
111 const ::vector_tile::Tile_Layer &layer = it.value().layers( mLayerNameToIndex[it.key()][layerName] );
112 QStringList fieldNames;
113 const int size = layer.keys_size();
114 fieldNames.reserve( size );
115 for ( int i = 0; i < size; ++i )
116 {
117 const QString fieldName = layer.keys( i ).c_str();
118 fieldNames << fieldName;
119 }
120 return fieldNames;
121 }
122 return QStringList();
123}
124
125QgsVectorTileFeatures QgsVectorTileMVTDecoder::layerFeatures( const QMap<QString, QgsFields> &perLayerFields, const QgsCoordinateTransform &ct, const QSet<QString> *layerSubset ) const
126{
127 QgsVectorTileFeatures features;
128
129 const int numTiles = static_cast<int>( pow( 2, mTileID.zoomLevel() ) ); // assuming we won't ever go over 30 zoom levels
130 const QgsTileMatrix &rootMatrix = mStructure.rootMatrix();
131 const double z0Width = rootMatrix.extent().width();
132 const double z0Height = rootMatrix.extent().height();
133 const double z0xMinimum = rootMatrix.extent().xMinimum();
134 const double z0yMaximum = rootMatrix.extent().yMaximum();
135
136 const double tileDX = z0Width / numTiles;
137 const double tileDY = z0Height / numTiles;
138 const double tileXMin = z0xMinimum + mTileID.column() * tileDX;
139 const double tileYMax = z0yMaximum - mTileID.row() * tileDY;
140
141 QMap<QString, vector_tile::Tile>::const_iterator it = tiles.constBegin();
142 for ( ; it != tiles.constEnd(); ++it )
143 {
144 vector_tile::Tile tile = it.value();
145
146 for ( int layerNum = 0; layerNum < tile.layers_size(); layerNum++ )
147 {
148 const ::vector_tile::Tile_Layer &layer = tile.layers( layerNum );
149
150 const QString layerName = layer.name().c_str();
151 if ( layerSubset && !layerSubset->contains( QString() ) && !layerSubset->contains( layerName ) )
152 continue;
153
154 QVector<QgsFeature> layerFeatures;
155 QgsFields layerFields = perLayerFields[layerName];
156
157 const auto allLayerFields = perLayerFields.find( QString() );
158 if ( allLayerFields != perLayerFields.end() )
159 {
160 // need to add the fields from any "all layer" rules to every layer
161 for ( const QgsField &field : allLayerFields.value() )
162 {
163 if ( layerFields.lookupField( field.name() ) == -1 )
164 {
165 layerFields.append( field );
166 }
167 }
168 }
169
170 // figure out how field indexes in MVT encoding map to field indexes in QgsFields (we may not use all available fields)
171 QHash<int, int> tagKeyIndexToFieldIndex;
172 for ( int i = 0; i < layer.keys_size(); ++i )
173 {
174 const int fieldIndex = layerFields.indexOf( layer.keys( i ).c_str() );
175 if ( fieldIndex != -1 )
176 tagKeyIndexToFieldIndex.insert( i, fieldIndex );
177 }
178
179 // go through features of a layer
180 for ( int featureNum = 0; featureNum < layer.features_size(); featureNum++ )
181 {
182 const ::vector_tile::Tile_Feature &feature = layer.features( featureNum );
183
184 QgsFeatureId fid;
185 {
186 // There is no assigned ID, but some parts of QGIS do not work correctly if all IDs are zero
187 // (e.g. labeling will not register two features with the same FID within a single layer),
188 // so let's generate some pseudo-unique FIDs to keep those bits happy
189 fid = featureNum;
190 fid |= ( layerNum & 0xff ) << 24;
191 fid |= ( static_cast<QgsFeatureId>( mTileID.row() ) & 0xff ) << 32;
192 fid |= ( static_cast<QgsFeatureId>( mTileID.column() ) & 0xff ) << 40;
193 }
194
195 QgsFeature f( layerFields, fid );
196
197 //
198 // parse attributes
199 //
200
201 for ( int tagNum = 0; tagNum + 1 < feature.tags_size(); tagNum += 2 )
202 {
203 const int keyIndex = static_cast<int>( feature.tags( tagNum ) );
204 const int fieldIndex = tagKeyIndexToFieldIndex.value( keyIndex, -1 );
205 if ( fieldIndex == -1 )
206 continue;
207
208 const int valueIndex = static_cast<int>( feature.tags( tagNum + 1 ) );
209 if ( valueIndex >= layer.values_size() )
210 {
211 QgsDebugError( u"Invalid value index for attribute"_s );
212 continue;
213 }
214 const ::vector_tile::Tile_Value &value = layer.values( valueIndex );
215
216 if ( value.has_string_value() )
217 f.setAttribute( fieldIndex, QString::fromStdString( value.string_value() ) );
218 else if ( value.has_float_value() )
219 f.setAttribute( fieldIndex, static_cast<double>( value.float_value() ) );
220 else if ( value.has_double_value() )
221 f.setAttribute( fieldIndex, value.double_value() );
222 else if ( value.has_int_value() )
223 f.setAttribute( fieldIndex, static_cast<long long>( value.int_value() ) );
224 else if ( value.has_uint_value() )
225 f.setAttribute( fieldIndex, static_cast<long long>( value.uint_value() ) );
226 else if ( value.has_sint_value() )
227 f.setAttribute( fieldIndex, static_cast<long long>( value.sint_value() ) );
228 else if ( value.has_bool_value() )
229 f.setAttribute( fieldIndex, static_cast<bool>( value.bool_value() ) );
230 else
231 {
232 QgsDebugError( u"Unexpected attribute value"_s );
233 }
234 }
235
236 //
237 // parse geometry
238 //
239
240 const int extent = static_cast<int>( layer.extent() );
241 int cursorx = 0, cursory = 0;
242
243 QVector<QgsPoint *> outputPoints; // for point/multi-point
244 QVector<QgsLineString *> outputLinestrings; // for linestring/multi-linestring
245 QVector<QgsPolygon *> outputPolygons;
246 QVector<QgsPoint> tmpPoints;
247
248 for ( int i = 0; i < feature.geometry_size(); i ++ )
249 {
250 const unsigned g = feature.geometry( i );
251 const unsigned cmdId = g & 0x7;
252 const int cmdCount = static_cast<int>( g >> 3 );
253 if ( cmdId == 1 ) // MoveTo
254 {
255 if ( i + static_cast<int>( cmdCount ) * 2 >= feature.geometry_size() )
256 {
257 QgsDebugError( u"Malformed geometry: invalid cmdCount"_s );
258 break;
259 }
260
261 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
262 outputPoints.reserve( static_cast<int>( outputPoints.size() ) + cmdCount );
263 else
264 tmpPoints.reserve( static_cast<int>( tmpPoints.size() ) + cmdCount );
265
266 for ( int j = 0; j < cmdCount; j++ )
267 {
268 const int v = static_cast<int>( feature.geometry( i + 1 ) );
269 const int w = static_cast<int>( feature.geometry( i + 2 ) );
270 const int dx = ( ( v >> 1 ) ^ ( -( v & 1 ) ) );
271 const int dy = ( ( w >> 1 ) ^ ( -( w & 1 ) ) );
272 cursorx += dx;
273 cursory += dy;
274 const double px = tileXMin + tileDX * double( cursorx ) / double( extent );
275 const double py = tileYMax - tileDY * double( cursory ) / double( extent );
276
277 if ( feature.type() == vector_tile::Tile_GeomType_POINT )
278 {
279 outputPoints.append( new QgsPoint( px, py ) );
280 }
281 else if ( feature.type() == vector_tile::Tile_GeomType_LINESTRING )
282 {
283 if ( tmpPoints.size() > 0 )
284 {
285 outputLinestrings.append( new QgsLineString( tmpPoints ) );
286 tmpPoints.clear();
287 }
288 tmpPoints.append( QgsPoint( px, py ) );
289 }
290 else if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
291 {
292 tmpPoints.append( QgsPoint( px, py ) );
293 }
294 i += 2;
295 }
296 }
297 else if ( cmdId == 2 ) // LineTo
298 {
299 if ( i + static_cast<int>( cmdCount ) * 2 >= feature.geometry_size() )
300 {
301 QgsDebugError( u"Malformed geometry: invalid cmdCount"_s );
302 break;
303 }
304 tmpPoints.reserve( tmpPoints.size() + cmdCount );
305 for ( int j = 0; j < cmdCount; j++ )
306 {
307 const int v = static_cast<int>( feature.geometry( i + 1 ) );
308 const int w = static_cast<int>( feature.geometry( i + 2 ) );
309 const int dx = ( v >> 1 ) ^ ( -( v & 1 ) );
310 const int dy = ( w >> 1 ) ^ ( -( w & 1 ) );
311 cursorx += dx;
312 cursory += dy;
313 const double px = tileXMin + tileDX * double( cursorx ) / double( extent );
314 const double py = tileYMax - tileDY * double( cursory ) / double( extent );
315
316 tmpPoints.push_back( QgsPoint( px, py ) );
317 i += 2;
318 }
319 }
320 else if ( cmdId == 7 ) // ClosePath
321 {
322 if ( feature.type() == vector_tile::Tile_GeomType_POLYGON )
323 {
324 tmpPoints.append( tmpPoints.first() ); // close the ring
325
326 auto ring = std::make_unique<QgsLineString>( tmpPoints );
327 tmpPoints.clear();
328
329 if ( QgsVectorTileMVTUtils::isExteriorRing( ring.get() ) )
330 {
331 // start a new polygon
332 QgsPolygon *p = new QgsPolygon;
333 p->setExteriorRing( ring.release() );
334 outputPolygons.append( p );
335 }
336 else
337 {
338 // interior ring (hole)
339 if ( outputPolygons.count() != 0 )
340 {
341 outputPolygons[outputPolygons.count() - 1]->addInteriorRing( ring.release() );
342 }
343 else
344 {
345 QgsDebugError( u"Malformed geometry: first ring of a polygon is interior ring"_s );
346 }
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:58
Q_INVOKABLE bool setAttribute(int field, const QVariant &attr)
Sets an attribute's value by field index.
QgsGeometry geometry
Definition qgsfeature.h:69
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
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:73
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:49
Polygon geometry type.
Definition qgspolygon.h:33
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:158
QgsRectangle extent() const
Returns extent of the tile matrix.
Definition qgstiles.h:213
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).