QGIS API Documentation 3.43.0-Master (261ee7da134)
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 "qgsgeotransform.h"
20#include "qgsline3dsymbol.h"
21#include "qgspoint3dsymbol.h"
22#include "qgspolygon3dsymbol.h"
26#include "qgschunknode.h"
27#include "qgseventtracing.h"
28#include "qgslogger.h"
29#include "qgsvectorlayer.h"
31#include "qgsapplication.h"
32#include "qgs3dsymbolregistry.h"
33#include "qgsabstract3dsymbol.h"
35
36#include <QtConcurrent>
37#include <Qt3DCore/QTransform>
38
40
41
42QgsVectorLayerChunkLoader::QgsVectorLayerChunkLoader( const QgsVectorLayerChunkLoaderFactory *factory, QgsChunkNode *node )
43 : QgsChunkLoader( node )
44 , mFactory( factory )
45 , mRenderContext( factory->mRenderContext )
46 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
47{
48 if ( node->level() < mFactory->mLeafLevel )
49 {
50 QTimer::singleShot( 0, this, &QgsVectorLayerChunkLoader::finished );
51 return;
52 }
53
54 QgsVectorLayer *layer = mFactory->mLayer;
55 mLayerName = mFactory->mLayer->name();
56
57 QgsFeature3DHandler *handler = QgsApplication::symbol3DRegistry()->createHandlerForSymbol( layer, mFactory->mSymbol.get() );
58 if ( !handler )
59 {
60 QgsDebugError( QStringLiteral( "Unknown 3D symbol type for vector layer: " ) + mFactory->mSymbol->type() );
61 return;
62 }
63 mHandler.reset( handler );
64
65 // only a subset of data to be queried
66 const QgsRectangle rect = node->box3D().toRectangle();
67 // origin for coordinates of the chunk - it is kind of arbitrary, but it should be
68 // picked so that the coordinates are relatively small to avoid numerical precision issues
69 QgsVector3D chunkOrigin( rect.center().x(), rect.center().y(), 0 );
70
72 exprContext.setFields( layer->fields() );
73 mRenderContext.setExpressionContext( exprContext );
74
75 QSet<QString> attributeNames;
76 if ( !mHandler->prepare( mRenderContext, attributeNames, chunkOrigin ) )
77 {
78 QgsDebugError( QStringLiteral( "Failed to prepare 3D feature handler!" ) );
79 return;
80 }
81
82 // build the feature request
85 QgsCoordinateTransform( layer->crs3D(), mRenderContext.crs(), mRenderContext.transformContext() )
86 );
87 req.setSubsetOfAttributes( attributeNames, layer->fields() );
88 req.setFilterRect( rect );
89
90 //
91 // this will be run in a background thread
92 //
93 mFutureWatcher = new QFutureWatcher<void>( this );
94 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
95
96 const QFuture<void> future = QtConcurrent::run( [req, this] {
97 const QgsEventTracing::ScopedEvent e( QStringLiteral( "3D" ), QStringLiteral( "VL chunk load" ) );
98
99 QgsFeature f;
100 QgsFeatureIterator fi = mSource->getFeatures( req );
101 while ( fi.nextFeature( f ) )
102 {
103 if ( mCanceled )
104 break;
105 mRenderContext.expressionContext().setFeature( f );
106 mHandler->processFeature( f, mRenderContext );
107 }
108 } );
109
110 // emit finished() as soon as the handler is populated with features
111 mFutureWatcher->setFuture( future );
112}
113
114QgsVectorLayerChunkLoader::~QgsVectorLayerChunkLoader()
115{
116 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
117 {
118 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
119 mFutureWatcher->waitForFinished();
120 }
121}
122
123void QgsVectorLayerChunkLoader::cancel()
124{
125 mCanceled = true;
126}
127
128Qt3DCore::QEntity *QgsVectorLayerChunkLoader::createEntity( Qt3DCore::QEntity *parent )
129{
130 if ( mNode->level() < mFactory->mLeafLevel )
131 {
132 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent ); // dummy entity
133 entity->setObjectName( mLayerName + "_CONTAINER_" + mNode->tileId().text() );
134 return entity;
135 }
136
137 if ( mHandler->featureCount() == 0 )
138 {
139 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
140 // we just make sure first that its initial estimated vertical range does not affect its parents' bboxes calculation
141 mNode->setExactBox3D( QgsBox3D() );
142 mNode->updateParentBoundingBoxesRecursively();
143 return nullptr;
144 }
145
146 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
147 entity->setObjectName( mLayerName + "_" + mNode->tileId().text() );
148 mHandler->finalize( entity, mRenderContext );
149
150 // fix the vertical range of the node from the estimated vertical range to the true range
151 if ( mHandler->zMinimum() != std::numeric_limits<float>::max() && mHandler->zMaximum() != std::numeric_limits<float>::lowest() )
152 {
153 QgsBox3D box = mNode->box3D();
154 box.setZMinimum( mHandler->zMinimum() );
155 box.setZMaximum( mHandler->zMaximum() );
156 mNode->setExactBox3D( box );
157 mNode->updateParentBoundingBoxesRecursively();
158 }
159
160 return entity;
161}
162
163
165
166
167QgsVectorLayerChunkLoaderFactory::QgsVectorLayerChunkLoaderFactory( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsAbstract3DSymbol *symbol, int leafLevel, double zMin, double zMax )
168 : mRenderContext( context )
169 , mLayer( vl )
170 , mSymbol( symbol->clone() )
171 , mLeafLevel( leafLevel )
172{
173 if ( context.crs().type() == Qgis::CrsType::Geocentric )
174 {
175 // TODO: add support for handling of vector layers
176 // (we're using dummy quadtree here to make sure the empty extent does not break the scene completely)
177 QgsDebugError( QStringLiteral( "Vector layers in globe scenes are not supported yet!" ) );
178 setupQuadtree( QgsBox3D( -1e7, -1e7, -1e7, 1e7, 1e7, 1e7 ), -1, leafLevel );
179 return;
180 }
181
182 QgsBox3D rootBox3D( context.extent(), zMin, zMax );
183 // add small padding to avoid clipping of point features located at the edge of the bounding box
184 rootBox3D.grow( 1.0 );
185 setupQuadtree( rootBox3D, -1, leafLevel ); // negative root error means that the node does not contain anything
186}
187
188QgsChunkLoader *QgsVectorLayerChunkLoaderFactory::createChunkLoader( QgsChunkNode *node ) const
189{
190 return new QgsVectorLayerChunkLoader( this, node );
191}
192
193
195
196
197QgsVectorLayerChunkedEntity::QgsVectorLayerChunkedEntity( Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsAbstract3DSymbol *symbol )
198 : QgsChunkedEntity( map,
199 -1, // max. allowed screen error (negative tau means that we need to go until leaves are reached)
200 new QgsVectorLayerChunkLoaderFactory( Qgs3DRenderContext::fromMapSettings( map ), vl, symbol, tilingSettings.zoomLevelsCount() - 1, zMin, zMax ), true )
201{
202 mTransform = new Qt3DCore::QTransform;
203 if ( applyTerrainOffset() )
204 {
205 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, static_cast<float>( map->terrainSettings()->elevationOffset() ) ) );
206 }
207 this->addComponent( mTransform );
208
209 connect( map, &Qgs3DMapSettings::terrainSettingsChanged, this, &QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged );
210
211 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
212}
213
214QgsVectorLayerChunkedEntity::~QgsVectorLayerChunkedEntity()
215{
216 // cancel / wait for jobs
217 cancelActiveJobs();
218}
219
220// if the AltitudeClamping is `Absolute`, do not apply the offset
221bool QgsVectorLayerChunkedEntity::applyTerrainOffset() const
222{
223 QgsVectorLayerChunkLoaderFactory *loaderFactory = static_cast<QgsVectorLayerChunkLoaderFactory *>( mChunkLoaderFactory );
224 if ( loaderFactory )
225 {
226 QString symbolType = loaderFactory->mSymbol.get()->type();
227 if ( symbolType == "line" )
228 {
229 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( loaderFactory->mSymbol.get() );
230 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
231 {
232 return false;
233 }
234 }
235 else if ( symbolType == "point" )
236 {
237 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( loaderFactory->mSymbol.get() );
238 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
239 {
240 return false;
241 }
242 }
243 else if ( symbolType == "polygon" )
244 {
245 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( loaderFactory->mSymbol.get() );
246 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
247 {
248 return false;
249 }
250 }
251 else
252 {
253 QgsDebugMsgLevel( QStringLiteral( "QgsVectorLayerChunkedEntity::applyTerrainOffset, unhandled symbol type %1" ).arg( symbolType ), 2 );
254 }
255 }
256
257 return true;
258}
259
260void QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged()
261{
262 QgsDebugMsgLevel( QStringLiteral( "QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged" ), 2 );
263 float newOffset = static_cast<float>( qobject_cast<Qgs3DMapSettings *>( sender() )->terrainSettings()->elevationOffset() );
264 if ( !applyTerrainOffset() )
265 {
266 newOffset = 0.0;
267 }
268 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, newOffset ) );
269}
270
271QVector<QgsRayCastingUtils::RayHit> QgsVectorLayerChunkedEntity::rayIntersection( const QgsRayCastingUtils::Ray3D &ray, const QgsRayCastingUtils::RayCastContext &context ) const
272{
273 return QgsVectorLayerChunkedEntity::rayIntersection( activeNodes(), mTransform->matrix(), ray, context, mMapSettings->origin() );
274}
275
276QVector<QgsRayCastingUtils::RayHit> QgsVectorLayerChunkedEntity::rayIntersection( const QList<QgsChunkNode *> &activeNodes, const QMatrix4x4 &transformMatrix, const QgsRayCastingUtils::Ray3D &ray, const QgsRayCastingUtils::RayCastContext &context, const QgsVector3D &origin )
277{
278 Q_UNUSED( context )
279 QgsDebugMsgLevel( QStringLiteral( "Ray cast on vector layer" ), 2 );
280#ifdef QGISDEBUG
281 int nodeUsed = 0;
282 int nodesAll = 0;
283 int hits = 0;
284 int ignoredGeometries = 0;
285#endif
286 QVector<QgsRayCastingUtils::RayHit> result;
287
288 float minDist = -1;
289 QVector3D intersectionPoint;
290 QgsFeatureId nearestFid = FID_NULL;
291
292 for ( QgsChunkNode *node : activeNodes )
293 {
294#ifdef QGISDEBUG
295 nodesAll++;
296#endif
297
298 QgsAABB nodeBbox = Qgs3DUtils::mapToWorldExtent( node->box3D(), origin );
299
300 if ( node->entity() && ( minDist < 0 || nodeBbox.distanceFromPoint( ray.origin() ) < minDist ) && QgsRayCastingUtils::rayBoxIntersection( ray, nodeBbox ) )
301 {
302#ifdef QGISDEBUG
303 nodeUsed++;
304#endif
305 const QList<Qt3DRender::QGeometryRenderer *> rendLst = node->entity()->findChildren<Qt3DRender::QGeometryRenderer *>();
306 for ( const auto &rend : rendLst )
307 {
308 auto *geom = rend->geometry();
309 QgsTessellatedPolygonGeometry *polygonGeom = qobject_cast<QgsTessellatedPolygonGeometry *>( geom );
310 if ( !polygonGeom )
311 {
312#ifdef QGISDEBUG
313 ignoredGeometries++;
314#endif
315 continue; // other QGeometry types are not supported for now
316 }
317
318 QVector3D nodeIntPoint;
319 int triangleIndex = -1;
320
321 // the node geometry has been translated by chunkOrigin
322 // This translation is stored in the QTransform component
323 // this needs to be taken into account to get the whole transformation
324 const QMatrix4x4 nodeTransformMatrix = node->entity()->findChild<QgsGeoTransform *>()->matrix();
325 const QMatrix4x4 fullTransformMatrix = transformMatrix * nodeTransformMatrix;
326 if ( QgsRayCastingUtils::rayMeshIntersection( rend, ray, fullTransformMatrix, nodeIntPoint, triangleIndex ) )
327 {
328#ifdef QGISDEBUG
329 hits++;
330#endif
331 float dist = ( ray.origin() - nodeIntPoint ).length();
332 if ( minDist < 0 || dist < minDist )
333 {
334 minDist = dist;
335 intersectionPoint = nodeIntPoint;
336 nearestFid = polygonGeom->triangleIndexToFeatureId( triangleIndex );
337 }
338 }
339 }
340 }
341 }
342 if ( !FID_IS_NULL( nearestFid ) )
343 {
344 QgsRayCastingUtils::RayHit hit( minDist, intersectionPoint, nearestFid );
345 result.append( hit );
346 }
347 QgsDebugMsgLevel( QStringLiteral( "Active Nodes: %1, checked nodes: %2, hits found: %3, incompatible geometries: %4" ).arg( nodesAll ).arg( nodeUsed ).arg( hits ).arg( ignoredGeometries ), 2 );
348 return result;
349}
350
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
@ Geocentric
Geocentric CRS.
Definition of the world.
const QgsAbstractTerrainSettings * terrainSettings() const
Returns the terrain settings.
void terrainSettingsChanged()
Emitted when the terrain settings are changed.
Rendering context for preparation of 3D entities.
QgsCoordinateReferenceSystem crs() const
Returns the coordinate reference system used in the 3D scene.
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.
Axis-aligned bounding box - in world coords.
Definition qgsaabb.h:35
float distanceFromPoint(float x, float y, float z) const
Returns shortest distance from the box to a point.
Definition qgsaabb.cpp:46
Abstract base class for 3D symbols that are used by VectorLayer3DRenderer objects.
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
Qgis::CrsType type() const
Returns the type of the CRS.
Handles coordinate transforms between two 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.
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
3D symbol that draws linestring geometries as planar polygons (created from lines using a buffer with...
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain)
QString name
Definition qgsmaplayer.h:81
QgsCoordinateReferenceSystem crs3D
Definition qgsmaplayer.h:86
3D symbol that draws point geometries as 3D objects using one of the predefined shapes.
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
3D symbol that draws polygon geometries as planar polygons, optionally extruded (with added walls).
Qgis::AltitudeClamping altitudeClamping() const
Returns method that determines altitude (whether to clamp to feature to terrain)
A rectangle specified with double values.
QgsPointXY center
Qt3DRender::QGeometry subclass that represents polygons tessellated into 3D geometry.
QgsFeatureId triangleIndexToFeatureId(uint triangleIndex) const
Returns ID of the feature to which given triangle index belongs (used for picking).
A 3D vector (similar to QVector3D) with the difference that it uses double precision instead of singl...
Definition qgsvector3d.h:30
Defines configuration of how a vector layer gets tiled for 3D rendering.
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 dataset.
#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:41
#define QgsDebugError(str)
Definition qgslogger.h:40
Helper struct to store ray casting parameters.
Helper struct to store ray casting results.