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