/
qgspdalprovider.cpp
454 lines (390 loc) · 14.2 KB
/
qgspdalprovider.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/***************************************************************************
qgspdaldataprovider.cpp
-----------------------
Date : November 2020
Copyright : (C) 2020 by Peter Petrik
Email : zilolv at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* 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 "qgis.h"
#include "qgspdalprovider.h"
#include "qgsruntimeprofiler.h"
#include "qgsapplication.h"
#include "qgslogger.h"
#include "qgsmessagelog.h"
#include "qgsjsonutils.h"
#include "json.hpp"
#include "qgspdalindexingtask.h"
#include "qgseptpointcloudindex.h"
#include "qgstaskmanager.h"
#include "qgsprovidersublayerdetails.h"
#include "qgsproviderutils.h"
#include <pdal/Options.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/Reader.hpp>
#include <QQueue>
#include <QFileInfo>
#include <QDir>
#define PROVIDER_KEY QStringLiteral( "pdal" )
#define PROVIDER_DESCRIPTION QStringLiteral( "PDAL point cloud data provider" )
QQueue<QgsPdalProvider *> QgsPdalProvider::sIndexingQueue;
QgsPdalProvider::QgsPdalProvider(
const QString &uri,
const QgsDataProvider::ProviderOptions &options,
QgsDataProvider::ReadFlags flags, bool generateCopc )
: QgsPointCloudDataProvider( uri, options, flags )
, mIndex( nullptr )
, mGenerateCopc( generateCopc )
{
std::unique_ptr< QgsScopedRuntimeProfile > profile;
if ( QgsApplication::profiler()->groupIsActive( QStringLiteral( "projectload" ) ) )
profile = std::make_unique< QgsScopedRuntimeProfile >( tr( "Open data source" ), QStringLiteral( "projectload" ) );
mIsValid = load( uri );
loadIndex( );
}
QgsPdalProvider::~QgsPdalProvider() = default;
QgsCoordinateReferenceSystem QgsPdalProvider::crs() const
{
return mCrs;
}
QgsRectangle QgsPdalProvider::extent() const
{
return mExtent;
}
QgsPointCloudAttributeCollection QgsPdalProvider::attributes() const
{
return mIndex ? mIndex->attributes() : QgsPointCloudAttributeCollection();
}
static QString _outEptDir( const QString &filename )
{
const QFileInfo fi( filename );
const QDir directory = fi.absoluteDir();
const QString outputDir = QStringLiteral( "%1/ept_%2" ).arg( directory.absolutePath() ).arg( fi.baseName() );
return outputDir;
}
static QString _outCopcFile( const QString &filename )
{
const QFileInfo fi( filename );
const QDir directory = fi.absoluteDir();
const QString outputFile = QStringLiteral( "%1/%2.copc.laz" ).arg( directory.absolutePath() ).arg( fi.baseName() );
return outputFile;
}
void QgsPdalProvider::generateIndex()
{
if ( mRunningIndexingTask || ( mIndex && mIndex->isValid() ) )
return;
if ( anyIndexingTaskExists() )
{
sIndexingQueue.push_back( this );
return;
}
QString outputPath;
if ( mGenerateCopc )
outputPath = _outCopcFile( dataSourceUri() );
else
outputPath = _outEptDir( dataSourceUri() );
QgsPdalIndexingTask *generationTask = new QgsPdalIndexingTask( dataSourceUri(), outputPath, mGenerateCopc ? QgsPdalIndexingTask::OutputFormat::Copc : QgsPdalIndexingTask::OutputFormat::Ept, QFileInfo( dataSourceUri() ).fileName() );
connect( generationTask, &QgsPdalIndexingTask::taskTerminated, this, &QgsPdalProvider::onGenerateIndexFailed );
connect( generationTask, &QgsPdalIndexingTask::taskCompleted, this, &QgsPdalProvider::onGenerateIndexFinished );
mRunningIndexingTask = generationTask;
QgsDebugMsgLevel( "Ept Generation Task Created", 2 );
emit indexGenerationStateChanged( PointCloudIndexGenerationState::Indexing );
QgsApplication::taskManager()->addTask( generationTask );
}
QgsPointCloudDataProvider::PointCloudIndexGenerationState QgsPdalProvider::indexingState()
{
if ( mIndex && mIndex->isValid() )
return PointCloudIndexGenerationState::Indexed;
else if ( mRunningIndexingTask )
return PointCloudIndexGenerationState::Indexing;
else
return PointCloudIndexGenerationState::NotIndexed;
}
void QgsPdalProvider::loadIndex( )
{
if ( mIndex && mIndex->isValid() )
return;
// Try to load copc index
if ( !mIndex || !mIndex->isValid() )
{
const QString outputFile = _outCopcFile( dataSourceUri() );
const QFileInfo fi( outputFile );
if ( fi.isFile() )
{
mIndex.reset( new QgsCopcPointCloudIndex );
mIndex->load( outputFile );
}
}
// Try to load ept index
if ( !mIndex || !mIndex->isValid() )
{
const QString outputDir = _outEptDir( dataSourceUri() );
const QString outEptJson = QStringLiteral( "%1/ept.json" ).arg( outputDir );
const QFileInfo fi( outEptJson );
if ( fi.isFile() )
{
mIndex.reset( new QgsEptPointCloudIndex );
mIndex->load( outEptJson );
}
}
if ( !mIndex || !mIndex->isValid() )
{
QgsDebugMsgLevel( QStringLiteral( "pdalprovider: neither copc or ept index for dataset %1 is not correctly loaded" ).arg( dataSourceUri() ), 2 );
}
}
void QgsPdalProvider::onGenerateIndexFinished()
{
QgsPdalIndexingTask *task = qobject_cast<QgsPdalIndexingTask *>( QObject::sender() );
// this may be already canceled task that we don't care anymore...
if ( task == mRunningIndexingTask )
{
mRunningIndexingTask = nullptr;
emit indexGenerationStateChanged( PointCloudIndexGenerationState::Indexed );
}
if ( !sIndexingQueue.empty() )
sIndexingQueue.takeFirst()->generateIndex();
}
void QgsPdalProvider::onGenerateIndexFailed()
{
QgsPdalIndexingTask *task = qobject_cast<QgsPdalIndexingTask *>( QObject::sender() );
// this may be already canceled task that we don't care anymore...
if ( task == mRunningIndexingTask )
{
QString error = task->errorMessage();
if ( !error.isEmpty() )
{
appendError( error );
}
mRunningIndexingTask = nullptr;
emit indexGenerationStateChanged( PointCloudIndexGenerationState::NotIndexed );
}
if ( !sIndexingQueue.empty() )
sIndexingQueue.takeFirst()->generateIndex();
}
bool QgsPdalProvider::anyIndexingTaskExists()
{
const QList< QgsTask * > tasks = QgsApplication::taskManager()->activeTasks();
for ( const QgsTask *task : tasks )
{
const QgsPdalIndexingTask *eptTask = qobject_cast<const QgsPdalIndexingTask *>( task );
if ( eptTask )
{
return true;
}
}
return false;
}
qint64 QgsPdalProvider::pointCount() const
{
return mPointCount;
}
QVariantMap QgsPdalProvider::originalMetadata() const
{
return mOriginalMetadata;
}
bool QgsPdalProvider::isValid() const
{
return mIsValid;
}
QString QgsPdalProvider::name() const
{
return QStringLiteral( "pdal" );
}
QString QgsPdalProvider::description() const
{
return QStringLiteral( "Point Clouds PDAL" );
}
QgsPointCloudIndex *QgsPdalProvider::index() const
{
return mIndex.get();
}
bool QgsPdalProvider::load( const QString &uri )
{
try
{
pdal::StageFactory stageFactory;
const std::string driver( stageFactory.inferReaderDriver( uri.toStdString() ) );
if ( driver.empty() )
throw pdal::pdal_error( "No driver for " + uri.toStdString() );
if ( pdal::Reader *reader = dynamic_cast<pdal::Reader *>( stageFactory.createStage( driver ) ) )
{
pdal::Options options;
options.add( pdal::Option( "filename", uri.toStdString() ) );
reader->setOptions( options );
pdal::PointTable table;
reader->prepare( table );
const std::string tableMetadata = pdal::Utils::toJSON( table.metadata() );
const QVariantMap readerMetadata = QgsJsonUtils::parseJson( tableMetadata ).toMap().value( QStringLiteral( "root" ) ).toMap();
// source metadata is only value present here!
if ( !readerMetadata.empty() )
mOriginalMetadata = readerMetadata.constBegin().value().toMap();
const pdal::QuickInfo quickInfo( reader->preview() );
const double xmin = quickInfo.m_bounds.minx;
const double xmax = quickInfo.m_bounds.maxx;
const double ymin = quickInfo.m_bounds.miny;
const double ymax = quickInfo.m_bounds.maxy;
mExtent = QgsRectangle( xmin, ymin, xmax, ymax );
mPointCount = quickInfo.m_pointCount;
if ( mPointCount == 0 )
throw pdal::pdal_error( "File contains no points" );
// projection
const QString wkt = QString::fromStdString( quickInfo.m_srs.getWKT() );
mCrs = QgsCoordinateReferenceSystem::fromWkt( wkt );
return quickInfo.valid();
}
else
{
throw pdal::pdal_error( "No reader for " + driver );
}
}
catch ( json::exception &error )
{
const QString errorString = QStringLiteral( "Error parsing table metadata: %1" ).arg( error.what() );
QgsDebugMsg( errorString );
appendError( errorString );
return false;
}
catch ( pdal::pdal_error &error )
{
const QString errorString = QString::fromStdString( error.what() );
QgsDebugMsg( errorString );
appendError( errorString );
return false;
}
}
QString QgsPdalProviderMetadata::sFilterString;
QStringList QgsPdalProviderMetadata::sExtensions;
QgsPdalProviderMetadata::QgsPdalProviderMetadata():
QgsProviderMetadata( PROVIDER_KEY, PROVIDER_DESCRIPTION )
{
}
QIcon QgsPdalProviderMetadata::icon() const
{
return QgsApplication::getThemeIcon( QStringLiteral( "mIconPointCloudLayer.svg" ) );
}
QgsPdalProvider *QgsPdalProviderMetadata::createProvider( const QString &uri, const QgsDataProvider::ProviderOptions &options, QgsDataProvider::ReadFlags flags )
{
return new QgsPdalProvider( uri, options, flags );
}
QgsProviderMetadata::ProviderMetadataCapabilities QgsPdalProviderMetadata::capabilities() const
{
return ProviderMetadataCapability::LayerTypesForUri
| ProviderMetadataCapability::PriorityForUri
| ProviderMetadataCapability::QuerySublayers;
}
QVariantMap QgsPdalProviderMetadata::decodeUri( const QString &uri ) const
{
const QString path = uri;
QVariantMap uriComponents;
uriComponents.insert( QStringLiteral( "path" ), path );
return uriComponents;
}
int QgsPdalProviderMetadata::priorityForUri( const QString &uri ) const
{
const QVariantMap parts = decodeUri( uri );
QString filePath = parts.value( QStringLiteral( "path" ) ).toString();
const QFileInfo fi( filePath );
if ( filePath.endsWith( QStringLiteral( ".copc.laz" ), Qt::CaseSensitivity::CaseInsensitive ) )
return 0;
if ( sExtensions.contains( fi.suffix(), Qt::CaseInsensitive ) )
return 100;
return 0;
}
QList<QgsMapLayerType> QgsPdalProviderMetadata::validLayerTypesForUri( const QString &uri ) const
{
const QVariantMap parts = decodeUri( uri );
QString filePath = parts.value( QStringLiteral( "path" ) ).toString();
const QFileInfo fi( filePath );
if ( sExtensions.contains( fi.suffix(), Qt::CaseInsensitive ) )
return QList<QgsMapLayerType>() << QgsMapLayerType::PointCloudLayer;
return QList<QgsMapLayerType>();
}
QList<QgsProviderSublayerDetails> QgsPdalProviderMetadata::querySublayers( const QString &uri, Qgis::SublayerQueryFlags, QgsFeedback * ) const
{
const QVariantMap parts = decodeUri( uri );
QString filePath = parts.value( QStringLiteral( "path" ) ).toString();
const QFileInfo fi( filePath );
if ( sExtensions.contains( fi.suffix(), Qt::CaseInsensitive ) )
{
QgsProviderSublayerDetails details;
details.setUri( uri );
details.setProviderKey( QStringLiteral( "pdal" ) );
details.setType( QgsMapLayerType::PointCloudLayer );
details.setName( QgsProviderUtils::suggestLayerNameFromFilePath( uri ) );
return {details};
}
else
{
return {};
}
}
QString QgsPdalProviderMetadata::filters( QgsProviderMetadata::FilterType type )
{
switch ( type )
{
case QgsProviderMetadata::FilterType::FilterVector:
case QgsProviderMetadata::FilterType::FilterRaster:
case QgsProviderMetadata::FilterType::FilterMesh:
case QgsProviderMetadata::FilterType::FilterMeshDataset:
return QString();
case QgsProviderMetadata::FilterType::FilterPointCloud:
buildSupportedPointCloudFileFilterAndExtensions();
return sFilterString;
}
return QString();
}
QgsProviderMetadata::ProviderCapabilities QgsPdalProviderMetadata::providerCapabilities() const
{
return FileBasedUris;
}
QList<QgsMapLayerType> QgsPdalProviderMetadata::supportedLayerTypes() const
{
return { QgsMapLayerType::PointCloudLayer };
}
QString QgsPdalProviderMetadata::encodeUri( const QVariantMap &parts ) const
{
const QString path = parts.value( QStringLiteral( "path" ) ).toString();
return path;
}
void QgsPdalProviderMetadata::buildSupportedPointCloudFileFilterAndExtensions()
{
// get supported extensions
static std::once_flag initialized;
std::call_once( initialized, [ = ]
{
const pdal::StageFactory f;
pdal::PluginManager<pdal::Stage>::loadAll();
const pdal::StringList stages = pdal::PluginManager<pdal::Stage>::names();
pdal::StageExtensions &extensions = pdal::PluginManager<pdal::Stage>::extensions();
// Let's call the defaultReader() method just so we trigger the private method extensions.load()
extensions.defaultReader( "laz" );
const QStringList allowedReaders {
QStringLiteral( "readers.las" ),
QStringLiteral( "readers.e57" ),
QStringLiteral( "readers.bpf" ) };
for ( const auto &stage : stages )
{
if ( ! allowedReaders.contains( QString::fromStdString( stage ) ) )
continue;
const pdal::StringList readerExtensions = extensions.extensions( stage );
for ( const auto &extension : readerExtensions )
{
sExtensions.append( QString::fromStdString( extension ) );
}
}
sExtensions.sort();
const QString extensionsString = QStringLiteral( "*." ).append( sExtensions.join( QLatin1String( " *." ) ) );
sFilterString = tr( "PDAL Point Clouds" ) + QString( " (%1 %2)" ).arg( extensionsString, extensionsString.toUpper() );
} );
}
QGISEXTERN QgsProviderMetadata *providerMetadataFactory()
{
return new QgsPdalProviderMetadata();
}