/
qgsalgorithmrasterize.cpp
355 lines (310 loc) · 13.4 KB
/
qgsalgorithmrasterize.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/***************************************************************************
qgsalgorithmrasterize.cpp - QgsRasterizeAlgorithm
---------------------
Original implementation in Python:
begin : 2016-10-05
copyright : (C) 2016 by OPENGIS.ch
email : matthias@opengis.ch
C++ port:
begin : 20.11.2019
copyright : (C) 2019 by Alessandro Pasotti
email : elpaso at itopen dot it
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsalgorithmrasterize.h"
#include "qgsprocessingparameters.h"
#include "qgsmapthemecollection.h"
#include "qgsrasterfilewriter.h"
#include "qgsmaprenderercustompainterjob.h"
#include "gdal.h"
#include "qgsgdalutils.h"
#include <QtConcurrent>
///@cond PRIVATE
QString QgsRasterizeAlgorithm::name() const
{
return QStringLiteral( "rasterize" );
}
QString QgsRasterizeAlgorithm::displayName() const
{
return QObject::tr( "Convert map to raster" );
}
QStringList QgsRasterizeAlgorithm::tags() const
{
return QObject::tr( "layer,raster,convert,file,map themes,tiles,render" ).split( ',' );
}
QString QgsRasterizeAlgorithm::group() const
{
return QObject::tr( "Raster tools" );
}
QString QgsRasterizeAlgorithm::groupId() const
{
return QStringLiteral( "rastertools" );
}
void QgsRasterizeAlgorithm::initAlgorithm( const QVariantMap & )
{
addParameter( new QgsProcessingParameterExtent(
QStringLiteral( "EXTENT" ),
QObject::tr( "Minimum extent to render" ) ) );
addParameter( new QgsProcessingParameterNumber(
QStringLiteral( "EXTENT_BUFFER" ),
QObject::tr( "Buffer around tiles in map units" ),
QgsProcessingParameterNumber::Type::Double,
0,
true,
0 ) );
addParameter( new QgsProcessingParameterNumber(
QStringLiteral( "TILE_SIZE" ),
QObject::tr( "Tile size" ),
QgsProcessingParameterNumber::Type::Integer,
1024,
false,
64 ) );
addParameter( new QgsProcessingParameterNumber(
QStringLiteral( "MAP_UNITS_PER_PIXEL" ),
QObject::tr( "Map units per pixel" ),
QgsProcessingParameterNumber::Type::Double,
100,
true,
0 ) );
addParameter( new QgsProcessingParameterBoolean(
QStringLiteral( "MAKE_BACKGROUND_TRANSPARENT" ),
QObject::tr( "Make background transparent" ),
false ) );
QStringList mapThemes { QgsProject::instance()->mapThemeCollection()->mapThemes() };
mapThemes.prepend( QString() );
addParameter( new QgsProcessingParameterEnum(
QStringLiteral( "MAP_THEME" ),
QObject::tr( "Map theme to render" ),
mapThemes,
false,
QString(),
true
) );
QList<QgsMapLayer *> projectLayers { QgsProject::instance()->mapLayers().values() };
addParameter( new QgsProcessingParameterMultipleLayers(
QStringLiteral( "LAYERS" ),
QObject::tr( "Layers to render" ),
QgsProcessing::TypeMapLayer,
QVariant(),
true
) );
addParameter( new QgsProcessingParameterRasterDestination(
QStringLiteral( "OUTPUT" ),
QObject::tr( "Output layer" ) ) );
}
QString QgsRasterizeAlgorithm::shortDescription() const
{
return QObject::tr( R"(This algorithm rasterizes map canvas content.
A map theme can be selected to render a predetermined set of layers with a defined style for each layer.
Alternatively, a set of layers layer can be selected if no map theme is set.
If neither map theme nor layer is set all the current project layers will be
rendered.
The minimum extent entered will internally be extended to be a multiple of the tile size.)" );
}
QString QgsRasterizeAlgorithm::shortHelpString() const
{
return QObject::tr( R"(This algorithm renders the map canvas to a raster file.
It's possible to choose the following parameters:
- Map theme to render
- Layers to render
- The minimum extent to render
- The tile size
- Map unit per pixel
- The output (can be saved to a file or to a temporary file and
automatically opened as layer in qgis)
)" );
}
QgsRasterizeAlgorithm *QgsRasterizeAlgorithm::createInstance() const
{
return new QgsRasterizeAlgorithm();
}
QVariantMap QgsRasterizeAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
// Note: MAP_THEME and LAYERS are handled and cloned in prepareAlgorithm
const QgsRectangle extent { parameterAsExtent( parameters, QStringLiteral( "EXTENT" ), context, context.project()->crs() ) };
const int tileSize { parameterAsInt( parameters, QStringLiteral( "TILE_SIZE" ), context ) };
const bool transparent { parameterAsBool( parameters, QStringLiteral( "MAKE_BACKGROUND_TRANSPARENT" ), context ) };
const double mapUnitsPerPixel { parameterAsDouble( parameters, QStringLiteral( "MAP_UNITS_PER_PIXEL" ), context ) };
const double extentBuffer { parameterAsDouble( parameters, QStringLiteral( "EXTENT_BUFFER" ), context ) };
const QString outputLayerFileName { parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context )};
int xTileCount { static_cast<int>( ceil( extent.width() / mapUnitsPerPixel / tileSize ) )};
int yTileCount { static_cast<int>( ceil( extent.height() / mapUnitsPerPixel / tileSize ) )};
int width { xTileCount * tileSize };
int height { yTileCount * tileSize };
int nBands { transparent ? 4 : 3 };
const QString driverName { QgsRasterFileWriter::driverForExtension( QFileInfo( outputLayerFileName ).suffix() ) };
if ( driverName.isEmpty() )
{
throw QgsProcessingException( QObject::tr( "Invalid output raster format" ) );
}
GDALDriverH hOutputFileDriver = GDALGetDriverByName( driverName.toLocal8Bit().constData() );
if ( !hOutputFileDriver )
{
throw QgsProcessingException( QObject::tr( "Error creating GDAL driver" ) );
}
gdal::dataset_unique_ptr hOutputDataset( GDALCreate( hOutputFileDriver, outputLayerFileName.toLocal8Bit().constData(), width, height, nBands, GDALDataType::GDT_Byte, nullptr ) );
if ( !hOutputDataset )
{
throw QgsProcessingException( QObject::tr( "Error creating GDAL output layer" ) );
}
GDALSetProjection( hOutputDataset.get(), context.project()->crs().toWkt( QgsCoordinateReferenceSystem::WKT2_2018 ).toLatin1().constData() );
double geoTransform[6];
geoTransform[0] = extent.xMinimum();
geoTransform[1] = mapUnitsPerPixel;
geoTransform[2] = 0;
geoTransform[3] = extent.yMaximum();
geoTransform[4] = 0;
geoTransform[5] = - mapUnitsPerPixel;
GDALSetGeoTransform( hOutputDataset.get(), geoTransform );
int red = context.project()->readNumEntry( QStringLiteral( "Gui" ), "/CanvasColorRedPart", 255 );
int green = context.project()->readNumEntry( QStringLiteral( "Gui" ), "/CanvasColorGreenPart", 255 );
int blue = context.project()->readNumEntry( QStringLiteral( "Gui" ), "/CanvasColorBluePart", 255 );
QColor bgColor;
if ( transparent )
{
bgColor = QColor( red, green, blue, 0 );
}
else
{
bgColor = QColor( red, green, blue );
}
QgsMapSettings mapSettings;
mapSettings.setOutputImageFormat( QImage::Format_ARGB32 );
mapSettings.setDestinationCrs( context.project()->crs() );
mapSettings.setFlag( QgsMapSettings::Antialiasing, true );
mapSettings.setFlag( QgsMapSettings::RenderMapTile, true );
mapSettings.setFlag( QgsMapSettings::UseAdvancedEffects, true );
mapSettings.setTransformContext( context.transformContext() );
mapSettings.setExtentBuffer( extentBuffer );
mapSettings.setBackgroundColor( bgColor );
// Set layers cloned in prepareAlgorithm
QList<QgsMapLayer *> layers;
for ( const auto &lptr : mMapLayers )
{
layers.push_back( lptr.get() );
}
mapSettings.setLayers( layers );
mapSettings.setLayerStyleOverrides( mMapThemeStyleOverrides );
// Start rendering
const double extentRatio { mapUnitsPerPixel * tileSize };
const int numTiles { xTileCount * yTileCount };
const QString fileExtension { QFileInfo( outputLayerFileName ).suffix() };
// Custom deleter for CPL allocation
struct CPLDelete
{
void operator()( uint8_t *ptr ) const
{
CPLFree( ptr );
}
};
QAtomicInt rendered = 0;
QMutex rasterWriteLocker;
const auto renderJob = [ & ]( const int x, const int y, QgsMapSettings mapSettings )
{
QImage image { tileSize, tileSize, QImage::Format::Format_ARGB32 };
mapSettings.setOutputDpi( image.logicalDpiX() );
mapSettings.setOutputSize( image.size() );
QPainter painter { &image };
if ( feedback->isCanceled() )
{
return;
}
image.fill( transparent ? bgColor.rgba() : bgColor.rgb() );
mapSettings.setExtent( QgsRectangle(
extent.xMinimum() + x * extentRatio,
extent.yMaximum() - ( y + 1 ) * extentRatio,
extent.xMinimum() + ( x + 1 ) * extentRatio,
extent.yMaximum() - y * extentRatio
) );
QgsMapRendererCustomPainterJob job( mapSettings, &painter );
job.start();
job.waitForFinished();
gdal::dataset_unique_ptr hIntermediateDataset( QgsGdalUtils::imageToMemoryDataset( image ) );
if ( !hIntermediateDataset )
{
throw QgsProcessingException( QStringLiteral( "Error reading tiles from the temporary image" ) );
}
const int xOffset { x * tileSize };
const int yOffset { y * tileSize };
std::unique_ptr<uint8_t, CPLDelete> buffer( static_cast< uint8_t * >( CPLMalloc( sizeof( uint8_t ) * static_cast<size_t>( tileSize * tileSize * nBands ) ) ) );
CPLErr err = GDALDatasetRasterIO( hIntermediateDataset.get(),
GF_Read, 0, 0, tileSize, tileSize,
buffer.get(),
tileSize, tileSize, GDT_Byte, nBands, nullptr, 0, 0, 0 );
if ( err != CE_None )
{
throw QgsProcessingException( QStringLiteral( "Error reading intermediate raster" ) );
}
{
QMutexLocker locker( &rasterWriteLocker );
err = GDALDatasetRasterIO( hOutputDataset.get(),
GF_Write, xOffset, yOffset, tileSize, tileSize,
buffer.get(),
tileSize, tileSize, GDT_Byte, nBands, nullptr, 0, 0, 0 );
rendered++;
feedback->setProgress( static_cast<double>( rendered ) / numTiles * 100.0 );
}
if ( err != CE_None )
{
throw QgsProcessingException( QStringLiteral( "Error writing output raster" ) );
}
};
feedback->setProgress( 0 );
std::vector<QFuture<void>> futures;
for ( int x = 0; x < xTileCount; ++x )
{
for ( int y = 0; y < yTileCount; ++y )
{
if ( feedback->isCanceled() )
{
return {};
}
futures.push_back( QtConcurrent::run( renderJob, x, y, mapSettings ) );
}
}
for ( auto &f : futures )
{
f.waitForFinished();
}
return { { QStringLiteral( "OUTPUT" ), outputLayerFileName } };
}
bool QgsRasterizeAlgorithm::prepareAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
Q_UNUSED( feedback )
// Retrieve and clone layers
const QString mapTheme { parameterAsString( parameters, QStringLiteral( "MAP_THEME" ), context ) };
const QList<QgsMapLayer *> mapLayers { parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context ) };
if ( ! mapTheme.isEmpty() && context.project()->mapThemeCollection()->hasMapTheme( mapTheme ) )
{
const auto constLayers { context.project()->mapThemeCollection()->mapThemeVisibleLayers( mapTheme ) };
for ( const QgsMapLayer *ml : constLayers )
{
mMapLayers.push_back( std::unique_ptr<QgsMapLayer>( ml->clone( ) ) );
}
mMapThemeStyleOverrides = context.project()->mapThemeCollection( )->mapThemeStyleOverrides( mapTheme );
}
else if ( ! mapLayers.isEmpty() )
{
for ( const QgsMapLayer *ml : qgis::as_const( mapLayers ) )
{
mMapLayers.push_back( std::unique_ptr<QgsMapLayer>( ml->clone( ) ) );
}
}
// Still no layers? Get them all from the project
if ( mMapLayers.size() == 0 )
{
const auto constLayers { context.project()->mapLayers().values() };
for ( const QgsMapLayer *ml : constLayers )
{
mMapLayers.push_back( std::unique_ptr<QgsMapLayer>( ml->clone( ) ) );
}
}
return mMapLayers.size() > 0;
}
///@endcond