QGIS API Documentation 3.99.0-Master (d270888f95f)
Loading...
Searching...
No Matches
qgsrulebasedchunkloader_p.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsrulebasedchunkloader_p.cpp
3 --------------------------------------
4 Date : November 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 "qgs3dutils.h"
20#include "qgschunknode.h"
21#include "qgseventtracing.h"
24#include "qgsline3dsymbol.h"
25#include "qgspoint3dsymbol.h"
26#include "qgspolygon3dsymbol.h"
29#include "qgsvectorlayer.h"
32
33#include <QString>
34#include <Qt3DCore/QTransform>
35#include <QtConcurrent>
36
37#include "moc_qgsrulebasedchunkloader_p.cpp"
38
39using namespace Qt::StringLiterals;
40
42
43
44QgsRuleBasedChunkLoader::QgsRuleBasedChunkLoader( const QgsRuleBasedChunkLoaderFactory *factory, QgsChunkNode *node )
45 : QgsChunkLoader( node )
46 , mFactory( factory )
47 , mContext( factory->mRenderContext )
48 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
49{
50}
51
52void QgsRuleBasedChunkLoader::start()
53{
54 QgsChunkNode *node = chunk();
55
56 QgsVectorLayer *layer = mFactory->mLayer;
57
58 QgsExpressionContext exprContext;
60 exprContext.setFields( layer->fields() );
61 mContext.setExpressionContext( exprContext );
62
63 // factory is shared among multiple loaders which may be run at the same time
64 // so we need a local copy of our rule tree that does not intefere with others
65 // (e.g. it happened that filter expressions with invalid syntax would cause
66 // nasty crashes when trying to simultaneously record evaluation error)
67 mRootRule.reset( mFactory->mRootRule->clone() );
68
69 mRootRule->createHandlers( layer, mHandlers );
70
71 QSet<QString> attributeNames;
72 mRootRule->prepare( mContext, attributeNames, node->box3D(), mHandlers );
73
74 // build the feature request
75 // only a subset of data to be queried
76 const QgsRectangle rect = node->box3D().toRectangle();
78 req.setDestinationCrs( mContext.crs(), mContext.transformContext() );
79 req.setSubsetOfAttributes( attributeNames, layer->fields() );
80 req.setFilterRect( rect );
81
82 //
83 // this will be run in a background thread
84 //
85 mFutureWatcher = new QFutureWatcher<void>( this );
86
87 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, [this] {
88 if ( !mCanceled )
89 mFactory->mNodesAreLeafs[mNode->tileId().text()] = mNodeIsLeaf;
90 } );
91
92 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
93
94 const QFuture<void> future = QtConcurrent::run( [req = std::move( req ), this] {
95 const QgsEventTracing::ScopedEvent e( u"3D"_s, u"RB chunk load"_s );
96
97 QgsFeature f;
98 QgsFeatureIterator fi = mSource->getFeatures( req );
99 int featureCount = 0;
100 bool featureLimitReached = false;
101 while ( fi.nextFeature( f ) )
102 {
103 if ( mCanceled )
104 break;
105
106 if ( ++featureCount > mFactory->mMaxFeatures )
107 {
108 featureLimitReached = true;
109 break;
110 }
111
112 mContext.expressionContext().setFeature( f );
113 mRootRule->registerFeature( f, mContext, mHandlers );
114 }
115 if ( !featureLimitReached )
116 {
117 QgsDebugMsgLevel( u"All features fetched for node: %1"_s.arg( mNode->tileId().text() ), 3 );
118
119 if ( featureCount == 0 || std::max<double>( mNode->box3D().width(), mNode->box3D().height() ) < QgsVectorLayer3DTilingSettings::maximumLeafExtent() )
120 mNodeIsLeaf = true;
121 }
122 } );
123
124 // emit finished() as soon as the handler is populated with features
125 mFutureWatcher->setFuture( future );
126}
127
128QgsRuleBasedChunkLoader::~QgsRuleBasedChunkLoader()
129{
130 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
131 {
132 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
133 mFutureWatcher->waitForFinished();
134 }
135
136 qDeleteAll( mHandlers );
137 mHandlers.clear();
138}
139
140void QgsRuleBasedChunkLoader::cancel()
141{
142 mCanceled = true;
143}
144
145Qt3DCore::QEntity *QgsRuleBasedChunkLoader::createEntity( Qt3DCore::QEntity *parent )
146{
147 long long featureCount = 0;
148 for ( auto it = mHandlers.constBegin(); it != mHandlers.constEnd(); ++it )
149 {
150 featureCount += it.value()->featureCount();
151 }
152 if ( featureCount == 0 )
153 {
154 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
155 return nullptr;
156 }
157
158 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
159 float zMin = std::numeric_limits<float>::max();
160 float zMax = std::numeric_limits<float>::lowest();
161 for ( auto it = mHandlers.constBegin(); it != mHandlers.constEnd(); ++it )
162 {
163 QgsFeature3DHandler *handler = it.value();
164 handler->finalize( entity, mContext );
165 if ( handler->zMinimum() < zMin )
166 zMin = handler->zMinimum();
167 if ( handler->zMaximum() > zMax )
168 zMax = handler->zMaximum();
169 }
170
171 // fix the vertical range of the node from the estimated vertical range to the true range
172 if ( zMin != std::numeric_limits<float>::max() && zMax != std::numeric_limits<float>::lowest() )
173 {
174 QgsBox3D box = mNode->box3D();
175 box.setZMinimum( zMin );
176 box.setZMaximum( zMax );
177 mNode->setExactBox3D( box );
178 mNode->updateParentBoundingBoxesRecursively();
179 }
180
181 return entity;
182}
183
184
186
187
188QgsRuleBasedChunkLoaderFactory::QgsRuleBasedChunkLoaderFactory( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsRuleBased3DRenderer::Rule *rootRule, double zMin, double zMax, int maxFeatures )
189 : mRenderContext( context )
190 , mLayer( vl )
191 , mRootRule( rootRule->clone() )
192 , mMaxFeatures( maxFeatures )
193{
194 if ( context.crs().type() == Qgis::CrsType::Geocentric )
195 {
196 // TODO: add support for handling of vector layers
197 // (we're using dummy quadtree here to make sure the empty extent does not break the scene completely)
198 QgsDebugError( u"Vector layers in globe scenes are not supported yet!"_s );
199 setupQuadtree( QgsBox3D( -7e6, -7e6, -7e6, 7e6, 7e6, 7e6 ), -1, 3 );
200 return;
201 }
202
203 QgsBox3D rootBox3D( context.extent(), zMin, zMax );
204 // add small padding to avoid clipping of point features located at the edge of the bounding box
205 rootBox3D.grow( 1.0 );
206
207 const float rootError = static_cast<float>( std::max<double>( rootBox3D.width(), rootBox3D.height() ) * QgsVectorLayer3DTilingSettings::tileGeometryErrorRatio() );
208 setupQuadtree( rootBox3D, rootError );
209}
210
211QgsRuleBasedChunkLoaderFactory::~QgsRuleBasedChunkLoaderFactory() = default;
212
213QgsChunkLoader *QgsRuleBasedChunkLoaderFactory::createChunkLoader( QgsChunkNode *node ) const
214{
215 return new QgsRuleBasedChunkLoader( this, node );
216}
217
218bool QgsRuleBasedChunkLoaderFactory::canCreateChildren( QgsChunkNode *node )
219{
220 return mNodesAreLeafs.contains( node->tileId().text() );
221}
222
223QVector<QgsChunkNode *> QgsRuleBasedChunkLoaderFactory::createChildren( QgsChunkNode *node ) const
224{
225 if ( mNodesAreLeafs.value( node->tileId().text(), false ) )
226 return {};
227
228 return QgsQuadtreeChunkLoaderFactory::createChildren( node );
229}
230
232
233QgsRuleBasedChunkedEntity::QgsRuleBasedChunkedEntity( Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsRuleBased3DRenderer::Rule *rootRule )
234 : QgsChunkedEntity( map, 3, new QgsRuleBasedChunkLoaderFactory( Qgs3DRenderContext::fromMapSettings( map ), vl, rootRule, zMin, zMax, tilingSettings.maximumChunkFeatures() ), true )
235{
236 mTransform = new Qt3DCore::QTransform;
237 if ( applyTerrainOffset() )
238 {
239 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, static_cast<float>( map->terrainSettings()->elevationOffset() ) ) );
240 }
241 this->addComponent( mTransform );
242 connect( map, &Qgs3DMapSettings::terrainSettingsChanged, this, &QgsRuleBasedChunkedEntity::onTerrainElevationOffsetChanged );
243
244 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
245}
246
247QgsRuleBasedChunkedEntity::~QgsRuleBasedChunkedEntity()
248{
249 // cancel / wait for jobs
250 cancelActiveJobs();
251}
252
253// if the AltitudeClamping is `Absolute`, do not apply the offset
254bool QgsRuleBasedChunkedEntity::applyTerrainOffset() const
255{
256 QgsRuleBasedChunkLoaderFactory *loaderFactory = static_cast<QgsRuleBasedChunkLoaderFactory *>( mChunkLoaderFactory );
257 if ( loaderFactory )
258 {
259 QgsRuleBased3DRenderer::Rule *rootRule = loaderFactory->mRootRule.get();
260 const QgsRuleBased3DRenderer::RuleList rules = rootRule->children();
261 for ( const auto &rule : rules )
262 {
263 if ( rule->symbol() )
264 {
265 QString symbolType = rule->symbol()->type();
266 if ( symbolType == "line" )
267 {
268 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( rule->symbol() );
269 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
270 {
271 return false;
272 }
273 }
274 else if ( symbolType == "point" )
275 {
276 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( rule->symbol() );
277 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
278 {
279 return false;
280 }
281 }
282 else if ( symbolType == "polygon" )
283 {
284 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( rule->symbol() );
285 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
286 {
287 return false;
288 }
289 }
290 else
291 {
292 QgsDebugMsgLevel( u"QgsRuleBasedChunkedEntityChunkedEntity::applyTerrainOffset, unhandled symbol type %1"_s.arg( symbolType ), 2 );
293 }
294 }
295 }
296 }
297
298 return true;
299}
300
301void QgsRuleBasedChunkedEntity::onTerrainElevationOffsetChanged()
302{
303 const float previousOffset = mTransform->translation()[1];
304 float newOffset = static_cast<float>( qobject_cast<Qgs3DMapSettings *>( sender() )->terrainSettings()->elevationOffset() );
305 if ( !applyTerrainOffset() )
306 {
307 newOffset = 0.0;
308 }
309
310 if ( newOffset != previousOffset )
311 {
312 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, newOffset ) );
313 }
314}
315
316QList<QgsRayCastHit> QgsRuleBasedChunkedEntity::rayIntersection( const QgsRay3D &ray, const QgsRayCastContext &context ) const
317{
318 return QgsVectorLayerChunkedEntity::rayIntersection( activeNodes(), mTransform->matrix(), ray, context, mMapSettings->origin() );
319}
@ 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.
double elevationOffset() const
Returns the elevation offset of the terrain (used to move the terrain up or down).
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.
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 & 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: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).
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
Responsible for defining parameters of the ray casting operations in 3D map canvases.
A rectangle specified with double values.
A child rule for a QgsRuleBased3DRenderer.
const QgsRuleBased3DRenderer::RuleList & children() const
Returns all children rules of this rule.
QList< QgsRuleBased3DRenderer::Rule * > RuleList
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.
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63