17#include "moc_qgs3dmapscene.cpp" 
   19#include <Qt3DRender/QCamera> 
   20#include <Qt3DRender/QMesh> 
   21#include <Qt3DRender/QRenderSettings> 
   22#include <Qt3DRender/QSceneLoader> 
   23#include <Qt3DExtras/QForwardRenderer> 
   24#include <Qt3DExtras/QPhongMaterial> 
   25#include <Qt3DExtras/QPhongAlphaMaterial> 
   26#include <Qt3DExtras/QDiffuseSpecularMaterial> 
   27#include <Qt3DExtras/QSphereMesh> 
   28#include <Qt3DLogic/QFrameAction> 
   29#include <Qt3DRender/QEffect> 
   30#include <Qt3DRender/QTechnique> 
   31#include <Qt3DRender/QRenderPass> 
   32#include <Qt3DRender/QRenderState> 
   33#include <Qt3DRender/QCullFace> 
   34#include <Qt3DRender/QDepthTest> 
   39#include <QOpenGLContext> 
   40#include <QOpenGLFunctions> 
   99  onBackgroundColorChanged();
 
  104  mEngine->
renderSettings()->setRenderPolicy( Qt3DRender::QRenderSettings::OnDemand );
 
  106  QRect viewportRect( QPoint( 0, 0 ), mEngine->
size() );
 
  112  float aspectRatio = ( float ) viewportRect.width() / viewportRect.height();
 
  113  mEngine->
camera()->lens()->setPerspectiveProjection( mMap.
fieldOfView(), aspectRatio, 10.f, 10000.0f );
 
  115  mFrameAction = 
new Qt3DLogic::QFrameAction();
 
  116  connect( mFrameAction, &Qt3DLogic::QFrameAction::triggered, 
this, &Qgs3DMapScene::onFrameTriggered );
 
  117  addComponent( mFrameAction ); 
 
  127  addCameraViewCenterEntity( mEngine->
camera() );
 
  128  addCameraRotationCenterEntity( mCameraController );
 
  133  createTerrainDeferred();
 
  163    const QList<QgsMapLayer *> modelVectorLayers = mModelVectorLayers;
 
  169        if ( renderer->
type() == QLatin1String( 
"vector" ) )
 
  172          if ( pointSymbol->
shapeProperty( QStringLiteral( 
"model" ) ).toString() == url )
 
  174            removeLayerEntity( layer );
 
  175            addLayerEntity( layer );
 
  178        else if ( renderer->
type() == QLatin1String( 
"rulebased" ) )
 
  181          for ( 
auto rule : rules )
 
  184            if ( pointSymbol->
shapeProperty( QStringLiteral( 
"model" ) ).toString() == url )
 
  186              removeLayerEntity( layer );
 
  187              addLayerEntity( layer );
 
  202  onSkyboxSettingsChanged();
 
  207  onEyeDomeShadingSettingsChanged();
 
  209  onDebugShadowMapSettingsChanged();
 
  210  onDebugDepthMapSettingsChanged();
 
  212  onAmbientOcclusionSettingsChanged();
 
  214  onCameraMovementSpeedChanged();
 
  216  on3DAxisSettingsChanged();
 
 
  229  const double side = std::max( extent.
width(), extent.
height() );
 
  230  double d = side / 2 / std::tan( 
cameraController()->camera()->fieldOfView() / 2 * M_PI / 180 );
 
  232  mCameraController->
resetView( 
static_cast<float>( d ) );
 
 
  243  const double xSide = std::abs( p1.
x() - p2.
x() );
 
  244  const double ySide = std::abs( p1.
y() - p2.
y() );
 
  245  const double side = std::max( xSide, ySide );
 
  247  const double fov = qDegreesToRadians( 
cameraController()->camera()->fieldOfView() );
 
  248  double distance = side / 2.0f / std::tan( fov / 2.0f );
 
  253    distance += zRange.
upper();
 
  257    static_cast<float>( center.
x() - origin.
x() ),
 
  258    static_cast<float>( center.
y() - origin.
y() ),
 
  259    static_cast<float>( distance )
 
 
  265  Qt3DRender::QCamera *camera = mCameraController->
camera();
 
  266  QVector<QgsPointXY> extent;
 
  267  QVector<int> pointsOrder = { 0, 1, 3, 2 };
 
  268  for ( 
int i : pointsOrder )
 
  270    const QPoint p( ( ( i >> 0 ) & 1 ) ? 0 : mEngine->
size().width(), ( ( i >> 1 ) & 1 ) ? 0 : mEngine->
size().height() );
 
  272    QVector3D dir = ray.direction();
 
  273    if ( dir.z() == 0.0 )
 
  274      dir.setZ( 0.000001 );
 
  275    double t = -ray.origin().z() / dir.z();
 
  279      t = camera->farPlane();
 
  284      t = std::min<float>( t, camera->farPlane() );
 
  286    QVector3D planePoint = ray.origin() + t * dir;
 
 
  296  for ( Qgs3DMapSceneEntity *entity : std::as_const( mSceneEntities ) )
 
  297    count += entity->pendingJobsCount();
 
 
  303  Qt3DRender::QCamera *camera = mCameraController->
camera();
 
  304  float fov = camera->fieldOfView();
 
  305  const QSize size = mEngine->
size();
 
  306  float screenSizePx = std::max( size.width(), size.height() ); 
 
  310  float frustumWidthAtDistance = 2 * distance * tan( fov / 2 );
 
  311  float err = frustumWidthAtDistance * epsilon / screenSizePx;
 
 
  315void Qgs3DMapScene::onCameraChanged()
 
  317  if ( mMap.
projectionType() == Qt3DRender::QCameraLens::OrthographicProjection )
 
  319    QRect viewportRect( QPoint( 0, 0 ), mEngine->
size() );
 
  320    const float viewWidthFromCenter = mCameraController->
distance();
 
  321    const float viewHeightFromCenter = viewportRect.height() * viewWidthFromCenter / viewportRect.width();
 
  322    mEngine->
