27#include <Qt3DCore/QEntity>
29#if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
30#include <Qt3DRender/QAttribute>
31#include <Qt3DRender/QBuffer>
32#include <Qt3DRender/QGeometry>
37#include <Qt3DCore/QAttribute>
38#include <Qt3DCore/QBuffer>
39#include <Qt3DCore/QGeometry>
45#include <Qt3DRender/QGeometryRenderer>
46#include <Qt3DRender/QTexture>
55static Qt3DQAttribute::VertexBaseType parseVertexBaseType(
int componentType )
57 switch ( componentType )
59 case TINYGLTF_COMPONENT_TYPE_BYTE:
60 return Qt3DQAttribute::Byte;
61 case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
62 return Qt3DQAttribute::UnsignedByte;
63 case TINYGLTF_COMPONENT_TYPE_SHORT:
64 return Qt3DQAttribute::Short;
65 case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
66 return Qt3DQAttribute::UnsignedShort;
67 case TINYGLTF_COMPONENT_TYPE_INT:
68 return Qt3DQAttribute::Int;
69 case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
70 return Qt3DQAttribute::UnsignedInt;
71 case TINYGLTF_COMPONENT_TYPE_FLOAT:
72 return Qt3DQAttribute::Float;
73 case TINYGLTF_COMPONENT_TYPE_DOUBLE:
74 return Qt3DQAttribute::Double;
77 return Qt3DQAttribute::UnsignedInt;
81static Qt3DRender::QAbstractTexture::Filter parseTextureFilter(
int filter )
85 case TINYGLTF_TEXTURE_FILTER_NEAREST:
86 return Qt3DRender::QTexture2D::Nearest;
87 case TINYGLTF_TEXTURE_FILTER_LINEAR:
88 return Qt3DRender::QTexture2D::Linear;
89 case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST:
90 return Qt3DRender::QTexture2D::NearestMipMapNearest;
91 case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST:
92 return Qt3DRender::QTexture2D::LinearMipMapNearest;
93 case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR:
94 return Qt3DRender::QTexture2D::NearestMipMapLinear;
95 case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR:
96 return Qt3DRender::QTexture2D::LinearMipMapLinear;
100 return Qt3DRender::QTexture2D::Nearest;
103static Qt3DRender::QTextureWrapMode::WrapMode parseTextureWrapMode(
int wrapMode )
107 case TINYGLTF_TEXTURE_WRAP_REPEAT:
108 return Qt3DRender::QTextureWrapMode::Repeat;
109 case TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE:
110 return Qt3DRender::QTextureWrapMode::ClampToEdge;
111 case TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT:
112 return Qt3DRender::QTextureWrapMode::MirroredRepeat;
116 return Qt3DRender::QTextureWrapMode::Repeat;
120static Qt3DQAttribute *parseAttribute( tinygltf::Model &model,
int accessorIndex )
122 tinygltf::Accessor &accessor = model.accessors[accessorIndex];
123 tinygltf::BufferView &bv = model.bufferViews[accessor.bufferView];
124 tinygltf::Buffer &b = model.buffers[bv.buffer];
127 QByteArray byteArray(
reinterpret_cast<const char *
>( b.data.data() ),
128 static_cast<int>( b.data.size() ) );
130 buffer->setData( byteArray );
135 if ( bv.target == TINYGLTF_TARGET_ARRAY_BUFFER )
136 attribute->setAttributeType( Qt3DQAttribute::VertexAttribute );
137 else if ( bv.target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER )
138 attribute->setAttributeType( Qt3DQAttribute::IndexAttribute );
140 attribute->setBuffer( buffer );
141 attribute->setByteOffset( bv.byteOffset + accessor.byteOffset );
142 attribute->setByteStride( bv.byteStride );
143 attribute->setCount( accessor.count );
144 attribute->setVertexBaseType( parseVertexBaseType( accessor.componentType ) );
145 attribute->setVertexSize( tinygltf::GetNumComponentsInType( accessor.type ) );
151static Qt3DQAttribute *reprojectPositions( tinygltf::Model &model,
int accessorIndex,
const QgsGltf3DUtils::EntityTransform &transform,
const QgsVector3D &tileTranslationEcef, QMatrix4x4 *matrix )
153 tinygltf::Accessor &accessor = model.accessors[accessorIndex];
155 QVector<double> vx, vy, vz;
156 bool res = QgsGltfUtils::accessorToMapCoordinates( model, accessorIndex, transform.tileTransform, transform.ecefToTargetCrs, tileTranslationEcef, matrix, transform.gltfUpAxis, vx, vy, vz );
160 QByteArray byteArray;
161 byteArray.resize( accessor.count * 4 * 3 );
162 float *out =
reinterpret_cast<float *
>( byteArray.data() );
164 QgsVector3D sceneOrigin = transform.chunkOriginTargetCrs;
165 for (
int i = 0; i < static_cast<int>( accessor.count ); ++i )
167 double x = vx[i] - sceneOrigin.
x();
168 double y = vy[i] - sceneOrigin.
y();
169 double z = ( vz[i] * transform.zValueScale ) + transform.zValueOffset - sceneOrigin.
z();
171 out[i * 3 + 0] =
static_cast<float>( x );
172 out[i * 3 + 1] =
static_cast<float>( y );
173 out[i * 3 + 2] =
static_cast<float>( z );
177 buffer->setData( byteArray );
180 attribute->setAttributeType( Qt3DQAttribute::VertexAttribute );
181 attribute->setBuffer( buffer );
182 attribute->setByteOffset( 0 );
183 attribute->setByteStride( 12 );
184 attribute->setCount( accessor.count );
185 attribute->setVertexBaseType( Qt3DQAttribute::Float );
186 attribute->setVertexSize( 3 );
191class TinyGltfTextureImageDataGenerator :
public Qt3DRender::QTextureImageDataGenerator
194 TinyGltfTextureImageDataGenerator( Qt3DRender::QTextureImageDataPtr imagePtr )
195 : mImagePtr( imagePtr ) {}
197 Qt3DRender::QTextureImageDataPtr operator()()
override
202 qintptr id()
const override
204#if QT_VERSION < QT_VERSION_CHECK( 6, 0, 0 )
205 return reinterpret_cast<qintptr
>( &Qt3DRender::FunctorType<TinyGltfTextureImageDataGenerator>::id );
207 return reinterpret_cast<qintptr
>( &Qt3DCore::FunctorType<TinyGltfTextureImageDataGenerator>::id );
211 bool operator==(
const QTextureImageDataGenerator &other )
const override
213 const TinyGltfTextureImageDataGenerator *otherFunctor =
dynamic_cast<const TinyGltfTextureImageDataGenerator *
>( &other );
214 return otherFunctor && mImagePtr.get() == otherFunctor->mImagePtr.get();
217 Qt3DRender::QTextureImageDataPtr mImagePtr;
220class TinyGltfTextureImage :
public Qt3DRender::QAbstractTextureImage
224 TinyGltfTextureImage( tinygltf::Image &image )
226 Q_ASSERT( image.bits == 8 );
227 Q_ASSERT( image.component == 4 );
228 Q_ASSERT( image.pixel_type == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE );
230 imgDataPtr.reset(
new Qt3DRender::QTextureImageData );
231 imgDataPtr->setWidth( image.width );
232 imgDataPtr->setHeight( image.height );
233 imgDataPtr->setDepth( 1 );
234 imgDataPtr->setFaces( 1 );
235 imgDataPtr->setLayers( 1 );
236 imgDataPtr->setMipLevels( 1 );
237 QByteArray imageBytes(
reinterpret_cast<const char *
>( image.image.data() ), image.image.size() );
238 imgDataPtr->setData( imageBytes, 4 );
239 imgDataPtr->setFormat( QOpenGLTexture::RGBA8_UNorm );
240 imgDataPtr->setPixelFormat( QOpenGLTexture::BGRA );
241 imgDataPtr->setPixelType( QOpenGLTexture::UInt8 );
242 imgDataPtr->setTarget( QOpenGLTexture::Target2D );
245 Qt3DRender::QTextureImageDataGeneratorPtr dataGenerator()
const override
247 return Qt3DRender::QTextureImageDataGeneratorPtr(
new TinyGltfTextureImageDataGenerator( imgDataPtr ) );
250 Qt3DRender::QTextureImageDataPtr imgDataPtr;
255static QByteArray fetchUri(
const QUrl &url, QStringList *errors )
257 if ( url.scheme().startsWith(
"http" ) )
259 QNetworkRequest request = QNetworkRequest( url );
260 request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );
261 request.setAttribute( QNetworkRequest::CacheSaveControlAttribute,
true );
267 *errors << QStringLiteral(
"Failed to download image: %1" ).arg( url.toString() );
275 else if ( url.isLocalFile() )
277 QString localFilePath = url.toLocalFile();
278 if ( localFilePath.contains(
".slpk/" ) )
280 const QStringList parts = localFilePath.split( QStringLiteral(
".slpk/" ) );
281 if ( parts.size() == 2 )
283 QString slpkPath = parts[0] +
".slpk";
284 QString imagePath = parts[1];
286 QByteArray imageData;
294 *errors << QStringLiteral(
"Unable to extract image '%1' from SLPK archive: %2" ).arg( imagePath ).arg( slpkPath );
300 *errors << QStringLiteral(
"Missing image path in SLPK archive: %1" ).arg( localFilePath );
303 else if ( QFile::exists( localFilePath ) )
305 QFile f( localFilePath );
306 if ( f.open( QIODevice::ReadOnly ) )
314 *errors << QStringLiteral(
"Unable to open image: %1" ).arg( url.toString() );
321static QgsMaterial *parseMaterial( tinygltf::Model &model,
int materialIndex, QString baseUri, QStringList *errors )
323 if ( materialIndex < 0 )
326 QgsMetalRoughMaterial *defaultMaterial =
new QgsMetalRoughMaterial;
327 defaultMaterial->setMetalness( 1 );
328 defaultMaterial->setRoughness( 1 );
329 defaultMaterial->setBaseColor( QColor::fromRgbF( 1, 1, 1 ) );
330 return defaultMaterial;
333 tinygltf::Material &material = model.materials[materialIndex];
334 tinygltf::PbrMetallicRoughness &pbr = material.pbrMetallicRoughness;
336 if ( pbr.baseColorTexture.index >= 0 )
338 tinygltf::Texture &tex = model.textures[pbr.baseColorTexture.index];
341 if ( tex.source < 0 )
343 QgsMetalRoughMaterial *pbrMaterial =
new QgsMetalRoughMaterial;
344 pbrMaterial->setMetalness( pbr.metallicFactor );
345 pbrMaterial->setRoughness( pbr.roughnessFactor );
346 pbrMaterial->setBaseColor( QColor::fromRgbF( pbr.baseColorFactor[0], pbr.baseColorFactor[1], pbr.baseColorFactor[2], pbr.baseColorFactor[3] ) );
350 tinygltf::Image &img = model.images[tex.source];
352 if ( !img.uri.empty() )
354 QString imgUri = QString::fromStdString( img.uri );
355 QUrl url = QUrl( baseUri ).resolved( imgUri );
356 QByteArray ba = fetchUri( url, errors );
359 if ( !QgsGltfUtils::loadImageDataWithQImage( &img, -1,
nullptr,
nullptr, 0, 0, (
const unsigned char * ) ba.constData(), ba.size(),
nullptr ) )
362 *errors << QStringLiteral(
"Failed to load image: %1" ).arg( imgUri );
367 if ( img.image.empty() )
369 QgsMetalRoughMaterial *pbrMaterial =
new QgsMetalRoughMaterial;
370 pbrMaterial->setMetalness( pbr.metallicFactor );
371 pbrMaterial->setRoughness( pbr.roughnessFactor );
372 pbrMaterial->setBaseColor( QColor::fromRgbF( pbr.baseColorFactor[0], pbr.baseColorFactor[1], pbr.baseColorFactor[2], pbr.baseColorFactor[3] ) );
376 TinyGltfTextureImage *textureImage =
new TinyGltfTextureImage( img );
378 Qt3DRender::QTexture2D *texture =
new Qt3DRender::QTexture2D;
379 texture->addTextureImage( textureImage );
382 texture->setMinificationFilter( Qt3DRender::QTexture2D::Linear );
383 texture->setMagnificationFilter( Qt3DRender::QTexture2D::Linear );
385 if ( tex.sampler >= 0 )
387 tinygltf::Sampler &sampler = model.samplers[tex.sampler];
388 if ( sampler.minFilter >= 0 )
389 texture->setMinificationFilter( parseTextureFilter( sampler.minFilter ) );
390 if ( sampler.magFilter >= 0 )
391 texture->setMagnificationFilter( parseTextureFilter( sampler.magFilter ) );
392 Qt3DRender::QTextureWrapMode wrapMode;
393 wrapMode.setX( parseTextureWrapMode( sampler.wrapS ) );
394 wrapMode.setY( parseTextureWrapMode( sampler.wrapT ) );
395 texture->setWrapMode( wrapMode );
401 QgsTextureMaterial *mat =
new QgsTextureMaterial;
402 mat->setTexture( texture );
409 QgsMetalRoughMaterial *pbrMaterial =
new QgsMetalRoughMaterial;
410 pbrMaterial->setMetalness( pbr.metallicFactor );
411 pbrMaterial->setRoughness( pbr.roughnessFactor );
412 pbrMaterial->setBaseColor( QColor::fromRgbF( pbr.baseColorFactor[0], pbr.baseColorFactor[1], pbr.baseColorFactor[2], pbr.baseColorFactor[3] ) );
417static QVector<Qt3DCore::QEntity *> parseNode( tinygltf::Model &model,
int nodeIndex,
const QgsGltf3DUtils::EntityTransform &transform,
const QgsVector3D &tileTranslationEcef, QString baseUri, QMatrix4x4 parentTransform, QStringList *errors )
419 tinygltf::Node &node = model.nodes[nodeIndex];
421 QVector<Qt3DCore::QEntity *> entities;
424 std::unique_ptr<QMatrix4x4> matrix = QgsGltfUtils::parseNodeTransform( node );
425 if ( !parentTransform.isIdentity() )
428 *matrix = parentTransform * *matrix;
431 matrix = std::make_unique<QMatrix4x4>( parentTransform );
436 if ( node.mesh >= 0 )
438 tinygltf::Mesh &mesh = model.meshes[node.mesh];
440 for (
const tinygltf::Primitive &primitive : mesh.primitives )
442 if ( primitive.mode != TINYGLTF_MODE_TRIANGLES )
445 *errors << QStringLiteral(
"Unsupported mesh primitive: %1" ).arg( primitive.mode );
449 auto posIt = primitive.attributes.find(
"POSITION" );
450 Q_ASSERT( posIt != primitive.attributes.end() );
451 int positionAccessorIndex = posIt->second;
453 tinygltf::Accessor &posAccessor = model.accessors[positionAccessorIndex];
454 if ( posAccessor.componentType != TINYGLTF_PARAMETER_TYPE_FLOAT || posAccessor.type != TINYGLTF_TYPE_VEC3 )
457 *errors << QStringLiteral(
"Unsupported position accessor type: %1 / %2" ).arg( posAccessor.componentType ).arg( posAccessor.type );
461 QgsMaterial *material = parseMaterial( model, primitive.material, baseUri, errors );
470 Qt3DQAttribute *positionAttribute = reprojectPositions( model, positionAccessorIndex, transform, tileTranslationEcef, matrix.get() );
471 positionAttribute->setName( Qt3DQAttribute::defaultPositionAttributeName() );
472 geom->addAttribute( positionAttribute );
474 auto normalIt = primitive.attributes.find(
"NORMAL" );
475 if ( normalIt != primitive.attributes.end() )
477 int normalAccessorIndex = normalIt->second;
478 Qt3DQAttribute *normalAttribute = parseAttribute( model, normalAccessorIndex );
479 normalAttribute->setName( Qt3DQAttribute::defaultNormalAttributeName() );
480 geom->addAttribute( normalAttribute );
486 auto texIt = primitive.attributes.find(
"TEXCOORD_0" );
487 if ( texIt != primitive.attributes.end() )
489 int texAccessorIndex = texIt->second;
490 Qt3DQAttribute *texAttribute = parseAttribute( model, texAccessorIndex );
491 texAttribute->setName( Qt3DQAttribute::defaultTextureCoordinateAttributeName() );
492 geom->addAttribute( texAttribute );
496 if ( primitive.indices != -1 )
498 indexAttribute = parseAttribute( model, primitive.indices );
499 geom->addAttribute( indexAttribute );
502 Qt3DRender::QGeometryRenderer *geomRenderer =
new Qt3DRender::QGeometryRenderer;
503 geomRenderer->setGeometry( geom );
504 geomRenderer->setPrimitiveType( Qt3DRender::QGeometryRenderer::Triangles );
505 geomRenderer->setVertexCount( indexAttribute ? indexAttribute->count() : model.accessors[positionAccessorIndex].count );
509 if ( normalIt == primitive.attributes.end() )
511 if ( QgsMetalRoughMaterial *pbrMat = qobject_cast<QgsMetalRoughMaterial *>( material ) )
513 pbrMat->setFlatShadingEnabled(
true );
517 Qt3DCore::QEntity *primitiveEntity =
new Qt3DCore::QEntity;
518 primitiveEntity->addComponent( geomRenderer );
519 primitiveEntity->addComponent( material );
520 entities << primitiveEntity;
525 for (
int childNodeIndex : node.children )
527 entities << parseNode( model, childNodeIndex, transform, tileTranslationEcef, baseUri, matrix ? *matrix : QMatrix4x4(), errors );
534Qt3DCore::QEntity *QgsGltf3DUtils::parsedGltfToEntity( tinygltf::Model &model,
const QgsGltf3DUtils::EntityTransform &transform, QString baseUri, QStringList *errors )
536 bool sceneOk =
false;
537 const std::size_t sceneIndex = QgsGltfUtils::sourceSceneForModel( model, sceneOk );
541 *errors <<
"No scenes present in the gltf data!";
545 tinygltf::Scene &scene = model.scenes[sceneIndex];
547 if ( scene.nodes.size() == 0 )
550 *errors <<
"No nodes present in the gltf data!";
554 const QgsVector3D tileTranslationEcef = QgsGltfUtils::extractTileTranslation( model );
556 Qt3DCore::QEntity *rootEntity =
new Qt3DCore::QEntity;
557 for (
const int nodeIndex : scene.nodes )
559 const QVector<Qt3DCore::QEntity *> entities = parseNode( model, nodeIndex, transform, tileTranslationEcef, baseUri, QMatrix4x4(), errors );
560 for ( Qt3DCore::QEntity *e : entities )
561 e->setParent( rootEntity );
567Qt3DCore::QEntity *QgsGltf3DUtils::gltfToEntity(
const QByteArray &data,
const QgsGltf3DUtils::EntityTransform &transform,
const QString &baseUri, QStringList *errors )
569 tinygltf::Model model;
570 QString gltfErrors, gltfWarnings;
572 bool res = QgsGltfUtils::loadGltfModel( data, model, &gltfErrors, &gltfWarnings );
573 if ( !gltfErrors.isEmpty() )
575 QgsDebugError( QStringLiteral(
"Error raised reading %1: %2" ).arg( baseUri, gltfErrors ) );
577 if ( !gltfWarnings.isEmpty() )
579 QgsDebugError( QStringLiteral(
"Warnings raised reading %1: %2" ).arg( baseUri, gltfWarnings ) );
585 errors->append( QStringLiteral(
"GLTF load error: " ) + gltfErrors );
590 return parsedGltfToEntity( model, transform, baseUri, errors );
594#include "qgsgltf3dutils.moc"
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
@ NoError
No error was encountered.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
Base class for all materials used within QGIS 3D views.
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
QByteArray content() const
Returns the reply content.
A 3D vector (similar to QVector3D) with the difference that it uses double precision instead of singl...
double y() const
Returns Y coordinate.
double z() const
Returns Z coordinate.
double x() const
Returns X coordinate.
static bool extractFileFromZip(const QString &zipFilename, const QString &filenameInZip, QByteArray &bytesOut)
Extracts a file from a zip archive, returns true on success.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Qt3DCore::QAttribute Qt3DQAttribute
Qt3DCore::QBuffer Qt3DQBuffer
Qt3DCore::QGeometry Qt3DQGeometry
bool operator==(const QgsFeatureIterator &fi1, const QgsFeatureIterator &fi2)
#define QgsDebugError(str)