26#include <QApplication>
32#include "moc_qgspointcloudlayerexporter.cpp"
34using namespace Qt::StringLiterals;
38#include <pdal/StageFactory.hpp>
39#include <pdal/io/BufferReader.hpp>
40#include <pdal/Dimension.hpp>
52 return u
"ESRI Shapefile"_s;
63 : mLayerAttributeCollection( layer->
attributes() )
64 , mIndex( layer->index() )
69 mPointRecordFormat = layer->
dataProvider()->originalMetadata().value( u
"dataformat_id"_s ).toInt( &ok );
71 mPointRecordFormat = 3;
91 mFilterGeometryEngine = std::make_unique<QgsGeos>( geometry );
92 mFilterGeometryEngine->prepareGeometry();
101 QVector< QgsGeometry > allGeometries;
104 if ( selectedFeaturesOnly )
116 allGeometries.append( f.
geometry() );
126 QgsDebugError( u
"Error transforming union of filter layer: %1"_s.arg( cse.
what() ) );
135 mRequestedAttributes.clear();
137 const QVector<QgsPointCloudAttribute> allAttributes = mLayerAttributeCollection.attributes();
141 if ( attribute.name().compare(
'X'_L1, Qt::CaseInsensitive )
142 && attribute.name().compare(
'Y'_L1, Qt::CaseInsensitive )
143 && attribute.name().compare(
'Z'_L1, Qt::CaseInsensitive )
144 && attributeList.contains( attribute.name() )
145 && !mRequestedAttributes.contains( attribute.name() ) )
147 mRequestedAttributes.append( attribute.name() );
154 QStringList allAttributeNames;
155 const QVector<QgsPointCloudAttribute> allAttributes = mLayerAttributeCollection.attributes();
158 allAttributeNames.append( attribute.name() );
165 const QVector<QgsPointCloudAttribute> allAttributes = mLayerAttributeCollection.
attributes();
170 if ( attribute.name().compare(
'X'_L1, Qt::CaseInsensitive )
171 || attribute.name().compare(
'Y'_L1, Qt::CaseInsensitive )
172 || attribute.name().compare(
'Z'_L1, Qt::CaseInsensitive )
173 || mRequestedAttributes.contains( attribute.name(), Qt::CaseInsensitive ) )
175 requestAttributes.
push_back( attribute );
178 return requestAttributes;
181QgsFields QgsPointCloudLayerExporter::outputFields()
183 const QVector<QgsPointCloudAttribute>
attributes = mLayerAttributeCollection.attributes();
186 for (
const QgsPointCloudAttribute &attribute :
attributes )
188 if ( mRequestedAttributes.contains( attribute.name(), Qt::CaseInsensitive ) )
189 fields.
append( QgsField( attribute.name(), attribute.variantType(), attribute.displayType() ) );
196 mMemoryLayer.reset();
202 if ( QApplication::instance()->thread() != QThread::currentThread() )
204 QgsDebugMsgLevel( u
"prepareExport() should better be called from the main thread!"_s, 2 );
215 if ( mExtent.isFinite() )
227 QStringList layerCreationOptions;
236 ExporterMemory exp(
this );
248 ExporterPdal exp(
this );
251 catch ( std::runtime_error &e )
253 setLastError( QString::fromLatin1( e.what() ) );
254 QgsDebugError( u
"PDAL has thrown an exception: {}"_s.arg( e.what() ) );
261 layerCreationOptions << u
"GEOMETRY=AS_XYZ"_s << u
"SEPARATOR=COMMA"_s;
278 ExporterVector exp(
this );
291 return mMemoryLayer.release();
296 const QFileInfo fileInfo( mFilename );
302 QString uri( mFilename );
303 uri +=
"|layername=" + mName;
311 const QFileInfo fileInfo( mFilename );
312 return new QgsVectorLayer( mFilename, fileInfo.completeBaseName(), u
"ogr"_s );
322void QgsPointCloudLayerExporter::ExporterBase::run()
325 geometryFilterRectangle( -std::numeric_limits<double>::infinity(), -std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(),
false );
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() )
339 QgsPointCloudNode node = mParent->mIndex.getNode( queue.front() );
341 const QgsBox3D nodeBounds = node.
bounds();
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() );
349 for ( QgsPointCloudNodeId child : node.
children() )
351 queue.push_back( child );
355 const qint64 pointsToExport = mParent->mPointsLimit > 0 ? std::min( mParent->mPointsLimit, pointCount ) : pointCount;
356 QgsPointCloudRequest request;
357 request.
setAttributes( mParent->requestedAttributeCollection() );
358 std::unique_ptr<QgsPointCloudBlock> block =
nullptr;
359 qint64 pointsExported = 0;
360 for ( QgsPointCloudNodeId node : nodes )
362 block = mParent->mIndex.nodeData( node, request );
363 const QgsPointCloudAttributeCollection attributesCollection = block->attributes();
364 const char *ptr = block->data();
365 int count = block->pointCount();
367 const QgsVector3D scale = block->scale();
368 const QgsVector3D offset = block->offset();
369 int xOffset = 0, yOffset = 0, zOffset = 0;
373 for (
int i = 0; i < count; ++i )
375 if ( mParent->mFeedback && i % 1000 == 0 )
377 if ( pointsToExport > 0 )
379 mParent->mFeedback->setProgress( 100 *
static_cast< float >( pointsExported ) / pointsToExport );
381 if ( mParent->mFeedback->isCanceled() )
383 mParent->setLastError( QObject::tr(
"Canceled by user" ) );
388 if ( pointsExported >= pointsToExport )
392 QgsPointCloudAttribute::getPointXYZ( ptr, i, recordSize, xOffset, xType, yOffset, yType, zOffset, zType, scale, offset, x, y, z );
393 if ( !mParent->mZRange.contains( z ) || !mParent->mExtent.contains( x, y ) || ( mParent->mFilterGeometryEngine && !mParent->mFilterGeometryEngine->contains( x, y ) ) )
400 mParent->mTransform.transformInPlace( x, y, z );
402 handlePoint( x, y, z, attributeMap, pointsExported );
405 catch (
const QgsCsException &cse )
424QgsPointCloudLayerExporter::ExporterMemory::~ExporterMemory()
426 mParent->mMemoryLayer->moveToThread( QApplication::instance()->thread() );
429void QgsPointCloudLayerExporter::ExporterMemory::handlePoint(
double x,
double y,
double z,
const QVariantMap &map,
const qint64 pointNumber )
431 Q_UNUSED( pointNumber )
434 feature.
setGeometry( QgsGeometry(
new QgsPoint( x, y, z ) ) );
435 QgsAttributes featureAttributes;
436 for (
const QString &attribute : std::as_const( mParent->mRequestedAttributes ) )
438 const double val = map[attribute].toDouble();
439 featureAttributes.append( val );
442 mFeatures.append( feature );
445void QgsPointCloudLayerExporter::ExporterMemory::handleNode()
447 QgsVectorLayer *vl = qgis::down_cast<QgsVectorLayer *>( mParent->mMemoryLayer.get() );
458void QgsPointCloudLayerExporter::ExporterMemory::handleAll()
470QgsPointCloudLayerExporter::ExporterVector::~ExporterVector()
472 mParent->mVectorSink.reset();
475void QgsPointCloudLayerExporter::ExporterVector::handlePoint(
double x,
double y,
double z,
const QVariantMap &map,
const qint64 pointNumber )
477 Q_UNUSED( pointNumber )
480 feature.
setGeometry( QgsGeometry(
new QgsPoint( x, y, z ) ) );
481 QgsAttributes featureAttributes;
482 for (
const QString &attribute : std::as_const( mParent->mRequestedAttributes ) )
484 const double val = map[attribute].toDouble();
485 featureAttributes.append( val );
488 mFeatures.append( feature );
491void QgsPointCloudLayerExporter::ExporterVector::handleNode()
493 if ( !mParent->mVectorSink->addFeatures( mFeatures ) )
495 mParent->setLastError( mParent->mVectorSink->lastError() );
500void QgsPointCloudLayerExporter::ExporterVector::handleAll()
510 : mPointFormat( exp->mPointRecordFormat )
514 mOptions.add(
"filename", mParent->mFilename.toStdString() );
515 mOptions.add(
"a_srs", mParent->mTargetCrs.toWkt().toStdString() );
516 mOptions.add(
"minor_version", u
"4"_s.toStdString() );
517 mOptions.add(
"format", QString::number( mPointFormat ).toStdString() );
518 if ( mParent->mTransform.isShortCircuited() )
520 mOptions.add(
"offset_x", QString::number( mParent->mIndex.offset().x() ).toStdString() );
521 mOptions.add(
"offset_y", QString::number( mParent->mIndex.offset().y() ).toStdString() );
522 mOptions.add(
"offset_z", QString::number( mParent->mIndex.offset().z() ).toStdString() );
523 mOptions.add(
"scale_x", QString::number( mParent->mIndex.scale().x() ).toStdString() );
524 mOptions.add(
"scale_y", QString::number( mParent->mIndex.scale().y() ).toStdString() );
525 mOptions.add(
"scale_z", QString::number( mParent->mIndex.scale().z() ).toStdString() );
528 mTable.layout()->registerDim( pdal::Dimension::Id::X );
529 mTable.layout()->registerDim( pdal::Dimension::Id::Y );
530 mTable.layout()->registerDim( pdal::Dimension::Id::Z );
532 mTable.layout()->registerDim( pdal::Dimension::Id::Classification );
533 mTable.layout()->registerDim( pdal::Dimension::Id::Intensity );
534 mTable.layout()->registerDim( pdal::Dimension::Id::ReturnNumber );
535 mTable.layout()->registerDim( pdal::Dimension::Id::NumberOfReturns );
536 mTable.layout()->registerDim( pdal::Dimension::Id::ScanDirectionFlag );
537 mTable.layout()->registerDim( pdal::Dimension::Id::EdgeOfFlightLine );
538 mTable.layout()->registerDim( pdal::Dimension::Id::ScanAngleRank );
539 mTable.layout()->registerDim( pdal::Dimension::Id::UserData );
540 mTable.layout()->registerDim( pdal::Dimension::Id::PointSourceId );
542 if ( mPointFormat == 6 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 9 || mPointFormat == 10 )
544 mTable.layout()->registerDim( pdal::Dimension::Id::ScanChannel );
545 mTable.layout()->registerDim( pdal::Dimension::Id::ClassFlags );
548 if ( mPointFormat != 0 && mPointFormat != 2 )
550 mTable.layout()->registerDim( pdal::Dimension::Id::GpsTime );
553 if ( mPointFormat == 2 || mPointFormat == 3 || mPointFormat == 5 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 10 )
555 mTable.layout()->registerDim( pdal::Dimension::Id::Red );
556 mTable.layout()->registerDim( pdal::Dimension::Id::Green );
557 mTable.layout()->registerDim( pdal::Dimension::Id::Blue );
560 if ( mPointFormat == 8 || mPointFormat == 10 )
562 mTable.layout()->registerDim( pdal::Dimension::Id::Infrared );
565 mView = std::make_shared<pdal::PointView>( mTable );
568void QgsPointCloudLayerExporter::ExporterPdal::handlePoint(
double x,
double y,
double z,
const QVariantMap &map,
const qint64 pointNumber )
570 mView->setField( pdal::Dimension::Id::X, pointNumber, x );
571 mView->setField( pdal::Dimension::Id::Y, pointNumber, y );
572 mView->setField( pdal::Dimension::Id::Z, pointNumber, z );
575 mView->setField( pdal::Dimension::Id::Classification, pointNumber, map[u
"Classification"_s].toInt() );
576 mView->setField( pdal::Dimension::Id::Intensity, pointNumber, map[u
"Intensity"_s].toInt() );
577 mView->setField( pdal::Dimension::Id::ReturnNumber, pointNumber, map[u
"ReturnNumber"_s].toInt() );
578 mView->setField( pdal::Dimension::Id::NumberOfReturns, pointNumber, map[u
"NumberOfReturns"_s].toInt() );
579 mView->setField( pdal::Dimension::Id::ScanDirectionFlag, pointNumber, map[u
"ScanDirectionFlag"_s].toInt() );
580 mView->setField( pdal::Dimension::Id::EdgeOfFlightLine, pointNumber, map[u
"EdgeOfFlightLine"_s].toInt() );
581 mView->setField( pdal::Dimension::Id::ScanAngleRank, pointNumber, map[u
"ScanAngleRank"_s].toFloat() );
582 mView->setField( pdal::Dimension::Id::UserData, pointNumber, map[u
"UserData"_s].toInt() );
583 mView->setField( pdal::Dimension::Id::PointSourceId, pointNumber, map[u
"PointSourceId"_s].toInt() );
585 if ( mPointFormat == 6 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 9 || mPointFormat == 10 )
587 mView->setField( pdal::Dimension::Id::ScanChannel, pointNumber, map[u
"ScannerChannel"_s].toInt() );
588 const int classificationFlags = ( map[u
"Synthetic"_s].toInt() & 0x01 ) << 0
589 | ( map[u
"KeyPoint"_s].toInt() & 0x01 ) << 1
590 | ( map[u
"Withheld"_s].toInt() & 0x01 ) << 2
591 | ( map[u
"Overlap"_s].toInt() & 0x01 ) << 3;
592 mView->setField( pdal::Dimension::Id::ClassFlags, pointNumber, classificationFlags );
595 if ( mPointFormat != 0 && mPointFormat != 2 )
597 mView->setField( pdal::Dimension::Id::GpsTime, pointNumber, map[u
"GpsTime"_s].toDouble() );
600 if ( mPointFormat == 2 || mPointFormat == 3 || mPointFormat == 5 || mPointFormat == 7 || mPointFormat == 8 || mPointFormat == 10 )
602 mView->setField( pdal::Dimension::Id::Red, pointNumber, map[u
"Red"_s].toInt() );
603 mView->setField( pdal::Dimension::Id::Green, pointNumber, map[u
"Green"_s].toInt() );
604 mView->setField( pdal::Dimension::Id::Blue, pointNumber, map[u
"Blue"_s].toInt() );
607 if ( mPointFormat == 8 || mPointFormat == 10 )
609 mView->setField( pdal::Dimension::Id::Infrared, pointNumber, map[u
"Infrared"_s].toInt() );
613void QgsPointCloudLayerExporter::ExporterPdal::handleNode()
616void QgsPointCloudLayerExporter::ExporterPdal::handleAll()
618 pdal::BufferReader reader;
619 reader.addView( mView );
621 pdal::StageFactory factory;
623 pdal::Stage *writer = factory.createStage(
"writers.las" );
625 writer->setInput( reader );
626 writer->setOptions( mOptions );
627 writer->prepare( mTable );
628 writer->execute( mTable );
644 mOwnedFeedback->cancel();
654 mExp->setFeedback( mOwnedFeedback.get() );
@ 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.
QgsRectangle toRectangle() const
Converts the box to a 2D rectangle.
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.
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.
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(), QgsFeedback *feedback=nullptr)
Compute the unary union on a list of geometries.
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.
A 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.
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.
QgsMapLayer * takeExportedLayer()
Gets a pointer to the exported layer.
QgsCoordinateReferenceSystem crs() const
Gets the crs for the exported file.
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.
QList< QgsPointCloudNodeId > children() const
Returns IDs of child nodes.
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.
void setAttributes(const QgsPointCloudAttributeCollection &attributes)
Set attributes filter in the request.
A rectangle specified with double values.
virtual void cancel()
Notifies the task that it should terminate.
QgsTask(const QString &description=QString(), QgsTask::Flags flags=AllFlags)
Constructor for QgsTask.
@ CanCancel
Task can be canceled.
void setProgress(double progress)
Sets the task's current progress.
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 QgsVectorFileWriter::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 dataset.
QgsFeatureIterator getSelectedFeatures(QgsFeatureRequest request=QgsFeatureRequest()) const
Returns an iterator of the selected features.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const final
Queries the layer for features specified in request.
QgsVectorDataProvider * dataProvider() final
Returns the layer's data provider, it may be nullptr.
#define BUILTIN_UNREACHABLE
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)