camera()->lens()->setOrthographicProjection( -viewWidthFromCenter, viewWidthFromCenter, -viewHeightFromCenter, viewHeightFromCenter, mEngine->
camera()->nearPlane(), mEngine->
camera()->farPlane() );
 
  326  updateCameraNearFarPlanes();
 
  328  onShadowSettingsChanged();
 
  339  constexpr float ORIGIN_SHIFT_THRESHOLD = 10'000;
 
  340  if ( mSceneOriginShiftEnabled && mEngine->
camera()->position().length() > ORIGIN_SHIFT_THRESHOLD )
 
  348void Qgs3DMapScene::updateScene( 
bool forceUpdate )
 
  350  if ( !mSceneUpdatesEnabled )
 
  356  QgsEventTracing::ScopedEvent traceEvent( QStringLiteral( 
"3D" ), forceUpdate ? QStringLiteral( 
"Force update scene" ) : QStringLiteral( 
"Update scene" ) );
 
  358  Qgs3DMapSceneEntity::SceneContext sceneContext;
 
  359  Qt3DRender::QCamera *camera = mEngine->
camera();
 
  360  sceneContext.cameraFov = camera->fieldOfView();
 
  361  sceneContext.cameraPos = camera->position();
 
  362  const QSize size = mEngine->
size();
 
  363  sceneContext.screenSizePx = std::max( size.width(), size.height() ); 
 
  371  float fovRadians = ( camera->fieldOfView() / 2.0f ) * 
