38#include <Qt3DExtras/QDiffuseMapMaterial>
39#include <Qt3DExtras/QPhongMaterial>
40#include <Qt3DRender/QAbstractTextureImage>
41#include <Qt3DRender/QCullFace>
42#include <Qt3DRender/QEffect>
43#include <Qt3DRender/QGeometryRenderer>
44#include <Qt3DRender/QTechnique>
45#include <Qt3DRender/QTexture>
50class QgsPolygon3DSymbolHandler :
public QgsFeature3DHandler
53 QgsPolygon3DSymbolHandler(
const QgsPolygon3DSymbol *symbol,
const QgsFeatureIds &selectedIds )
54 : mSymbol( static_cast<QgsPolygon3DSymbol *>( symbol->clone() ) )
55 , mSelectedIds( selectedIds )
58 bool prepare(
const Qgs3DRenderContext &context, QSet<QString> &attributeNames,
const QgsBox3D &chunkExtent )
override;
59 void processFeature(
const QgsFeature &f,
const Qgs3DRenderContext &context )
override;
60 void finalize( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context )
override;
66 std::unique_ptr<QgsTessellator> tessellator;
67 QVector<QgsFeatureId> triangleIndexFids;
68 QVector<uint> triangleIndexStartingIndices;
69 QByteArray materialDataDefined;
72 void processPolygon(
const QgsPolygon *poly,
QgsFeatureId fid,
float offset,
float extrusionHeight,
const Qgs3DRenderContext &context, PolygonData &out );
73 void processMaterialDatadefined( uint verticesCount,
const QgsExpressionContext &context, PolygonData &out );
74 void makeEntity( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context, PolygonData &out,
bool selected );
75 QgsMaterial *material(
const QgsPolygon3DSymbol *symbol,
bool isSelected,
const Qgs3DRenderContext &context )
const;
78 std::unique_ptr<QgsPolygon3DSymbol> mSymbol;
82 PolygonData outNormal;
83 PolygonData outSelected;
85 QgsLineVertexData outEdges;
88 bool mWasClippedToExtent =
false;
92bool QgsPolygon3DSymbolHandler::prepare(
const Qgs3DRenderContext &context, QSet<QString> &attributeNames,
const QgsBox3D &chunkExtent )
94 mChunkOrigin = chunkExtent.
center();
95 mChunkOrigin.
setZ( 0. );
96 mChunkExtent = chunkExtent;
98 outEdges.withAdjacency =
true;
99 outEdges.init( mSymbol->altitudeClamping(), mSymbol->altitudeBinding(), 0, context, mChunkOrigin );
101 const bool requiresTextureCoordinates = mSymbol->materialSettings() && mSymbol->materialSettings()->requiresTextureCoordinates();
102 const bool requiresTangents = mSymbol->materialSettings() && mSymbol->materialSettings()->requiresTangents();
104 auto tessellator = std::make_unique<QgsTessellator>();
105 tessellator->setOrigin( mChunkOrigin );
106 tessellator->setAddNormals(
true );
107 tessellator->setInvertNormals( mSymbol->invertNormals() );
108 tessellator->setBackFacesEnabled( mSymbol->addBackFaces() );
109 tessellator->setExtrusionFaces( mSymbol->extrusionFaces() );
110 tessellator->setAddTextureUVs( requiresTextureCoordinates );
111 tessellator->setAddTangents( requiresTangents );
114 outNormal.tessellator = std::move( tessellator );
116 tessellator = std::make_unique<QgsTessellator>();
117 tessellator->setOrigin( mChunkOrigin );
118 tessellator->setAddNormals(
true );
119 tessellator->setInvertNormals( mSymbol->invertNormals() );
120 tessellator->setBackFacesEnabled( mSymbol->addBackFaces() );
121 tessellator->setExtrusionFaces( mSymbol->extrusionFaces() );
122 tessellator->setAddTextureUVs( requiresTextureCoordinates );
123 tessellator->setAddTangents( requiresTangents );
126 outSelected.tessellator = std::move( tessellator );
128 QSet<QString> attrs = mSymbol->dataDefinedProperties().referencedFields( context.
expressionContext() );
129 attributeNames.unite( attrs );
130 attrs = mSymbol->materialSettings()->dataDefinedProperties().referencedFields( context.
expressionContext() );
131 attributeNames.unite( attrs );
137 std::unique_ptr<QgsPolygon> polyClone( poly->
clone() );
139 if ( mSymbol->edgesEnabled() )
148 if ( mWasClippedToExtent )
153 const QVector< QgsPointXY > extentPoints {
154 { mChunkExtent.xMinimum(), mChunkExtent.yMinimum() },
155 { mChunkExtent.xMaximum(), mChunkExtent.yMinimum() },
156 { mChunkExtent.xMaximum(), mChunkExtent.yMaximum() },
157 { mChunkExtent.xMinimum(), mChunkExtent.yMaximum() },
158 { mChunkExtent.xMinimum(), mChunkExtent.yMinimum() }
160 auto extentLinestring = std::make_unique<QgsLineString>( extentPoints );
164 cleanedExteriorRingGeometry = exteriorRingGeometry.
difference(
QgsGeometry( extentLinestring.release() ) );
172 outEdges.addLineString( *line, offset );
177 for (
int i = 0; i < mline->numGeometries(); ++i )
180 outEdges.addLineString( *line, offset );
186 for (
int i = 0; i < polyClone->numInteriorRings(); ++i )
187 outEdges.addLineString( *
static_cast<const QgsLineString *
>( polyClone->interiorRing( i ) ), offset );
189 if ( extrusionHeight != 0.f )
195 outEdges.addLineString( *line, extrusionHeight + offset );
196 outEdges.addVerticalLines( *line, extrusionHeight, offset );
201 for (
int i = 0; i < mline->numGeometries(); ++i )
204 outEdges.addLineString( *line, extrusionHeight + offset );
205 outEdges.addVerticalLines( *line, extrusionHeight, offset );
211 for (
int i = 0; i < polyClone->numInteriorRings(); ++i )
214 outEdges.addLineString( *interior, extrusionHeight + offset );
215 outEdges.addVerticalLines( *interior, extrusionHeight, offset );
222 Q_ASSERT( out.tessellator->dataVerticesCount() % 3 == 0 );
223 const uint startingTriangleIndex =
static_cast<uint
>( out.tessellator->dataVerticesCount() / 3 );
224 out.triangleIndexStartingIndices.append( startingTriangleIndex );
225 out.triangleIndexFids.append( fid );
227 const size_t oldVertexCount = out.tessellator->uniqueVertexCount();
228 out.tessellator->addPolygon( *polyClone, extrusionHeight );
229 if ( !out.tessellator->error().isEmpty() )
234 if ( mSymbol->materialSettings()->dataDefinedProperties().hasActiveProperties() )
236 const uint newUniqueVertices = out.tessellator->uniqueVertexCount() - oldVertexCount;
237 processMaterialDatadefined( newUniqueVertices, context.
expressionContext(), out );
241void QgsPolygon3DSymbolHandler::processMaterialDatadefined( uint verticesCount,
const QgsExpressionContext &context, QgsPolygon3DSymbolHandler::PolygonData &out )
244 out.materialDataDefined.append( bytes.repeated( verticesCount ) );
252 PolygonData &out = mSelectedIds.contains( f.
id() ) ? outSelected : outNormal;
255 mWasClippedToExtent = clipGeometryIfTooLarge( geom );
273 float offset = mSymbol->offset();
274 float extrusionHeight = mSymbol->extrusionHeight();
277 if ( hasDDExtrusion )
282 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
286 for (
int i = 0; i < mpoly->numGeometries(); ++i )
288 const QgsPolygon *poly = mpoly->polygonN( i );
289 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
294 for (
int i = 0; i < gc->numGeometries(); ++i )
300 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
306 for (
int i = 0; i < polySurface->numPatches(); ++i )
308 const QgsPolygon *poly = polySurface->patchN( i );
309 processPolygon( poly, f.
id(), offset, extrusionHeight, context, out );
313 qWarning() <<
"not a polygon";
318void QgsPolygon3DSymbolHandler::finalize( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context )
321 makeEntity( parent, context, outNormal,
false );
322 makeEntity( parent, context, outSelected,
true );
324 mZMin = std::min( outNormal.tessellator->zMinimum(), outSelected.tessellator->zMinimum() );
325 mZMax = std::max( outNormal.tessellator->zMaximum(), outSelected.tessellator->zMaximum() );
328 if ( mSymbol->edgesEnabled() && !outEdges.indexes.isEmpty() && !mHighlightingEnabled )
330 QgsLineMaterial *mat =
new QgsLineMaterial;
331 mat->setLineColor( mSymbol->edgeColor() );
332 mat->setLineWidth( mSymbol->edgeWidth() );
334 Qt3DCore::QEntity *entity =
new Qt3DCore::QEntity;
335 entity->setObjectName( parent->objectName() +
"_EDGES" );
338 Qt3DRender::QGeometryRenderer *renderer =
new Qt3DRender::QGeometryRenderer;
339 renderer->setPrimitiveType( Qt3DRender::QGeometryRenderer::LineStripAdjacency );
340 renderer->setGeometry( outEdges.createGeometry( entity ) );
341 renderer->setVertexCount( outEdges.indexes.count() );
342 renderer->setPrimitiveRestartEnabled(
true );
343 renderer->setRestartIndexValue( 0 );
346 QgsGeoTransform *tr =
new QgsGeoTransform;
347 tr->setGeoTranslation( mChunkOrigin );
350 entity->addComponent( renderer );
351 entity->addComponent( mat );
352 entity->addComponent( tr );
353 entity->setParent( parent );
358void QgsPolygon3DSymbolHandler::makeEntity( Qt3DCore::QEntity *parent,
const Qgs3DRenderContext &context, PolygonData &polyData,
bool selected )
360 if ( polyData.tessellator->dataVerticesCount() == 0 )
363 QgsMaterial *mat = material( mSymbol.get(), selected, context );
366 const QByteArray vertexBuffer = polyData.tessellator->vertexBuffer();
367 const QByteArray indexBuffer = polyData.tessellator->indexBuffer();
368 const int vertexCount = polyData.tessellator->uniqueVertexCount();
369 const size_t indexCount = polyData.tessellator->dataVerticesCount();
373 mSymbol->invertNormals(),
374 mSymbol->addBackFaces(),
375 mSymbol->materialSettings() && mSymbol->materialSettings()->requiresTextureCoordinates(),
376 mSymbol->materialSettings() && mSymbol->materialSettings()->requiresTangents()
379 geometry->
setVertexBufferData( vertexBuffer, vertexCount, polyData.triangleIndexFids, polyData.triangleIndexStartingIndices );
382 if ( mSymbol->materialSettings()->dataDefinedProperties().hasActiveProperties() )
386 Qt3DRender::QGeometryRenderer *renderer =
new Qt3DRender::QGeometryRenderer;
387 renderer->setGeometry( geometry );
390 QgsGeoTransform *tr =
new QgsGeoTransform;
391 tr->setGeoTranslation( mChunkOrigin );
394 Qt3DCore::QEntity *entity =
new Qt3DCore::QEntity;
395 entity->setObjectName( parent->objectName() +
"_CHUNK_MESH" );
396 entity->addComponent( renderer );
397 entity->addComponent( mat );
398 entity->addComponent( tr );
399 entity->setParent( parent );
411 const auto techniques = material->effect()->techniques();
412 for (
auto tit = techniques.constBegin(); tit != techniques.constEnd(); ++tit )
414 auto renderPasses = ( *tit )->renderPasses();
415 for (
auto rpit = renderPasses.begin(); rpit != renderPasses.end(); ++rpit )
417 Qt3DRender::QCullFace *cullFace =
new Qt3DRender::QCullFace;
419 ( *rpit )->addRenderState( cullFace );
431 const bool dataDefined = mSymbol->materialSettings()->dataDefinedProperties().hasActiveProperties();
433 applyCullingMode( symbol->
cullingMode(), material );
441namespace Qgs3DSymbolImpl
445 QgsFeature3DHandler *handlerForPolygon3DSymbol( QgsVectorLayer *layer,
const QgsAbstract3DSymbol *symbol )
447 const QgsPolygon3DSymbol *polygonSymbol =
dynamic_cast<const QgsPolygon3DSymbol *
>( symbol );
448 if ( !polygonSymbol )
@ Triangles
Triangle based rendering (default).
@ TrianglesDataDefined
Triangle based rendering with possibility of datadefined color.
Rendering context for preparation of 3D entities.
QColor selectionColor() const
Returns color used for selected features.
QgsExpressionContext & expressionContext()
Gets the expression context.
@ Main3DRenderer
Renderer for normal entities.
static const char * PROP_NAME_3D_RENDERER_FLAG
Qt property name to hold the 3D geometry renderer flag.
CullingMode
Triangle culling mode.
static Qt3DRender::QCullFace::CullingMode qt3DcullingMode(Qgs3DTypes::CullingMode mode)
Converts Qgs3DTypes::CullingMode mode into its Qt3D equivalent.
static void clampAltitudes(QgsLineString *lineString, Qgis::AltitudeClamping altClamp, Qgis::AltitudeBinding altBind, const QgsPoint ¢roid, float offset, const Qgs3DRenderContext &context)
Clamps altitude of vertices of a linestring according to the settings.
static QgsMaterial * toMaterial(const QgsAbstractMaterialSettings *settings, Qgis::MaterialRenderingTechnique technique, const QgsMaterialContext &context)
Creates a new QgsMaterial object representing the material settings.
static QByteArray materialDataDefinedVertexColorsAsByte(const QgsAbstractMaterialSettings *settings, const QgsExpressionContext &expressionContext)
Returns byte array corresponding to the data defined colors depending of the expressionContext,...
static void applyMaterialDataDefinedToGeometry(const QgsAbstractMaterialSettings *settings, Qt3DCore::QGeometry *geometry, int vertexCount, const QByteArray &dataDefinedBytes)
Applies the data defined bytes, dataDefinedBytes, on the geometry by filling a specific vertex buffer...
@ ExtrusionHeight
Extrusion height (zero means no extrusion).
@ Height
Height (altitude).
Abstract base class for all geometries.
virtual const QgsAbstractGeometry * simplifiedTypeRef() const
Returns a reference to the simplest lossless representation of this geometry, e.g.
virtual QgsAbstractGeometry * segmentize(double tolerance=M_PI/180., SegmentationToleranceType toleranceType=MaximumAngle) const
Returns a version of the geometry without curves.
Qgis::WkbType wkbType() const
Returns the WKB type of the geometry.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
double valueAsDouble(int key, const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property with the specified key and interprets it as a double.
A 3-dimensional box composed of x, y, z coordinates.
QgsVector3D center() const
Returns the center of the box as a vector.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
bool convertGeometryCollectionToSubclass(Qgis::GeometryType geomType)
Converts geometry collection to a the desired geometry type subclass (multi-point,...
QgsGeometry difference(const QgsGeometry &geometry, const QgsGeometryParameters ¶meters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr) const
Returns a geometry representing the points making up this geometry that do not make up other.
Line string geometry type, with support for z-dimension and m-values.
Context settings for a material.
void setIsSelected(bool isSelected)
Sets whether the material should represent a selected state.
void setSelectionColor(const QColor &color)
Sets the color for representing materials in a selected state.
void setIsHighlighted(bool isHighlighted)
Sets whether the material should represent a highlighted state.
Base class for all materials used within QGIS 3D views.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE(), Qgis::StringFormat format=Qgis::StringFormat::PlainText)
Adds a message to the log instance (and creates it if necessary).
Multi line string geometry collection.
Multi polygon geometry collection.
3D symbol that draws polygon geometries as planar polygons, optionally extruded (with added walls).
QgsAbstractMaterialSettings * materialSettings() const
Returns material settings used for shading of the symbol.
Qgs3DTypes::CullingMode cullingMode() const
Returns front/back culling mode.
QgsPolygon * clone() const override
Clones the geometry by performing a deep copy.
Polyhedral surface geometry type.
A grouped map of multiple QgsProperty objects, each referenced by an integer key value.
bool isActive(int key) const final
Returns true if the collection contains an active property with the specified key.
Qt3DRender::QGeometry subclass that represents polygons tessellated into 3D geometry.
void setVertexBufferData(const QByteArray &vertexBufferData, int vertexCount, const QVector< QgsFeatureId > &triangleIndexFids, const QVector< uint > &triangleIndexStartingIndices)
Initializes vertex buffer (and other members) from data that were already tessellated.
void setIndexBufferData(const QByteArray &indexBufferData, size_t indexCount)
Sets index buffer data.
void setZ(double z)
Sets Z coordinate.
Q_INVOKABLE const QgsFeatureIds & selectedFeatureIds() const
Returns a list of the selected features IDs in this layer.
static Q_INVOKABLE bool isCurvedType(Qgis::WkbType type)
Returns true if the WKB type is a curved type or can contain curved geometries.
static Qgis::WkbType flatType(Qgis::WkbType type)
Returns the flat type for a WKB type.
T qgsgeometry_cast(QgsAbstractGeometry *geom)
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features