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