QGIS API Documentation 3.99.0-Master (752b475928d)
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"
23#include "qgsline3dsymbol.h"
24#include "qgspoint3dsymbol.h"
25#include "qgspolygon3dsymbol.h"
28#include "qgsvectorlayer.h"
31
32#include <Qt3DCore/QTransform>
33#include <QtConcurrent>
34
35#include "moc_qgsrulebasedchunkloader_p.cpp"
36
38
39
40QgsRuleBasedChunkLoader::QgsRuleBasedChunkLoader( const QgsRuleBasedChunkLoaderFactory *factory, QgsChunkNode *node )
41 : QgsChunkLoader( node )
42 , mFactory( factory )
43 , mContext( factory->mRenderContext )
44 , mSource( new QgsVectorLayerFeatureSource( factory->mLayer ) )
45{
46}
47
48void QgsRuleBasedChunkLoader::start()
49{
50 QgsChunkNode *node = chunk();
51 if ( node->level() < mFactory->mLeafLevel )
52 {
53 QTimer::singleShot( 0, this, &QgsRuleBasedChunkLoader::finished );
54 return;
55 }
56
57 QgsVectorLayer *layer = mFactory->mLayer;
58
59 // only a subset of data to be queried
60 const QgsRectangle rect = node->box3D().toRectangle();
61 // origin for coordinates of the chunk - it is kind of arbitrary, but it should be
62 // picked so that the coordinates are relatively small to avoid numerical precision issues
63 QgsVector3D chunkOrigin( rect.center().x(), rect.center().y(), 0 );
64
65 QgsExpressionContext exprContext;
67 exprContext.setFields( layer->fields() );
68 mContext.setExpressionContext( exprContext );
69
70 // factory is shared among multiple loaders which may be run at the same time
71 // so we need a local copy of our rule tree that does not intefere with others
72 // (e.g. it happened that filter expressions with invalid syntax would cause
73 // nasty crashes when trying to simultaneously record evaluation error)
74 mRootRule.reset( mFactory->mRootRule->clone() );
75
76 mRootRule->createHandlers( layer, mHandlers );
77
78 QSet<QString> attributeNames;
79 mRootRule->prepare( mContext, attributeNames, chunkOrigin, mHandlers );
80
81 // build the feature request
83 req.setDestinationCrs( mContext.crs(), mContext.transformContext() );
84 req.setSubsetOfAttributes( attributeNames, layer->fields() );
85 req.setFilterRect( rect );
86
87 //
88 // this will be run in a background thread
89 //
90 mFutureWatcher = new QFutureWatcher<void>( this );
91 connect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
92
93 const QFuture<void> future = QtConcurrent::run( [req = std::move( req ), this] {
94 const QgsEventTracing::ScopedEvent e( QStringLiteral( "3D" ), QStringLiteral( "RB chunk load" ) );
95
96 QgsFeature f;
97 QgsFeatureIterator fi = mSource->getFeatures( req );
98 while ( fi.nextFeature( f ) )
99 {
100 if ( mCanceled )
101 break;
102 mContext.expressionContext().setFeature( f );
103 mRootRule->registerFeature( f, mContext, mHandlers );
104 }
105 } );
106
107 // emit finished() as soon as the handler is populated with features
108 mFutureWatcher->setFuture( future );
109}
110
111QgsRuleBasedChunkLoader::~QgsRuleBasedChunkLoader()
112{
113 if ( mFutureWatcher && !mFutureWatcher->isFinished() )
114 {
115 disconnect( mFutureWatcher, &QFutureWatcher<void>::finished, this, &QgsChunkQueueJob::finished );
116 mFutureWatcher->waitForFinished();
117 }
118
119 qDeleteAll( mHandlers );
120 mHandlers.clear();
121}
122
123void QgsRuleBasedChunkLoader::cancel()
124{
125 mCanceled = true;
126}
127
128Qt3DCore::QEntity *QgsRuleBasedChunkLoader::createEntity( Qt3DCore::QEntity *parent )
129{
130 if ( mNode->level() < mFactory->mLeafLevel )
131 {
132 return new Qt3DCore::QEntity( parent ); // dummy entity
133 }
134
135 long long featureCount = 0;
136 for ( auto it = mHandlers.constBegin(); it != mHandlers.constEnd(); ++it )
137 {
138 featureCount += it.value()->featureCount();
139 }
140 if ( featureCount == 0 )
141 {
142 // an empty node, so we return no entity. This tags the node as having no data and effectively removes it.
143 return nullptr;
144 }
145
146 Qt3DCore::QEntity *entity = new Qt3DCore::QEntity( parent );
147 float zMin = std::numeric_limits<float>::max();
148 float zMax = std::numeric_limits<float>::lowest();
149 for ( auto it = mHandlers.constBegin(); it != mHandlers.constEnd(); ++it )
150 {
151 QgsFeature3DHandler *handler = it.value();
152 handler->finalize( entity, mContext );
153 if ( handler->zMinimum() < zMin )
154 zMin = handler->zMinimum();
155 if ( handler->zMaximum() > zMax )
156 zMax = handler->zMaximum();
157 }
158
159 // fix the vertical range of the node from the estimated vertical range to the true range
160 if ( zMin != std::numeric_limits<float>::max() && zMax != std::numeric_limits<float>::lowest() )
161 {
162 QgsBox3D box = mNode->box3D();
163 box.setZMinimum( zMin );
164 box.setZMaximum( zMax );
165 mNode->setExactBox3D( box );
166 mNode->updateParentBoundingBoxesRecursively();
167 }
168
169 return entity;
170}
171
172
174
175
176QgsRuleBasedChunkLoaderFactory::QgsRuleBasedChunkLoaderFactory( const Qgs3DRenderContext &context, QgsVectorLayer *vl, QgsRuleBased3DRenderer::Rule *rootRule, int leafLevel, double zMin, double zMax )
177 : mRenderContext( context )
178 , mLayer( vl )
179 , mRootRule( rootRule->clone() )
180 , mLeafLevel( leafLevel )
181{
182 const QgsBox3D rootBox3D( context.extent(), zMin, zMax );
183 setupQuadtree( rootBox3D, -1, leafLevel ); // negative root error means that the node does not contain anything
184}
185
186QgsRuleBasedChunkLoaderFactory::~QgsRuleBasedChunkLoaderFactory() = default;
187
188QgsChunkLoader *QgsRuleBasedChunkLoaderFactory::createChunkLoader( QgsChunkNode *node ) const
189{
190 return new QgsRuleBasedChunkLoader( this, node );
191}
192
193
195
196QgsRuleBasedChunkedEntity::QgsRuleBasedChunkedEntity( Qgs3DMapSettings *map, QgsVectorLayer *vl, double zMin, double zMax, const QgsVectorLayer3DTilingSettings &tilingSettings, QgsRuleBased3DRenderer::Rule *rootRule )
197 : QgsChunkedEntity( map,
198 -1, // max. allowed screen error (negative tau means that we need to go until leaves are reached)
199 new QgsRuleBasedChunkLoaderFactory( Qgs3DRenderContext::fromMapSettings( map ), vl, rootRule, tilingSettings.zoomLevelsCount() - 1, zMin, zMax ), true )
200{
201 mTransform = new Qt3DCore::QTransform;
202 if ( applyTerrainOffset() )
203 {
204 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, static_cast<float>( map->terrainSettings()->elevationOffset() ) ) );
205 }
206 this->addComponent( mTransform );
207 connect( map, &Qgs3DMapSettings::terrainSettingsChanged, this, &QgsRuleBasedChunkedEntity::onTerrainElevationOffsetChanged );
208
209 setShowBoundingBoxes( tilingSettings.showBoundingBoxes() );
210}
211
212QgsRuleBasedChunkedEntity::~QgsRuleBasedChunkedEntity()
213{
214 // cancel / wait for jobs
215 cancelActiveJobs();
216}
217
218// if the AltitudeClamping is `Absolute`, do not apply the offset
219bool QgsRuleBasedChunkedEntity::applyTerrainOffset() const
220{
221 QgsRuleBasedChunkLoaderFactory *loaderFactory = static_cast<QgsRuleBasedChunkLoaderFactory *>( mChunkLoaderFactory );
222 if ( loaderFactory )
223 {
224 QgsRuleBased3DRenderer::Rule *rootRule = loaderFactory->mRootRule.get();
225 const QgsRuleBased3DRenderer::RuleList rules = rootRule->children();
226 for ( const auto &rule : rules )
227 {
228 if ( rule->symbol() )
229 {
230 QString symbolType = rule->symbol()->type();
231 if ( symbolType == "line" )
232 {
233 QgsLine3DSymbol *lineSymbol = static_cast<QgsLine3DSymbol *>( rule->symbol() );
234 if ( lineSymbol && lineSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
235 {
236 return false;
237 }
238 }
239 else if ( symbolType == "point" )
240 {
241 QgsPoint3DSymbol *pointSymbol = static_cast<QgsPoint3DSymbol *>( rule->symbol() );
242 if ( pointSymbol && pointSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
243 {
244 return false;
245 }
246 }
247 else if ( symbolType == "polygon" )
248 {
249 QgsPolygon3DSymbol *polygonSymbol = static_cast<QgsPolygon3DSymbol *>( rule->symbol() );
250 if ( polygonSymbol && polygonSymbol->altitudeClamping() == Qgis::AltitudeClamping::Absolute )
251 {
252 return false;
253 }
254 }
255 else
256 {
257 QgsDebugMsgLevel( QStringLiteral( "QgsRuleBasedChunkedEntityChunkedEntity::applyTerrainOffset, unhandled symbol type %1" ).arg( symbolType ), 2 );
258 }
259 }
260 }
261 }
262
263 return true;
264}
265
266void QgsRuleBasedChunkedEntity::onTerrainElevationOffsetChanged()
267{
268 const float previousOffset = mTransform->translation()[1];
269 float newOffset = static_cast<float>( qobject_cast<Qgs3DMapSettings *>( sender() )->terrainSettings()->elevationOffset() );
270 if ( !applyTerrainOffset() )
271 {
272 newOffset = 0.0;
273 }
274
275 if ( newOffset != previousOffset )
276 {
277 mTransform->setTranslation( QVector3D( 0.0f, 0.0f, newOffset ) );
278 }
279}
280
281QList<QgsRayCastHit> QgsRuleBasedChunkedEntity::rayIntersection( const QgsRay3D &ray, const QgsRayCastContext &context ) const
282{
283 return QgsVectorLayerChunkedEntity::rayIntersection( activeNodes(), mTransform->matrix(), ray, context, mMapSettings->origin() );
284}
@ Absolute
Elevation is taken directly from feature and is independent of terrain height (final elevation = feat...
Definition qgis.h:3983
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.
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: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
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: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).
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
Responsible for defining parameters of the ray casting operations in 3D map canvases.
A rectangle specified with double values.
QgsPointXY center
A child rule for a QgsRuleBased3DRenderer.
const QgsRuleBased3DRenderer::RuleList & children() const
Returns all children rules of this rule.
QList< QgsRuleBased3DRenderer::Rule * > RuleList
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 QgsDebugMsgLevel(str, level)
Definition qgslogger.h:61