QGIS API Documentation 3.30.0-'s-Hertogenbosch (f186b8efe0)
qgs3dsceneexporter.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgs3dsceneexporter.cpp
3 --------------------------------------
4 Date : June 2020
5 Copyright : (C) 2020 by Belgacem Nedjima
6 Email : gb underscore nedjima at esi dot dz
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
16#include "qgs3dsceneexporter.h"
17
18#include <QVector>
19#include <Qt3DCore/QEntity>
20#include <Qt3DCore/QComponent>
21#include <Qt3DCore/QNode>
22
23#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
24#include <Qt3DRender/QAttribute>
25#include <Qt3DRender/QBuffer>
26#include <Qt3DRender/QGeometry>
27
28typedef Qt3DRender::QAttribute Qt3DQAttribute;
29typedef Qt3DRender::QBuffer Qt3DQBuffer;
30typedef Qt3DRender::QGeometry Qt3DQGeometry;
31#else
32#include <Qt3DCore/QAttribute>
33#include <Qt3DCore/QBuffer>
34#include <Qt3DCore/QGeometry>
35
36typedef Qt3DCore::QAttribute Qt3DQAttribute;
37typedef Qt3DCore::QBuffer Qt3DQBuffer;
38typedef Qt3DCore::QGeometry Qt3DQGeometry;
39#endif
40
41#include <Qt3DRender/QGeometryRenderer>
42#include <Qt3DExtras/QPlaneGeometry>
43#include <Qt3DCore/QTransform>
44#include <Qt3DRender/QMaterial>
45#include <Qt3DExtras/QDiffuseSpecularMaterial>
46#include <Qt3DExtras/QTextureMaterial>
47#include <Qt3DRender/QTextureImage>
48#include <Qt3DRender/QTexture>
49#include <Qt3DRender/QMesh>
50#include <Qt3DRender/QSceneLoader>
51#include <Qt3DRender/QAbstractTexture>
52#include <Qt3DExtras/QCylinderGeometry>
53#include <Qt3DExtras/QConeGeometry>
54#include <Qt3DExtras/QSphereGeometry>
55#include <Qt3DExtras/QCuboidGeometry>
56#include <Qt3DExtras/QTorusGeometry>
57#include <Qt3DExtras/QExtrudedTextMesh>
58#include <Qt3DExtras/QPhongMaterial>
59#include <Qt3DRender/QAbstractTextureImage>
60
61#include <QByteArray>
62#include <QFile>
63#include <QTextStream>
64
67#include "qgsterrainentity_p.h"
68#include "qgschunknode_p.h"
69#include "qgsterraingenerator.h"
70#include "qgs3dmapsettings.h"
75#include "qgs3dexportobject.h"
78#include "qgsmeshterraingenerator.h"
79#include "qgsvectorlayer.h"
83#include "qgs3dutils.h"
84#include "qgsimagetexture.h"
85
86#include <numeric>
87
88template<typename T>
89QVector<T> getAttributeData( Qt3DQAttribute *attribute, const QByteArray &data )
90{
91 const uint bytesOffset = attribute->byteOffset();
92 const uint bytesStride = attribute->byteStride();
93 const uint vertexSize = attribute->vertexSize();
94 QVector<T> result;
95
96 if ( bytesStride == 0 )
97 {
98 QgsDebugMsg( "bytesStride==0, the attribute probably was not set properly" );
99 return result;
100 }
101
102 const char *pData = data.constData();
103 for ( int i = bytesOffset; i < data.size(); i += bytesStride )
104 {
105 for ( unsigned int j = 0; j < vertexSize * sizeof( T ); j += sizeof( T ) )
106 {
107 T v;
108 memcpy( &v, pData + i + j, sizeof( T ) );
109 result.push_back( v );
110 }
111 }
112 return result;
113}
114
115template<typename T>
116QVector<uint> _getIndexDataImplementation( const QByteArray &data )
117{
118 QVector<uint> result;
119 const char *pData = data.constData();
120 for ( int i = 0; i < data.size(); i += sizeof( T ) )
121 {
122 T v;
123 memcpy( &v, pData + i, sizeof( T ) );
124 result.push_back( ( uint ) v );
125 }
126 return result;
127}
128
129QVector<uint> getIndexData( Qt3DQAttribute *indexAttribute, const QByteArray &data )
130{
131 switch ( indexAttribute->vertexBaseType() )
132 {
133 case Qt3DQAttribute::VertexBaseType::Int:
134 return _getIndexDataImplementation<int>( data );
135 case Qt3DQAttribute::VertexBaseType::UnsignedInt:
136 return _getIndexDataImplementation<uint>( data );
137 case Qt3DQAttribute::VertexBaseType::Short:
138 return _getIndexDataImplementation<short>( data );
139 case Qt3DQAttribute::VertexBaseType::UnsignedShort:
140 return _getIndexDataImplementation<ushort>( data );
141 case Qt3DQAttribute::VertexBaseType::Byte:
142 return _getIndexDataImplementation<char>( data );
143 case Qt3DQAttribute::VertexBaseType::UnsignedByte:
144 return _getIndexDataImplementation<uchar>( data );
145 default:
146 QgsDebugMsg( "Probably trying to get index data using an attribute that has vertex data" );
147 break;
148 }
149 return QVector<uint>();
150}
151
152QByteArray getData( Qt3DQBuffer *buffer )
153{
154 QByteArray bytes = buffer->data();
155 if ( bytes.isNull() )
156 {
157 QgsDebugMsg( "QBuffer is null" );
158 }
159 return bytes;
160}
161
162Qt3DQAttribute *findAttribute( Qt3DQGeometry *geometry, const QString &name, Qt3DQAttribute::AttributeType type )
163{
164 for ( Qt3DQAttribute *attribute : geometry->attributes() )
165 {
166 if ( attribute->attributeType() != type ) continue;
167 if ( attribute->name() == name ) return attribute;
168 }
169 return nullptr;
170}
171
172template<typename Component>
173Component *findTypedComponent( Qt3DCore::QEntity *entity )
174{
175 if ( entity == nullptr ) return nullptr;
176 for ( Qt3DCore::QComponent *component : entity->components() )
177 {
178 Component *typedComponent = qobject_cast<Component *>( component );
179 if ( typedComponent != nullptr )
180 return typedComponent;
181 }
182 return nullptr;
183}
184
185bool Qgs3DSceneExporter::parseVectorLayerEntity( Qt3DCore::QEntity *entity, QgsVectorLayer *layer )
186{
187 QgsAbstract3DRenderer *abstractRenderer = layer->renderer3D();
188 const QString rendererType = abstractRenderer->type();
189
190 if ( rendererType == "mesh" )
191 {
192 // TODO: handle mesh layers
193 }
194 else
195 {
196 QgsAbstractVectorLayer3DRenderer *abstractVectorRenderer = dynamic_cast< QgsAbstractVectorLayer3DRenderer *>( abstractRenderer );
197 if ( rendererType == "rulebased" )
198 {
199 // Potential bug: meshes loaded using Qt3DRender::QSceneLoader will probably have wrong scale and translation
200 const QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
201 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
202 {
203 Qt3DCore::QEntity *parentEntity = qobject_cast<Qt3DCore::QEntity *>( renderer->parent() );
204 if ( !parentEntity )
205 continue;
206 Qgs3DExportObject *object = processGeometryRenderer( renderer, layer->name() + QStringLiteral( "_" ) );
207 if ( object == nullptr ) continue;
208 if ( mExportTextures )
209 processEntityMaterial( parentEntity, object );
210 mObjects.push_back( object );
211 }
212 return true;
213 }
214 else
215 {
216 QgsVectorLayer3DRenderer *vectorLayerRenderer = dynamic_cast< QgsVectorLayer3DRenderer *>( abstractVectorRenderer );
217 if ( vectorLayerRenderer )
218 {
219 const QgsAbstract3DSymbol *symbol = vectorLayerRenderer->symbol();
220 const bool exported = symbol->exportGeometries( this, entity, layer->name() + QStringLiteral( "_" ) );
221 return exported;
222 }
223 else
224 return false;
225 }
226 }
227 return false;
228}
229
230void Qgs3DSceneExporter::processEntityMaterial( Qt3DCore::QEntity *entity, Qgs3DExportObject *object )
231{
232 Qt3DExtras::QPhongMaterial *phongMaterial = findTypedComponent<Qt3DExtras::QPhongMaterial>( entity );
233 if ( phongMaterial != nullptr )
234 {
236 object->setupMaterial( &material );
237 }
238 Qt3DExtras::QDiffuseSpecularMaterial *diffuseMapMaterial = findTypedComponent<Qt3DExtras::QDiffuseSpecularMaterial>( entity );
239
240 if ( diffuseMapMaterial != nullptr )
241 {
242 const QVector<Qt3DRender::QAbstractTextureImage *> textureImages = diffuseMapMaterial->diffuse().value< Qt3DRender::QTexture2D * >()->textureImages();
243 QgsImageTexture *imageTexture = nullptr;
244 for ( Qt3DRender::QAbstractTextureImage *tex : textureImages )
245 {
246 imageTexture = dynamic_cast<QgsImageTexture *>( tex );
247 if ( imageTexture != nullptr ) break;
248 }
249 if ( imageTexture != nullptr )
250 {
251 const QImage image = imageTexture->getImage();
252 object->setTextureImage( image );
253 }
254 }
255}
256
257void Qgs3DSceneExporter::parseTerrain( QgsTerrainEntity *terrain, const QString &layerName )
258{
259 const Qgs3DMapSettings &settings = terrain->map3D();
260 if ( !settings.terrainRenderingEnabled() )
261 return;
262
263 QgsChunkNode *node = terrain->rootNode();
264
265 QgsTerrainGenerator *generator = settings.terrainGenerator();
266 if ( !generator )
267 return;
268 QgsTerrainTileEntity *terrainTile = nullptr;
269 QgsTerrainTextureGenerator *textureGenerator = terrain->textureGenerator();
270 textureGenerator->waitForFinished();
271 const QSize oldResolution = textureGenerator->textureSize();
272 textureGenerator->setTextureSize( QSize( mTerrainTextureResolution, mTerrainTextureResolution ) );
273 switch ( generator->type() )
274 {
276 terrainTile = getDemTerrainEntity( terrain, node );
277 parseDemTile( terrainTile, layerName + QStringLiteral( "_" ) );
278 break;
280 terrainTile = getFlatTerrainEntity( terrain, node );
281 parseFlatTile( terrainTile, layerName + QStringLiteral( "_" ) );
282 break;
283 // TODO: implement other terrain types
285 terrainTile = getMeshTerrainEntity( terrain, node );
286 parseMeshTile( terrainTile, layerName + QStringLiteral( "_" ) );
287 break;
289 break;
290 }
291 textureGenerator->setTextureSize( oldResolution );
292}
293
294QgsTerrainTileEntity *Qgs3DSceneExporter::getFlatTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
295{
296 QgsFlatTerrainGenerator *generator = dynamic_cast<QgsFlatTerrainGenerator *>( terrain->map3D().terrainGenerator() );
297 FlatTerrainChunkLoader *flatTerrainLoader = qobject_cast<FlatTerrainChunkLoader *>( generator->createChunkLoader( node ) );
298 if ( mExportTextures )
299 terrain->textureGenerator()->waitForFinished();
300 // the entity we created will be deallocated once the scene exporter is deallocated
301 Qt3DCore::QEntity *entity = flatTerrainLoader->createEntity( this );
302 QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( entity );
303 return tileEntity;
304}
305
306QgsTerrainTileEntity *Qgs3DSceneExporter::getDemTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
307{
308 // Just create a new tile (we don't need to export exact level of details as in the scene)
309 // create the entity synchronously and then it will be deleted once our scene exporter instance is deallocated
310 QgsDemTerrainGenerator *generator = dynamic_cast<QgsDemTerrainGenerator *>( terrain->map3D().terrainGenerator()->clone() );
311 generator->setResolution( mTerrainResolution );
312 QgsDemTerrainTileLoader *loader = qobject_cast<QgsDemTerrainTileLoader *>( generator->createChunkLoader( node ) );
313 generator->heightMapGenerator()->waitForFinished();
314 if ( mExportTextures )
315 terrain->textureGenerator()->waitForFinished();
316 QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( loader->createEntity( this ) );
317 delete generator;
318 return tileEntity;
319}
320
321QgsTerrainTileEntity *Qgs3DSceneExporter::getMeshTerrainEntity( QgsTerrainEntity *terrain, QgsChunkNode *node )
322{
323 QgsMeshTerrainGenerator *generator = dynamic_cast<QgsMeshTerrainGenerator *>( terrain->map3D().terrainGenerator() );
324 QgsMeshTerrainTileLoader *loader = qobject_cast<QgsMeshTerrainTileLoader *>( generator->createChunkLoader( node ) );
325 // TODO: export textures
326 QgsTerrainTileEntity *tileEntity = qobject_cast<QgsTerrainTileEntity *>( loader->createEntity( this ) );
327 return tileEntity;
328}
329
330void Qgs3DSceneExporter::parseFlatTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
331{
332 Qt3DRender::QGeometryRenderer *mesh = findTypedComponent<Qt3DRender::QGeometryRenderer>( tileEntity );
333 Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( tileEntity );
334
335 Qt3DQGeometry *geometry = mesh->geometry();
336 Qt3DExtras::QPlaneGeometry *tileGeometry = qobject_cast<Qt3DExtras::QPlaneGeometry *>( geometry );
337 if ( tileGeometry == nullptr )
338 {
339 QgsDebugMsg( "Qt3DExtras::QPlaneGeometry* is expected but something else was given" );
340 return;
341 }
342
343 const float scale = transform->scale();
344 const QVector3D translation = transform->translation();
345
346 // Generate vertice data
347 Qt3DQAttribute *positionAttribute = tileGeometry->positionAttribute();
348 const QByteArray verticesBytes = getData( positionAttribute->buffer() );
349 const QVector<float> positionBuffer = getAttributeData<float>( positionAttribute, verticesBytes );
350
351 // Generate index data
352 Qt3DQAttribute *indexAttribute = tileGeometry->indexAttribute();
353 const QByteArray indexBytes = getData( indexAttribute->buffer() );
354 const QVector<uint> indexesBuffer = getIndexData( indexAttribute, indexBytes );
355
356 QString objectNamePrefix = layerName;
357 if ( objectNamePrefix != QString() ) objectNamePrefix += QString();
358
359 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "Flat_tile" ) ) );
360 mObjects.push_back( object );
361
362 object->setSmoothEdges( mSmoothEdges );
363 object->setupPositionCoordinates( positionBuffer, scale, translation );
364 object->setupFaces( indexesBuffer );
365
366 if ( mExportNormals )
367 {
368 // Everts
369 QVector<float> normalsBuffer;
370 for ( int i = 0; i < positionBuffer.size(); i += 3 ) normalsBuffer << 0.0f << 1.0f << 0.0f;
371 object->setupNormalCoordinates( normalsBuffer );
372 }
373
374 Qt3DQAttribute *texCoordsAttribute = tileGeometry->texCoordAttribute();
375 if ( mExportTextures && texCoordsAttribute != nullptr )
376 {
377 // Reuse vertex buffer data for texture coordinates
378 const QVector<float> texCoords = getAttributeData<float>( texCoordsAttribute, verticesBytes );
379 object->setupTextureCoordinates( texCoords );
380
381 QgsTerrainTextureImage *textureImage = tileEntity->textureImage();
382 const QImage img = textureImage->getImage();
383 object->setTextureImage( img );
384 }
385}
386
387void Qgs3DSceneExporter::parseDemTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
388{
389 Qt3DRender::QGeometryRenderer *mesh = findTypedComponent<Qt3DRender::QGeometryRenderer>( tileEntity );
390 Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( tileEntity );
391
392 Qt3DQGeometry *geometry = mesh->geometry();
393 DemTerrainTileGeometry *tileGeometry = qobject_cast<DemTerrainTileGeometry *>( geometry );
394 if ( tileGeometry == nullptr )
395 {
396 QgsDebugMsg( "DemTerrainTileGeometry* is expected but something else was given" );
397 return;
398 }
399
400 const float scale = transform->scale();
401 const QVector3D translation = transform->translation();
402
403 Qt3DQAttribute *positionAttribute = tileGeometry->positionAttribute();
404 const QByteArray positionBytes = positionAttribute->buffer()->data();
405 const QVector<float> positionBuffer = getAttributeData<float>( positionAttribute, positionBytes );
406
407 Qt3DQAttribute *indexAttribute = tileGeometry->indexAttribute();
408 const QByteArray indexBytes = indexAttribute->buffer()->data();
409 const QVector<unsigned int> indexBuffer = getIndexData( indexAttribute, indexBytes );
410
411 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( layerName + QStringLiteral( "DEM_tile" ) ) );
412 mObjects.push_back( object );
413
414 object->setSmoothEdges( mSmoothEdges );
415 object->setupPositionCoordinates( positionBuffer, scale, translation );
416 object->setupFaces( indexBuffer );
417
418 Qt3DQAttribute *normalsAttributes = tileGeometry->normalAttribute();
419 if ( mExportNormals && normalsAttributes != nullptr )
420 {
421 const QByteArray normalsBytes = normalsAttributes->buffer()->data();
422 const QVector<float> normalsBuffer = getAttributeData<float>( normalsAttributes, normalsBytes );
423 object->setupNormalCoordinates( normalsBuffer );
424 }
425
426 Qt3DQAttribute *texCoordsAttribute = tileGeometry->texCoordsAttribute();
427 if ( mExportTextures && texCoordsAttribute != nullptr )
428 {
429 const QByteArray texCoordsBytes = texCoordsAttribute->buffer()->data();
430 const QVector<float> texCoordsBuffer = getAttributeData<float>( texCoordsAttribute, texCoordsBytes );
431 object->setupTextureCoordinates( texCoordsBuffer );
432
433 QgsTerrainTextureImage *textureImage = tileEntity->textureImage();
434 const QImage img = textureImage->getImage();
435 object->setTextureImage( img );
436 }
437}
438
439void Qgs3DSceneExporter::parseMeshTile( QgsTerrainTileEntity *tileEntity, const QString &layerName )
440{
441 QString objectNamePrefix = layerName;
442 if ( objectNamePrefix != QString() ) objectNamePrefix += QStringLiteral( "_" );
443
444 const QList<Qt3DRender::QGeometryRenderer *> renderers = tileEntity->findChildren<Qt3DRender::QGeometryRenderer *>();
445 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
446 {
447 Qgs3DExportObject *obj = processGeometryRenderer( renderer, objectNamePrefix );
448 if ( obj == nullptr ) continue;
449 mObjects << obj;
450 }
451}
452
453QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processInstancedPointGeometry( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
454{
455 QVector<Qgs3DExportObject *> objects;
456 const QList<Qt3DQGeometry *> geometriesList = entity->findChildren<Qt3DQGeometry *>();
457 for ( Qt3DQGeometry *geometry : geometriesList )
458 {
459 Qt3DQAttribute *positionAttribute = findAttribute( geometry, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
460 Qt3DQAttribute *indexAttribute = nullptr;
461 for ( Qt3DQAttribute *attribute : geometry->attributes() )
462 {
463 if ( attribute->attributeType() == Qt3DQAttribute::IndexAttribute )
464 indexAttribute = attribute;
465 }
466 if ( positionAttribute == nullptr || indexAttribute == nullptr )
467 continue;
468 const QByteArray vertexBytes = getData( positionAttribute->buffer() );
469 const QByteArray indexBytes = getData( indexAttribute->buffer() );
470 const QVector<float> positionData = getAttributeData<float>( positionAttribute, vertexBytes );
471 const QVector<uint> indexData = getIndexData( indexAttribute, indexBytes );
472
473 Qt3DQAttribute *instanceDataAttribute = findAttribute( geometry, QStringLiteral( "pos" ), Qt3DQAttribute::VertexAttribute );
474 const QByteArray instancePositionBytes = getData( instanceDataAttribute->buffer() );
475 QVector<float> instancePosition = getAttributeData<float>( instanceDataAttribute, instancePositionBytes );
476 for ( int i = 0; i < instancePosition.size(); i += 3 )
477 {
478 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "shape_geometry" ) ) );
479 objects.push_back( object );
480 object->setupPositionCoordinates( positionData, 1.0f, QVector3D( instancePosition[i], instancePosition[i + 1], instancePosition[i + 2] ) );
481 object->setupFaces( indexData );
482
483 object->setSmoothEdges( mSmoothEdges );
484
485 Qt3DQAttribute *normalsAttribute = findAttribute( geometry, Qt3DQAttribute::defaultNormalAttributeName(), Qt3DQAttribute::VertexAttribute );
486 if ( mExportNormals && normalsAttribute != nullptr )
487 {
488 // Reuse vertex bytes
489 const QVector<float> normalsData = getAttributeData<float>( normalsAttribute, vertexBytes );
490 object->setupNormalCoordinates( normalsData );
491 }
492 }
493 }
494 return objects;
495}
496
497QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processSceneLoaderGeometries( Qt3DRender::QSceneLoader *sceneLoader, const QString &objectNamePrefix )
498{
499 QVector<Qgs3DExportObject *> objects;
500 Qt3DCore::QEntity *sceneLoaderParent = qobject_cast<Qt3DCore::QEntity *>( sceneLoader->parent() );
501 Qt3DCore::QTransform *entityTransform = findTypedComponent<Qt3DCore::QTransform>( sceneLoaderParent );
502 float sceneScale = 1.0f;
503 QVector3D sceneTranslation( 0.0f, 0.0f, 0.0f );
504 if ( entityTransform != nullptr )
505 {
506 sceneScale = entityTransform->scale();
507 sceneTranslation = entityTransform->translation();
508 }
509 for ( const QString &entityName : sceneLoader->entityNames() )
510 {
511 Qt3DRender::QGeometryRenderer *mesh = qobject_cast<Qt3DRender::QGeometryRenderer *>( sceneLoader->component( entityName, Qt3DRender::QSceneLoader::GeometryRendererComponent ) );
512 Qgs3DExportObject *object = processGeometryRenderer( mesh, objectNamePrefix, sceneScale, sceneTranslation );
513 if ( object == nullptr ) continue;
514 objects.push_back( object );
515 }
516 return objects;
517}
518
519Qgs3DExportObject *Qgs3DSceneExporter::processGeometryRenderer( Qt3DRender::QGeometryRenderer *mesh, const QString &objectNamePrefix, float sceneScale, QVector3D sceneTranslation )
520{
521 // We only export triangles for now
522 if ( mesh->primitiveType() != Qt3DRender::QGeometryRenderer::Triangles ) return nullptr;
523
524 float scale = 1.0f;
525 QVector3D translation( 0.0f, 0.0f, 0.0f );
526 QObject *parent = mesh->parent();
527 while ( parent != nullptr )
528 {
529 Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( parent );
530 Qt3DCore::QTransform *transform = findTypedComponent<Qt3DCore::QTransform>( entity );
531 if ( transform != nullptr )
532 {
533 scale *= transform->scale();
534 translation += transform->translation();
535 }
536 parent = parent->parent();
537 }
538
539 Qt3DQGeometry *geometry = mesh->geometry();
540
541 Qt3DQAttribute *positionAttribute = findAttribute( geometry, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
542 Qt3DQAttribute *indexAttribute = nullptr;
543 QByteArray indexBytes, vertexBytes;
544 QVector<uint> indexData;
545 QVector<float> positionData;
546 for ( Qt3DQAttribute *attribute : geometry->attributes() )
547 {
548 if ( attribute->attributeType() == Qt3DQAttribute::IndexAttribute )
549 indexAttribute = attribute;
550 }
551
552 if ( indexAttribute != nullptr )
553 {
554 indexBytes = getData( indexAttribute->buffer() );
555 indexData = getIndexData( indexAttribute, indexBytes );
556 }
557
558 if ( positionAttribute != nullptr )
559 {
560 vertexBytes = getData( positionAttribute->buffer() );
561 positionData = getAttributeData<float>( positionAttribute, vertexBytes );
562 }
563
564// For tessellated polygons that don't have index attributes
565 if ( positionAttribute != nullptr && indexAttribute == nullptr )
566 {
567 for ( int i = 0; i < positionData.size() / 3; ++i )
568 indexData.push_back( i );
569 }
570
571 if ( positionAttribute == nullptr )
572 {
573 QgsDebugMsg( "Geometry renderer with null data was being processed" );
574 return nullptr;
575 }
576
577 Qgs3DExportObject *object = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "mesh_geometry" ) ) );
578 object->setupPositionCoordinates( positionData, scale * sceneScale, translation + sceneTranslation );
579 object->setupFaces( indexData );
580
581 Qt3DQAttribute *normalsAttribute = findAttribute( geometry, Qt3DQAttribute::defaultNormalAttributeName(), Qt3DQAttribute::VertexAttribute );
582 if ( mExportNormals && normalsAttribute != nullptr )
583 {
584 // Reuse vertex bytes
585 const QVector<float> normalsData = getAttributeData<float>( normalsAttribute, vertexBytes );
586 object->setupNormalCoordinates( normalsData );
587 }
588
589 Qt3DQAttribute *texCoordsAttribute = findAttribute( geometry, Qt3DQAttribute::defaultTextureCoordinateAttributeName(), Qt3DQAttribute::VertexAttribute );
590 if ( mExportTextures && texCoordsAttribute != nullptr )
591 {
592 // Reuse vertex bytes
593 const QVector<float> texCoordsData = getAttributeData<float>( texCoordsAttribute, vertexBytes );
594 object->setupTextureCoordinates( texCoordsData );
595 }
596
597 return object;
598}
599
600QVector<Qgs3DExportObject *> Qgs3DSceneExporter::processLines( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
601{
602 QVector<Qgs3DExportObject *> objs;
603 const QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
604 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
605 {
606 if ( renderer->primitiveType() != Qt3DRender::QGeometryRenderer::LineStripAdjacency ) continue;
607 Qt3DQGeometry *geom = renderer->geometry();
608 Qt3DQAttribute *positionAttribute = findAttribute( geom, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
609 Qt3DQAttribute *indexAttribute = nullptr;
610 for ( Qt3DQAttribute *attribute : geom->attributes() )
611 {
612 if ( attribute->attributeType() == Qt3DQAttribute::IndexAttribute )
613 {
614 indexAttribute = attribute;
615 break;
616 }
617 }
618 if ( positionAttribute == nullptr || indexAttribute == nullptr )
619 {
620 QgsDebugMsg( "Position or index attribute was not found" );
621 continue;
622 }
623
624 const QByteArray vertexBytes = getData( positionAttribute->buffer() );
625 const QByteArray indexBytes = getData( indexAttribute->buffer() );
626 const QVector<float> positionData = getAttributeData<float>( positionAttribute, vertexBytes );
627 const QVector<uint> indexData = getIndexData( indexAttribute, indexBytes );
628
629 Qgs3DExportObject *exportObject = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "line" ) ) );
630 exportObject->setType( Qgs3DExportObject::LineStrip );
631 exportObject->setupPositionCoordinates( positionData );
632 exportObject->setupLine( indexData );
633
634 objs.push_back( exportObject );
635 }
636 return objs;
637}
638
639Qgs3DExportObject *Qgs3DSceneExporter::processPoints( Qt3DCore::QEntity *entity, const QString &objectNamePrefix )
640{
641 QVector<float> points;
642 const QList<Qt3DRender::QGeometryRenderer *> renderers = entity->findChildren<Qt3DRender::QGeometryRenderer *>();
643 for ( Qt3DRender::QGeometryRenderer *renderer : renderers )
644 {
645 Qt3DQGeometry *geometry = qobject_cast<QgsBillboardGeometry *>( renderer->geometry() );
646 if ( geometry == nullptr )
647 continue;
648 Qt3DQAttribute *positionAttribute = findAttribute( geometry, Qt3DQAttribute::defaultPositionAttributeName(), Qt3DQAttribute::VertexAttribute );
649 const QByteArray positionBytes = getData( positionAttribute->buffer() );
650 if ( positionBytes.size() == 0 )
651 continue;
652 const QVector<float> positions = getAttributeData<float>( positionAttribute, positionBytes );
653 points << positions;
654 }
655 Qgs3DExportObject *obj = new Qgs3DExportObject( getObjectName( objectNamePrefix + QStringLiteral( "points" ) ) );
657 obj->setupPositionCoordinates( points );
658 return obj;
659}
660
661void Qgs3DSceneExporter::save( const QString &sceneName, const QString &sceneFolderPath )
662{
663 const QString objFilePath = QDir( sceneFolderPath ).filePath( sceneName + QStringLiteral( ".obj" ) );
664 const QString mtlFilePath = QDir( sceneFolderPath ).filePath( sceneName + QStringLiteral( ".mtl" ) );
665
666 QFile file( objFilePath );
667 if ( !file.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
668 return;
669 QFile mtlFile( mtlFilePath );
670 if ( !mtlFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate ) )
671 return;
672
673 float maxfloat = std::numeric_limits<float>::max(), minFloat = std::numeric_limits<float>::lowest();
674 float minX = maxfloat, minY = maxfloat, minZ = maxfloat, maxX = minFloat, maxY = minFloat, maxZ = minFloat;
675 for ( Qgs3DExportObject *obj : mObjects ) obj->objectBounds( minX, minY, minZ, maxX, maxY, maxZ );
676
677 float diffX = 1.0f, diffY = 1.0f, diffZ = 1.0f;
678 diffX = maxX - minX;
679 diffY = maxY - minY;
680 diffZ = maxZ - minZ;
681
682 const float centerX = ( minX + maxX ) / 2.0f;
683 const float centerY = ( minY + maxY ) / 2.0f;
684 const float centerZ = ( minZ + maxZ ) / 2.0f;
685
686 const float scale = std::max( diffX, std::max( diffY, diffZ ) );
687
688 QTextStream out( &file );
689 // set material library name
690 const QString mtlLibName = sceneName + ".mtl";
691 out << "mtllib " << mtlLibName << "\n";
692
693 QTextStream mtlOut( &mtlFile );
694 for ( Qgs3DExportObject *obj : mObjects )
695 {
696 if ( obj == nullptr ) continue;
697 // Set object name
698 const QString material = obj->saveMaterial( mtlOut, sceneFolderPath );
699 out << "o " << obj->name() << "\n";
700 if ( material != QString() )
701 out << "usemtl " << material << "\n";
702 obj->saveTo( out, scale / mScale, QVector3D( centerX, centerY, centerZ ) );
703 }
704}
705
706QString Qgs3DSceneExporter::getObjectName( const QString &name )
707{
708 QString ret = name;
709 if ( usedObjectNamesCounter.contains( name ) )
710 {
711 ret = QStringLiteral( "%1%2" ).arg( name ).arg( usedObjectNamesCounter[name] );
712 usedObjectNamesCounter[name]++;
713 }
714 else
715 usedObjectNamesCounter[name] = 2;
716 return ret;
717}
Manages the data of each object of the scene (positions, normals, texture coordinates ....
void saveTo(QTextStream &out, float scale, const QVector3D &center)
Saves the current object to the output stream while scaling the object and centering it to be visible...
void setType(ObjectType type)
Sets the object type.
void objectBounds(float &minX, float &minY, float &minZ, float &maxX, float &maxY, float &maxZ)
Updates the box bounds explained with the current object bounds This expands the bounding box if the ...
void setupPositionCoordinates(const QVector< float > &positionsBuffer, float scale=1.0f, const QVector3D &translation=QVector3D(0, 0, 0))
Sets positions coordinates and does the translation and scaling.
QString name() const
Returns the object name.
QString saveMaterial(QTextStream &mtlOut, const QString &folder)
saves the texture of the object and material information
void setupLine(const QVector< uint > &facesIndexes)
sets line vertex indexes
QgsTerrainGenerator * terrainGenerator() const
Returns the terrain generator.
bool terrainRenderingEnabled() const
Returns whether the 2D terrain surface will be rendered.
void parseTerrain(QgsTerrainEntity *terrain, const QString &layer)
Creates terrain export objects from the terrain entity.
void save(const QString &sceneName, const QString &sceneFolderPath)
Saves the scene to a .obj file.
float scale() const
Returns the scale of the exported 3D model.
bool parseVectorLayerEntity(Qt3DCore::QEntity *entity, QgsVectorLayer *layer)
Creates necessary export objects from entity if it represents valid vector layer entity Returns false...
static QgsPhongMaterialSettings phongMaterialFromQt3DComponent(Qt3DExtras::QPhongMaterial *material)
Returns phong material settings object based on the Qt3D material.
Definition: qgs3dutils.cpp:674
Base class for all renderers that may to participate in 3D view.
virtual QString type() const =0
Returns unique identifier of the renderer class (used to identify subclass)
virtual bool exportGeometries(Qgs3DSceneExporter *exporter, Qt3DCore::QEntity *entity, const QString &objectNamePrefix) const
Exports the geometries contained within the hierarchy of entity.
QgsDemHeightMapGenerator * heightMapGenerator()
Returns height map generator object - takes care of extraction of elevations from the layer)
QgsChunkLoader * createChunkLoader(QgsChunkNode *node) const override
void setResolution(int resolution)
Sets resolution of the generator (how many elevation samples on one side of a terrain tile)
QgsChunkLoader * createChunkLoader(QgsChunkNode *node) const override SIP_FACTORY
Holds an image that can be used as a texture in the 3D view.
QImage getImage() const
Returns the image.
QString name
Definition: qgsmaplayer.h:76
QgsAbstract3DRenderer * renderer3D() const
Returns 3D renderer associated with the layer.
@ Dem
Terrain is built from raster layer with digital elevation model.
@ Online
Terrain is built from downloaded tiles with digital elevation model.
@ Mesh
Terrain is built from mesh layer with z value on vertices.
@ Flat
The whole terrain is flat area.
virtual Type type() const =0
What texture generator implementation is this.
3D renderer that renders all features of a vector layer with the same 3D symbol.
const QgsAbstract3DSymbol * symbol() const
Returns 3D symbol associated with the renderer.
Represents a vector layer which manages a vector based data sets.
Qt3DCore::QAttribute Qt3DQAttribute
Definition: qgs3daxis.cpp:28
Qt3DCore::QBuffer Qt3DQBuffer
Definition: qgs3daxis.cpp:30
Qt3DCore::QGeometry Qt3DQGeometry
Definition: qgs3daxis.cpp:29
QVector< T > getAttributeData(Qt3DQAttribute *attribute, const QByteArray &data)
Qt3DQAttribute * findAttribute(Qt3DQGeometry *geometry, const QString &name, Qt3DQAttribute::AttributeType type)
Qt3DCore::QAttribute Qt3DQAttribute
QVector< uint > getIndexData(Qt3DQAttribute *indexAttribute, const QByteArray &data)
QByteArray getData(Qt3DQBuffer *buffer)
Qt3DCore::QBuffer Qt3DQBuffer
QVector< uint > _getIndexDataImplementation(const QByteArray &data)
Component * findTypedComponent(Qt3DCore::QEntity *entity)
Qt3DCore::QGeometry Qt3DQGeometry
#define QgsDebugMsg(str)
Definition: qgslogger.h:38