20#include <QApplication>
24#include "moc_qgspointcloudlayerexporter.cpp"
32#include <pdal/StageFactory.hpp>
33#include <pdal/io/BufferReader.hpp>
34#include <pdal/Dimension.hpp>
42 return QStringLiteral(
"GPKG" );
44 return QStringLiteral(
"DXF" );
46 return QStringLiteral(
"ESRI Shapefile" );
48 return QStringLiteral(
"CSV" );
57 : mLayerAttributeCollection( layer->attributes() )
58 , mIndex( layer->dataProvider()->index()->clone().release() )
65 mPointRecordFormat = 3;
89 mFilterGeometryEngine.reset(
new QgsGeos( geometry ) );
90 mFilterGeometryEngine->prepareGeometry();
99 QVector< QgsGeometry > allGeometries;
102 if ( selectedFeaturesOnly )
114 allGeometries.append( f.
geometry() );
124 QgsDebugError( QStringLiteral(
"Error transforming union of filter layer: %1" ).arg( cse.
what() ) );
125 QgsDebugError( QStringLiteral(
"FilterGeometry will be ignored." ) );
133 mRequestedAttributes.clear();
135 const QVector<QgsPointCloudAttribute> allAttributes = mLayerAttributeCollection.
attributes();
139 if ( attribute.name().compare( QLatin1String(
"X" ), Qt::CaseInsensitive ) &&
140 attribute.name().compare( QLatin1String(
"Y" ), Qt::CaseInsensitive ) &&
141 attribute.name().compare( QLatin1String(
"Z" ), Qt::CaseInsensitive ) &&
142 attributeList.contains( attribute.name() ) &&
143 ! mRequestedAttributes.contains( attribute.name() ) )
145 mRequestedAttributes.append( attribute.name() );
152 QStringList allAttributeNames;
153 const QVector<QgsPointCloudAttribute> allAttributes = mLayerAttributeCollection.
attributes();
156 allAttributeNames.append( attribute.name() );
163 const QVector<QgsPointCloudAttribute> allAttributes = mLayerAttributeCollection.
attributes();
168 if ( attribute.name().compare( QLatin1String(
"X" ), Qt::CaseInsensitive ) ||
169 attribute.name().compare( QLatin1String(
"Y" ), Qt::CaseInsensitive ) ||
170 attribute.name().compare( QLatin1String(
"Z" ), Qt::CaseInsensitive ) ||
171 mRequestedAttributes.contains( attribute.name(), Qt::CaseInsensitive ) )
173 requestAttributes.
push_back( attribute );
176 return requestAttributes;
179QgsFields QgsPointCloudLayerExporter::outputFields()
186 if ( mRequestedAttributes.contains( attribute.name(), Qt::CaseInsensitive ) )
187 fields.
append(
QgsField( attribute.name(), attribute.variantType(), attribute.displayType() ) );
195 mMemoryLayer =
nullptr;
199 if ( QApplication::instance()->thread() != QThread::currentThread() )
200 QgsDebugMsgLevel( QStringLiteral(
"prepareExport() should better be called from the main thread!" ), 2 );
217 QgsDebugError( QStringLiteral(
"Error transforming extent: %1" ).arg( cse.
what() ) );
221 QStringList layerCreationOptions;
230 ExporterMemory exp(
this );
242 ExporterPdal exp(
this );
245 catch ( std::runtime_error &e )
247 setLastError( QString::fromLatin1( e.what() ) );
248 QgsDebugError( QStringLiteral(
"PDAL has thrown an exception: {}" ).arg( e.what() ) );
255 layerCreationOptions << QStringLiteral(
"GEOMETRY=AS_XYZ" )
256 << QStringLiteral(
"SEPARATOR=COMMA" );
273 ExporterVector exp(
this );
287 mMemoryLayer =
nullptr;
293 const QFileInfo fileInfo( mFilename );
294 return new QgsPointCloudLayer( mFilename, fileInfo.completeBaseName(), QStringLiteral(
"pdal" ) );
299 QString uri( mFilename );
300 uri +=
"|layername=" + mName;
308 const QFileInfo fileInfo( mFilename );
309 return new QgsVectorLayer( mFilename, fileInfo.completeBaseName(), QStringLiteral(
"ogr" ) );
319void QgsPointCloudLayerExporter::ExporterBase::run()
321 QgsRectangle geometryFilterRectangle( -std::numeric_limits<double>::infinity(),
322 -std::numeric_limits<double>::infinity(),
323 std::numeric_limits<double>::infinity(),
324 std::numeric_limits<double>::infinity(),
326 if ( mParent->mFilterGeometryEngine )
333 QVector<QgsPointCloudNodeId> nodes;
334 qint64 pointCount = 0;
335 QQueue<QgsPointCloudNodeId> queue;
336 queue.push_back( mParent->mIndex->root() );
337 while ( !queue.empty() )
342 if ( mParent->mExtent.intersects( nodeBounds.
toRectangle() ) &&
343 mParent->mZRange.overlaps( { nodeBounds.zMinimum(), nodeBounds.zMaximum() } ) &&
344 geometryFilterRectangle.intersects( nodeBounds.
toRectangle() ) )
347 nodes.push_back( node.
id() );
351 queue.push_back( child );
355 const qint64 pointsToExport = mParent->mPointsLimit > 0 ? std::min( mParent->mPointsLimit, pointCount ) : pointCount;
357 request.
setAttributes( mParent->requestedAttributeCollection() );
358 std::unique_ptr<QgsPointCloudBlock> block =
nullptr;
359 qint64 pointsExported = 0;
362 block = mParent->mIndex->nodeData( node, request );
364 const char *ptr = block->data();
365 int count = block->pointCount();
369 int xOffset = 0, yOffset = 0, zOffset = 0;
373 for (
int i = 0; i < count; ++i )
376 if ( mParent->mFeedback &&
379 mParent->mFeedback->setProgress( 100 *
static_cast< float >( pointsExported ) / pointsToExport );
380 if ( mParent->mFeedback->isCanceled() )
382 mParent->setLastError( QObject::tr(
"Canceled by user" ) );
387 if ( pointsExported >= pointsToExport )
397 if ( ! mParent->mZRange.contains( z ) ||
398 ! mParent->mExtent.contains( x, y ) ||
399 ( mParent->mFilterGeometryEngine && ! mParent->mFilterGeometryEngine->contains( x, y ) ) )
406 mParent->mTransform->transformInPlace( x, y, z );
408 handlePoint( x, y, z, attributeMap, pointsExported );
413 QgsDebugError( QStringLiteral(
"Error transforming point: %1" ).arg( cse.
what() ) );
430QgsPointCloudLayerExporter::ExporterMemory::~ExporterMemory()
432 mParent->mMemoryLayer->moveToThread( QApplication::instance()->thread() );
435void QgsPointCloudLayerExporter::ExporterMemory::handlePoint(
double x,
double y,
double z,
const QVariantMap &map,
const qint64 pointNumber )
437 Q_UNUSED( pointNumber )
442 for (
const QString &attribute : std::as_const( mParent->mRequestedAttributes ) )
444 const double val = map[ attribute ].toDouble();
445 featureAttributes.append( val );
448 mFeatures.append( feature );
451void QgsPointCloudLayerExporter::ExporterMemory::handleNode()
453 QgsVectorLayer *vl = qgis::down_cast<QgsVectorLayer *>( mParent->mMemoryLayer );
464void QgsPointCloudLayerExporter::ExporterMemory::handleAll()
478QgsPointCloudLayerExporter::ExporterVector::~ExporterVector()
480 delete mParent->mVectorSink;
481 mParent->mVectorSink =
nullptr;
484void QgsPointCloudLayerExporter::ExporterVector::handlePoint(
double x,
double y,
double z,
const QVariantMap &map,
const qint64 pointNumber )
486 Q_UNUSED( pointNumber )
491 for (
const QString &attribute : std::as_const( mParent->mRequestedAttributes ) )
493 const double val = map[ attribute ].toDouble();
494 featureAttributes.append( val );
497 mFeatures.append( feature );
500void QgsPointCloudLayerExporter::ExporterVector::handleNode()
502 if ( ! mParent->mVectorSink->addFeatures( mFeatures ) )
504 mParent->setLastError( mParent->mVectorSink->lastError() );
509void QgsPointCloudLayerExporter::ExporterVector::handleAll()
521 : mPointFormat( exp->mPointRecordFormat )
525 mOptions.add(
"filename", mParent->mFilename.toStdString() );
526 mOptions.add(
"a_srs", mParent->mTargetCrs.toWkt().toStdString() );
527 mOptions.add(
"minor_version", QStringLiteral(
"4" ).toStdString() );
528 mOptions.add(
"format", QString::number( mPointFormat ).toStdString() );
529 if ( mParent->mTransform->isShortCircuited() )
531 mOptions.add(
"offset_x", QString::number( mParent->mIndex->offset().x() ).toStdString() );
532 mOptions.add(
"offset_y", QString::number( mParent->mIndex->offset().y() ).toStdString() );
533 mOptions.add(
"offset_z", QString::number( mParent->mIndex->offset().z() ).toStdString() );
534 mOptions.add(
"scale_x", QString::number( mParent->mIndex->scale().x() ).toStdString() );
535 mOptions.add(
"scale_y", QString::number( mParent->mIndex->scale().y() ).toStdString() );
536 mOptions.add(
"scale_z", QString::number( mParent->mIndex->scale().z() ).toStdString() );
539 mTable.layout()->registerDim( pdal::Dimension::Id::X );
540 mTable.layout()->registerDim( pdal::Dimension::Id::Y );
541 mTable.layout()->registerDim( pdal::Dimension::Id::Z );
543 mTable.layout()->registerDim( pdal::Dimension::Id::Classification );
544 mTable.layout()->registerDim( pdal::Dimension::Id::Intensity );
545 mTable.layout()->registerDim( pdal::Dimension::Id::ReturnNumber );
546 mTable.layout()->registerDim( pdal::Dimension::Id::NumberOfReturns );
547 mTable.layout()->registerDim( pdal::Dimension::Id::ScanDirectionFlag );
548 mTable.layout()->registerDim( pdal::Dimension::Id::EdgeOfFlightLine );
549 mTable.layout()->registerDim( pdal::Dimension::Id::ScanAngleRank );
550 mTable.layout()->registerDim( pdal::Dimension::Id::UserData );
551 mTable.layout()->registerDim( pdal::Dimension::Id::PointSourceId );
553 if ( mPointFormat == 6 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 9 || mPointFormat == 10 )
555 mTable.layout()->registerDim( pdal::Dimension::Id::ScanChannel );
556 mTable.layout()->registerDim( pdal::Dimension::Id::ClassFlags );
559 if ( mPointFormat != 0 && mPointFormat != 2 )
561 mTable.layout()->registerDim( pdal::Dimension::Id::GpsTime );
564 if ( mPointFormat == 2 || mPointFormat == 3 || mPointFormat == 5 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 10 )
566 mTable.layout()->registerDim( pdal::Dimension::Id::Red );
567 mTable.layout()->registerDim( pdal::Dimension::Id::Green );
568 mTable.layout()->registerDim( pdal::Dimension::Id::Blue );
571 if ( mPointFormat == 8 || mPointFormat == 10 )
573 mTable.layout()->registerDim( pdal::Dimension::Id::Infrared );
576 mView.reset(
new pdal::PointView( mTable ) );
579void QgsPointCloudLayerExporter::ExporterPdal::handlePoint(
double x,
double y,
double z,
const QVariantMap &map,
const qint64 pointNumber )
581 mView->setField( pdal::Dimension::Id::X, pointNumber, x );
582 mView->setField( pdal::Dimension::Id::Y, pointNumber, y );
583 mView->setField( pdal::Dimension::Id::Z, pointNumber, z );
586 mView->setField( pdal::Dimension::Id::Classification, pointNumber, map[ QStringLiteral(
"Classification" ) ].toInt() );
587 mView->setField( pdal::Dimension::Id::Intensity, pointNumber, map[ QStringLiteral(
"Intensity" ) ].toInt() );
588 mView->setField( pdal::Dimension::Id::ReturnNumber, pointNumber, map[ QStringLiteral(
"ReturnNumber" ) ].toInt() );
589 mView->setField( pdal::Dimension::Id::NumberOfReturns, pointNumber, map[ QStringLiteral(
"NumberOfReturns" ) ].toInt() );
590 mView->setField( pdal::Dimension::Id::ScanDirectionFlag, pointNumber, map[ QStringLiteral(
"ScanDirectionFlag" ) ].toInt() );
591 mView->setField( pdal::Dimension::Id::EdgeOfFlightLine, pointNumber, map[ QStringLiteral(
"EdgeOfFlightLine" ) ].toInt() );
592 mView->setField( pdal::Dimension::Id::ScanAngleRank, pointNumber, map[ QStringLiteral(
"ScanAngleRank" ) ].toFloat() );
593 mView->setField( pdal::Dimension::Id::UserData, pointNumber, map[ QStringLiteral(
"UserData" ) ].toInt() );
594 mView->setField( pdal::Dimension::Id::PointSourceId, pointNumber, map[ QStringLiteral(
"PointSourceId" ) ].toInt() );
596 if ( mPointFormat == 6 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 9 || mPointFormat == 10 )
598 mView->setField( pdal::Dimension::Id::ScanChannel, pointNumber, map[ QStringLiteral(
"ScannerChannel" ) ].toInt() );
599 const int classificationFlags = ( map[ QStringLiteral(
"Synthetic" ) ].toInt() & 0x01 ) << 0 |
600 ( map[ QStringLiteral(
"KeyPoint" ) ].toInt() & 0x01 ) << 1 |
601 ( map[ QStringLiteral(
"Withheld" ) ].toInt() & 0x01 ) << 2 |
602 ( map[ QStringLiteral(
"Overlap" ) ].toInt() & 0x01 ) << 3;
603 mView->setField( pdal::Dimension::Id::ClassFlags, pointNumber, classificationFlags );
606 if ( mPointFormat != 0 && mPointFormat != 2 )
608 mView->setField( pdal::Dimension::Id::GpsTime, pointNumber, map[ QStringLiteral(
"GpsTime" ) ].toDouble() );
611 if ( mPointFormat == 2 || mPointFormat == 3 || mPointFormat == 5 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 10 )
613 mView->setField( pdal::Dimension::Id::Red, pointNumber, map[ QStringLiteral(
"Red" ) ].toInt() );
614 mView->setField( pdal::Dimension::Id::Green, pointNumber, map[ QStringLiteral(
"Green" ) ].toInt() );
615 mView->setField( pdal::Dimension::Id::Blue, pointNumber, map[ QStringLiteral(
"Blue" ) ].toInt() );
618 if ( mPointFormat == 8 || mPointFormat == 10 )
620 mView->setField( pdal::Dimension::Id::Infrared, pointNumber, map[ QStringLiteral(
"Infrared" ) ].toInt() );
624void QgsPointCloudLayerExporter::ExporterPdal::handleNode()
629void QgsPointCloudLayerExporter::ExporterPdal::handleAll()
631 pdal::BufferReader reader;
632 reader.addView( mView );
634 pdal::StageFactory factory;
636 pdal::Stage *writer = factory.createStage(
"writers.las" );
638 writer->setInput( reader );
639 writer->setOptions( mOptions );
640 writer->prepare( mTable );
641 writer->execute( mTable );
658 mOwnedFeedback->cancel();
@ NoSymbology
Export only data.
@ Reverse
Reverse/inverse transform (from destination to source)
Abstract base class for all geometries.
virtual QgsRectangle boundingBox() const
Returns the minimal bounding box for the geometry.
A 3-dimensional box composed of x, y, z coordinates.
QgsRectangle toRectangle() const
Converts the box to a 2D rectangle.
This class represents a coordinate reference system (CRS).
Contains information about the context in which a coordinate transform is executed.
Custom exception class for Coordinate Reference System related exceptions.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setNoAttributes()
Set that no attributes will be fetched.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
void progressChanged(double progress)
Emitted when the feedback object reports a progress change.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
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.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters ¶meters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
Does vector analysis using the GEOS library and handles import, export, and exception handling.
Base class for all map layer types.
QgsCoordinateReferenceSystem crs
static QgsVectorLayer * createMemoryLayer(const QString &name, const QgsFields &fields, Qgis::WkbType geometryType=Qgis::WkbType::NoGeometry, const QgsCoordinateReferenceSystem &crs=QgsCoordinateReferenceSystem(), bool loadDefaultStyle=true) SIP_FACTORY
Creates a new memory layer using the specified parameters.
Collection of point cloud attributes.
void push_back(const QgsPointCloudAttribute &attribute)
Adds extra attribute.
int pointRecordSize() const
Returns total size of record.
const QgsPointCloudAttribute * find(const QString &attributeName, int &offset) const
Finds the attribute with the name.
QVector< QgsPointCloudAttribute > attributes() const
Returns all attributes.
Attribute for point cloud data pair of name and size in bytes.
DataType
Systems of unit measurement.
static void getPointXYZ(const char *ptr, int i, std::size_t pointRecordSize, int xOffset, QgsPointCloudAttribute::DataType xType, int yOffset, QgsPointCloudAttribute::DataType yType, int zOffset, QgsPointCloudAttribute::DataType zType, const QgsVector3D &indexScale, const QgsVector3D &indexOffset, double &x, double &y, double &z)
Retrieves the x, y, z values for the point at index i.
static QVariantMap getAttributeMap(const char *data, std::size_t recordOffset, const QgsPointCloudAttributeCollection &attributeCollection)
Retrieves all the attributes of a point.
DataType type() const
Returns the data type.
virtual QVariantMap originalMetadata() const
Returns a representation of the original metadata included in a point cloud dataset.
void cancel() override
Notifies the task that it should terminate.
QgsPointCloudLayerExporterTask(QgsPointCloudLayerExporter *exporter)
Constructor for QgsPointCloudLayerExporterTask.
void exportComplete()
Emitted when exporting the layer is successfully completed.
void finished(bool result) override
If the task is managed by a QgsTaskManager, this will be called after the task has finished (whether ...
bool run() override
Performs the task's operation.
Handles exporting point cloud layers to memory layers, OGR supported files and PDAL supported files.
void setFeedback(QgsFeedback *feedback)
Sets a QgsFeedback object to allow cancellation / progress reporting.
QgsMapLayer * takeExportedLayer()
Gets a pointer to the exported layer.
ExportFormat format() const
Returns the format for the exported file or layer.
void setAttributes(const QStringList &attributes)
Sets the list of point cloud attributes that will be exported.
ExportFormat
Supported export formats for point clouds.
@ Csv
Comma separated values.
@ Las
LAS/LAZ point cloud.
~QgsPointCloudLayerExporter()
void setAllAttributes()
Sets that all attributes will be exported.
bool setFormat(const ExportFormat format)
Sets the format for the exported file.
static QString getOgrDriverName(ExportFormat format)
Gets the OGR driver name for the specified format.
QStringList attributes() const
Gets the list of point cloud attributes that will be exported.
QgsPointCloudLayerExporter(QgsPointCloudLayer *layer)
Constructor for QgsPointCloudLayerExporter, associated with the specified layer.
void prepareExport()
Creates the QgsVectorLayer for exporting to a memory layer, if necessary.
static QList< ExportFormat > supportedFormats()
Gets a list of the supported export formats.
void setFilterGeometry(const QgsAbstractGeometry *geometry)
Sets a spatial filter for points to be exported based on geom in the point cloud's CRS.
void doExport()
Performs the actual exporting operation.
Represents a map layer supporting display of point clouds.
QgsPointCloudDataProvider * dataProvider() override
Returns the layer's data provider, it may be nullptr.
Represents a indexed point cloud node's position in octree.
Keeps metadata for indexed point cloud node.
qint64 pointCount() const
Returns number of points contained in node data.
QgsPointCloudNodeId id() const
Returns node's ID (unique in index)
QgsBox3D bounds() const
Returns node's bounding cube in CRS coords.
Point cloud data request.
void setAttributes(const QgsPointCloudAttributeCollection &attributes)
Set attributes filter in the request.
Point geometry type, with support for z-dimension and m-values.
A rectangle specified with double values.
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Abstract base class for long running background tasks.
virtual void cancel()
Notifies the task that it should terminate.
void setProgress(double progress)
Sets the task's current progress.
Class for storage of 3D vectors similar to QVector3D, with the difference that it uses double precisi...
QString lastError() const override
Returns the most recent error encountered by the sink, e.g.
bool addFeatures(QgsFeatureList &flist, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
Options to pass to writeAsVectorFormat()
QString driverName
OGR driver to use.
QString layerName
Layer name. If let empty, it will be derived from the filename.
QStringList layerOptions
List of OGR layer creation options.
Qgis::FeatureSymbologyExport symbologyExport
Symbology to export.
QgsVectorFileWriter::ActionOnExistingFile actionOnExistingFile
Action on existing file.
QStringList datasourceOptions
List of OGR data source creation options.
QgsFeedback * feedback
Optional feedback object allowing cancellation of layer save.
static QStringList defaultLayerOptions(const QString &driverName)
Returns a list of the default layer options for a specified driver.
static QgsVectorFileWriter * create(const QString &fileName, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &srs, const QgsCoordinateTransformContext &transformContext, const QgsVectorFileWriter::SaveVectorOptions &options, QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QString *newFilename=nullptr, QString *newLayer=nullptr)
Create a new vector file writer.
static QStringList defaultDatasetOptions(const QString &driverName)
Returns a list of the default dataset options for a specified driver.
Represents a vector layer which manages a vector based data sets.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
#define BUILTIN_UNREACHABLE
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
const QgsCoordinateReferenceSystem & crs