QGIS API Documentation 3.99.0-Master (d270888f95f)
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
18#include "qgs3dsymbolregistry.h"
19#include "qgs3dutils.h"
20#include "qgsabstract3dsymbol.h"
23#include "qgsapplication.h"
24#include "qgschunknode.h"
25#include "qgseventtracing.h"
28#include "qgsgeotransform.h"
29#include "qgsline3dsymbol.h"
30#include "qgslogger.h"
31#include "qgspoint3dsymbol.h"
32#include "qgspolygon3dsymbol.h"
33#include "qgsray3d.h"
34#include "qgsraycastcontext.h"
35#include "qgsraycastingutils.h"
37#include "qgsvectorlayer.h"
39
40#include <QString>
41#include <Qt3DCore/QTransform>
42#include <QtConcurrent>
43
44#include "moc_qgsvectorlayerchunkloader_p.cpp"
45
46using namespace Qt::StringLiterals;
47
49
50
51QgsVectorLayerChunkLoader::QgsVectorLayerChunkLoader( const QgsVectorLayerChunkLoaderFactory *factory, QgsChunkNode *node )
52 : QgsChunkLoader( node )
53 , mFactory( factory )
54 , mRenderContext( factory->mRenderContext )
55 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
56{
57}
58
59void QgsVectorLayerChunkLoader::start()
60{
61 QgsChunkNode *node = chunk();
62
63 QgsVectorLayer *layer = mFactory->mLayer;
64 mLayerName = mFactory->mLayer->name();
65
66 QgsFeature3DHandler *handler = QgsApplication::symbol3DRegistry()->createHandlerForSymbol( layer, mFactory->mSymbol.get() );
67 if ( !handler )
68 {
69 QgsDebugError( u"Unknown 3D symbol type for vector layer: "_s + mFactory->mSymbol->type() );
70 return;
71 }
72 mHandler.reset( handler );
73
74 QgsExpressionContext exprContext;
76 exprContext.setFields( layer->fields() );
77 mRenderContext.setExpressionContext( exprContext );
78
79 QSet<QString> attributeNames;
80 if ( !mHandler->prepare( mRenderContext, attributeNames, node->box3D() ) )
81 {
82 QgsDebugError( u"Failed to prepare 3D feature handler!"_s );
83 return;
84 }
85
86 // build the feature request
87 // only a subset of data to be queried
88 const QgsRectangle rect = node->box3D().toRectangle();
91 QgsCoordinateTransform( layer->crs3D(), mRenderContext.crs(), mRenderContext.transformContext() )
92 );
93 req.setSubsetOfAttributes( attributeNames, layer->fields() );
94 req.setFilterRect( rect );
95
96 //
97 // this will be run in a background thread
98 //
99 mFutureWatcher = new QFutureWatcher<void>( this );
100
101 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, [this] {
102 if ( !mCanceled )
103 mFactory->mNodesAreLeafs[mNode->tileId().text()] = mNodeIsLeaf;
104 } );
105
106 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
107
108 const QFuture<void> future = QtConcurrent::run( [req = std::move( req ), this] {
109 const QgsEventTracing::ScopedEvent e( u"3D"_s, u"VL chunk load"_s );
110
111 QgsFeature f;
112 QgsFeatureIterator fi = mSource->getFeatures( req );
113 int featureCount = 0;
114 bool featureLimitReached = false;
115 while ( fi.nextFeature( f ) )
116 {
117 if ( mCanceled )
118 return;
119
120 if ( ++featureCount > mFactory->mMaxFeatures )
121 {
122 featureLimitReached = true;
123 break;
124 }
125
126 mRenderContext.expressionContext().setFeature( f );
127 mHandler->processFeature( f, mRenderContext );
128 }
129
130 if ( !featureLimitReached )
131 {
132 QgsDebugMsgLevel( u"All features fetched for node: %1"_s.arg( mNode->tileId().text() ), 3 );
133
134 if ( featureCount == 0 || std::max<double>( mNode->box3D().width(), mNode->box3D().height() ) < QgsVectorLayer3DTilingSettings::maximumLeafExtent() )
135 mNodeIsLeaf = true;
136 }
137 } );
138
139 // emit finished() as soon as the handler is populated with features
140 mFutureWatcher->setFuture( future );
141}
142
143QgsVectorLayerChunkLoader::~QgsVectorLayerChunkLoader()
144{
145 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
146 {
147 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
148 mFutureWatcher->waitForFinished();
149 }
150}
151
152void QgsVectorLayerChunkLoader::cancel()
153{
154 mCanceled = true;
155}
156
157Qt3DCore::QEntity *QgsVectorLayerChunkLoader::createEntity( Qt3DCore::QEntity *parent )
158{
159 if ( mHandler->featureCount() == 0 )
160 {
161 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
162 // we just make sure first that its initial estimated vertical range does not affect its parents' bboxes calculation
163 mNode->setExactBox3D( QgsBox3D() );
164 mNode->updateParentBoundingBoxesRecursively();
165 return nullptr;
166 }
167
168 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
169 entity->setObjectName( mLayerName + "_" + mNode->tileId().text() );
170 mHandler->finalize( entity, mRenderContext );
171
172 // fix the vertical range of the node from the estimated vertical range to the true range
173 if ( mHandler->zMinimum() != std::numeric_limits<float>::max() && mHandler->zMaximum() != std::numeric_limits<float>::lowest() )
174 {
175 QgsBox3D box = mNode->box3D();
176 box.setZMinimum( mHandler->zMinimum() );
177 box.setZMaximum( mHandler->zMaximum() );
178 mNode->setExactBox3D( box );
179 mNode->updateParentBoundingBoxesRecursively();
180 }
181
182 return entity;
183}
184
185
187
188
189QgsVectorLayerChunkLoaderFactory::QgsVectorLayerChunkLoaderFactory( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsAbstract3DSymbol *symbol, double zMin, double zMax, int maxFeatures )
190 : mRenderContext( context )
191 , mLayer( vl )
192 , mSymbol( symbol->clone() )
193 , mMaxFeatures( maxFeatures )
194{
195 if ( context.crs().type() == Qgis::CrsType::Geocentric )
196 {
197 // TODO: add support for handling of vector layers
198 // (we're using dummy quadtree here to make sure the empty extent does not break the scene completely)
199 QgsDebugError( u"Vector layers in globe scenes are not supported yet!"_s );
200 setupQuadtree( QgsBox3D( -7e6, -7e6, -7e6, 7e6, 7e6, 7e6 ), -1, 3 );
201 return;
202 }
203
204 QgsBox3D rootBox3D( context.extent(), zMin, zMax );
205 // add small padding to avoid clipping of point features located at the edge of the bounding box
206 rootBox3D.grow( 1.0 );
207
208 const float rootError = static_cast<float>( std::max<double>( rootBox3D.width(), rootBox3D.height() ) * QgsVectorLayer3DTilingSettings::tileGeometryErrorRatio() );
209 setupQuadtree( rootBox3D, rootError );
210}
211
212QgsChunkLoader *QgsVectorLayerChunkLoaderFactory::createChunkLoader( QgsChunkNode *node ) const
213{
214 return new QgsVectorLayerChunkLoader( this, node );
215}
216
217bool QgsVectorLayerChunkLoaderFactory::canCreateChildren( QgsChunkNode *node )
218{
219 return mNodesAreLeafs.contains( node->tileId().text() );
220}
221
222QVector<QgsChunkNode *> QgsVectorLayerChunkLoaderFactory::createChildren( QgsChunkNode *node ) const
223{
224 if ( mNodesAreLeafs.value( node->tileId().text(), false ) )
225 return {};
226
227 return QgsQuadtreeChunkLoaderFactory::createChildren( node );
228}
229
230
232
233
234QgsVectorLayerChunkedEntity::QgsVectorLayerChunkedEntity( Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsAbstract3DSymbol *symbol )
235 : QgsChunkedEntity( map, 3, new QgsVectorLayerChunkLoaderFactory( Qgs3DRenderContext::fromMapSettings( map ), vl, symbol, zMin, zMax, tilingSettings.maximumChunkFeatures() ), true )
236{
237 mTransform = new Qt3DCore::QTransform;
238 if ( applyTerrainOffset() )
239 {
240 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, static_cast<float>( map->terrainSettings()->elevationOffset() ) ) );
241 }
242 this->addComponent( mTransform );
243
244 connect( map, &Qgs3DMapSettings::terrainSettingsChanged, this, &QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged );
245
246 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
247}
248
249QgsVectorLayerChunkedEntity::~QgsVectorLayerChunkedEntity()
250{
251 // cancel / wait for jobs
252 cancelActiveJobs();
253}
254
255// if the AltitudeClamping is `Absolute`, do not apply the offset
256bool QgsVectorLayerChunkedEntity::applyTerrainOffset() const
257{
258 QgsVectorLayerChunkLoaderFactory *loaderFactory = static_cast<QgsVectorLayerChunkLoaderFactory *>( mChunkLoaderFactory );
259 if ( loaderFactory )
260 {
261 QString symbolType = loaderFactory->mSymbol.get()->type();
262 if ( symbolType == "line" )
263 {
264 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( loaderFactory->mSymbol.get() );
265 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
266 {
267 return false;
268 }
269 }
270 else if ( symbolType == "point" )
271 {
272 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( loaderFactory->mSymbol.get() );
273 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
274 {
275 return false;
276 }
277 }
278 else if ( symbolType == "polygon" )
279 {
280 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( loaderFactory->mSymbol.get() );
281 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
282 {
283 return false;
284 }
285 }
286 else
287 {
288 QgsDebugMsgLevel( u"QgsVectorLayerChunkedEntity::applyTerrainOffset, unhandled symbol type %1"_s.arg( symbolType ), 2 );
289 }
290 }
291
292 return true;
293}
294
295void QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged()
296{
297 QgsDebugMsgLevel( u"QgsVectorLayerChunkedEntity::onTerrainElevationOffsetChanged"_s, 2 );
298 float newOffset = static_cast<float>( qobject_cast<Qgs3DMapSettings *>( sender() )->terrainSettings()->elevationOffset() );
299 if ( !applyTerrainOffset() )
300 {
301 newOffset = 0.0;
302 }
303 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, newOffset ) );
304}
305
306QList<QgsRayCastHit> QgsVectorLayerChunkedEntity::rayIntersection( const QgsRay3D &ray, const QgsRayCastContext &context ) const
307{
308 return QgsVectorLayerChunkedEntity::rayIntersection( activeNodes(), mTransform->matrix(), ray, context, mMapSettings->origin() );
309}
310
311QList<QgsRayCastHit> QgsVectorLayerChunkedEntity::rayIntersection( const QList<QgsChunkNode *> &activeNodes, const QMatrix4x4 &transformMatrix, const QgsRay3D &ray, const QgsRayCastContext &context, const QgsVector3D &origin )
312{
313 Q_UNUSED( context )
314 QgsDebugMsgLevel( u"Ray cast on vector layer"_s, 2 );
315#ifdef QGISDEBUG
316 int nodeUsed = 0;
317 int nodesAll = 0;
318 int hits = 0;
319 int ignoredGeometries = 0;
320#endif
321 QList<QgsRayCastHit> result;
322
323 float minDist = -1;
324 QVector3D intersectionPoint;
325 QgsFeatureId nearestFid = FID_NULL;
326
327 for ( QgsChunkNode *node : activeNodes )
328 {
329#ifdef QGISDEBUG
330 nodesAll++;
331#endif
332
333 QgsAABB nodeBbox = Qgs3DUtils::mapToWorldExtent( node->box3D(), origin );
334
335 if ( node->entity() && ( minDist < 0 || nodeBbox.distanceFromPoint( ray.origin() ) < minDist ) && QgsRayCastingUtils::rayBoxIntersection( ray, nodeBbox ) )
336 {
337#ifdef QGISDEBUG
338 nodeUsed++;
339#endif
340 const QList<Qt3DRender::QGeometryRenderer *> rendLst = node->entity()->findChildren<Qt3DRender::QGeometryRenderer *>();
341 for ( const auto &rend : rendLst )
342 {
343 auto *geom = rend->geometry();
344 QgsTessellatedPolygonGeometry *polygonGeom = qobject_cast<QgsTessellatedPolygonGeometry *>( geom );
345 if ( !polygonGeom )
346 {
347#ifdef QGISDEBUG
348 ignoredGeometries++;
349#endif
350 continue; // other QGeometry types are not supported for now
351 }
352
353 QVector3D nodeIntPoint;
354 int triangleIndex = -1;
355
356 // the node geometry has been translated by chunkOrigin
357 // This translation is stored in the QTransform component
358 // this needs to be taken into account to get the whole transformation
359 const QMatrix4x4 nodeTransformMatrix = node->entity()->findChild<QgsGeoTransform *>()->matrix();
360 const QMatrix4x4 fullTransformMatrix = transformMatrix * nodeTransformMatrix;
361 if ( QgsRayCastingUtils::rayMeshIntersection( rend, ray, context.maximumDistance(), fullTransformMatrix, nodeIntPoint, triangleIndex ) )
362 {
363#ifdef QGISDEBUG
364 hits++;
365#endif
366 float dist = ( ray.origin() - nodeIntPoint ).length();
367 if ( minDist < 0 || dist < minDist )
368 {
369 minDist = dist;
370 intersectionPoint = nodeIntPoint;
371 nearestFid = polygonGeom->triangleIndexToFeatureId( triangleIndex );
372 }
373 }
374 }
375 }
376 }
377 if ( !FID_IS_NULL( nearestFid ) )
378 {
379 QgsRayCastHit hit;
380 hit.setDistance( minDist );
381 hit.setMapCoordinates( Qgs3DUtils::worldToMapCoordinates( intersectionPoint, origin ) );
382 hit.setProperties( { { u"fid"_s, nearestFid } } );
383 result.append( hit );
384 }
385 QgsDebugMsgLevel( u"Active Nodes: %1, checked nodes: %2, hits found: %3, incompatible geometries: %4"_s.arg( nodesAll ).arg( nodeUsed ).arg( hits ).arg( ignoredGeometries ), 2 );
386 return result;
387}
388
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
Definition qgis.h:4042
@ Geocentric
Geocentric CRS.
Definition qgis.h:2388
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 QgsVector3D worldToMapCoordinates(const QgsVector3D &worldCoords, const QgsVector3D &origin)
Converts 3D world coordinates to map coordinates (applies offset).
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:50
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:45
void setZMinimum(double z)
Sets the minimum z value.
Definition qgsbox3d.cpp:94
void setZMaximum(double z)
Sets the maximum z value.
Definition qgsbox3d.cpp:99
void grow(double delta)
Grows the box in place by the specified amount in all dimensions.
Definition qgsbox3d.cpp:307
Qgis::CrsType type() const
Returns the type of the CRS.
Handles coordinate transforms between two coordinate systems.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
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:60
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:87
QgsCoordinateReferenceSystem crs3D
Definition qgsmaplayer.h:92
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).
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 representation of a ray in 3D.
Definition qgsray3d.h:31
QVector3D origin() const
Returns the origin of the ray.
Definition qgsray3d.h:44
Responsible for defining parameters of the ray casting operations in 3D map canvases.
float maximumDistance() const
The maximum distance from ray origin to look for hits when casting a ray.
Contains details about the ray intersecting entities when ray casting in a 3D map canvas.
void setProperties(const QVariantMap &attributes)
Sets the point cloud point attributes, empty map if hit was not on a point cloud point.
void setMapCoordinates(const QgsVector3D &point)
Sets the hit point position in 3d map coordinates.
void setDistance(double distance)
Sets the hit's distance from the ray's origin.
A rectangle specified with double values.
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:33
Defines configuration of how a vector layer gets tiled for 3D rendering.
static double tileGeometryErrorRatio()
This is the ratio of tile's largest size to geometry error and is used when setting the root tile's e...
bool showBoundingBoxes() const
Returns whether to display bounding boxes of entity's tiles (for debugging).
static double maximumLeafExtent()
This is the maximum width or height a tile can have and still be considered a leaf node.
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.
bool rayBoxIntersection(const QgsRay3D &ray, const QgsAABB &nodeBbox)
Tests whether an axis aligned box is intersected by a ray.
bool rayMeshIntersection(Qt3DRender::QGeometryRenderer *geometryRenderer, const QgsRay3D &r, float maxDist, const QMatrix4x4 &worldTransform, QVector3D &intPt, int &triangleIndex)
Tests whether a triangular mesh is intersected by a ray.
#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:63
#define QgsDebugError(str)
Definition qgslogger.h:59