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