QGIS API Documentation 3.99.0-Master (d270888f95f)
Loading...
Searching...
No Matches
qgsheatmaprenderer.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsheatmaprenderer.cpp
3 ----------------------
4 begin : November 2014
5 copyright : (C) 2014 Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsheatmaprenderer.h"
17
18#include <memory>
19
20#include "qgscolorramp.h"
21#include "qgscolorrampimpl.h"
23#include "qgsfeature.h"
24#include "qgsrendercontext.h"
26#include "qgssymbol.h"
27#include "qgssymbollayerutils.h"
28
29#include <QDomDocument>
30#include <QDomElement>
31#include <QString>
32
33using namespace Qt::StringLiterals;
34
36 : QgsFeatureRenderer( u"heatmapRenderer"_s )
37{
38 mGradientRamp = new QgsGradientColorRamp( QColor( 255, 255, 255 ), QColor( 0, 0, 0 ) );
39 mLegendSettings.setMinimumLabel( QObject::tr( "Minimum" ) );
40 mLegendSettings.setMaximumLabel( QObject::tr( "Maximum" ) );
41}
42
44{
45 delete mGradientRamp;
46}
47
48void QgsHeatmapRenderer::initializeValues( QgsRenderContext &context )
49{
50 mValues.resize( context.painter()->device()->width() * context.painter()->device()->height() / ( mRenderQuality * mRenderQuality ) );
51 mValues.fill( 0 );
52 mCalculatedMaxValue = 0;
53 mFeaturesRendered = 0;
54 mRadiusPixels = std::round( context.convertToPainterUnits( mRadius, mRadiusUnit, mRadiusMapUnitScale ) / mRenderQuality );
55 mRadiusSquared = mRadiusPixels * mRadiusPixels;
56}
57
59{
60 QgsFeatureRenderer::startRender( context, fields );
61
62 if ( !context.painter() )
63 {
64 return;
65 }
66
67 // find out classification attribute index from name
68 mWeightAttrNum = fields.lookupField( mWeightExpressionString );
69 if ( mWeightAttrNum == -1 )
70 {
71 mWeightExpression = std::make_unique<QgsExpression>( mWeightExpressionString );
72 mWeightExpression->prepare( &context.expressionContext() );
73 }
74
75 bool ok = false;
76 const double dataDefinedExplicitMax = dataDefinedProperties().valueAsDouble( Property::HeatmapMaximum, context.expressionContext(), mExplicitMax, &ok );
77 if ( ok )
78 mExplicitMax = dataDefinedExplicitMax;
79
80 const double dataDefinedRadius = dataDefinedProperties().valueAsDouble( Property::HeatmapRadius, context.expressionContext(), mRadius, &ok );
81 if ( ok )
82 mRadius = dataDefinedRadius;
83
84 initializeValues( context );
85}
86
87QgsMultiPointXY QgsHeatmapRenderer::convertToMultipoint( const QgsGeometry *geom )
88{
89 QgsMultiPointXY multiPoint;
90 if ( !geom->isMultipart() )
91 {
92 multiPoint << geom->asPoint();
93 }
94 else
95 {
96 multiPoint = geom->asMultiPoint();
97 }
98
99 return multiPoint;
100}
101
102bool QgsHeatmapRenderer::renderFeature( const QgsFeature &feature, QgsRenderContext &context, int layer, bool selected, bool drawVertexMarker )
103{
104 Q_UNUSED( layer )
105 Q_UNUSED( selected )
106 Q_UNUSED( drawVertexMarker )
107
108 if ( !context.painter() )
109 {
110 return false;
111 }
112
113 if ( !feature.hasGeometry() || feature.geometry().type() != Qgis::GeometryType::Point )
114 {
115 //can only render point type
116 return false;
117 }
118
119 double weight = 1.0;
120 if ( !mWeightExpressionString.isEmpty() )
121 {
122 QVariant value;
123 if ( mWeightAttrNum == -1 )
124 {
125 Q_ASSERT( mWeightExpression.get() );
126 value = mWeightExpression->evaluate( &context.expressionContext() );
127 }
128 else
129 {
130 const QgsAttributes attrs = feature.attributes();
131 value = attrs.value( mWeightAttrNum );
132 }
133 bool ok = false;
134 const double evalWeight = value.toDouble( &ok );
135 if ( ok )
136 {
137 weight = evalWeight;
138 }
139 }
140
141 const int width = context.painter()->device()->width() / mRenderQuality;
142 const int height = context.painter()->device()->height() / mRenderQuality;
143
144 //transform geometry if required
145 QgsGeometry geom = feature.geometry();
146 const QgsCoordinateTransform xform = context.coordinateTransform();
147 if ( xform.isValid() )
148 {
149 geom.transform( xform );
150 }
151
152 //convert point to multipoint
153 const QgsMultiPointXY multiPoint = convertToMultipoint( &geom );
154
155 //loop through all points in multipoint
156 for ( QgsMultiPointXY::const_iterator pointIt = multiPoint.constBegin(); pointIt != multiPoint.constEnd(); ++pointIt )
157 {
158 const QgsPointXY pixel = context.mapToPixel().transform( *pointIt );
159 const int pointX = pixel.x() / mRenderQuality;
160 const int pointY = pixel.y() / mRenderQuality;
161 for ( int x = std::max( pointX - mRadiusPixels, 0 ); x < std::min( pointX + mRadiusPixels, width ); ++x )
162 {
163 if ( context.renderingStopped() )
164 break;
165
166 for ( int y = std::max( pointY - mRadiusPixels, 0 ); y < std::min( pointY + mRadiusPixels, height ); ++y )
167 {
168 const int index = y * width + x;
169 if ( index >= mValues.count() )
170 {
171 continue;
172 }
173 const double distanceSquared = std::pow( pointX - x, 2.0 ) + std::pow( pointY - y, 2.0 );
174 if ( distanceSquared > mRadiusSquared )
175 {
176 continue;
177 }
178
179 const double score = weight * quarticKernel( std::sqrt( distanceSquared ), mRadiusPixels );
180 const double value = mValues.at( index ) + score;
181 if ( value > mCalculatedMaxValue )
182 {
183 mCalculatedMaxValue = value;
184 }
185 mValues[ index ] = value;
186 }
187 }
188 }
189
190 mFeaturesRendered++;
191#if 0
192 //TODO - enable progressive rendering
193 if ( mFeaturesRendered % 200 == 0 )
194 {
195 renderImage( context );
196 }
197#endif
198 return true;
199}
200
201
202double QgsHeatmapRenderer::uniformKernel( const double distance, const int bandwidth ) const
203{
204 Q_UNUSED( distance )
205 Q_UNUSED( bandwidth )
206 return 1.0;
207}
208
209double QgsHeatmapRenderer::quarticKernel( const double distance, const int bandwidth ) const
210{
211 return std::pow( 1. - std::pow( distance / static_cast< double >( bandwidth ), 2 ), 2 );
212}
213
214double QgsHeatmapRenderer::triweightKernel( const double distance, const int bandwidth ) const
215{
216 return std::pow( 1. - std::pow( distance / static_cast< double >( bandwidth ), 2 ), 3 );
217}
218
219double QgsHeatmapRenderer::epanechnikovKernel( const double distance, const int bandwidth ) const
220{
221 return ( 1. - std::pow( distance / static_cast< double >( bandwidth ), 2 ) );
222}
223
224double QgsHeatmapRenderer::triangularKernel( const double distance, const int bandwidth ) const
225{
226 return ( 1. - ( distance / static_cast< double >( bandwidth ) ) );
227}
228
230{
232
233 renderImage( context );
234 mWeightExpression.reset();
235}
236
237void QgsHeatmapRenderer::renderImage( QgsRenderContext &context )
238{
239 if ( !context.painter() || !mGradientRamp || context.renderingStopped() )
240 {
241 return;
242 }
243
244 QImage image( context.painter()->device()->width() / mRenderQuality,
245 context.painter()->device()->height() / mRenderQuality,
246 QImage::Format_ARGB32 );
247 image.fill( Qt::transparent );
248
249 const double scaleMax = mExplicitMax > 0 ? mExplicitMax : mCalculatedMaxValue;
250
251 int idx = 0;
252 double pixVal = 0;
253 QColor pixColor;
254 for ( int heightIndex = 0; heightIndex < image.height(); ++heightIndex )
255 {
256 if ( context.renderingStopped() )
257 break;
258
259 QRgb *scanLine = reinterpret_cast< QRgb * >( image.scanLine( heightIndex ) );
260 for ( int widthIndex = 0; widthIndex < image.width(); ++widthIndex )
261 {
262 //scale result to fit in the range [0, 1]
263 pixVal = mValues.at( idx ) > 0 ? std::min( ( mValues.at( idx ) / scaleMax ), 1.0 ) : 0;
264
265 //convert value to color from ramp
266 pixColor = mGradientRamp->color( pixVal );
267
268 scanLine[widthIndex] = pixColor.rgba();
269 idx++;
270 }
271 }
272
273 if ( mRenderQuality > 1 )
274 {
275 const QImage resized = image.scaled( context.painter()->device()->width(),
276 context.painter()->device()->height() );
277 context.painter()->drawImage( 0, 0, resized );
278 }
279 else
280 {
281 context.painter()->drawImage( 0, 0, image );
282 }
283}
284
286{
287 return u"[HEATMAP]"_s;
288}
289
291{
292 QgsHeatmapRenderer *newRenderer = new QgsHeatmapRenderer();
293 if ( mGradientRamp )
294 {
295 newRenderer->setColorRamp( mGradientRamp->clone() );
296 }
297 newRenderer->setRadius( mRadius );
298 newRenderer->setRadiusUnit( mRadiusUnit );
299 newRenderer->setRadiusMapUnitScale( mRadiusMapUnitScale );
300 newRenderer->setMaximumValue( mExplicitMax );
301 newRenderer->setRenderQuality( mRenderQuality );
302 newRenderer->setWeightExpression( mWeightExpressionString );
303 newRenderer->setLegendSettings( mLegendSettings );
304 copyRendererData( newRenderer );
305
306 return newRenderer;
307}
308
310{
311 //we need to expand out the request extent so that it includes points which are up to the heatmap radius outside of the
312 //actual visible extent
313 const double extension = context.convertToMapUnits( mRadius, mRadiusUnit, mRadiusMapUnitScale );
314 extent.setXMinimum( extent.xMinimum() - extension );
315 extent.setXMaximum( extent.xMaximum() + extension );
316 extent.setYMinimum( extent.yMinimum() - extension );
317 extent.setYMaximum( extent.yMaximum() + extension );
318}
319
321{
322 Q_UNUSED( context )
324 r->setRadius( element.attribute( u"radius"_s, u"50.0"_s ).toFloat() );
325 r->setRadiusUnit( static_cast< Qgis::RenderUnit >( element.attribute( u"radius_unit"_s, u"0"_s ).toInt() ) );
326 r->setRadiusMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( element.attribute( u"radius_map_unit_scale"_s, QString() ) ) );
327 r->setMaximumValue( element.attribute( u"max_value"_s, u"0.0"_s ).toFloat() );
328 r->setRenderQuality( element.attribute( u"quality"_s, u"0"_s ).toInt() );
329 r->setWeightExpression( element.attribute( u"weight_expression"_s ) );
330
331 QDomElement sourceColorRampElem = element.firstChildElement( u"colorramp"_s );
332 if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( u"name"_s ) == "[source]"_L1 )
333 {
334 r->setColorRamp( QgsSymbolLayerUtils::loadColorRamp( sourceColorRampElem ).release() );
335 }
336
338 legendSettings.readXml( element, context );
340
341 return r;
342}
343
344QDomElement QgsHeatmapRenderer::save( QDomDocument &doc, const QgsReadWriteContext &context )
345{
346 QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME );
347 rendererElem.setAttribute( u"type"_s, u"heatmapRenderer"_s );
348 rendererElem.setAttribute( u"radius"_s, QString::number( mRadius ) );
349 rendererElem.setAttribute( u"radius_unit"_s, QString::number( static_cast< int >( mRadiusUnit ) ) );
350 rendererElem.setAttribute( u"radius_map_unit_scale"_s, QgsSymbolLayerUtils::encodeMapUnitScale( mRadiusMapUnitScale ) );
351 rendererElem.setAttribute( u"max_value"_s, QString::number( mExplicitMax ) );
352 rendererElem.setAttribute( u"quality"_s, QString::number( mRenderQuality ) );
353 rendererElem.setAttribute( u"weight_expression"_s, mWeightExpressionString );
354
355 if ( mGradientRamp )
356 {
357 const QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( u"[source]"_s, mGradientRamp, doc );
358 rendererElem.appendChild( colorRampElem );
359 }
360 mLegendSettings.writeXml( doc, rendererElem, context );
361
362 saveRendererData( doc, rendererElem, context );
363
364 return rendererElem;
365}
366
368{
369 Q_UNUSED( feature )
370 return nullptr;
371}
372
377
379{
380 QSet<QString> attributes;
381
382 // mAttrName can contain either attribute name or an expression.
383 // Sometimes it is not possible to distinguish between those two,
384 // e.g. "a - b" can be both a valid attribute name or expression.
385 // Since we do not have access to fields here, try both options.
386 attributes << mWeightExpressionString;
387
388 const QgsExpression testExpr( mWeightExpressionString );
389 if ( !testExpr.hasParserError() )
390 attributes.unite( testExpr.referencedColumns() );
391
392 return attributes;
393}
394
396{
397 if ( renderer->type() == "heatmapRenderer"_L1 )
398 {
399 return dynamic_cast<QgsHeatmapRenderer *>( renderer->clone() );
400 }
401 else
402 {
403 auto res = std::make_unique< QgsHeatmapRenderer >();
404 renderer->copyRendererData( res.get() );
405 return res.release();
406 }
407}
408
410{
411 if ( mGradientRamp )
412 {
413 QgsStyleColorRampEntity entity( mGradientRamp );
414 if ( !visitor->visit( QgsStyleEntityVisitorInterface::StyleLeaf( &entity ) ) )
415 return false;
416 }
417 return true;
418}
419
420QList<QgsLayerTreeModelLegendNode *> QgsHeatmapRenderer::createLegendNodes( QgsLayerTreeLayer *nodeLayer ) const
421{
422 return
423 {
424 new QgsColorRampLegendNode( nodeLayer,
425 mGradientRamp->clone(),
426 mLegendSettings,
427 0,
428 1 )
429 };
430}
431
433{
434 delete mGradientRamp;
435 mGradientRamp = ramp;
436}
437
439{
440 mLegendSettings = settings;
441}
@ Point
Points.
Definition qgis.h:366
RenderUnit
Rendering size units.
Definition qgis.h:5255
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 vector of attributes.
Settings for a color ramp legend node.
A legend node which renders a color ramp.
Abstract base class for color ramps.
Handles coordinate transforms between two coordinate systems.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
Handles parsing and evaluation of expressions (formerly called "search strings").
bool hasParserError() const
Returns true if an error occurred when parsing the input expression.
QSet< QString > referencedColumns() const
Gets list of columns referenced by the expression.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the renderer's property collection, used for data defined overrides.
QgsFeatureRenderer(const QString &type)
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
@ HeatmapRadius
Heatmap renderer radius.
@ HeatmapMaximum
Heatmap maximum value.
QString type() const
void copyRendererData(QgsFeatureRenderer *destRenderer) const
Clones generic renderer data to another renderer.
void saveRendererData(QDomDocument &doc, QDomElement &element, const QgsReadWriteContext &context)
Saves generic renderer data into the specified element.
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:69
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Container of fields for a vector layer.
Definition qgsfields.h:46
Q_INVOKABLE int lookupField(const QString &fieldName) const
Looks up field's index from the field name.
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
QgsMultiPointXY asMultiPoint() const
Returns the contents of the geometry as a multi-point.
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
Qgis::GeometryType type
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
Gradient color ramp, which smoothly interpolates between two colors and also supports optional extra ...
void setColorRamp(QgsColorRamp *ramp)
Sets the color ramp to use for shading the heatmap.
QgsSymbol * symbolForFeature(const QgsFeature &feature, QgsRenderContext &context) const override
To be overridden.
void modifyRequestExtent(QgsRectangle &extent, QgsRenderContext &context) override
Allows for a renderer to modify the extent of a feature request prior to rendering.
void startRender(QgsRenderContext &context, const QgsFields &fields) override
Must be called when a new render cycle is started.
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Returns a list of attributes required by this renderer.
void setRadius(const double radius)
Sets the radius for the heatmap.
void setLegendSettings(const QgsColorRampLegendNodeSettings &settings)
Sets the color ramp legend settings.
void setRadiusUnit(const Qgis::RenderUnit unit)
Sets the units used for the heatmap's radius.
static QgsFeatureRenderer * create(QDomElement &element, const QgsReadWriteContext &context)
Creates a new heatmap renderer instance from XML.
void setRenderQuality(const int quality)
Sets the render quality used for drawing the heatmap.
bool renderFeature(const QgsFeature &feature, QgsRenderContext &context, int layer=-1, bool selected=false, bool drawVertexMarker=false) override
Render a feature using this renderer in the given context.
static QgsHeatmapRenderer * convertFromRenderer(const QgsFeatureRenderer *renderer)
void setWeightExpression(const QString &expression)
Sets the expression used for weighting points when generating the heatmap.
void setMaximumValue(const double value)
Sets the maximum value used for shading the heatmap.
void stopRender(QgsRenderContext &context) override
Must be called when a render cycle has finished, to allow the renderer to clean up.
QString dump() const override
Returns debug information about this renderer.
QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context) override
Stores renderer properties to an XML element.
QList< QgsLayerTreeModelLegendNode * > createLegendNodes(QgsLayerTreeLayer *nodeLayer) const override
Returns a list of legend nodes to be used for the legend for the renderer.
QgsHeatmapRenderer * clone() const override
Create a deep copy of this renderer.
const QgsColorRampLegendNodeSettings & legendSettings() const
Returns the color ramp legend settings.
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified symbology visitor, causing it to visit all symbols associated with the renderer...
void setRadiusMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale used for the heatmap's radius.
QgsSymbolList symbols(QgsRenderContext &context) const override
Returns list of symbols used by the renderer.
Layer tree node points to a map layer.
QgsLayerTreeLayer * clone() const override
Create a copy of the node. Returns new instance.
QgsPointXY transform(const QgsPointXY &p) const
Transforms a point p from map (world) coordinates to device coordinates.
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
A container for the context for various read/write operations on objects.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
void setYMinimum(double y)
Set the minimum y value.
void setXMinimum(double x)
Set the minimum x value.
void setYMaximum(double y)
Set the maximum y value.
void setXMaximum(double x)
Set the maximum x value.
double yMaximum
Contains information about the context of a rendering operation.
double convertToMapUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
double convertToPainterUnits(double size, Qgis::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale(), Qgis::RenderSubcomponentProperty property=Qgis::RenderSubcomponentProperty::Generic) const
Converts a size from the specified units to painter units (pixels).
QPainter * painter()
Returns the destination QPainter for the render operation.
QgsExpressionContext & expressionContext()
Gets the expression context.
const QgsMapToPixel & mapToPixel() const
Returns the context's map to pixel transform, which transforms between map coordinates and device coo...
bool renderingStopped() const
Returns true if the rendering operation has been stopped and any ongoing rendering should be canceled...
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context.
A color ramp entity for QgsStyle databases.
Definition qgsstyle.h:1430
An interface for classes which can visit style entity (e.g.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
static std::unique_ptr< QgsColorRamp > loadColorRamp(QDomElement &element)
Creates a color ramp from the settings encoded in an XML element.
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
static QDomElement saveColorRamp(const QString &name, const QgsColorRamp *ramp, QDomDocument &doc)
Encodes a color ramp's settings to an XML element.
Abstract base class for all rendered symbols.
Definition qgssymbol.h:231
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition qgsgeometry.h:98
#define RENDERER_TAG_NAME
Definition qgsrenderer.h:57
QList< QgsSymbol * > QgsSymbolList
Definition qgsrenderer.h:51
Contains information relating to the style entity currently being visited.