QGIS API Documentation 3.41.0-Master (af5edcb665c)
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 "moc_qgsvectorlayerchunkloader_p.cpp"
18#include "qgs3dutils.h"
19#include "qgsline3dsymbol.h"
20#include "qgspoint3dsymbol.h"
21#include "qgspolygon3dsymbol.h"
25#include "qgschunknode.h"
26#include "qgseventtracing.h"
27#include "qgslogger.h"
28#include "qgsvectorlayer.h"
30#include "qgsapplication.h"
31#include "qgs3dsymbolregistry.h"
32#include "qgsabstract3dsymbol.h"
34
35#include <QtConcurrent>
36#include <Qt3DCore/QTransform>
37
39
40
41QgsVectorLayerChunkLoader::QgsVectorLayerChunkLoader( const QgsVectorLayerChunkLoaderFactory *factory, QgsChunkNode *node )
42 : QgsChunkLoader( node )
43 , mFactory( factory )
44 , mRenderContext( factory->mRenderContext )
45 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
46{
47 if ( node->level() < mFactory->mLeafLevel )
48 {
49 QTimer::singleShot( 0, this, &QgsVectorLayerChunkLoader::finished );
50 return;
51 }
52
53 QgsVectorLayer *layer = mFactory->mLayer;
54 mLayerName = mFactory->mLayer->name();
55
56 QgsFeature3DHandler *handler = QgsApplication::symbol3DRegistry()->createHandlerForSymbol( layer, mFactory->mSymbol.get() );
57 if ( !handler )
58 {
59 QgsDebugError( QStringLiteral( "Unknown 3D symbol type for vector layer: " ) + mFactory->mSymbol->type() );
60 return;
61 }
62 mHandler.reset( handler );
63
64 // only a subset of data to be queried
65 const QgsRectangle rect = node->box3D().toRectangle();
66 // origin for coordinates of the chunk - it is kind of arbitrary, but it should be
67 // picked so that the coordinates are relatively small to avoid numerical precision issues
68 QgsVector3D chunkOrigin( rect.center().x(), rect.center().y(), 0 );
69
71 exprContext.setFields( layer->fields() );
72 mRenderContext.setExpressionContext( exprContext );
73
74 QSet<QString> attributeNames;
75 if ( !mHandler->prepare( mRenderContext, attributeNames, chunkOrigin ) )
76 {
77 QgsDebugError( QStringLiteral( "Failed to prepare 3D feature handler!" ) );
78 return;
79 }
80
81 // build the feature request
84 QgsCoordinateTransform( layer->crs3D(), mRenderContext.crs(), mRenderContext.transformContext() )
85 );
86 req.setSubsetOfAttributes( attributeNames, layer->fields() );
87 req.setFilterRect( rect );
88
89 //
90 // this will be run in a background thread
91 //
92 mFutureWatcher = new QFutureWatcher<void>( this );
93 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
94
95 const QFuture<void> future = QtConcurrent::run( [req, this] {
96 const QgsEventTracing::ScopedEvent e( QStringLiteral( "3D" ), QStringLiteral( "VL chunk load" ) );
97
98 QgsFeature f;
99 QgsFeatureIterator fi = mSource->getFeatures( req );
100 while ( fi.nextFeature( f ) )
101 {
102 if ( mCanceled )
103 break;
104 mRenderContext.expressionContext().setFeature( f );
105 mHandler->processFeature( f, mRenderContext );
106 }
107 } );
108
109 // emit finished() as soon as the handler is populated with features
110 mFutureWatcher->setFuture( future );
111}
112
113QgsVectorLayerChunkLoader::~QgsVectorLayerChunkLoader()
114{
115 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
116 {
117 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
118 mFutureWatcher->waitForFinished();
119 }
120}
121
122void QgsVectorLayerChunkLoader::cancel()
123{
124 mCanceled = true;
125}
126
127Qt3DCore::QEntity *QgsVectorLayerChunkLoader::createEntity( Qt3DCore::QEntity *parent )
128{
129 if ( mNode->level() < mFactory->mLeafLevel )
130 {
131 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent ); // dummy entity
132 entity->setObjectName( mLayerName + "_CONTAINER_" + mNode->tileId().text() );
133 return entity;
134 }
135
136 if ( mHandler->featureCount() == 0 )
137 {
138 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
139 // we just make sure first that its initial estimated vertical range does not affect its parents' bboxes calculation
140 mNode->setExactBox3D( QgsBox3D() );
141 mNode->updateParentBoundingBoxesRecursively();
142 return nullptr;
143 }
144
145 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
146 entity->setObjectName( mLayerName + "_" + mNode->tileId().text() );
147 mHandler->finalize( entity, mRenderContext );
148
149 // fix the vertical range of the node from the estimated vertical range to the true range
150 if ( mHandler->zMinimum() != std::numeric_limits<float>::max() && mHandler->zMaximum() != std::numeric_limits<float>::lowest() )
151 {
152 QgsBox3D box = mNode->box3D();
153 box.setZMinimum( mHandler->zMinimum() );
154 box.setZMaximum( mHandler->zMaximum() );
155 mNode->setExactBox3D( box );
156 mNode->updateParentBoundingBoxesRecursively();
157 }
158
159 return entity;
160}
161
162
164
165
166QgsVectorLayerChunkLoaderFactory::QgsVectorLayerChunkLoaderFactory( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsAbstract3DSymbol *symbol, int leafLevel, double zMin, double zMax )
167 : mRenderContext( context )
168 , mLayer( vl )
169 , mSymbol( symbol->clone() )
170 , mLeafLevel( leafLevel )
171{
172 QgsBox3D rootBox3D( context.extent(), zMin, zMax );
173 // add small padding to avoid clipping of point features located at the edge of the bounding box
174 rootBox3D.grow( 1.0 );
175 setupQuadtree( rootBox3D, -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( Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsAbstract3DSymbol *symbol )
188 : QgsChunkedEntity( map,
189 -1, // max. allowed screen error (negative tau means that we need to go until leaves are reached)
190 new QgsVectorLayerChunkLoaderFactory( Qgs3DRenderContext::fromMapSettings( map ), vl, symbol, tilingSettings.zoomLevelsCount() - 1, zMin, zMax ), true )
191{
192 mTransform = new Qt3DCore::QTransform;
193 if ( applyTerrainOffset() )
194 {
195 mTransform->setTranslation( QVector3D( 0.0f, static_cast<float>( map->terrainSettings()->elevationOffset() ), 0.0f ) );
196 }
197 this->addComponent( mTransform );
198
199 connect( map, &Qgs3DMapSettings::terrainSettingsChanged, this, &QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged );
200
201 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
202}
203
204QgsVectorLayerChunkedEntity::~QgsVectorLayerChunkedEntity()
205{
206 // cancel / wait for jobs
207 cancelActiveJobs();
208}
209
210// if the AltitudeClamping is `Absolute`, do not apply the offset
211bool QgsVectorLayerChunkedEntity::applyTerrainOffset() const
212{
213 QgsVectorLayerChunkLoaderFactory *loaderFactory = static_cast<QgsVectorLayerChunkLoaderFactory *>( mChunkLoaderFactory );
214 if ( loaderFactory )
215 {
216 QString symbolType = loaderFactory->mSymbol.get()->type();
217 if ( symbolType == "line" )
218 {
219 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( loaderFactory->mSymbol.get() );
220 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
221 {
222 return false;
223 }
224 }
225 else if ( symbolType == "point" )
226 {
227 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( loaderFactory->mSymbol.get() );
228 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
229 {
230 return false;
231 }
232 }
233 else if ( symbolType == "polygon" )
234 {
235 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( loaderFactory->mSymbol.get() );
236 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
237 {
238 return false;
239 }
240 }
241 else
242 {
243 QgsDebugMsgLevel( QStringLiteral( "QgsVectorLayerChunkedEntity::applyTerrainOffset, unhandled symbol type %1" ).arg( symbolType ), 2 );
244 }
245 }
246
247 return true;
248}
249
250void QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged()
251{
252 QgsDebugMsgLevel( QStringLiteral( "QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged" ), 2 );
253 float newOffset = static_cast<float>( qobject_cast<Qgs3DMapSettings *>( sender() )->terrainSettings()->elevationOffset() );
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, mMapSettings->origin() );
264}
265
266QVector<QgsRayCastingUtils::RayHit> QgsVectorLayerChunkedEntity::rayIntersection( const QList<QgsChunkNode *> &activeNodes, const QMatrix4x4 &transformMatrix, const QgsRayCastingUtils::Ray3D &ray, const QgsRayCastingUtils::RayCastContext &context, const QgsVector3D &origin )
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
288 QgsAABB nodeBbox = Qgs3DUtils::mapToWorldExtent( node->box3D(), origin );
289
290 if ( node->entity() && ( minDist < 0 || nodeBbox.distanceFromPoint( ray.origin() ) < minDist ) && QgsRayCastingUtils::rayBoxIntersection( ray, nodeBbox ) )
291 {
292#ifdef QGISDEBUG
293 nodeUsed++;
294#endif
295 const QList<Qt3DRender::QGeometryRenderer *> rendLst = node->entity()->findChildren<Qt3DRender::QGeometryRenderer *>();
296 for ( const auto &rend : rendLst )
297 {
298 auto *geom = rend->geometry();
299 QgsTessellatedPolygonGeometry *polygonGeom = qobject_cast<QgsTessellatedPolygonGeometry *>( geom );
300 if ( !polygonGeom )
301 {
302#ifdef QGISDEBUG
303 ignoredGeometries++;
304#endif
305 continue; // other QGeometry types are not supported for now
306 }
307
308 QVector3D nodeIntPoint;
309 int triangleIndex = -1;
310
311 if ( QgsRayCastingUtils::rayMeshIntersection( rend, ray, transformMatrix, nodeIntPoint, triangleIndex ) )
312 {
313#ifdef QGISDEBUG
314 hits++;
315#endif
316 float dist = ( ray.origin() - nodeIntPoint ).length();
317 if ( minDist < 0 || dist < minDist )
318 {
319 minDist = dist;
320 intersectionPoint = nodeIntPoint;
321 nearestFid = polygonGeom->triangleIndexToFeatureId( triangleIndex );
322 }
323 }
324 }
325 }
326 }
327 if ( !FID_IS_NULL( nearestFid ) )
328 {
329 QgsRayCastingUtils::RayHit hit( minDist, intersectionPoint, nearestFid );
330 result.append( hit );
331 }
332 QgsDebugMsgLevel( QStringLiteral( "Active Nodes: %1, checked nodes: %2, hits found: %3, incompatible geometries: %4" ).arg( nodesAll ).arg( nodeUsed ).arg( hits ).arg( ignoredGeometries ), 2 );
333 return result;
334}
335
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
const QgsAbstractTerrainSettings * terrainSettings() const
Returns the terrain settings.
void terrainSettingsChanged()
Emitted when the terrain settings are changed.
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 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 distanceFromPoint(float x, float y, float z) const
Returns shortest distance from the box to a point.
Definition qgsaabb.cpp:46
double elevationOffset() const
Returns the elevation offset of the terrain (used to move the terrain up or down).
static Qgs3DSymbolRegistry * symbol3DRegistry()
Returns registry of available 3D symbols.
A 3-dimensional box composed of x, y, z coordinates.
Definition qgsbox3d.h:43
void setZMinimum(double z)
Sets the minimum z value.
Definition qgsbox3d.cpp:88
void setZMaximum(double z)
Sets the maximum z value.
Definition qgsbox3d.cpp:93
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)
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain)
A rectangle specified with double values.
QgsPointXY center
QgsFeatureId triangleIndexToFeatureId(uint triangleIndex) const
Returns ID of the feature to which given triangle index belongs (used for picking).
Class for storage of 3D vectors similar to QVector3D, with the difference that it uses double precisi...
Definition qgsvector3d.h:31
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.