33#include <Qt3DCore/QAttribute>
34#include <Qt3DCore/QBuffer>
35#include <Qt3DCore/QEntity>
36#include <Qt3DCore/QGeometry>
37#include <Qt3DRender/QGeometryRenderer>
38#include <Qt3DRender/QTexture>
40using namespace Qt::StringLiterals;
44static Qt3DCore::QAttribute::VertexBaseType parseVertexBaseType(
int componentType )
46 switch ( componentType )
48 case TINYGLTF_COMPONENT_TYPE_BYTE:
49 return Qt3DCore::QAttribute::Byte;
50 case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
51 return Qt3DCore::QAttribute::UnsignedByte;
52 case TINYGLTF_COMPONENT_TYPE_SHORT:
53 return Qt3DCore::QAttribute::Short;
54 case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
55 return Qt3DCore::QAttribute::UnsignedShort;
56 case TINYGLTF_COMPONENT_TYPE_INT:
57 return Qt3DCore::QAttribute::Int;
58 case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
59 return Qt3DCore::QAttribute::UnsignedInt;
60 case TINYGLTF_COMPONENT_TYPE_FLOAT:
61 return Qt3DCore::QAttribute::Float;
62 case TINYGLTF_COMPONENT_TYPE_DOUBLE:
63 return Qt3DCore::QAttribute::Double;
66 return Qt3DCore::QAttribute::UnsignedInt;
70static Qt3DRender::QAbstractTexture::Filter parseTextureFilter(
int filter )
74 case TINYGLTF_TEXTURE_FILTER_NEAREST:
75 return Qt3DRender::QTexture2D::Nearest;
76 case TINYGLTF_TEXTURE_FILTER_LINEAR:
77 return Qt3DRender::QTexture2D::Linear;
78 case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST:
79 return Qt3DRender::QTexture2D::NearestMipMapNearest;
80 case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST:
81 return Qt3DRender::QTexture2D::LinearMipMapNearest;
82 case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR:
83 return Qt3DRender::QTexture2D::NearestMipMapLinear;
84 case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR:
85 return Qt3DRender::QTexture2D::LinearMipMapLinear;
89 return Qt3DRender::QTexture2D::Nearest;
92static Qt3DRender::QTextureWrapMode::WrapMode parseTextureWrapMode(
int wrapMode )
96 case TINYGLTF_TEXTURE_WRAP_REPEAT:
97 return Qt3DRender::QTextureWrapMode::Repeat;
98 case TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE:
99 return Qt3DRender::QTextureWrapMode::ClampToEdge;
100 case TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT:
101 return Qt3DRender::QTextureWrapMode::MirroredRepeat;
105 return Qt3DRender::QTextureWrapMode::Repeat;
109static Qt3DCore::QAttribute *parseAttribute( tinygltf::Model &model,
int accessorIndex )
111 tinygltf::Accessor &accessor = model.accessors[accessorIndex];
112 tinygltf::BufferView &bv = model.bufferViews[accessor.bufferView];
113 tinygltf::Buffer &b = model.buffers[bv.buffer];
116 QByteArray byteArray(
reinterpret_cast<const char *
>( b.data.data() ),
117 static_cast<int>( b.data.size() ) );
118 Qt3DCore::QBuffer *buffer =
new Qt3DCore::QBuffer();
119 buffer->setData( byteArray );
121 Qt3DCore::QAttribute *attribute =
new Qt3DCore::QAttribute();
124 if ( bv.target == TINYGLTF_TARGET_ARRAY_BUFFER )
125 attribute->setAttributeType( Qt3DCore::QAttribute::VertexAttribute );
126 else if ( bv.target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER )
127 attribute->setAttributeType( Qt3DCore::QAttribute::IndexAttribute );
129 attribute->setBuffer( buffer );
130 attribute->setByteOffset( bv.byteOffset + accessor.byteOffset );
131 attribute->setByteStride( bv.byteStride );
132 attribute->setCount( accessor.count );
133 attribute->setVertexBaseType( parseVertexBaseType( accessor.componentType ) );
134 attribute->setVertexSize( tinygltf::GetNumComponentsInType( accessor.type ) );
140static Qt3DCore::QAttribute *reprojectPositions( tinygltf::Model &model,
int accessorIndex,
const QgsGltf3DUtils::EntityTransform &transform,
const QgsVector3D &tileTranslationEcef, QMatrix4x4 *matrix )
142 tinygltf::Accessor &accessor = model.accessors[accessorIndex];
144 QVector<double> vx, vy, vz;
145 bool res = QgsGltfUtils::accessorToMapCoordinates( model, accessorIndex, transform.tileTransform, transform.ecefToTargetCrs, tileTranslationEcef, matrix, transform.gltfUpAxis, vx, vy, vz );
149 QByteArray byteArray;
150 byteArray.resize( accessor.count * 4 * 3 );
151 float *out =
reinterpret_cast<float *
>( byteArray.data() );
153 QgsVector3D sceneOrigin = transform.chunkOriginTargetCrs;
154 for (
int i = 0; i < static_cast<int>( accessor.count ); ++i )
156 double x = vx[i] - sceneOrigin.
x();
157 double y = vy[i] - sceneOrigin.
y();
158 double z = ( vz[i] * transform.zValueScale ) + transform.zValueOffset - sceneOrigin.
z();
160 out[i * 3 + 0] =
static_cast<float>( x );
161 out[i * 3 + 1] =
static_cast<float>( y );
162 out[i * 3 + 2] =
static_cast<float>( z );
165 Qt3DCore::QBuffer *buffer =
new Qt3DCore::QBuffer();
166 buffer->setData( byteArray );
168 Qt3DCore::QAttribute *attribute =
new Qt3DCore::QAttribute();
169 attribute->setAttributeType( Qt3DCore::QAttribute::VertexAttribute );
170 attribute->setBuffer( buffer );
171 attribute->setByteOffset( 0 );
172 attribute->setByteStride( 12 );
173 attribute->setCount( accessor.count );
174 attribute->setVertexBaseType( Qt3DCore::QAttribute::Float );
175 attribute->setVertexSize( 3 );
180class TinyGltfTextureImageDataGenerator :
public Qt3DRender::QTextureImageDataGenerator
183 TinyGltfTextureImageDataGenerator( Qt3DRender::QTextureImageDataPtr imagePtr )
184 : mImagePtr( imagePtr )
187 Qt3DRender::QTextureImageDataPtr operator()()
override {
return mImagePtr; }
189 qintptr id()
const override {
return reinterpret_cast<qintptr
>( &Qt3DCore::FunctorType<TinyGltfTextureImageDataGenerator>::id ); }
191 bool operator==(
const QTextureImageDataGenerator &other )
const override
193 const TinyGltfTextureImageDataGenerator *otherFunctor =
dynamic_cast<const TinyGltfTextureImageDataGenerator *
>( &other );
194 return otherFunctor && mImagePtr.get() == otherFunctor->mImagePtr.get();
197 Qt3DRender::QTextureImageDataPtr mImagePtr;
200class TinyGltfTextureImage :
public Qt3DRender::QAbstractTextureImage
204 TinyGltfTextureImage( tinygltf::Image &image )
206 Q_ASSERT( image.bits == 8 );
207 Q_ASSERT( image.component == 4 );
208 Q_ASSERT( image.pixel_type == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE );
210 imgDataPtr.reset(
new Qt3DRender::QTextureImageData );
211 imgDataPtr->setWidth( image.width );
212 imgDataPtr->setHeight( image.height );
213 imgDataPtr->setDepth( 1 );
214 imgDataPtr->setFaces( 1 );
215 imgDataPtr->setLayers( 1 );
216 imgDataPtr->setMipLevels( 1 );
217 QByteArray imageBytes(
reinterpret_cast<const char *
>( image.image.data() ), image.image.size() );
218 imgDataPtr->setData( imageBytes, 4 );
219 imgDataPtr->setFormat( QOpenGLTexture::RGBA8_UNorm );
220 imgDataPtr->setPixelFormat( QOpenGLTexture::BGRA );
221 imgDataPtr->setPixelType( QOpenGLTexture::UInt8 );
222 imgDataPtr->setTarget( QOpenGLTexture::Target2D );
225 Qt3DRender::QTextureImageDataGeneratorPtr dataGenerator()
const override {
return Qt3DRender::QTextureImageDataGeneratorPtr(
new TinyGltfTextureImageDataGenerator( imgDataPtr ) ); }
227 Qt3DRender::QTextureImageDataPtr imgDataPtr;
232static QByteArray fetchUri(
const QUrl &url, QStringList *errors )
234 if ( url.scheme().startsWith(
"http" ) )
236 QNetworkRequest request = QNetworkRequest( url );
237 request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );
238 request.setAttribute( QNetworkRequest::CacheSaveControlAttribute,
true );
244 *errors << u
"Failed to download image: %1"_s.arg( url.toString() );
252 else if ( url.isLocalFile() )
254 QString localFilePath = url.toLocalFile();
255 if ( localFilePath.contains(
".slpk/" ) )
257 const QStringList parts = localFilePath.split( u
".slpk/"_s );
258 if ( parts.size() == 2 )
260 QString slpkPath = parts[0] +
".slpk";
261 QString imagePath = parts[1];
263 QByteArray imageData;
271 *errors << u
"Unable to extract image '%1' from SLPK archive: %2"_s.arg( imagePath ).arg( slpkPath );
277 *errors << u
"Missing image path in SLPK archive: %1"_s.arg( localFilePath );
280 else if ( QFile::exists( localFilePath ) )
282 QFile f( localFilePath );
283 if ( f.open( QIODevice::ReadOnly ) )
291 *errors << u
"Unable to open image: %1"_s.arg( url.toString() );
298static QgsMaterial *parseMaterial( tinygltf::Model &model,
int materialIndex, QString baseUri, QStringList *errors )
300 if ( materialIndex < 0 )
303 QgsMetalRoughMaterial *defaultMaterial =
new QgsMetalRoughMaterial;
304 defaultMaterial->setMetalness( 1 );
305 defaultMaterial->setRoughness( 1 );
306 defaultMaterial->setBaseColor( QColor::fromRgbF( 1, 1, 1 ) );
307 return defaultMaterial;
310 tinygltf::Material &material = model.materials[materialIndex];
311 tinygltf::PbrMetallicRoughness &pbr = material.pbrMetallicRoughness;
313 if ( pbr.baseColorTexture.index >= 0 )
315 tinygltf::Texture &tex = model.textures[pbr.baseColorTexture.index];
318 if ( tex.source < 0 )
320 QgsMetalRoughMaterial *pbrMaterial =
new QgsMetalRoughMaterial;
321 pbrMaterial->setMetalness( pbr.metallicFactor );
322 pbrMaterial->setRoughness( pbr.roughnessFactor );
323 pbrMaterial->setBaseColor( QColor::fromRgbF( pbr.baseColorFactor[0], pbr.baseColorFactor[1], pbr.baseColorFactor[2], pbr.baseColorFactor[3] ) );
327 tinygltf::Image &img = model.images[tex.source];
329 if ( !img.uri.empty() )
331 QString imgUri = QString::fromStdString( img.uri );
332 QUrl url = QUrl( baseUri ).resolved( imgUri );
333 QByteArray ba = fetchUri( url, errors );
336 if ( !QgsGltfUtils::loadImageDataWithQImage( &img, -1,
nullptr,
nullptr, 0, 0, (
const unsigned char * ) ba.constData(), ba.size(),
nullptr ) )
339 *errors << u
"Failed to load image: %1"_s.arg( imgUri );
344 if ( img.image.empty() )
346 QgsMetalRoughMaterial *pbrMaterial =
new QgsMetalRoughMaterial;
347 pbrMaterial->setMetalness( pbr.metallicFactor );
348 pbrMaterial->setRoughness( pbr.roughnessFactor );
349 pbrMaterial->setBaseColor( QColor::fromRgbF( pbr.baseColorFactor[0], pbr.baseColorFactor[1], pbr.baseColorFactor[2], pbr.baseColorFactor[3] ) );
353 TinyGltfTextureImage *textureImage =
new TinyGltfTextureImage( img );
355 Qt3DRender::QTexture2D *texture =
new Qt3DRender::QTexture2D;
356 texture->addTextureImage( textureImage );
359 texture->setMinificationFilter( Qt3DRender::QTexture2D::Linear );
360 texture->setMagnificationFilter( Qt3DRender::QTexture2D::Linear );
362 if ( tex.sampler >= 0 )
364 tinygltf::Sampler &sampler = model.samplers[tex.sampler];
365 if ( sampler.minFilter >= 0 )
366 texture->setMinificationFilter( parseTextureFilter( sampler.minFilter ) );
367 if ( sampler.magFilter >= 0 )
368 texture->setMagnificationFilter( parseTextureFilter( sampler.magFilter ) );
369 Qt3DRender::QTextureWrapMode wrapMode;
370 wrapMode.setX( parseTextureWrapMode( sampler.wrapS ) );
371 wrapMode.setY( parseTextureWrapMode( sampler.wrapT ) );
372 texture->setWrapMode( wrapMode );
378 QgsTextureMaterial *mat =
new QgsTextureMaterial;
379 mat->setTexture( texture );
386 QgsMetalRoughMaterial *pbrMaterial =
new QgsMetalRoughMaterial;
387 pbrMaterial->setMetalness( pbr.metallicFactor );
388 pbrMaterial->setRoughness( pbr.roughnessFactor );
389 pbrMaterial->setBaseColor( QColor::fromRgbF( pbr.baseColorFactor[0], pbr.baseColorFactor[1], pbr.baseColorFactor[2], pbr.baseColorFactor[3] ) );
394static QVector<Qt3DCore::QEntity *> parseNode(
395 tinygltf::Model &model,
int nodeIndex,
const QgsGltf3DUtils::EntityTransform &transform,
const QgsVector3D &tileTranslationEcef, QString baseUri, QMatrix4x4 parentTransform, QStringList *errors
398 tinygltf::Node &node = model.nodes[nodeIndex];
400 QVector<Qt3DCore::QEntity *> entities;
403 std::unique_ptr<QMatrix4x4> matrix = QgsGltfUtils::parseNodeTransform( node );
404 if ( !parentTransform.isIdentity() )
407 *matrix = parentTransform * *matrix;
410 matrix = std::make_unique<QMatrix4x4>( parentTransform );
415 if ( node.mesh >= 0 )
417 tinygltf::Mesh &mesh = model.meshes[node.mesh];
419 for (
const tinygltf::Primitive &primitive : mesh.primitives )
421 if ( primitive.mode != TINYGLTF_MODE_TRIANGLES )
424 *errors << u
"Unsupported mesh primitive: %1"_s.arg( primitive.mode );
428 auto posIt = primitive.attributes.find(
"POSITION" );
429 Q_ASSERT( posIt != primitive.attributes.end() );
430 int positionAccessorIndex = posIt->second;
432 tinygltf::Accessor &posAccessor = model.accessors[positionAccessorIndex];
433 if ( posAccessor.componentType != TINYGLTF_PARAMETER_TYPE_FLOAT || posAccessor.type != TINYGLTF_TYPE_VEC3 )
436 *errors << u
"Unsupported position accessor type: %1 / %2"_s.arg( posAccessor.componentType ).arg( posAccessor.type );
440 QgsMaterial *material = parseMaterial( model, primitive.material, baseUri, errors );
447 Qt3DCore::QGeometry *geom =
new Qt3DCore::QGeometry;
449 Qt3DCore::QAttribute *positionAttribute = reprojectPositions( model, positionAccessorIndex, transform, tileTranslationEcef, matrix.get() );
450 positionAttribute->setName( Qt3DCore::QAttribute::defaultPositionAttributeName() );
451 geom->addAttribute( positionAttribute );
453 auto normalIt = primitive.attributes.find(
"NORMAL" );
454 if ( normalIt != primitive.attributes.end() )
456 int normalAccessorIndex = normalIt->second;
457 Qt3DCore::QAttribute *normalAttribute = parseAttribute( model, normalAccessorIndex );
458 normalAttribute->setName( Qt3DCore::QAttribute::defaultNormalAttributeName() );
459 geom->addAttribute( normalAttribute );
465 auto texIt = primitive.attributes.find(
"TEXCOORD_0" );
466 if ( texIt != primitive.attributes.end() )
468 int texAccessorIndex = texIt->second;
469 Qt3DCore::QAttribute *texAttribute = parseAttribute( model, texAccessorIndex );
470 texAttribute->setName( Qt3DCore::QAttribute::defaultTextureCoordinateAttributeName() );
471 geom->addAttribute( texAttribute );
474 Qt3DCore::QAttribute *indexAttribute =
nullptr;
475 if ( primitive.indices != -1 )
477 indexAttribute = parseAttribute( model, primitive.indices );
478 geom->addAttribute( indexAttribute );
481 Qt3DRender::QGeometryRenderer *geomRenderer =
new Qt3DRender::QGeometryRenderer;
482 geomRenderer->setGeometry( geom );
483 geomRenderer->setPrimitiveType( Qt3DRender::QGeometryRenderer::Triangles );
484 geomRenderer->setVertexCount( indexAttribute ? indexAttribute->count() : model.accessors[positionAccessorIndex].count );
488 if ( normalIt == primitive.attributes.end() )
490 if ( QgsMetalRoughMaterial *pbrMat = qobject_cast<QgsMetalRoughMaterial *>( material ) )
492 pbrMat->setFlatShadingEnabled(
true );
496 Qt3DCore::QEntity *primitiveEntity =
new Qt3DCore::QEntity;
497 primitiveEntity->addComponent( geomRenderer );
498 primitiveEntity->addComponent( material );
499 entities << primitiveEntity;
504 for (
int childNodeIndex : node.children )
506 entities << parseNode( model, childNodeIndex, transform, tileTranslationEcef, baseUri, matrix ? *matrix : QMatrix4x4(), errors );
513Qt3DCore::QEntity *QgsGltf3DUtils::parsedGltfToEntity( tinygltf::Model &model,
const QgsGltf3DUtils::EntityTransform &transform, QString baseUri, QStringList *errors )
515 bool sceneOk =
false;
516 const std::size_t sceneIndex = QgsGltfUtils::sourceSceneForModel( model, sceneOk );
520 *errors <<
"No scenes present in the gltf data!";
524 tinygltf::Scene &scene = model.scenes[sceneIndex];
526 if ( scene.nodes.size() == 0 )
529 *errors <<
"No nodes present in the gltf data!";
533 const QgsVector3D tileTranslationEcef = QgsGltfUtils::extractTileTranslation( model );
535 Qt3DCore::QEntity *rootEntity =
new Qt3DCore::QEntity;
536 for (
const int nodeIndex : scene.nodes )
538 const QVector<Qt3DCore::QEntity *> entities = parseNode( model, nodeIndex, transform, tileTranslationEcef, baseUri, QMatrix4x4(), errors );
539 for ( Qt3DCore::QEntity *e : entities )
540 e->setParent( rootEntity );
546Qt3DCore::QEntity *QgsGltf3DUtils::gltfToEntity(
const QByteArray &data,
const QgsGltf3DUtils::EntityTransform &transform,
const QString &baseUri, QStringList *errors )
548 tinygltf::Model model;
549 QString gltfErrors, gltfWarnings;
551 bool res = QgsGltfUtils::loadGltfModel( data, model, &gltfErrors, &gltfWarnings );
552 if ( !gltfErrors.isEmpty() )
554 QgsDebugError( u
"Error raised reading %1: %2"_s.arg( baseUri, gltfErrors ) );
556 if ( !gltfWarnings.isEmpty() )
558 QgsDebugError( u
"Warnings raised reading %1: %2"_s.arg( baseUri, gltfWarnings ) );
564 errors->append( u
"GLTF load error: "_s + gltfErrors );
569 return parsedGltfToEntity( model, transform, baseUri, errors );
573#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).
bool operator==(const QgsFeatureIterator &fi1, const QgsFeatureIterator &fi2)
#define QgsDebugError(str)