QGIS API Documentation 3.31.0-Master (9f23a2c1dc)
qgsvectorlayerchunkloader_p.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectorlayerchunkloader_p.cpp
3 --------------------------------------
4 Date : July 2019
5 Copyright : (C) 2019 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#include "qgs3dutils.h"
21#include "qgschunknode_p.h"
22#include "qgseventtracing.h"
23#include "qgslogger.h"
24#include "qgsvectorlayer.h"
26#include "qgsapplication.h"
27#include "qgs3dsymbolregistry.h"
28#include "qgsabstract3dsymbol.h"
29
30#include <QtConcurrent>
31#include <Qt3DCore/QTransform>
32
34
35
36QgsVectorLayerChunkLoader::QgsVectorLayerChunkLoader( const QgsVectorLayerChunkLoaderFactory *factory, QgsChunkNode *node )
37 : QgsChunkLoader( node )
38 , mFactory( factory )
39 , mContext( factory->mMap )
40 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
41{
42 if ( node->level() < mFactory->mLeafLevel )
43 {
44 QTimer::singleShot( 0, this, &QgsVectorLayerChunkLoader::finished );
45 return;
46 }
47
48 QgsVectorLayer *layer = mFactory->mLayer;
49 const Qgs3DMapSettings &map = mFactory->mMap;
50
51 QgsFeature3DHandler *handler = QgsApplication::symbol3DRegistry()->createHandlerForSymbol( layer, mFactory->mSymbol.get() );
52 if ( !handler )
53 {
54 QgsDebugError( QStringLiteral( "Unknown 3D symbol type for vector layer: " ) + mFactory->mSymbol->type() );
55 return;
56 }
57 mHandler.reset( handler );
58
60 exprContext.setFields( layer->fields() );
61 mContext.setExpressionContext( exprContext );
62
63 QSet<QString> attributeNames;
64 if ( !mHandler->prepare( mContext, attributeNames ) )
65 {
66 QgsDebugError( QStringLiteral( "Failed to prepare 3D feature handler!" ) );
67 return;
68 }
69
70 // build the feature request
72 req.setDestinationCrs( map.crs(), map.transformContext() );
73 req.setSubsetOfAttributes( attributeNames, layer->fields() );
74
75 // only a subset of data to be queried
76 const QgsRectangle rect = Qgs3DUtils::worldToMapExtent( node->bbox(), map.origin() );
77 req.setFilterRect( rect );
78
79 //
80 // this will be run in a background thread
81 //
82 mFutureWatcher = new QFutureWatcher<void>( this );
83 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
84
85 const QFuture<void> future = QtConcurrent::run( [req, this]
86 {
87 const QgsEventTracing::ScopedEvent e( QStringLiteral( "3D" ), QStringLiteral( "VL chunk load" ) );
88
89 QgsFeature f;
90 QgsFeatureIterator fi = mSource->getFeatures( req );
91 while ( fi.nextFeature( f ) )
92 {
93 if ( mCanceled )
94 break;
95 mContext.expressionContext().setFeature( f );
96 mHandler->processFeature( f, mContext );
97 }
98 } );
99
100 // emit finished() as soon as the handler is populated with features
101 mFutureWatcher->setFuture( future );
102}
103
104QgsVectorLayerChunkLoader::~QgsVectorLayerChunkLoader()
105{
106 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
107 {
108 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
109 mFutureWatcher->waitForFinished();
110 }
111}
112
113void QgsVectorLayerChunkLoader::cancel()
114{
115 mCanceled = true;
116}
117
118Qt3DCore::QEntity *QgsVectorLayerChunkLoader::createEntity( Qt3DCore::QEntity *parent )
119{
120 if ( mNode->level() < mFactory->mLeafLevel )
121 {
122 return new Qt3DCore::QEntity( parent ); // dummy entity
123 }
124
125 if ( mHandler->featureCount() == 0 )
126 {
127 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
128 return nullptr;
129 }
130
131 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
132 mHandler->finalize( entity, mContext );
133
134 // fix the vertical range of the node from the estimated vertical range to the true range
135 if ( mHandler->zMinimum() != std::numeric_limits<float>::max() && mHandler->zMaximum() != std::numeric_limits<float>::lowest() )
136 {
137 QgsAABB box = mNode->bbox();
138 box.yMin = mHandler->zMinimum();
139 box.yMax = mHandler->zMaximum();
140 mNode->setExactBbox( box );
141 mNode->updateParentBoundingBoxesRecursively();
142 }
143
144 return entity;
145}
146
147
149
150
151QgsVectorLayerChunkLoaderFactory::QgsVectorLayerChunkLoaderFactory( const Qgs3DMapSettings &map, QgsVectorLayer *vl, QgsAbstract3DSymbol *symbol, int leafLevel, double zMin, double zMax )
152 : mMap( map )
153 , mLayer( vl )
154 , mSymbol( symbol->clone() )
155 , mLeafLevel( leafLevel )
156{
157 QgsAABB rootBbox = Qgs3DUtils::mapToWorldExtent( map.extent(), zMin, zMax, map.origin() );
158 // add small padding to avoid clipping of point features located at the edge of the bounding box
159 rootBbox.xMin -= 1.0;
160 rootBbox.xMax += 1.0;
161 rootBbox.yMin -= 1.0;
162 rootBbox.yMax += 1.0;
163 rootBbox.zMin -= 1.0;
164 rootBbox.zMax += 1.0;
165 setupQuadtree( rootBbox, -1, leafLevel ); // negative root error means that the node does not contain anything
166}
167
168QgsChunkLoader *QgsVectorLayerChunkLoaderFactory::createChunkLoader( QgsChunkNode *node ) const
169{
170 return new QgsVectorLayerChunkLoader( this, node );
171}
172
173
175
176
177QgsVectorLayerChunkedEntity::QgsVectorLayerChunkedEntity( QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsAbstract3DSymbol *symbol, const Qgs3DMapSettings &map )
178 : QgsChunkedEntity( -1, // max. allowed screen error (negative tau means that we need to go until leaves are reached)
179 new QgsVectorLayerChunkLoaderFactory( map, vl, symbol, tilingSettings.zoomLevelsCount() - 1, zMin, zMax ), true )
180{
181 mTransform = new Qt3DCore::QTransform;
182 mTransform->setTranslation( QVector3D( 0.0f, map.terrainElevationOffset(), 0.0f ) );
183 this->addComponent( mTransform );
184
185 connect( &map, &Qgs3DMapSettings::terrainElevationOffsetChanged, this, &QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged );
186
187 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
188}
189
190QgsVectorLayerChunkedEntity::~QgsVectorLayerChunkedEntity()
191{
192 // cancel / wait for jobs
193 cancelActiveJobs();
194}
195
196void QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged( float newOffset )
197{
198 QgsDebugMsgLevel( QStringLiteral( "QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged" ), 2 );
199 mTransform->setTranslation( QVector3D( 0.0f, newOffset, 0.0f ) );
200}
201
202QVector<QgsRayCastingUtils::RayHit> QgsVectorLayerChunkedEntity::rayIntersection( const QgsRayCastingUtils::Ray3D &ray, const QgsRayCastingUtils::RayCastContext &context ) const
203{
204 return QgsVectorLayerChunkedEntity::rayIntersection( activeNodes(), mTransform->matrix(), ray, context );
205}
206
207QVector<QgsRayCastingUtils::RayHit> QgsVectorLayerChunkedEntity::rayIntersection( const QList<QgsChunkNode *> &activeNodes, const QMatrix4x4 &transformMatrix, const QgsRayCastingUtils::Ray3D &ray, const QgsRayCastingUtils::RayCastContext &context )
208{
209 Q_UNUSED( context )
210 QgsDebugMsgLevel( QStringLiteral( "Ray cast on vector layer" ), 2 );
211#ifdef QGISDEBUG
212 int nodeUsed = 0;
213 int nodesAll = 0;
214 int hits = 0;
215 int ignoredGeometries = 0;
216#endif
217 QVector<QgsRayCastingUtils::RayHit> result;
218
219 float minDist = -1;
220 QVector3D intersectionPoint;
221 QgsFeatureId nearestFid = FID_NULL;
222
223 for ( QgsChunkNode *node : activeNodes )
224 {
225#ifdef QGISDEBUG
226 nodesAll++;
227#endif
228 if ( node->entity() &&
229 ( minDist < 0 || node->bbox().distanceFromPoint( ray.origin() ) < minDist ) &&
230 QgsRayCastingUtils::rayBoxIntersection( ray, node->bbox() ) )
231 {
232#ifdef QGISDEBUG
233 nodeUsed++;
234#endif
235 const QList<Qt3DRender::QGeometryRenderer *> rendLst = node->entity()->findChildren<Qt3DRender::QGeometryRenderer *>();
236 for ( const auto &rend : rendLst )
237 {
238 auto *geom = rend->geometry();
239 QgsTessellatedPolygonGeometry *polygonGeom = qobject_cast<QgsTessellatedPolygonGeometry *>( geom );
240 if ( !polygonGeom )
241 {
242#ifdef QGISDEBUG
243 ignoredGeometries++;
244#endif
245 continue; // other QGeometry types are not supported for now
246 }
247
248 QVector3D nodeIntPoint;
250 if ( polygonGeom->rayIntersection( ray, transformMatrix, nodeIntPoint, fid ) )
251 {
252#ifdef QGISDEBUG
253 hits++;
254#endif
255 float dist = ( ray.origin() - nodeIntPoint ).length();
256 if ( minDist < 0 || dist < minDist )
257 {
258 minDist = dist;
259 intersectionPoint = nodeIntPoint;
260 nearestFid = fid;
261 }
262 }
263 }
264 }
265 }
266 if ( !FID_IS_NULL( nearestFid ) )
267 {
268 QgsRayCastingUtils::RayHit hit( minDist, intersectionPoint, nearestFid );
269 result.append( hit );
270 }
271 QgsDebugMsgLevel( QStringLiteral( "Active Nodes: %1, checked nodes: %2, hits found: %3, incompatible geometries: %4" ).arg( nodesAll ).arg( nodeUsed ).arg( hits ).arg( ignoredGeometries ), 2 );
272 return result;
273}
274
QgsRectangle extent() const
Returns the 3D scene's 2D extent in project's CRS.
float terrainElevationOffset() const
Returns the elevation offset of the terrain (used to move the terrain up or down)
void terrainElevationOffsetChanged(float newElevation)
Emitted when the terrain elevation offset is changed.
QgsCoordinateReferenceSystem crs() const
Returns coordinate reference system used in the 3D scene.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
QgsVector3D origin() const
Returns coordinates in map CRS at which 3D scene has origin (0,0,0)
QgsFeature3DHandler * createHandlerForSymbol(QgsVectorLayer *layer, const QgsAbstract3DSymbol *symbol)
Creates a feature handler for a symbol, for the specified vector layer.
static QgsRectangle worldToMapExtent(const QgsAABB &bbox, const QgsVector3D &mapOrigin)
Converts axis aligned bounding box in 3D world coordinates to extent in map coordinates.
Definition: qgs3dutils.cpp:610
static QgsAABB mapToWorldExtent(const QgsRectangle &extent, double zMin, double zMax, const QgsVector3D &mapOrigin)
Converts map extent to axis aligned bounding box in 3D world coordinates.
Definition: qgs3dutils.cpp:599
static QgsExpressionContext globalProjectLayerExpressionContext(QgsVectorLayer *layer)
Returns expression context for use in preparation of 3D data of a layer.
Definition: qgs3dutils.cpp:673
3
Definition: qgsaabb.h:34
float yMax
Definition: qgsaabb.h:88
float xMax
Definition: qgsaabb.h:87
float xMin
Definition: qgsaabb.h:84
float zMax
Definition: qgsaabb.h:89
float yMin
Definition: qgsaabb.h:85
float zMin
Definition: qgsaabb.h:86
static Qgs3DSymbolRegistry * symbol3DRegistry()
Returns registry of available 3D symbols.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
A rectangle specified with double values.
Definition: qgsrectangle.h:42
bool rayIntersection(const QgsRayCastingUtils::Ray3D &ray, const QMatrix4x4 &worldTransform, QVector3D &intersectionPoint, QgsFeatureId &fid)
Tests whether the geometry is intersected by ray.
bool showBoundingBoxes() const
Returns whether to display bounding boxes of entity's tiles (for debugging)
Partial snapshot of vector layer's state (only the members necessary for access to features)
Represents a vector layer which manages a vector based data sets.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
#define FID_NULL
Definition: qgsfeatureid.h:29
#define FID_IS_NULL(fid)
Definition: qgsfeatureid.h:30
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
#define QgsDebugError(str)
Definition: qgslogger.h:38