QGIS API Documentation 3.99.0-Master (e9821da5c6b)
Loading...
Searching...
No Matches
qgsquantizedmeshterraingenerator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsterraingenerator.h
3 --------------------------------------
4 Date : August 2024
5 Copyright : (C) 2024 by David Koňařík
6 Email : dvdkon at konarici dot cz
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 "qgs3dmapsettings.h"
20#include "qgsapplication.h"
21#include "qgschunkloader.h"
22#include "qgschunknode.h"
24#include "qgsgeotransform.h"
25#include "qgsgltf3dutils.h"
26#include "qgslogger.h"
27#include "qgsmesh3dentity_p.h"
28#include "qgsmeshlayerutils.h"
30#include "qgsproject.h"
33#include "qgsrectangle.h"
34#include "qgsterrainentity.h"
37#include "qgstiledsceneindex.h"
38#include "qgstiledscenelayer.h"
39#include "qgstiledscenetile.h"
40#include "qgstiles.h"
41#include "qgstriangularmesh.h"
42#include "qgsvector3d.h"
43
44#include <QComponent>
45#include <QDiffuseSpecularMaterial>
46#include <QEntity>
47#include <QPhongMaterial>
48#include <QString>
49#include <QTextureMaterial>
50#include <QtConcurrentRun>
51#include <QtGlobal>
52
53#include "moc_qgsquantizedmeshterraingenerator.cpp"
54
55using namespace Qt::StringLiterals;
56
58
59class QgsQuantizedMeshTerrainChunkLoader : public QgsTerrainTileLoader
60{
61 Q_OBJECT
62 public:
63 QgsQuantizedMeshTerrainChunkLoader(
64 QgsTerrainEntity *terrain, QgsChunkNode *node, long long tileId, QgsTiledSceneIndex index, const QgsCoordinateTransform &tileCrsToMapCrs
65 );
66 void start() override;
67 Qt3DCore::QEntity *createEntity( Qt3DCore::QEntity *parent ) override;
68
69 protected:
70 void onTextureLoaded() override;
71
72 private:
73 QgsTerrainTileEntity *mEntity = nullptr;
74 bool mMeshLoaded = false;
75 bool mTextureLoaded = false;
76 std::mutex mFinishedMutex;
77 long long mTileId;
78 QgsTiledSceneIndex mIndex;
79 QgsCoordinateTransform mTileCrsToMapCrs;
80};
81
82QgsQuantizedMeshTerrainChunkLoader::QgsQuantizedMeshTerrainChunkLoader( QgsTerrainEntity *terrain_, QgsChunkNode *node, long long tileId, QgsTiledSceneIndex index, const QgsCoordinateTransform &tileCrsToMapCrs )
83 : QgsTerrainTileLoader( terrain_, node )
84 , mTileId( tileId )
85 , mIndex( std::move( index ) )
86 , mTileCrsToMapCrs( tileCrsToMapCrs )
87{
88}
89
90void QgsQuantizedMeshTerrainChunkLoader::start()
91{
92 QgsChunkNode *node = chunk();
93
94 loadTexture(); // Start loading texture
95
96 // Access terrain only on the original thread.
97 Qgs3DMapSettings *map = terrain()->mapSettings();
98 double vertScale = map->terrainSettings()->verticalScale();
99 bool shadingEnabled = map->isTerrainShadingEnabled();
100 QgsVector3D chunkOrigin = node->box3D().center();
101
102 QThreadPool::globalInstance()->start( [this, node, vertScale, chunkOrigin, shadingEnabled]() {
103 if ( mTileId == QgsQuantizedMeshIndex::ROOT_TILE_ID )
104 {
105 // Nothing to load for imaginary root tile
106 emit finished();
107 return;
108 }
109
110 QgsTiledSceneTile tile = mIndex.getTile( mTileId );
111
112 QString uri = tile.resources().value( u"content"_s ).toString();
113 Q_ASSERT( !uri.isEmpty() );
114
115 uri = tile.baseUrl().resolved( uri ).toString();
116 QByteArray content = mIndex.retrieveContent( uri );
117
118 QgsGltf3DUtils::EntityTransform entityTransform;
119 entityTransform.tileTransform = ( tile.transform() ? *tile.transform() : QgsMatrix4x4() );
120 entityTransform.chunkOriginTargetCrs = chunkOrigin;
121 entityTransform.ecefToTargetCrs = &mTileCrsToMapCrs;
122 entityTransform.gltfUpAxis = static_cast<Qgis::Axis>( tile.metadata().value( u"gltfUpAxis"_s, static_cast<int>( Qgis::Axis::Y ) ).toInt() );
123
124 try
125 {
126 QgsBox3D box3D = node->box3D();
127 QgsQuantizedMeshTile qmTile( content );
128 qmTile.removeDegenerateTriangles();
129
130 // We now know the exact height range of the tile, set it to the node.
131 box3D.setZMinimum( qmTile.mHeader.MinimumHeight * vertScale );
132 box3D.setZMaximum( qmTile.mHeader.MaximumHeight * vertScale );
133 node->setExactBox3D( box3D );
134
135 if ( shadingEnabled && qmTile.mNormalCoords.size() == 0 )
136 {
137 qmTile.generateNormals();
138 }
139
140 tinygltf::Model model = qmTile.toGltf( true, 100, true );
141
142 QStringList errors;
143 Qt3DCore::QEntity *gltfEntity = QgsGltf3DUtils::parsedGltfToEntity( model, entityTransform, uri, &errors );
144 if ( !errors.isEmpty() )
145 {
146 QgsDebugError( "gltf load errors: " + errors.join( '\n' ) );
147 emit finished();
148 return;
149 }
150
151 QgsTerrainTileEntity *terrainEntity = new QgsTerrainTileEntity( node->tileId() );
152 // We count on only having one mesh.
153 Q_ASSERT( gltfEntity->children().size() == 1 );
154 gltfEntity->children()[0]->setParent( terrainEntity );
155
156 QgsGeoTransform *transform = new QgsGeoTransform;
157 transform->setGeoTranslation( chunkOrigin );
158 terrainEntity->addComponent( transform );
159
160 terrainEntity->moveToThread( QgsApplication::instance()->thread() );
161 mEntity = terrainEntity;
162 }
164 {
165 QgsDebugError( u"Failed to parse tile from '%1'"_s.arg( uri ) );
166 emit finished();
167 return;
168 }
169
170 {
171 std::lock_guard lock( mFinishedMutex );
172 if ( mTextureLoaded )
173 emit finished();
174 mMeshLoaded = true;
175 }
176 } );
177}
178
179Qt3DCore::QEntity *QgsQuantizedMeshTerrainChunkLoader::createEntity( Qt3DCore::QEntity *parent )
180{
181 if ( mEntity )
182 {
183 mEntity->setParent( parent );
184 Qt3DRender::QTexture2D *texture = createTexture( mEntity );
185
186 // Copied from part of QgsTerrainTileLoader::createTextureComponent, since we can't use that directly on the GLTF entity.
187 Qt3DRender::QMaterial *material = nullptr;
188 Qgs3DMapSettings *map = terrain()->mapSettings();
189 if ( map->isTerrainShadingEnabled() )
190 {
191 const QgsPhongMaterialSettings &shadingMaterial = map->terrainShadingMaterial();
192 Qt3DExtras::QDiffuseSpecularMaterial *diffuseMapMaterial = new Qt3DExtras::QDiffuseSpecularMaterial;
193 diffuseMapMaterial->setDiffuse( QVariant::fromValue( texture ) );
194 diffuseMapMaterial->setAmbient( shadingMaterial.ambient() );
195 diffuseMapMaterial->setSpecular( shadingMaterial.specular() );
196 diffuseMapMaterial->setShininess( shadingMaterial.shininess() );
197 material = diffuseMapMaterial;
198 }
199 else
200 {
201 Qt3DExtras::QTextureMaterial *textureMaterial = new Qt3DExtras::QTextureMaterial;
202 textureMaterial->setTexture( texture );
203 material = textureMaterial;
204 }
205 // Get the child that actually has the mesh and add the texture
206 Qt3DCore::QEntity *gltfEntity = mEntity->findChild<Qt3DCore::QEntity *>();
207 // Remove default material
208 auto oldMaterial = gltfEntity->componentsOfType<QgsMetalRoughMaterial>();
209 Q_ASSERT( oldMaterial.size() > 0 );
210 gltfEntity->removeComponent( oldMaterial[0] );
211 gltfEntity->addComponent( material );
212 }
213 return mEntity;
214}
215
216void QgsQuantizedMeshTerrainChunkLoader::onTextureLoaded()
217{
218 std::lock_guard lock( mFinishedMutex );
219 if ( mMeshLoaded )
220 emit finished();
221 mTextureLoaded = true;
222}
223
225
230
232{
233 mTerrain = t;
234 mTileCrsToMapCrs = QgsCoordinateTransform(
235 mMetadata->mCrs,
236 mTerrain->mapSettings()->crs(),
237 mTerrain->mapSettings()->transformContext()
238 );
239}
240
242{
244 if ( mIsValid )
245 clone->setLayer( layer() );
246 else
247 clone->mLayer = mLayer; // Copy just the reference
248 return clone;
249}
250
255
257{
258 mMapExtent = extent;
259}
260
262{
263 return mMetadata->mBoundingVolume.bounds().toRectangle();
264}
265
267{
268 Q_UNUSED( map );
269 return mMetadata->geometricErrorAtZoom( -1 );
270}
271
272void QgsQuantizedMeshTerrainGenerator::rootChunkHeightRange( float &hMin, float &hMax ) const
273{
274 hMin = mMetadata->mBoundingVolume.bounds().zMinimum();
275 hMax = mMetadata->mBoundingVolume.bounds().xMaximum();
276}
277float QgsQuantizedMeshTerrainGenerator::heightAt( double x, double y, const Qgs3DRenderContext &context ) const
278{
279 // We fetch the most detailed tile containing the given point and then interpolate.
280 QgsTileMatrix zoomedMatrix = QgsTileMatrix::fromTileMatrix( mMetadata->mMaxZoom, mMetadata->mTileMatrix );
281 QgsPointXY point = QgsCoordinateTransform( context.crs(), mMetadata->mCrs, context.transformContext() ).transform( QgsPointXY( x, y ) );
282 QPointF tileCoords = zoomedMatrix.mapToTileCoordinates( point );
283 QgsTileXYZ tileXyz( floor( tileCoords.x() ), floor( tileCoords.y() ), mMetadata->mMaxZoom );
284 if ( !mMetadata->containsTile( tileXyz ) )
285 {
286 // This doesn't deal with a possible dataset where the whole extent doesn't
287 // have full coverage at maxZoom, but has coverage at a lower zoom level.
288 QgsDebugError( u"Quantized Mesh layer doesn't contain max-zoom tile for %1, %2"_s.arg( x ).arg( y ) );
289 return 0;
290 }
291 // TODO: Make heightAt asynchronous?
292 QgsTiledSceneIndex index = mIndex; // Copy to get rid of const
293 QgsTiledSceneTile sceneTile = index.getTile( QgsQuantizedMeshIndex::encodeTileId( tileXyz ) );
294 QString uri = sceneTile.resources().value( u"content"_s ).toString();
295 Q_ASSERT( !uri.isEmpty() );
296
297 uri = sceneTile.baseUrl().resolved( uri ).toString();
298 QByteArray content = index.retrieveContent( uri );
299 QgsQuantizedMeshTile qmTile( content );
301 QgsMesh mesh = qmTile.toMesh( zoomedMatrix.tileExtent( tileXyz ) );
302 QgsTriangularMesh triMesh;
303 triMesh.update( &mesh );
304
305 return QgsMeshLayerUtils::interpolateZForPoint( triMesh, point.x(), point.y() );
306}
307
308QgsChunkLoader *QgsQuantizedMeshTerrainGenerator::createChunkLoader( QgsChunkNode *node ) const
309{
310 long long tileId = QgsQuantizedMeshIndex::encodeTileId( nodeIdToTile( node->tileId() ) );
311 return new QgsQuantizedMeshTerrainChunkLoader( mTerrain, node, tileId, mIndex, mTileCrsToMapCrs );
312}
313
315{
316 return new QgsChunkNode(
317 { 0, 0, 0 },
318 mRootBox3D, // Given to us by setupQuadtree()
319 mMetadata->geometricErrorAtZoom( -1 )
320 );
321}
322
323QVector<QgsChunkNode *> QgsQuantizedMeshTerrainGenerator::createChildren( QgsChunkNode *node ) const
324{
325 QVector<QgsChunkNode *> children;
326
327 for ( auto offset : std::vector<std::pair<int, int>> { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } } )
328 {
329 QgsChunkNodeId childId(
330 node->tileId().d + 1,
331 node->tileId().x * 2 + offset.first,
332 node->tileId().y * 2 + offset.second
333 );
334 QgsTileXYZ tile = nodeIdToTile( childId );
335 if ( !mMetadata->containsTile( tile ) )
336 continue;
337
338 QgsTileMatrix zoomedTileMatrix = QgsTileMatrix::fromTileMatrix( tile.zoomLevel(), mMetadata->mTileMatrix );
339 QgsRectangle extent2d = zoomedTileMatrix.tileExtent( tile );
340 if ( !extent2d.intersects( mMapExtent ) )
341 continue; // Don't render terrain inside layer extent, but outside map extent
342 Q_ASSERT( mTerrain );
343 QgsRectangle mapExtent2d = mTileCrsToMapCrs.transform( extent2d );
344 QgsVector3D corner1( mapExtent2d.xMinimum(), mapExtent2d.yMinimum(), mMetadata->dummyZRange.lower() );
345 QgsVector3D corner2( mapExtent2d.xMaximum(), mapExtent2d.yMaximum(), mMetadata->dummyZRange.upper() );
346 children.push_back(
347 new QgsChunkNode(
348 childId,
349 QgsBox3D( corner1, corner2 ),
350 mMetadata->geometricErrorAtZoom( tile.zoomLevel() ),
351 node
352 )
353 );
354 }
355
356 return children;
357}
358
360{
361 if ( !layer )
362 {
363 mIsValid = false;
364 return false;
365 }
366
367 mLayer = layer;
368 const QgsQuantizedMeshDataProvider *provider = qobject_cast<const QgsQuantizedMeshDataProvider *>( layer->dataProvider() );
369 if ( !provider )
370 {
371 QgsDebugError( "QgsQuantizedMeshTerrainGenerator provided with non-QM layer" );
372 return false;
373 }
374 mMetadata = provider->quantizedMeshMetadata();
375 mIndex = provider->index();
376
377 mTerrainTilingScheme = QgsTilingScheme( mMetadata->mTileMatrix.extent(), mMetadata->mCrs );
378
379 mIsValid = true;
380 return true;
381}
382
387
388QgsTileXYZ QgsQuantizedMeshTerrainGenerator::nodeIdToTile( QgsChunkNodeId nodeId ) const
389{
390 // nodeId zoom=0 is tile zoom=-1 to get unique root tile
391 if ( nodeId.d == 0 )
392 return { 0, 0, -1 };
393 return {
394 nodeId.x,
395 mMetadata->mTileScheme == u"tms"_s
396 ? ( 1 << ( nodeId.d - 1 ) ) - nodeId.y - 1
397 : nodeId.y,
398 nodeId.d - 1
399 };
400}
401
402#include "qgsquantizedmeshterraingenerator.moc"
Axis
Cartesian axes.
Definition qgis.h:2509
@ Y
Y-axis.
Definition qgis.h:2511
Definition of the world.
const QgsAbstractTerrainSettings * terrainSettings() const
Returns the terrain settings.
bool isTerrainShadingEnabled() const
Returns whether terrain shading is enabled.
QgsPhongMaterialSettings terrainShadingMaterial() const
Returns terrain shading material.
Rendering context for preparation of 3D entities.
QgsCoordinateReferenceSystem crs() const
Returns the coordinate reference system used in the 3D scene.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
double verticalScale() const
Returns the vertical scale (exaggeration) for terrain.
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
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
Handles coordinate transforms between two coordinate systems.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
A simple 4x4 matrix implementation useful for transformation in 3D space.
Basic shading material used for rendering based on the Phong shading model with three color component...
void setDiffuse(const QColor &diffuse)
Sets diffuse color component.
QColor specular() const
Returns specular color component.
QColor ambient() const
Returns ambient color component.
double shininess() const
Returns shininess of the surface.
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
Exception thrown on failure to parse Quantized Mesh tile (malformed data).
bool setLayer(QgsTiledSceneLayer *layer)
Set layer to take tiles from.
void setTerrain(QgsTerrainEntity *t) override
Sets terrain entity for the generator (does not transfer ownership).
QVector< QgsChunkNode * > createChildren(QgsChunkNode *node) const override
QgsTiledSceneLayer * layer() const
Returns the layer we take tiles from.
QgsRectangle rootChunkExtent() const override
extent of the terrain's root chunk in terrain's CRS
static QgsTerrainGenerator * create()
Creates a new instance of a QgsQuantizedMeshTerrainGenerator object.
void rootChunkHeightRange(float &hMin, float &hMax) const override
Returns height range of the root chunk in world coordinates.
QgsTerrainGenerator::Type type() const override
What texture generator implementation is this.
QgsTerrainGenerator * clone() const override
Makes a copy of the current instance.
float rootChunkError(const Qgs3DMapSettings &map) const override
Returns error of the root chunk in world coordinates.
QgsChunkLoader * createChunkLoader(QgsChunkNode *node) const override
float heightAt(double x, double y, const Qgs3DRenderContext &context) const override
Returns height at (x,y) in map's CRS.
void setExtent(const QgsRectangle &extent) override
sets the extent of the terrain in terrain's CRS
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
bool intersects(const QgsRectangle &rect) const
Returns true when rectangle intersects with other rectangle.
double yMaximum
Base class for generators of terrain.
Type
Enumeration of the available terrain generators.
@ QuantizedMesh
Terrain is built from quantized mesh tiles.
QgsTilingScheme mTerrainTilingScheme
Tiling scheme of the terrain.
QgsTerrainEntity * mTerrain
Defines a matrix of tiles for a single zoom level: it is defined by its size (width *.
Definition qgstiles.h:162
QgsRectangle tileExtent(QgsTileXYZ id) const
Returns extent of the given tile in this matrix.
Definition qgstiles.cpp:85
QPointF mapToTileCoordinates(const QgsPointXY &mapPoint) const
Returns row/column coordinates (floating point number) from the given point in map coordinates.
Definition qgstiles.cpp:125
static QgsTileMatrix fromTileMatrix(int zoomLevel, const QgsTileMatrix &tileMatrix)
Returns a tile matrix based on another one.
Definition qgstiles.cpp:65
Stores coordinates of a tile in a tile matrix set.
Definition qgstiles.h:43
int zoomLevel() const
Returns tile's zoom level (Z).
Definition qgstiles.h:56
An index for tiled scene data providers.
QByteArray retrieveContent(const QString &uri, QgsFeedback *feedback=nullptr)
Retrieves index content for the specified uri.
QgsTiledSceneTile getTile(long long id)
Returns the tile with matching id, or an invalid tile if the matching tile is not available.
Represents a map layer supporting display of tiled scene objects.
Represents an individual tile from a tiled scene data source.
QVariantMap resources() const
Returns the resources attached to the tile.
QVariantMap metadata() const
Returns additional metadata attached to the tile.
const QgsMatrix4x4 * transform() const
Returns the tile's transform.
QUrl baseUrl() const
Returns the tile's base URL.
Encapsulates tiling schemes (just like with WMTS / TMS / XYZ layers).
A triangular/derived mesh with vertices in map coordinates.
bool update(QgsMesh *nativeMesh, const QgsCoordinateTransform &transform)
Constructs triangular mesh from layer's native mesh and transform to destination CRS.
A 3D vector (similar to QVector3D) with the difference that it uses double precision instead of singl...
Definition qgsvector3d.h:33
#define QgsDebugError(str)
Definition qgslogger.h:59
Mesh - vertices, edges and faces.
QgsMesh toMesh(QgsRectangle tileBounds)