QGIS API Documentation 3.40.0-Bratislava (b56115d8743)
Loading...
Searching...
No Matches
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"
18#include "qgsline3dsymbol.h"
19#include "qgspoint3dsymbol.h"
20#include "qgspolygon3dsymbol.h"
24#include "qgschunknode.h"
25#include "qgseventtracing.h"
26#include "qgslogger.h"
27#include "qgsvectorlayer.h"
29#include "qgsapplication.h"
30#include "qgs3dsymbolregistry.h"
31#include "qgsabstract3dsymbol.h"
32
33#include <QtConcurrent>
34#include <Qt3DCore/QTransform>
35
37
38
39QgsVectorLayerChunkLoader::QgsVectorLayerChunkLoader( const QgsVectorLayerChunkLoaderFactory *factory, QgsChunkNode *node )
40 : QgsChunkLoader( node )
41 , mFactory( factory )
42 , mRenderContext( factory->mRenderContext )
43 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
44{
45 if ( node->level() < mFactory->mLeafLevel )
46 {
47 QTimer::singleShot( 0, this, &QgsVectorLayerChunkLoader::finished );
48 return;
49 }
50
51 QgsVectorLayer *layer = mFactory->mLayer;
52 mLayerName = mFactory->mLayer->name();
53
54 QgsFeature3DHandler *handler = QgsApplication::symbol3DRegistry()->createHandlerForSymbol( layer, mFactory->mSymbol.get() );
55 if ( !handler )
56 {
57 QgsDebugError( QStringLiteral( "Unknown 3D symbol type for vector layer: " ) + mFactory->mSymbol->type() );
58 return;
59 }
60 mHandler.reset( handler );
61
63 exprContext.setFields( layer->fields() );
64 mRenderContext.setExpressionContext( exprContext );
65
66 QSet<QString> attributeNames;
67 if ( !mHandler->prepare( mRenderContext, attributeNames ) )
68 {
69 QgsDebugError( QStringLiteral( "Failed to prepare 3D feature handler!" ) );
70 return;
71 }
72
73 // build the feature request
76 QgsCoordinateTransform( layer->crs3D(), mRenderContext.crs(), mRenderContext.transformContext() )
77 );
78 req.setSubsetOfAttributes( attributeNames, layer->fields() );
79
80 // only a subset of data to be queried
81 const QgsRectangle rect = Qgs3DUtils::worldToMapExtent( node->bbox(), mRenderContext.origin() );
82 req.setFilterRect( rect );
83
84 //
85 // this will be run in a background thread
86 //
87 mFutureWatcher = new QFutureWatcher<void>( this );
88 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
89
90 const QFuture<void> future = QtConcurrent::run( [req, this]
91 {
92 const QgsEventTracing::ScopedEvent e( QStringLiteral( "3D" ), QStringLiteral( "VL chunk load" ) );
93
94 QgsFeature f;
95 QgsFeatureIterator fi = mSource->getFeatures( req );
96 while ( fi.nextFeature( f ) )
97 {
98 if ( mCanceled )
99 break;
100 mRenderContext.expressionContext().setFeature( f );
101 mHandler->processFeature( f, mRenderContext );
102 }
103 } );
104
105 // emit finished() as soon as the handler is populated with features
106 mFutureWatcher->setFuture( future );
107}
108
109QgsVectorLayerChunkLoader::~QgsVectorLayerChunkLoader()
110{
111 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
112 {
113 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
114 mFutureWatcher->waitForFinished();
115 }
116}
117
118void QgsVectorLayerChunkLoader::cancel()
119{
120 mCanceled = true;
121}
122
123Qt3DCore::QEntity *QgsVectorLayerChunkLoader::createEntity( Qt3DCore::QEntity *parent )
124{
125 if ( mNode->level() < mFactory->mLeafLevel )
126 {
127 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent ); // dummy entity
128 entity->setObjectName( mLayerName + "_CONTAINER_" + mNode->tileId().text() );
129 return entity;
130 }
131
132 if ( mHandler->featureCount() == 0 )
133 {
134 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
135 // we just make sure first that its initial estimated vertical range does not affect its parents' bboxes calculation
136 mNode->setExactBbox( QgsAABB() );
137 mNode->updateParentBoundingBoxesRecursively();
138 return nullptr;
139 }
140
141 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
142 entity->setObjectName( mLayerName + "_" + mNode->tileId().text() );
143 mHandler->finalize( entity, mRenderContext );
144
145 // fix the vertical range of the node from the estimated vertical range to the true range
146 if ( mHandler->zMinimum() != std::numeric_limits<float>::max() && mHandler->zMaximum() != std::numeric_limits<float>::lowest() )
147 {
148 QgsAABB box = mNode->bbox();
149 box.yMin = mHandler->zMinimum();
150 box.yMax = mHandler->zMaximum();
151 mNode->setExactBbox( box );
152 mNode->updateParentBoundingBoxesRecursively();
153 }
154
155 return entity;
156}
157
158
160
161
162QgsVectorLayerChunkLoaderFactory::QgsVectorLayerChunkLoaderFactory( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsAbstract3DSymbol *symbol, int leafLevel, double zMin, double zMax )
163 : mRenderContext( context )
164 , mLayer( vl )
165 , mSymbol( symbol->clone() )
166 , mLeafLevel( leafLevel )
167{
168 QgsAABB rootBbox = Qgs3DUtils::mapToWorldExtent( context.extent(), zMin, zMax, context.origin() );
169 // add small padding to avoid clipping of point features located at the edge of the bounding box
170 rootBbox.xMin -= 1.0;
171 rootBbox.xMax += 1.0;
172 rootBbox.yMin -= 1.0;
173 rootBbox.yMax += 1.0;
174 rootBbox.zMin -= 1.0;
175 rootBbox.zMax += 1.0;
176 setupQuadtree( rootBbox, -1, leafLevel ); // negative root error means that the node does not contain anything
177}
178
179QgsChunkLoader *QgsVectorLayerChunkLoaderFactory::createChunkLoader( QgsChunkNode *node ) const
180{
181 return new QgsVectorLayerChunkLoader( this, node );
182}
183
184
186
187
188QgsVectorLayerChunkedEntity::QgsVectorLayerChunkedEntity( Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsAbstract3DSymbol *symbol )
189 : QgsChunkedEntity( map,
190 -1, // max. allowed screen error (negative tau means that we need to go until leaves are reached)
191 new QgsVectorLayerChunkLoaderFactory( Qgs3DRenderContext::fromMapSettings( map ), vl, symbol, tilingSettings.zoomLevelsCount() - 1, zMin, zMax ), true )
192{
193 mTransform = new Qt3DCore::QTransform;
194 if ( applyTerrainOffset() )
195 {
196 mTransform->setTranslation( QVector3D( 0.0f, map->terrainElevationOffset(), 0.0f ) );
197 }
198 this->addComponent( mTransform );
199
200 connect( map, &Qgs3DMapSettings::terrainElevationOffsetChanged, this, &QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged );
201
202 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
203}
204
205QgsVectorLayerChunkedEntity::~QgsVectorLayerChunkedEntity()
206{
207 // cancel / wait for jobs
208 cancelActiveJobs();
209}
210
211// if the AltitudeClamping is `Absolute`, do not apply the offset
212bool QgsVectorLayerChunkedEntity::applyTerrainOffset() const
213{
214 QgsVectorLayerChunkLoaderFactory *loaderFactory = static_cast<QgsVectorLayerChunkLoaderFactory *>( mChunkLoaderFactory );
215 if ( loaderFactory )
216 {
217 QString symbolType = loaderFactory->mSymbol.get()->type();
218 if ( symbolType == "line" )
219 {
220 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( loaderFactory->mSymbol.get() );
221 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
222 {
223 return false;
224 }
225 }
226 else if ( symbolType == "point" )
227 {
228 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( loaderFactory->mSymbol.get() );
229 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
230 {
231 return false;
232 }
233 }
234 else if ( symbolType == "polygon" )
235 {
236 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( loaderFactory->mSymbol.get() );
237 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
238 {
239 return false;
240 }
241 }
242 else
243 {
244 QgsDebugMsgLevel( QStringLiteral( "QgsVectorLayerChunkedEntity::applyTerrainOffset, unhandled symbol type %1" ).arg( symbolType ), 2 );
245 }
246 }
247
248 return true;
249}
250
251void QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged( float newOffset )
252{
253 QgsDebugMsgLevel( QStringLiteral( "QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged" ), 2 );
254 if ( !applyTerrainOffset() )
255 {
256 newOffset = 0.0;
257 }
258 mTransform->setTranslation( QVector3D( 0.0f, newOffset, 0.0f ) );
259}
260
261QVector<QgsRayCastingUtils::RayHit> QgsVectorLayerChunkedEntity::rayIntersection( const QgsRayCastingUtils::Ray3D &ray, const QgsRayCastingUtils::RayCastContext &context ) const
262{
263 return QgsVectorLayerChunkedEntity::rayIntersection( activeNodes(), mTransform->matrix(), ray, context );
264}
265
266QVector<QgsRayCastingUtils::RayHit> QgsVectorLayerChunkedEntity::rayIntersection( const QList<QgsChunkNode *> &activeNodes, const QMatrix4x4 &transformMatrix, const QgsRayCastingUtils::Ray3D &ray, const QgsRayCastingUtils::RayCastContext &context )
267{
268 Q_UNUSED( context )
269 QgsDebugMsgLevel( QStringLiteral( "Ray cast on vector layer" ), 2 );
270#ifdef QGISDEBUG
271 int nodeUsed = 0;
272 int nodesAll = 0;
273 int hits = 0;
274 int ignoredGeometries = 0;
275#endif
276 QVector<QgsRayCastingUtils::RayHit> result;
277
278 float minDist = -1;
279 QVector3D intersectionPoint;
280 QgsFeatureId nearestFid = FID_NULL;
281
282 for ( QgsChunkNode *node : activeNodes )
283 {
284#ifdef QGISDEBUG
285 nodesAll++;
286#endif
287 if ( node->entity() &&
288 ( minDist < 0 || node->bbox().distanceFromPoint( ray.origin() ) < minDist ) &&
289 QgsRayCastingUtils::rayBoxIntersection( ray, node->bbox() ) )
290 {
291#ifdef QGISDEBUG
292 nodeUsed++;
293#endif
294 const QList<Qt3DRender::QGeometryRenderer *> rendLst = node->entity()->findChildren<Qt3DRender::QGeometryRenderer *>();
295 for ( const auto &rend : rendLst )
296 {
297 auto *geom = rend->geometry();
298 QgsTessellatedPolygonGeometry *polygonGeom = qobject_cast<QgsTessellatedPolygonGeometry *>( geom );
299 if ( !polygonGeom )
300 {
301#ifdef QGISDEBUG
302 ignoredGeometries++;
303#endif
304 continue; // other QGeometry types are not supported for now
305 }
306
307 QVector3D nodeIntPoint;
308 int triangleIndex = -1;
309
310 if ( QgsRayCastingUtils::rayMeshIntersection( rend, ray, transformMatrix, nodeIntPoint, triangleIndex ) )
311 {
312#ifdef QGISDEBUG
313 hits++;
314#endif
315 float dist = ( ray.origin() - nodeIntPoint ).length();
316 if ( minDist < 0 || dist < minDist )
317 {
318 minDist = dist;
319 intersectionPoint = nodeIntPoint;
320 nearestFid = polygonGeom->triangleIndexToFeatureId( triangleIndex );
321 }
322 }
323 }
324 }
325 }
326 if ( !FID_IS_NULL( nearestFid ) )
327 {
328 QgsRayCastingUtils::RayHit hit( minDist, intersectionPoint, nearestFid );
329 result.append( hit );
330 }
331 QgsDebugMsgLevel( QStringLiteral( "Active Nodes: %1, checked nodes: %2, hits found: %3, incompatible geometries: %4" ).arg( nodesAll ).arg( nodeUsed ).arg( hits ).arg( ignoredGeometries ), 2 );
332 return result;
333}
334
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
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.
QgsVector3D origin() const
Returns coordinates in map CRS at which 3D scene has origin (0,0,0)
QgsRectangle extent() const
Returns the 3D scene's 2D extent in the 3D scene's CRS.
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.
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.
static QgsExpressionContext globalProjectLayerExpressionContext(QgsVectorLayer *layer)
Returns expression context for use in preparation of 3D data of a layer.
float yMax
Definition qgsaabb.h:90
float xMax
Definition qgsaabb.h:89
float xMin
Definition qgsaabb.h:86
float zMax
Definition qgsaabb.h:91
float yMin
Definition qgsaabb.h:87
float zMin
Definition qgsaabb.h:88
static Qgs3DSymbolRegistry * symbol3DRegistry()
Returns registry of available 3D symbols.
Class for doing transforms between two map coordinate systems.
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)
Fetch next feature and stores in f, returns true on success.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setCoordinateTransform(const QgsCoordinateTransform &transform)
Sets the coordinate transform which will be used to transform the feature's geometries.
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
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:58
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain)
QString name
Definition qgsmaplayer.h:80
QgsCoordinateReferenceSystem crs3D
Definition qgsmaplayer.h:85
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain)
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain)
A rectangle specified with double values.
QgsFeatureId triangleIndexToFeatureId(uint triangleIndex) const
Returns ID of the feature to which given triangle index belongs (used for picking).
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.
#define FID_NULL
#define FID_IS_NULL(fid)
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
#define QgsDebugError(str)
Definition qgslogger.h:38
Helper struct to store ray casting parameters.
Helper struct to store ray casting results.