static_cast<float>( M_PI ) / 180.0f;
 
  372  float fovCotan = std::cos( fovRadians ) / std::sin( fovRadians );
 
  373  QMatrix4x4 projMatrix(
 
  374    fovCotan / camera->aspectRatio(), 0, 0, 0,
 
  379  sceneContext.viewProjectionMatrix = projMatrix * camera->viewMatrix();
 
  382  for ( Qgs3DMapSceneEntity *entity : std::as_const( mSceneEntities ) )
 
  384    if ( forceUpdate || ( entity->isEnabled() && entity->needsUpdate() ) )
 
  386      entity->handleSceneUpdate( sceneContext );
 
  387      if ( entity->hasReachedGpuMemoryLimit() )
 
  395bool Qgs3DMapScene::updateCameraNearFarPlanes()
 
  410  QMatrix4x4 viewMatrix = camera->viewMatrix();
 
  416  for ( Qgs3DMapSceneEntity *se : std::as_const( mSceneEntities ) )
 
  418    const QgsRange<float> depthRange = se->getNearFarPlaneRange( viewMatrix );
 
  420    fnear = std::min( fnear, depthRange.
lower() );
 
  421    ffar = std::max( ffar, depthRange.
upper() );
 
  430  if ( fnear == 1e9 && ffar == 0 )
 
  440    std::swap( fnear, ffar );
 
  443  float newFar = ffar * 2;
 
  444  float newNear = fnear / 2;
 
  447    camera->setFarPlane( newFar );
 
  448    camera->setNearPlane( newNear );
 
  455void Qgs3DMapScene::onFrameTriggered( 
float dt )
 
  457  QgsEventTracing::addEvent( QgsEventTracing::EventType::Instant, QStringLiteral( 
"3D" ), QStringLiteral( 
"Frame begins" ) );
 
  464  static int frameCount = 0;
 
  465  static float accumulatedTime = 0.0f;
 
  475  accumulatedTime += dt;
 
  476  if ( accumulatedTime >= 0.2f )
 
  478    float fps = ( float ) frameCount / accumulatedTime;
 
  480    accumulatedTime = 0.0f;
 
  485void Qgs3DMapScene::createTerrain()
 
  489    mSceneEntities.removeOne( mTerrain );
 
  497    mSceneEntities.removeOne( mGlobe );
 
  503  if ( !mTerrainUpdateScheduled )
 
  506    QTimer::singleShot( 0, 
this, &Qgs3DMapScene::createTerrainDeferred );
 
  507    mTerrainUpdateScheduled = 
true;
 
  516void Qgs3DMapScene::createTerrainDeferred()
 
  518  QgsChunkedEntity *terrainOrGlobe = 
nullptr;
 
  522    mGlobe = 
new QgsGlobeEntity( &mMap );
 
  523    terrainOrGlobe = mGlobe;
 
  532    mMap.
terrainGenerator()->setupQuadtree( rootBox3D, rootError, maxZoomLevel, clippingBox3D );
 
  534    mTerrain = 
new QgsTerrainEntity( &mMap );
 
  535    terrainOrGlobe = mTerrain;
 
  538  if ( terrainOrGlobe )
 
  540    terrainOrGlobe->setParent( 
this );
 
  543    mSceneEntities << terrainOrGlobe;
 
  546    connect( terrainOrGlobe, &Qgs3DMapSceneEntity::newEntityCreated, 
this, [
this]( Qt3DCore::QEntity *entity ) {
 
  548      const QList<QgsGeoTransform *> transforms = entity->findChildren<QgsGeoTransform *>();
 
  549      for ( QgsGeoTransform *transform : transforms )
 
  551        transform->setOrigin( mMap.
origin() );
 
  555      handleClippingOnEntity( entity );
 
  564    removeLayerEntity( layer );
 
  567    addLayerEntity( layer );
 
  572  mTerrainUpdateScheduled = 
false;
 
  575void Qgs3DMapScene::onBackgroundColorChanged()
 
  580void Qgs3DMapScene::updateLights()
 
  582  for ( Qt3DCore::QEntity *entity : std::as_const( mLightEntities ) )
 
  583    entity->deleteLater();
 
  584  mLightEntities.clear();
 
  586  const QList<QgsLightSource *> newLights = mMap.
lightSources();
 
  589    mLightEntities.append( source->createEntity( mMap, 
this ) );
 
  592  onShadowSettingsChanged();
 
  595void Qgs3DMapScene::updateCameraLens()
 
  602void Qgs3DMapScene::onLayerRenderer3DChanged()
 
  604  QgsMapLayer *layer = qobject_cast<QgsMapLayer *>( sender() );
 
  608  removeLayerEntity( layer );
 
  611  addLayerEntity( layer );
 
  614void Qgs3DMapScene::onLayersChanged()
 
  616  QSet<QgsMapLayer *> layersBefore = qgis::listToSet( mLayerEntities.keys() );
 
  617  QList<QgsMapLayer *> layersAdded;
 
  621    if ( !layersBefore.contains( layer ) )
 
  623      layersAdded << layer;
 
  627      layersBefore.remove( layer );
 
  632  for ( 
QgsMapLayer *layer : std::as_const( layersBefore ) )
 
  634    removeLayerEntity( layer );
 
  637  for ( 
QgsMapLayer *layer : std::as_const( layersAdded ) )
 
  639    addLayerEntity( layer );
 
  645  const QList<QgsMapLayer *> 
layers = mLayerEntities.keys();
 
  650      if ( temporalProperties->isActive() )
 
  652        removeLayerEntity( layer );
 
  653        addLayerEntity( layer );
 
 
  661  Q_ASSERT( sceneNewEntity );
 
  663  mSceneEntities.append( sceneNewEntity );
 
  665  sceneNewEntity->setParent( 
this );
 
  667  finalizeNewEntity( sceneNewEntity );
 
  669  connect( sceneNewEntity, &Qgs3DMapSceneEntity::newEntityCreated, 
this, [
this]( Qt3DCore::QEntity *entity ) {
 
  670    finalizeNewEntity( entity );
 
  672    updateCameraNearFarPlanes();
 
 
  682  Q_ASSERT( sceneEntity );
 
  684  mSceneEntities.removeOne( sceneEntity );
 
  686  sceneEntity->deleteLater();
 
 
  690void Qgs3DMapScene::addLayerEntity( 
QgsMapLayer *layer )
 
  702      if ( renderer->
type() == QLatin1String( 
"vector" ) )
 
  710            mModelVectorLayers.append( layer );
 
  714      else if ( renderer->
type() == QLatin1String( 
"rulebased" ) )
 
  717        for ( 
auto rule : rules )
 
  722            mModelVectorLayers.append( layer );
 
  750    Qt3DCore::QEntity *newEntity = renderer->
createEntity( &mMap );
 
  753      mLayerEntities.insert( layer, newEntity );
 
  755      if ( Qgs3DMapSceneEntity *sceneNewEntity = qobject_cast<Qgs3DMapSceneEntity *>( newEntity ) )
 
  762        newEntity->setParent( 
this );
 
  763        finalizeNewEntity( newEntity );
 
  790void Qgs3DMapScene::removeLayerEntity( 
QgsMapLayer *layer )
 
  792  Qt3DCore::QEntity *entity = mLayerEntities.take( layer );
 
  794  if ( Qgs3DMapSceneEntity *sceneEntity = qobject_cast<Qgs3DMapSceneEntity *>( entity ) )
 
  802      entity->deleteLater();
 
  812    mModelVectorLayers.removeAll( layer );
 
  829void Qgs3DMapScene::finalizeNewEntity( Qt3DCore::QEntity *newEntity )
 
  832  const QList<QgsGeoTransform *> transforms = newEntity->findChildren<QgsGeoTransform *>();
 
  833  for ( QgsGeoTransform *transform : transforms )
 
  835    transform->setOrigin( mMap.
origin() );
 
  839  handleClippingOnEntity( newEntity );
 
  843  const QList<QgsLineMaterial *> childLineMaterials = newEntity->findChildren<QgsLineMaterial *>();
 
  844  for ( QgsLineMaterial *lm : childLineMaterials )
 
  847      lm->setViewportSize( mEngine->
size() );
 
  850    lm->setViewportSize( mEngine->
size() );
 
  857      bm->setViewportSize( mEngine->
size() );
 
  866  const QList<Qt3DRender::QMaterial *> childMaterials = newEntity->findChildren<Qt3DRender::QMaterial *>();
 
  867  for ( Qt3DRender::QMaterial *material : childMaterials )
 
  870    if ( Qt3DExtras::QDiffuseSpecularMaterial *ph = qobject_cast<Qt3DExtras::QDiffuseSpecularMaterial *>( material ) )
 
  872      if ( ph->diffuse().value<QColor>().alphaF() != 1.0f )
 
  874        Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( ph->parent() );
 
  875        if ( entity && !entity->components().contains( transparentLayer ) )
 
  877          entity->addComponent( transparentLayer );
 
  884      Qt3DRender::QEffect *effect = material->effect();
 
  887        const QVector<Qt3DRender::QParameter *> parameters = effect->parameters();
 
  888        for ( 
const Qt3DRender::QParameter *parameter : parameters )
 
  890          if ( parameter->name() == 
"opacity" && parameter->value() != 1.0f )
 
  892            Qt3DCore::QEntity *entity = qobject_cast<Qt3DCore::QEntity *>( material->parent() );
 
  893            if ( entity && !entity->components().contains( transparentLayer ) )
 
  895              entity->addComponent( transparentLayer );
 
  905int Qgs3DMapScene::maximumTextureSize()
 const 
  907  QSurface *surface = mEngine->
surface();
 
  908  QOpenGLContext context;
 
  910  bool success = context.makeCurrent( surface );
 
  914    QOpenGLFunctions openglFunctions = QOpenGLFunctions( &context );
 
  917    openglFunctions.initializeOpenGLFunctions();
 
  918    openglFunctions.glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size );
 
  927void Qgs3DMapScene::addCameraViewCenterEntity( Qt3DRender::QCamera *camera )
 
  929  mEntityCameraViewCenter = 
new Qt3DCore::QEntity;
 
  931  Qt3DCore::QTransform *trCameraViewCenter = 
new Qt3DCore::QTransform;
 
  932  mEntityCameraViewCenter->addComponent( trCameraViewCenter );
 
  933  connect( camera, &Qt3DRender::QCamera::viewCenterChanged, 
this, [trCameraViewCenter, camera] {
 
  934    trCameraViewCenter->setTranslation( camera->viewCenter() );
 
  937  Qt3DExtras::QPhongMaterial *materialCameraViewCenter = 
new Qt3DExtras::QPhongMaterial;
 
  938  materialCameraViewCenter->setAmbient( Qt::red );
 
  939  mEntityCameraViewCenter->addComponent( materialCameraViewCenter );
 
  941  Qt3DExtras::QSphereMesh *rendererCameraViewCenter = 
new Qt3DExtras::QSphereMesh;
 
  942  rendererCameraViewCenter->setRadius( 10 );
 
  943  mEntityCameraViewCenter->addComponent( rendererCameraViewCenter );
 
  946  mEntityCameraViewCenter->setParent( 
this );
 
  955  if ( mSceneState == state )
 
  961void Qgs3DMapScene::updateSceneState()
 
  963  if ( mTerrainUpdateScheduled )
 
  969  for ( Qgs3DMapSceneEntity *entity : std::as_const( mSceneEntities ) )
 
  971    if ( entity->isEnabled() && entity->pendingJobsCount() > 0 )
 
  978  setSceneState( 
Ready );
 
  981void Qgs3DMapScene::onSkyboxSettingsChanged()
 
  986    mSkybox->deleteLater();
 
  994    QMap<QString, QString> faces;
 
 1000          faces[QStringLiteral( 
"posX" )], faces[QStringLiteral( 
"posY" )], faces[QStringLiteral( 
"posZ" )],
 
 1001          faces[QStringLiteral( 
"negX" )], faces[QStringLiteral( 
"negY" )], faces[QStringLiteral( 
"negZ" )],
 
 1012void Qgs3DMapScene::onShadowSettingsChanged()
 
 1017void Qgs3DMapScene::onAmbientOcclusionSettingsChanged()
 
 1022void Qgs3DMapScene::onDebugShadowMapSettingsChanged()
 
 1027void Qgs3DMapScene::onDebugDepthMapSettingsChanged()
 
 1032void Qgs3DMapScene::onDebugOverlayEnabledChanged()
 
 1038void Qgs3DMapScene::onEyeDomeShadingSettingsChanged()
 
 1043void Qgs3DMapScene::onCameraMovementSpeedChanged()
 
 1048void Qgs3DMapScene::onCameraNavigationModeChanged()
 
 1055  QVector<QString> notParsedLayers;
 
 1065  for ( 
auto it = mLayerEntities.constBegin(); it != mLayerEntities.constEnd(); ++it )
 
 1068    Qt3DCore::QEntity *rootEntity = it.value();
 
 1070    switch ( layerType )
 
 1074          notParsedLayers.push_back( layer->
name() );
 
 1084        notParsedLayers.push_back( layer->
name() );
 
 1098  if ( !notParsedLayers.empty() )
 
 1100    QString message = tr( 
"The following layers were not exported:" ) + 
"\n";
 
 1101    for ( 
const QString &layerName : notParsedLayers )
 
 1102      message += layerName + 
"\n";
 
 
 1111  QVector<const QgsChunkNode *> chunks;
 
 1112  if ( !mLayerEntities.contains( layer ) )
 
 1114  if ( QgsChunkedEntity *
c = qobject_cast<QgsChunkedEntity *>( mLayerEntities[layer] ) )
 
 1116    const QList<QgsChunkNode *> activeNodes = 
c->activeNodes();
 
 1117    for ( QgsChunkNode *n : activeNodes )
 
 1118      chunks.push_back( n );
 
 
 1130  double zMin = std::numeric_limits<double>::max();
 
 1131  double zMax = std::numeric_limits<double>::lowest();
 
 1134    const QgsBox3D box3D = mTerrain->rootNode()->box3D();
 
 1135    zMin = std::min( zMin, box3D.
zMinimum() );
 
 1136    zMax = std::max( zMax, box3D.
zMaximum() );
 
 1139  for ( 
auto it = mLayerEntities.constBegin(); it != mLayerEntities.constEnd(); it++ )
 
 1142    switch ( layer->
type() )
 
 1148        zMin = std::min( zMin, zRange.
lower() );
 
 1149        zMax = std::max( zMax, zRange.
upper() );
 
 1154        QgsMeshLayer *meshLayer = qobject_cast<QgsMeshLayer *>( layer );
 
 1162          zMin = std::min( zMin, verticalGroupMetadata.
minimum() * verticalScale );
 
 1163          zMax = std::max( zMax, verticalGroupMetadata.
maximum() * verticalScale );
 
 1173          zMin = std::min( zMin, zRange.
lower() );
 
 1174          zMax = std::max( zMax, zRange.
upper() );
 
 1187  const QgsDoubleRange zRange( std::min( zMin, std::numeric_limits<double>::max() ), std::max( zMax, std::numeric_limits<double>::lowest() ) );
 
 
 1198  mEntityRotationCenter = 
new Qt3DCore::QEntity;
 
 1200  Qt3DCore::QTransform *trRotationCenter = 
new Qt3DCore::QTransform;
 
 1201  mEntityRotationCenter->addComponent( trRotationCenter );
 
 1202  Qt3DExtras::QPhongMaterial *materialRotationCenter = 
new Qt3DExtras::QPhongMaterial;
 
 1203  materialRotationCenter->setAmbient( Qt::blue );
 
 1204  mEntityRotationCenter->addComponent( materialRotationCenter );
 
 1205  Qt3DExtras::QSphereMesh *rendererRotationCenter = 
new Qt3DExtras::QSphereMesh;
 
 1206  rendererRotationCenter->setRadius( 10 );
 
 1207  mEntityRotationCenter->addComponent( rendererRotationCenter );
 
 1208  mEntityRotationCenter->setEnabled( 
false );
 
 1209  mEntityRotationCenter->setParent( 
this );
 
 1212    trRotationCenter->setTranslation( center );
 
 1220void Qgs3DMapScene::on3DAxisSettingsChanged()
 
 1235void Qgs3DMapScene::onOriginChanged()
 
 1237  const QList<QgsGeoTransform *> geoTransforms = findChildren<QgsGeoTransform *>();
 
 1238  for ( QgsGeoTransform *transform : geoTransforms )
 
 1240    transform->setOrigin( mMap.
origin() );
 
 1244  for ( QgsGeoTransform *transform : rubberBandGeoTransforms )
 
 1246    transform->setOrigin( mMap.
origin() );
 
 1252  if ( !mClipPlanesEquations.isEmpty() )
 
 1261    QList<QVector4D> newPlanes;
 
 1263    for ( QVector4D plane : std::as_const( mClipPlanesEquations ) )
 
 1265      plane.setW( originShift.
x() * plane.x() + originShift.
y() * plane.y() + originShift.
z() * plane.z() + plane.w() );
 
 1266      newPlanes.append( plane );
 
 1272void Qgs3DMapScene::handleClippingOnEntity( QEntity *entity )
 const 
 1274  if ( mClipPlanesEquations.isEmpty() ) 
 
 1278      material->disableClipping();
 
 1285      material->enableClipping( mClipPlanesEquations );
 
 1291  for ( QObject *child : entity->children() )
 
 1293    Qt3DCore::QEntity *childEntity = qobject_cast<Qt3DCore::QEntity *>( child );
 
 1296      handleClippingOnEntity( childEntity );
 
 1301void Qgs3DMapScene::handleClippingOnAllEntities()
 const 
 1305  for ( 
auto it = mLayerEntities.constBegin(); it != mLayerEntities.constEnd(); ++it )
 
 1307    handleClippingOnEntity( it.value() );
 
 1311    handleClippingOnEntity( mTerrain );
 
 1315    handleClippingOnEntity( mGlobe );
 
 1323    QgsDebugMsgLevel( QStringLiteral( 
"Qgs3DMapScene::enableClipping: it is not possible to use more than %1 clipping planes." ).arg( mMaxClipPlanes ), 2 );
 
 1331  handleClippingOnAllEntities();
 
 
 1336  mClipPlanesEquations.clear();
 
 1342  handleClippingOnAllEntities();
 
 
 1345void Qgs3DMapScene::onStopUpdatesChanged()
 
LayerType
Types of layers that can be added to a map.
 
@ Group
Composite group layer. Added in QGIS 3.24.
 
@ Plugin
Plugin based layer.
 
@ TiledScene
Tiled scene layer. Added in QGIS 3.34.
 
@ Annotation
Contains freeform, georeferenced annotations. Added in QGIS 3.16.
 
@ VectorTile
Vector tile layer. Added in QGIS 3.14.
 
@ Mesh
Mesh layer. Added in QGIS 3.2.
 
@ PointCloud
Point cloud layer. Added in QGIS 3.18.
 
@ Globe
Scene is represented as a globe using a geocentric CRS.
 
@ Local
Local scene based on a projected CRS.
 
Display 3D ortho axis in the main 3D view.
 
void onAxisSettingsChanged()
Force update of the axis and the viewport when a setting has changed.
 
Convenience wrapper to simplify the creation of a 3D window ready to be used with QGIS.
 
Manages the various settings the user can choose from when exporting a 3D scene.
 
bool exportNormals() const
Returns whether normals will be exported.
 
int terrrainResolution() const
Returns the terrain resolution.
 
QString sceneFolderPath() const
Returns the scene folder path.
 
float scale() const
Returns the scale of the exported model.
 
int terrainTextureResolution() const
Returns the terrain texture resolution.
 
QString sceneName() const
Returns the scene name.
 
bool smoothEdges() const
Returns whether triangles edges will look smooth.
 
bool exportTextures() const
Returns whether textures will be exported.
 
QVector< const QgsChunkNode * > getLayerActiveChunkNodes(QgsMapLayer *layer)
Returns the active chunk nodes of layer.
 
void viewed2DExtentFrom3DChanged(QVector< QgsPointXY > extent)
Emitted when the viewed 2D extent seen by the 3D camera has changed.
 
QList< QVector4D > clipPlaneEquations() const
Returns list of clipping planes if clipping is enabled, otherwise an empty list.
 
static std::function< QMap< QString, Qgs3DMapScene * >()> sOpenScenesFunction
Static function for returning open 3D map scenes.
 
void fpsCountChanged(float fpsCount)
Emitted when the FPS count changes.
 
void setViewFrom2DExtent(const QgsRectangle &extent)
Resets camera view to show the extent extent (top view)
 
void disableClipping()
Disables OpenGL clipping.
 
Qgs3DMapScene(Qgs3DMapSettings &map, QgsAbstract3DEngine *engine)
Constructs a 3D scene based on map settings and Qt 3D renderer configuration.
 
QgsAbstract3DEngine * engine() const
Returns the abstract 3D engine.
 
void gpuMemoryLimitReached()
Emitted when one of the entities reaches its GPU memory limit and it is not possible to lower the GPU...
 
QgsCameraController * cameraController() const
Returns camera controller.
 
SceneState
Enumeration of possible states of the 3D scene.
 
@ Ready
The scene is fully loaded/updated.
 
@ Updating
The scene is still being loaded/updated.
 
bool exportScene(const Qgs3DMapExportSettings &exportSettings)
Exports the scene according to the scene export settings Returns false if the operation failed.
 
int totalPendingJobsCount() const
Returns number of pending jobs for all chunked entities.
 
void updateTemporal()
Updates the temporale entities.
 
static Q_DECL_DEPRECATED QMap< QString, Qgs3DMapScene * > openScenes()
Returns a map of 3D map scenes (by name) open in the QGIS application.
 
void totalPendingJobsCountChanged()
Emitted when the total number of pending jobs changes.
 
void fpsCounterEnabledChanged(bool fpsCounterEnabled)
Emitted when the FPS counter is activated or deactivated.
 
QgsDoubleRange elevationRange(bool ignoreTerrain=false) const
Returns the scene's elevation range.
 
QgsRectangle sceneExtent() const
Returns the scene extent in the map's CRS.
 
void sceneStateChanged()
Emitted when the scene's state has changed.
 
void removeSceneEntity(Qgs3DMapSceneEntity *entity)
Removes a 3D scene entity for the scene.
 
QList< QgsMapLayer * > layers() const
Returns the layers that contain chunked entities.
 
QVector< QgsPointXY > viewFrustum2DExtent() const
Calculates the 2D extent viewed by the 3D camera as the vertices of the viewed trapezoid.
 
void enableClipping(const QList< QVector4D > &clipPlaneEquations)
Enables OpenGL clipping based on the planes equations defined in clipPlaneEquations.
 
float worldSpaceError(float epsilon, float distance) const
Given screen error (in pixels) and distance from camera (in 3D world coordinates),...
 
void terrainEntityChanged()
Emitted when the current terrain entity is replaced by a new one.
 
void addSceneEntity(Qgs3DMapSceneEntity *entity)
Adds a 3D map scene entity to the scene.
 
void viewZoomFull()
Resets camera view to show the whole scene (top view)
 
void extentChanged()
Emitted when the 3d view's 2d extent has changed.
 
bool isDebugOverlayEnabled() const
Returns whether debug overlay is enabled.
 
void originChanged()
Emitted when the world's origin point has been shifted.
 
void eyeDomeLightingDistanceChanged()
Emitted when the eye dome lighting distance has changed.
 
void terrainShadingChanged()
Emitted when terrain shading enabled flag or terrain shading material has changed.
 
QgsVector3D mapToWorldCoordinates(const QgsVector3D &mapCoords) const
Converts map coordinates to 3D world coordinates (applies offset and turns (x,y,z) into (x,...
 
double cameraMovementSpeed() const
Returns the camera movement speed.
 
Qt3DRender::QCameraLens::ProjectionType projectionType() const
Returns the camera lens' projection type.
 
bool isSkyboxEnabled() const
Returns whether the skybox is enabled.
 
void debugDepthMapSettingsChanged()
Emitted when depth map debugging has changed.
 
Qgis::NavigationMode cameraNavigationMode() const
Returns the navigation mode used by the camera.
 
void backgroundColorChanged()
Emitted when the background color has changed.
 
bool showCameraViewCenter() const
Returns whether to show camera's view center as a sphere (for debugging)
 
void showCameraRotationCenterChanged()
Emitted when the flag whether camera's rotation center is shown has changed.
 
const QgsAbstractTerrainSettings * terrainSettings() const
Returns the terrain settings.
 
void cameraNavigationModeChanged()
Emitted when the camera navigation mode was changed.
 
void shadowSettingsChanged()
Emitted when shadow rendering settings are changed.
 
bool stopUpdates() const
Returns whether the scene updates on camera movement.
 
void eyeDomeLightingEnabledChanged()
Emitted when the flag whether eye dome lighting is used has changed.
 
void debugOverlayEnabledChanged(bool debugOverlayEnabled)
Emitted when the debug overaly is enabled or disabled.
 
Qgis::SceneMode sceneMode() const
Returns mode of the 3D scene - whether it is represented as a globe (when using Geocentric CRS such a...
 
void setOrigin(const QgsVector3D &origin)
Sets coordinates in map CRS at which our 3D world has origin (0,0,0)
 
void skyboxSettingsChanged()
Emitted when skybox settings are changed.
 
QgsShadowSettings shadowSettings() const
Returns the current configuration of shadows.
 
QList< QgsLightSource * > lightSources() const
Returns list of directional light sources defined in the scene.
 
void projectionTypeChanged()
Emitted when the camera lens projection type changes.
 
float fieldOfView() const
Returns the camera lens' field of view.
 
QgsAmbientOcclusionSettings ambientOcclusionSettings() const
Returns the current configuration of screen space ambient occlusion.
 
QgsRectangle extent() const
Returns the 3D scene's 2D extent in the 3D scene's CRS.
 
void stopUpdatesChanged()
Emitted when the flag whether to keep updating scene has changed.
 
void lightSourcesChanged()
Emitted when any of the light source settings in the map changes.
 
void showLightSourceOriginsChanged()
Emitted when the flag whether light source origins are shown has changed.
 
QgsTerrainGenerator * terrainGenerator() const
Returns the terrain generator.
 
QColor backgroundColor() const
Returns background color of the 3D map view.
 
void terrainSettingsChanged()
Emitted when the terrain settings are changed.
 
QgsVector3D worldToMapCoordinates(const QgsVector3D &worldCoords) const
Converts 3D world coordinates to map coordinates (applies offset and turns (x,y,z) into (x,...
 
bool showTerrainBoundingBoxes() const
Returns whether to display bounding boxes of terrain tiles (for debugging)
 
bool terrainRenderingEnabled() const
Returns whether the 2D terrain surface will be rendered.
 
void fpsCounterEnabledChanged(bool fpsCounterEnabled)
Emitted when the FPS counter is enabled or disabled.
 
void axisSettingsChanged()
Emitted when 3d axis rendering settings are changed.
 
void ambientOcclusionSettingsChanged()
Emitted when ambient occlusion rendering settings are changed.
 
void layersChanged()
Emitted when the list of map layers for 3d rendering has changed.
 
void eyeDomeLightingStrengthChanged()
Emitted when the eye dome lighting strength has changed.
 
QgsSkyboxSettings skyboxSettings() const
Returns the current configuration of the skybox.
 
void cameraMovementSpeedChanged()
Emitted when the camera movement speed was changed.
 
bool isFpsCounterEnabled() const
Returns whether FPS counter label is enabled.
 
void fieldOfViewChanged()
Emitted when the camera lens field of view changes.
 
QList< QgsMapLayer * > layers() const
Returns the list of 3D map layers to be rendered in the scene.
 
void terrainGeneratorChanged()
Emitted when the terrain generator has changed.
 
void debugShadowMapSettingsChanged()
Emitted when shadow map debugging has changed.
 
void showCameraViewCenterChanged()
Emitted when the flag whether camera's view center is shown has changed.
 
QgsVector3D origin() const
Returns coordinates in map CRS at which 3D scene has origin (0,0,0).
 
bool showCameraRotationCenter() const
Returns whether to show camera's rotation center as a sphere (for debugging)
 
Entity that handles the exporting of 3D scenes.
 
bool save(const QString &sceneName, const QString &sceneFolderPath, int precision=6)
Saves the scene to a .obj file Returns false if the operation failed.
 
void setExportTextures(bool exportTextures)
Sets whether the textures will be exported.
 
void parseTerrain(QgsTerrainEntity *terrain, const QString &layer)
Creates terrain export objects from the terrain entity.
 
void setTerrainResolution(int resolution)
Sets the terrain resolution.
 
void setTerrainTextureResolution(int resolution)
Sets the terrain texture resolution.
 
bool parseVectorLayerEntity(Qt3DCore::QEntity *entity, QgsVectorLayer *layer)
Creates necessary export objects from entity if it represents valid vector layer entity Returns false...
 
void setScale(float scale)
Sets the scale of the exported 3D model.
 
void setExportNormals(bool exportNormals)
Sets whether the normals will be exported.
 
void setSmoothEdges(bool smoothEdges)
Sets whether the triangles will look smooth.
 
static int maxZoomLevel(double tile0width, double tileResolution, double maxError)
Calculates the highest needed zoom level for tiles in quad-tree given width of the base tile (zoom le...
 
static QgsAABB mapToWorldExtent(const QgsRectangle &extent, double zMin, double zMax, const QgsVector3D &mapOrigin)
Converts map extent to axis aligned bounding box in 3D world coordinates.
 
static void computeBoundingBoxNearFarPlanes(const QgsAABB &bbox, const QMatrix4x4 &viewMatrix, float &fnear, float &ffar)
This routine computes nearPlane farPlane from the closest and farthest corners point of bounding box ...
 
static QgsRay3D rayFromScreenPoint(const QPoint &point, const QSize &windowSize, Qt3DRender::QCamera *camera)
Convert from clicked point on the screen to a ray in world coordinates.
 
static int openGlMaxClipPlanes(QSurface *surface)
Gets the maximum number of clip planes that can be used.
 
Axis-aligned bounding box - in world coords.
 
Base class for 3D engine implementation.
 
void sizeChanged()
Emitted after a call to setSize()
 
virtual QSurface * surface() const =0
Returns the surface of the engine.
 
virtual Qt3DRender::QCamera * camera()=0
Returns pointer to the engine's camera entity.
 
virtual void setClearColor(const QColor &color)=0
Sets background color of the scene.
 
virtual void setFrustumCullingEnabled(bool enabled)=0
Sets whether frustum culling is enabled (this should make rendering faster by not rendering entities ...
 
QgsFrameGraph * frameGraph()
Returns the shadow rendering frame graph object used to render the scene.
 
virtual QSize size() const =0
Returns size of the engine's rendering area in pixels.
 
virtual Qt3DRender::QRenderSettings * renderSettings()=0
Returns access to the engine's render settings (the frame graph can be accessed from here)
 
Base class for all renderers that participate in 3D views.
 
virtual QString type() const =0
Returns unique identifier of the renderer class (used to identify subclass)
 
virtual Qt3DCore::QEntity * createEntity(Qgs3DMapSettings *map) const =0
Returns a 3D entity that will be used to show renderer's data in 3D scene.
 
double maximumGroundError() const
Returns the maximum ground error of terrain tiles in world units.
 
int mapTileResolution() const
Returns the resolution (in pixels) of the texture of a terrain tile.
 
Base class for 3D renderers that are based on vector layers.
 
static QgsSourceCache * sourceCache()
Returns the application's source cache, used for caching embedded and remote source strings as local ...
 
A 3-dimensional box composed of x, y, z coordinates.
 
double zMaximum() const
Returns the maximum z value.
 
double zMinimum() const
Returns the minimum z value.
 
Object that controls camera movement based on user input.
 
Qt3DRender::QCamera * camera() const
Returns camera that is being controlled.
 
const QgsVector3D origin() const
Returns the origin of the scene in map coordinates.
 
float distance() const
Returns distance of the camera from the point it is looking at.
 
void setCameraNavigationMode(Qgis::NavigationMode navigationMode)
Sets the navigation mode used by the camera controller.
 
void cameraChanged()
Emitted when camera has been updated.
 
void frameTriggered(float dt)
Called internally from 3D scene when a new frame is generated. Updates camera according to keyboard/m...
 
void resetView(float distance)
Move camera back to the initial position (looking down towards origin of world's coordinates)
 
void setViewFromTop(float worldX, float worldY, float distance, float yaw=0)
Sets camera to look down towards given point in world coordinate, in given distance from plane with z...
 
void resetGlobe(float distance, double lat=0, double lon=0)
Resets view of the globe to look at a particular location given as latitude and longitude (in degrees...
 
void setOrigin(const QgsVector3D &origin)
Reacts to the shift of origin of the scene, updating camera pose and any other member variables so th...
 
void setCameraMovementSpeed(double movementSpeed)
Sets the camera movement speed.
 
void cameraRotationCenterChanged(QVector3D position)
Emitted when the camera rotation center changes.
 
A skybox constructed from 6 cube faces.
 
QgsRange which stores a range of double values.
 
bool isInfinite() const
Returns true if the range consists of all possible values.
 
Qt3DRender::QLayer * transparentObjectLayer()
Returns a layer object used to indicate that the object is transparent.
 
Container class that holds different objects related to frame graphs of 3D scenes.
 
void updateAmbientOcclusionSettings(const QgsAmbientOcclusionSettings &settings)
Updates settings for ambient occlusion.
 
void updateEyeDomeSettings(const Qgs3DMapSettings &settings)
Updates settings for eye dome lighting.
 
void updateShadowSettings(const QgsShadowSettings &shadowSettings, const QList< QgsLightSource * > &lightSources)
Updates shadow bias, light and texture size according to shadowSettings and lightSources.
 
void addClipPlanes(int nrClipPlanes)
Setups nrClipPlanes clip planes in the forward pass to enable OpenGL clipping.
 
void updateDebugShadowMapSettings(const Qgs3DMapSettings &settings)
Updates settings for shadows debug map.
 
void removeClipPlanes()
Disables OpenGL clipping.
 
Qt3DCore::QEntity * rubberBandsRootEntity()
Returns entity for all rubber bands (to show them always on top)
 
void setDebugOverlayEnabled(bool enabled)
Sets whether debug overlay is enabled.
 
void updateDebugDepthMapSettings(const Qgs3DMapSettings &settings)
Updates settings for depth debug map.
 
QgsForwardRenderView & forwardRenderView()
Returns forward renderview.
 
Base class for light sources in 3d scenes.
 
virtual QgsDoubleRange calculateZRange(QgsMapLayer *layer) const
Attempts to calculate the overall elevation or z range for the specified layer, using the settings de...
 
Base class for storage of map layer temporal properties.
 
Base class for all map layer types.
 
QgsAbstract3DRenderer * renderer3D() const
Returns 3D renderer associated with the layer.
 
void request3DUpdate()
Signal emitted when a layer requires an update in any 3D maps.
 
void renderer3DChanged()
Signal emitted when 3D renderer associated with the layer has changed.
 
void rendererChanged()
Signal emitted when renderer is changed.
 
virtual QgsMapLayerTemporalProperties * temporalProperties()
Returns the layer's temporal properties.
 
void layerModified()
Emitted when modifications has been done on layer.
 
Base class for all materials used within QGIS 3D views.
 
3D symbol that draws mesh geometry as planar triangles.
 
double verticalScale() const
Returns mesh vertical scale.
 
int verticalDatasetGroupIndex() const
Returns the index of the dataset group that will be used to render the vertical component of the 3D m...
 
void setMaximumTextureSize(int maximumTextureSize)
Sets the maximum texture size supported by the hardware Used to store the GL_MAX_TEXTURE_SIZE value t...
 
QgsMesh3DSymbol * clone() const override SIP_FACTORY
Returns a new instance of the symbol with the same settings.
 
3D renderer that renders all mesh triangles of a mesh layer.
 
void setSymbol(QgsMesh3DSymbol *symbol)
Sets 3D symbol associated with the renderer.
 
const QgsMesh3DSymbol * symbol() const
Returns 3D symbol associated with the renderer.
 
void setLayer(QgsMeshLayer *layer)
Sets vector layer associated with the renderer.
 
Represents a mesh layer supporting display of data on structured or unstructured meshes.
 
QgsMeshDatasetGroupMetadata datasetGroupMetadata(const QgsMeshDatasetIndex &index) const
Returns the dataset groups metadata.
 
virtual void showMessage(bool blocking=true)=0
display the message to the user and deletes itself
 
A skybox constructed from a panoramic image.
 
Material of the billboard rendering for points in 3D map view.
 
void setViewportSize(const QSizeF size)
Set the size of the view port.
 
3D symbol that draws point geometries as 3D objects using one of the predefined shapes.
 
Qgis::Point3DShape shape() const
Returns 3D shape for points.
 
QVariant shapeProperty(const QString &property) const
Returns the value for a specific shape property.
 
3D renderer that renders all points from a point cloud layer.
 
void setLayer(QgsPointCloudLayer *layer)
Sets point cloud layer associated with the renderer.
 
Represents a map layer supporting display of point clouds.
 
QgsMapLayerElevationProperties * elevationProperties() override
Returns the layer's elevation properties.
 
void subsetStringChanged()
Emitted when the layer's subset string has changed.
 
A template based class for storing ranges (lower to upper values).
 
T lower() const
Returns the lower bound of the range.
 
T upper() const
Returns the upper bound of the range.
 
bool isEmpty() const
Returns true if the range is empty, ie the lower bound equals (or exceeds) the upper bound and either...
 
A representation of a ray in 3D.
 
A rectangle specified with double values.
 
QList< QgsRuleBased3DRenderer::Rule * > RuleList
 
Contains the configuration of a skybox entity.
 
QMap< QString, QString > cubeMapFacesPaths() const
Returns a map containing the path of each texture specified by the user.
 
QgsSkyboxEntity::SkyboxType skyboxType() const
Returns the type of the skybox.
 
QString panoramicTexturePath() const
Returns the panoramic texture path of a skybox of type "Panormaic skybox".
 
void remoteSourceFetched(const QString &url)
Emitted when the cache has finished retrieving a 3D model from a remote url.
 
virtual QgsBox3D rootChunkBox3D(const Qgs3DMapSettings &map) const
Returns 3D box (in map coordinates) of the root chunk.
 
virtual float rootChunkError(const Qgs3DMapSettings &map) const
Returns error of the root chunk in world coordinates.
 
virtual QgsRectangle rootChunkExtent() const =0
extent of the terrain's root chunk in terrain's CRS
 
3D renderer that renders content of a tiled scene layer.
 
void setLayer(QgsTiledSceneLayer *layer)
Sets tiled scene layer associated with the renderer.
 
Represents a map layer supporting display of tiled scene objects.
 
QgsMapLayerElevationProperties * elevationProperties() override
Returns the layer's elevation properties.
 
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.
 
QString toString(int precision=17) const
Returns a string representation of the 3D vector.
 
double x() const
Returns X coordinate.
 
3D renderer that renders all features of a vector layer with the same 3D symbol.
 
Represents a vector layer which manages a vector based dataset.
 
Q_INVOKABLE Qgis::GeometryType geometryType() const
Returns point, line or polygon.
 
void selectionChanged(const QgsFeatureIds &selected, const QgsFeatureIds &deselected, bool clearAndSelect)
Emitted when selection was changed.
 
On-screen 3D engine: it creates an OpenGL window (QWindow) and displays rendered 3D scenes there.
 
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
 
bool qgsFloatNear(float a, float b, float epsilon=4 *FLT_EPSILON)
Compare two floats (but allow some difference)
 
#define QgsDebugMsgLevel(str, level)