QGIS API Documentation 3.39.0-Master (d85f3c2a281)
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#include "qgschunkloader_p.h"
18#include "qgschunknode_p.h"
20#include "qgslogger.h"
21#include "qgsmesh3dentity_p.h"
23#include "qgsproject.h"
26#include "qgsrectangle.h"
29#include "qgstiledsceneindex.h"
30#include "qgstiledscenelayer.h"
31#include "qgstiledscenetile.h"
32#include "qgstiles.h"
33#include "qgstriangularmesh.h"
34#include "qgsgltf3dutils.h"
35#include "qgsterrainentity_p.h"
36#include "qgs3dmapsettings.h"
37#include "qgsvector3d.h"
38#include "qgsapplication.h"
39#include <qcomponent.h>
40#include <qdiffusespecularmaterial.h>
41#include <qentity.h>
42#include <qglobal.h>
43#include <qnamespace.h>
44#include <qphongmaterial.h>
45#include <qtconcurrentrun.h>
46#include <qtexturematerial.h>
47
49
50class QgsQuantizedMeshTerrainChunkLoader : public QgsTerrainTileLoader
51{
52 Q_OBJECT
53 public:
54 QgsQuantizedMeshTerrainChunkLoader(
55 QgsTerrainEntity *terrain, QgsChunkNode *node, long long tileId, QgsTiledSceneIndex index, const QgsCoordinateTransform &tileCrsToMapCrs );
56 virtual Qt3DCore::QEntity *createEntity( Qt3DCore::QEntity *parent ) override;
57
58 protected:
59 virtual void onTextureLoaded() override;
60
61 private:
62 QgsTerrainTileEntity *mEntity = nullptr;
63 bool mMeshLoaded = false;
64 bool mTextureLoaded = false;
65 std::mutex mFinishedMutex;
66};
67
68QgsQuantizedMeshTerrainChunkLoader::QgsQuantizedMeshTerrainChunkLoader( QgsTerrainEntity *terrain_, QgsChunkNode *node, long long tileId, QgsTiledSceneIndex index, const QgsCoordinateTransform &tileCrsToMapCrs )
69 : QgsTerrainTileLoader( terrain_, node )
70{
71 loadTexture(); // Start loading texture
72
73 // Access terrain only on the original thread.
74 Qgs3DMapSettings *map = terrain()->mapSettings();
75 double vertScale = map->terrainVerticalScale();
76 QgsVector3D mapOrigin = map->origin();
77 bool shadingEnabled = map->isTerrainShadingEnabled();
78
79 QThreadPool::globalInstance()->start( [ this, node, tileId, index, tileCrsToMapCrs, vertScale, mapOrigin, shadingEnabled ]()
80 {
81 if ( tileId == QgsQuantizedMeshIndex::ROOT_TILE_ID )
82 {
83 // Nothing to load for imaginary root tile
84 emit finished();
85 return;
86 }
87
88 // We need to copy index, since capture makes it const. It's just a wrapped smart pointer anyway.
89 QgsTiledSceneIndex index2 = index;
90 QgsTiledSceneTile tile = index2.getTile( tileId );
91
92 QString uri = tile.resources().value( QStringLiteral( "content" ) ).toString();
93 Q_ASSERT( !uri.isEmpty() );
94
95 uri = tile.baseUrl().resolved( uri ).toString();
96 QByteArray content = index2.retrieveContent( uri );
97
98 QgsGltf3DUtils::EntityTransform entityTransform;
99 entityTransform.tileTransform = ( tile.transform() ? *tile.transform() : QgsMatrix4x4() );
100 entityTransform.sceneOriginTargetCrs = mapOrigin;
101 entityTransform.ecefToTargetCrs = &tileCrsToMapCrs;
102 entityTransform.gltfUpAxis = static_cast< Qgis::Axis >( tile.metadata().value( QStringLiteral( "gltfUpAxis" ), static_cast< int >( Qgis::Axis::Y ) ).toInt() );
103
104 try
105 {
106 QgsAABB bbox = node->bbox();
107 QgsQuantizedMeshTile qmTile( content );
108 qmTile.removeDegenerateTriangles();
109
110 // We now know the exact height range of the tile, set it to the node.
111 node->setExactBbox(
112 QgsAABB(
113 // Note that in the 3D view, Y is up!
114 bbox.xMin, qmTile.mHeader.MinimumHeight * vertScale, bbox.zMin,
115 bbox.xMax, qmTile.mHeader.MaximumHeight * vertScale, bbox.zMax ) );
116
117 if ( shadingEnabled && qmTile.mNormalCoords.size() == 0 )
118 {
119 qmTile.generateNormals();
120 }
121
122 tinygltf::Model model = qmTile.toGltf( true, 100, true );
123
124 QStringList errors;
125 Qt3DCore::QEntity *gltfEntity = QgsGltf3DUtils::parsedGltfToEntity( model, entityTransform, uri, &errors );
126 if ( !errors.isEmpty() )
127 {
128 QgsDebugError( "gltf load errors: " + errors.join( '\n' ) );
129 emit finished();
130 return;
131 }
132
133 QgsTerrainTileEntity *terrainEntity = new QgsTerrainTileEntity( node->tileId() );
134 // We count on only having one mesh.
135 Q_ASSERT( gltfEntity->children().size() == 1 );
136 gltfEntity->children()[0]->setParent( terrainEntity );
137 terrainEntity->moveToThread( QgsApplication::instance()->thread() );
138 mEntity = terrainEntity;
139 }
141 {
142 QgsDebugError( QStringLiteral( "Failed to parse tile from '%1'" ).arg( uri ) );
143 emit finished();
144 return;
145 }
146
147 {
148 std::lock_guard lock( mFinishedMutex );
149 if ( mTextureLoaded )
150 emit finished();
151 mMeshLoaded = true;
152 }
153 } );
154}
155
156Qt3DCore::QEntity *QgsQuantizedMeshTerrainChunkLoader::createEntity( Qt3DCore::QEntity *parent )
157{
158 if ( mEntity )
159 {
160 mEntity->setParent( parent );
161 Qt3DRender::QTexture2D *texture = createTexture( mEntity );
162
163 // Copied from part of QgsTerrainTileLoader::createTextureComponent, since we can't use that directly on the GLTF entity.
164 Qt3DRender::QMaterial *material = nullptr;
165 Qgs3DMapSettings *map = terrain()->mapSettings();
166 if ( map->isTerrainShadingEnabled() )
167 {
168 const QgsPhongMaterialSettings &shadingMaterial = map->terrainShadingMaterial();
169 Qt3DExtras::QDiffuseSpecularMaterial *diffuseMapMaterial = new Qt3DExtras::QDiffuseSpecularMaterial;
170 diffuseMapMaterial->setDiffuse( QVariant::fromValue( texture ) );
171 diffuseMapMaterial->setAmbient( shadingMaterial.ambient() );
172 diffuseMapMaterial->setSpecular( shadingMaterial.specular() );
173 diffuseMapMaterial->setShininess( shadingMaterial.shininess() );
174 material = diffuseMapMaterial;
175 }
176 else
177 {
178 Qt3DExtras::QTextureMaterial *textureMaterial = new Qt3DExtras::QTextureMaterial;
179 textureMaterial->setTexture( texture );
180 material = textureMaterial;
181 }
182 // Get the child that actually has the mesh and add the texture
183 Qt3DCore::QEntity *gltfEntity = mEntity->findChild<Qt3DCore::QEntity *>();
184 // Remove default material
185 auto oldMaterial = gltfEntity->componentsOfType<QgsMetalRoughMaterial>();
186 Q_ASSERT( oldMaterial.size() > 0 );
187 gltfEntity->removeComponent( oldMaterial[0] );
188 gltfEntity->addComponent( material );
189 }
190 return mEntity;
191}
192
193void QgsQuantizedMeshTerrainChunkLoader::onTextureLoaded()
194{
195 std::lock_guard lock( mFinishedMutex );
196 if ( mMeshLoaded )
197 emit finished();
198 mTextureLoaded = true;
199}
200
202
204{
205 mTerrain = t;
206 mTileCrsToMapCrs =
208 mMetadata->mCrs,
209 mTerrain->mapSettings()->crs(),
210 mTerrain->mapSettings()->transformContext() );
211}
212
214{
216 if ( mIsValid )
217 clone->setLayer( layer() );
218 else
219 clone->mLayerRef = mLayerRef; // Copy just the reference
220 return clone;
221}
222
227
229{
230 return mMetadata->mBoundingVolume.bounds().toRectangle();
231}
232
234{
235 Q_UNUSED( map );
236 return mMetadata->geometricErrorAtZoom( -1 );
237}
238
239void QgsQuantizedMeshTerrainGenerator::rootChunkHeightRange( float &hMin, float &hMax ) const
240{
241 hMin = mMetadata->mBoundingVolume.bounds().zMinimum();
242 hMax = mMetadata->mBoundingVolume.bounds().xMaximum();
243}
244float QgsQuantizedMeshTerrainGenerator::heightAt( double x, double y, const Qgs3DRenderContext &context ) const
245{
246 // TODO: This is the interesting part! We can read the height from the best
247 // currently loaded tile, or fetch the most precise tile for the coordinates
248 // given, but both have downsides.
249 Q_UNUSED( x );
250 Q_UNUSED( y );
251 Q_UNUSED( context );
252 return 0;
253}
254
255void QgsQuantizedMeshTerrainGenerator::writeXml( QDomElement &elem ) const
256{
257 QDomDocument doc = elem.ownerDocument();
258
259 elem.setAttribute( QStringLiteral( "layer" ), mLayerRef.layerId );
260}
261
262void QgsQuantizedMeshTerrainGenerator::readXml( const QDomElement &elem )
263{
264 QgsMapLayerRef layerRef = QgsMapLayerRef( elem.attribute( QStringLiteral( "layer" ) ) );
265 // We can't call setLayer yet, the reference is not resolved
266 mLayerRef = layerRef;
267}
268
270{
271 mLayerRef.resolve( &project );
272 setLayer( layer() );
273}
274
275QgsChunkLoader *QgsQuantizedMeshTerrainGenerator::createChunkLoader( QgsChunkNode *node ) const
276{
277 long long tileId = QgsQuantizedMeshIndex::encodeTileId( nodeIdToTile( node->tileId() ) );
278 return new QgsQuantizedMeshTerrainChunkLoader( mTerrain, node, tileId, mIndex, mTileCrsToMapCrs );
279}
280
282{
283 return new QgsChunkNode(
284 {0, 0, 0},
285 mRootBbox, // Given to us by setupQuadtree()
286 mMetadata->geometricErrorAtZoom( -1 ) );
287}
288
289QVector<QgsChunkNode *> QgsQuantizedMeshTerrainGenerator::createChildren( QgsChunkNode *node ) const
290{
291 QVector<QgsChunkNode *> children;
292
293 for ( auto offset : std::vector<std::pair<int, int>> {{0, 0}, {0, 1}, {1, 0}, {1, 1}} )
294 {
295 QgsChunkNodeId childId(
296 node->tileId().d + 1,
297 node->tileId().x * 2 + offset.first,
298 node->tileId().y * 2 + offset.second
299 );
300 QgsTileXYZ tile = nodeIdToTile( childId );
301 if ( !mMetadata->containsTile( tile ) )
302 continue;
303
304 QgsTileMatrix zoomedTileMatrix = QgsTileMatrix::fromTileMatrix( tile.zoomLevel(), mMetadata->mTileMatrix );
305 QgsRectangle extent2d = mTileCrsToMapCrs.transform( zoomedTileMatrix.tileExtent( tile ) );
306 Q_ASSERT( mTerrain );
307 QgsVector3D corner1 = mTerrain->mapSettings()->mapToWorldCoordinates(
308 {extent2d.xMinimum(), extent2d.yMinimum(), mMetadata->dummyZRange.lower()} );
309 QgsVector3D corner2 = mTerrain->mapSettings()->mapToWorldCoordinates(
310 {extent2d.xMaximum(), extent2d.yMaximum(), mMetadata->dummyZRange.upper()} );
311 children.push_back(
312 new QgsChunkNode(
313 childId,
314 QgsAABB(
315 corner1.x(), corner1.y(), corner1.z(),
316 corner2.x(), corner2.y(), corner2.z() ),
317 mMetadata->geometricErrorAtZoom( tile.zoomLevel() ),
318 node ) );
319 }
320
321 return children;
322}
323
325{
326 if ( !layer )
327 {
328 mIsValid = false;
329 return false;
330 }
331
332 mLayerRef = layer;
333 const QgsQuantizedMeshDataProvider *provider = qobject_cast<const QgsQuantizedMeshDataProvider *>( layer->dataProvider() );
334 if ( !provider )
335 {
336 QgsDebugError( "QgsQuantizedMeshTerrainGenerator provided with non-QM layer" );
337 return false;
338 }
339 mMetadata = provider->quantizedMeshMetadata();
340 mIndex = provider->index();
341
342 mTerrainTilingScheme = QgsTilingScheme( mMetadata->mTileMatrix.extent(), mMetadata->mCrs );
343
344 mIsValid = true;
345 return true;
346}
347
349{
350 return qobject_cast<QgsTiledSceneLayer *>( mLayerRef.get() );
351}
352
353QgsQuantizedMeshTerrainGenerator::QgsQuantizedMeshTerrainGenerator( QgsMapLayerRef layerRef, const QgsQuantizedMeshMetadata &metadata )
354 : mLayerRef( layerRef )
355 , mMetadata( metadata )
356{
357}
358
359QgsTileXYZ QgsQuantizedMeshTerrainGenerator::nodeIdToTile( QgsChunkNodeId nodeId ) const
360{
361 // nodeId zoom=0 is tile zoom=-1 to get unique root tile
362 if ( nodeId.d == 0 )
363 return { 0, 0, -1 };
364 return
365 {
366 nodeId.x,
367 mMetadata->mTileScheme == QStringLiteral( "tms" )
368 ? ( 1 << ( nodeId.d - 1 ) ) - nodeId.y - 1
369 : nodeId.y,
370 nodeId.d - 1 };
371}
372
373#include "qgsquantizedmeshterraingenerator.moc"
Axis
Cartesian axes.
Definition qgis.h:2283
@ Y
Y-axis.
double terrainVerticalScale() const
Returns vertical scale (exaggeration) of terrain.
bool isTerrainShadingEnabled() const
Returns whether terrain shading is enabled.
QgsPhongMaterialSettings terrainShadingMaterial() const
Returns terrain shading material.
QgsVector3D origin() const
Returns coordinates in map CRS at which 3D scene has origin (0,0,0).
float xMax
Definition qgsaabb.h:89
float xMin
Definition qgsaabb.h:86
float zMax
Definition qgsaabb.h:91
float zMin
Definition qgsaabb.h:88
static QgsApplication * instance()
Returns the singleton instance of the QgsApplication.
Class for doing transforms between two map 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.
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.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:107
Exception thrown on failure to parse Quantized Mesh tile (malformed data)
virtual QgsChunkNode * createRootNode() const override
bool setLayer(QgsTiledSceneLayer *layer)
Set layer to take tiles from.
virtual void resolveReferences(const QgsProject &project) override
After read of XML, resolve references to any layers that have been read as layer IDs.
virtual void setTerrain(QgsTerrainEntity *t) override
Sets terrain entity for the generator (does not transfer ownership)
virtual QVector< QgsChunkNode * > createChildren(QgsChunkNode *node) const override
QgsTiledSceneLayer * layer() const
Returns the layer we take tiles from.
virtual QgsRectangle rootChunkExtent() const override
extent of the terrain's root chunk in terrain's CRS
virtual void writeXml(QDomElement &elem) const override
Write terrain generator's configuration to XML.
virtual void rootChunkHeightRange(float &hMin, float &hMax) const override
Returns height range of the root chunk in world coordinates.
virtual QgsTerrainGenerator::Type type() const override
What texture generator implementation is this.
virtual QgsTerrainGenerator * clone() const override
Makes a copy of the current instance.
virtual float rootChunkError(const Qgs3DMapSettings &map) const override
Returns error of the root chunk in world coordinates.
virtual QgsChunkLoader * createChunkLoader(QgsChunkNode *node) const override
virtual void readXml(const QDomElement &elem) override
Read terrain generator's configuration from XML.
virtual float heightAt(double x, double y, const Qgs3DRenderContext &context) const override
Returns height at (x,y) in terrain's CRS.
A rectangle specified with double values.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double xMaximum() const
Returns the x maximum value (right side of rectangle).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
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:136
QgsRectangle tileExtent(QgsTileXYZ id) const
Returns extent of the given tile in this matrix.
Definition qgstiles.cpp:81
static QgsTileMatrix fromTileMatrix(int zoomLevel, const QgsTileMatrix &tileMatrix)
Returns a tile matrix based on another one.
Definition qgstiles.cpp:61
Stores coordinates of a tile in a tile matrix set.
Definition qgstiles.h:40
int zoomLevel() const
Returns tile's zoom level (Z)
Definition qgstiles.h:53
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.
QgsTiledSceneDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
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.
Class for storage of 3D vectors similar to QVector3D, with the difference that it uses double precisi...
Definition qgsvector3d.h:31
double y() const
Returns Y coordinate.
Definition qgsvector3d.h:50
double z() const
Returns Z coordinate.
Definition qgsvector3d.h:52
double x() const
Returns X coordinate.
Definition qgsvector3d.h:48
#define QgsDebugError(str)
Definition qgslogger.h:38
_LayerRef< QgsMapLayer > QgsMapLayerRef
TYPE * get() const
Returns a pointer to the layer, or nullptr if the reference has not yet been matched to a layer.
TYPE * resolve(const QgsProject *project)
Resolves the map layer by attempting to find a layer with matching ID within a project.
QString layerId
Original layer ID.