31 #include <QDomElement>
32 #include <QApplication>
34 #include <QStringList>
48 QReadWriteLock QgsCoordinateTransform::sCacheLock;
50 bool QgsCoordinateTransform::sDisableCache =
false;
54 const QString &desiredOperation )> QgsCoordinateTransform::sFallbackOperationOccurredHandler =
nullptr;
58 d =
new QgsCoordinateTransformPrivate();
64 d =
new QgsCoordinateTransformPrivate( source, destination, mContext );
69 if ( !d->checkValidity() )
73 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
84 d =
new QgsCoordinateTransformPrivate( source, destination, mContext );
90 if ( !d->checkValidity() )
94 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
104 d =
new QgsCoordinateTransformPrivate( source, destination, sourceDatumTransform, destinationDatumTransform );
109 if ( !d->checkValidity() )
113 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
122 : mContext( o.mContext )
124 , mHasContext( o.mHasContext )
135 mHasContext = o.mHasContext;
137 mContext = o.mContext;
138 mLastError = QString();
148 if ( !d->checkValidity() )
151 d->calculateTransforms( mContext );
153 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
164 if ( !d->checkValidity() )
167 d->calculateTransforms( mContext );
169 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
184 if ( !d->checkValidity() )
187 d->calculateTransforms( mContext );
189 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
204 return d->mSourceCRS;
214 if ( !d->mIsValid || d->mShortCircuit )
218 double x = point.
x();
219 double y = point.
y();
252 if ( !d->mIsValid || d->mShortCircuit )
276 #ifdef COORDINATE_TRANSFORM_VERBOSE
277 QgsDebugMsg( QStringLiteral(
"Rect projection..." ) );
288 double x = point.
x();
289 double y = point.
y();
290 double z = point.
z();
307 if ( !d->mIsValid || d->mShortCircuit )
328 double xd =
static_cast< double >( x ), yd =
static_cast< double >( y );
337 if ( !d->mIsValid || d->mShortCircuit )
363 if ( !d->mIsValid || d->mShortCircuit )
369 int nVertices = poly.size();
371 QVector<double> x( nVertices );
372 QVector<double> y( nVertices );
373 QVector<double> z( nVertices );
374 double *destX = x.data();
375 double *destY = y.data();
376 double *destZ = z.data();
378 const QPointF *polyData = poly.constData();
379 for (
int i = 0; i < nVertices; ++i )
381 *destX++ = polyData->x();
382 *destY++ = polyData->y();
398 QPointF *destPoint = poly.data();
399 const double *srcX = x.constData();
400 const double *srcY = y.constData();
401 for (
int i = 0; i < nVertices; ++i )
403 destPoint->rx() = *srcX++;
404 destPoint->ry() = *srcY++;
409 if ( !err.isEmpty() )
414 QVector<double> &x, QVector<double> &y, QVector<double> &z,
418 if ( !d->mIsValid || d->mShortCircuit )
421 Q_ASSERT( x.size() == y.size() );
442 QVector<float> &x, QVector<float> &y, QVector<float> &z,
445 if ( !d->mIsValid || d->mShortCircuit )
448 Q_ASSERT( x.size() == y.size() );
458 int vectorSize = x.size();
459 QVector<double> xd( x.size() );
460 QVector<double> yd( y.size() );
461 QVector<double> zd( z.size() );
463 double *destX = xd.data();
464 double *destY = yd.data();
465 double *destZ = zd.data();
467 const float *srcX = x.constData();
468 const float *srcY = y.constData();
469 const float *srcZ = z.constData();
471 for (
int i = 0; i < vectorSize; ++i )
473 *destX++ =
static_cast< double >( *srcX++ );
474 *destY++ =
static_cast< double >( *srcY++ );
475 *destZ++ =
static_cast< double >( *srcZ++ );
481 float *destFX = x.data();
482 float *destFY = y.data();
483 float *destFZ = z.data();
484 const double *srcXD = xd.constData();
485 const double *srcYD = yd.constData();
486 const double *srcZD = zd.constData();
487 for (
int i = 0; i < vectorSize; ++i )
489 *destFX++ =
static_cast< float >( *srcXD++ );
490 *destFY++ =
static_cast< float >( *srcYD++ );
491 *destFZ++ =
static_cast< float >( *srcZD++ );
509 if ( !d->mIsValid || d->mShortCircuit )
522 const int nPoints = 1000;
523 double d = std::sqrt( ( rect.
width() * rect.
height() ) / std::pow( std::sqrt(
static_cast< double >( nPoints ) ) - 1, 2.0 ) );
524 int nXPoints = std::min(
static_cast< int >( std::ceil( rect.
width() / d ) ) + 1, 1000 );
525 int nYPoints = std::min(
static_cast< int >( std::ceil( rect.
height() / d ) ) + 1, 1000 );
532 QVector<double> x( nXPoints * nYPoints );
533 QVector<double> y( nXPoints * nYPoints );
534 QVector<double> z( nXPoints * nYPoints );
536 QgsDebugMsgLevel( QStringLiteral(
"Entering transformBoundingBox..." ), 4 );
540 double dx = rect.
width() /
static_cast< double >( nXPoints - 1 );
541 double dy = rect.
height() /
static_cast< double >( nYPoints - 1 );
545 for (
int i = 0; i < nYPoints ; i++ )
551 for (
int j = 0; j < nXPoints; j++ )
553 x[( i * nXPoints ) + j] = pointX;
554 y[( i * nXPoints ) + j] = pointY;
556 z[( i * nXPoints ) + j] = 0.0;
567 transformCoords( nXPoints * nYPoints, x.data(), y.data(), z.data(), direction );
578 for (
int i = 0; i < nXPoints * nYPoints; i++ )
580 if ( !std::isfinite( x[i] ) || !std::isfinite( y[i] ) )
585 if ( handle180Crossover )
599 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
602 if ( handle180Crossover )
623 if ( !d->mIsValid || d->mShortCircuit )
626 if ( !d->mSourceCRS.isValid() )
629 "The coordinates can not be reprojected. The CRS is: %1" )
630 .arg( d->mSourceCRS.toProj() ), QObject::tr(
"CRS" ) );
633 if ( !d->mDestCRS.isValid() )
636 "The coordinates can not be reprojected. The CRS is: %1" ).arg( d->mDestCRS.toProj() ), QObject::tr(
"CRS" ) );
640 std::vector< int > zNanPositions;
641 for (
int i = 0; i < numPoints; i++ )
643 if ( std::isnan( z[i] ) )
645 zNanPositions.push_back( i );
650 std::vector< double > xprev( numPoints );
651 memcpy( xprev.data(), x,
sizeof(
double ) * numPoints );
652 std::vector< double > yprev( numPoints );
653 memcpy( yprev.data(), y,
sizeof(
double ) * numPoints );
654 std::vector< double > zprev( numPoints );
655 memcpy( zprev.data(), z,
sizeof(
double ) * numPoints );
657 const bool useTime = !std::isnan( d->mDefaultTime );
658 std::vector< double > t( useTime ? numPoints : 0, d->mDefaultTime );
660 #ifdef COORDINATE_TRANSFORM_VERBOSE
663 QgsDebugMsg( QStringLiteral(
"[[[[[[ Number of points to transform: %1 ]]]]]]" ).arg( numPoints ) );
668 QgsDebugMsgLevel( QStringLiteral(
"No QgsCoordinateTransformContext context set for transform" ), 4 );
675 ProjData projData = d->threadLocalProjData();
679 proj_errno_reset( projData );
680 proj_trans_generic( projData, ( direction ==
ForwardTransform && !d->mIsReversed ) || ( direction ==
ReverseTransform && d->mIsReversed ) ? PJ_FWD : PJ_INV,
681 x,
sizeof(
double ), numPoints,
682 y,
sizeof(
double ), numPoints,
683 z,
sizeof(
double ), numPoints,
684 useTime ? t.data() :
nullptr,
sizeof(
double ), useTime ? numPoints : 0 );
694 if ( numPoints == 1 )
696 projResult = proj_errno( projData );
697 actualRes = projResult;
701 actualRes = proj_errno( projData );
703 if ( actualRes == 0 )
707 if ( std::any_of( x, x + numPoints, [](
double v ) {
return std::isinf( v ); } )
708 || std::any_of( y, y + numPoints, [](
double v ) {
return std::isinf( v ); } )
709 || std::any_of( z, z + numPoints, [](
double v ) {
return std::isinf( v ); } ) )
715 mFallbackOperationOccurred =
false;
717 && ( d->mAvailableOpCount > 1 || d->mAvailableOpCount == -1 )
718 && ( d->mAllowFallbackTransforms || mBallparkTransformsAreAppropriate ) )
721 if (
PJ *
transform = d->threadLocalFallbackProjData() )
726 xprev.data(),
sizeof(
double ), numPoints,
727 yprev.data(),
sizeof(
double ), numPoints,
728 zprev.data(),
sizeof(
double ), numPoints,
729 useTime ? t.data() :
nullptr,
sizeof(
double ), useTime ? numPoints : 0 );
738 if ( numPoints == 1 )
743 projResult = std::isinf( xprev[0] ) || std::isinf( yprev[0] ) || std::isinf( zprev[0] ) ? 1 : 0;
746 if ( projResult == 0 )
748 memcpy( x, xprev.data(),
sizeof(
double ) * numPoints );
749 memcpy( y, yprev.data(),
sizeof(
double ) * numPoints );
750 memcpy( z, zprev.data(),
sizeof(
double ) * numPoints );
751 mFallbackOperationOccurred =
true;
754 if ( !mBallparkTransformsAreAppropriate && !mDisableFallbackHandler && sFallbackOperationOccurredHandler )
756 sFallbackOperationOccurredHandler( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation );
758 const QString warning = QStringLiteral(
"A fallback coordinate operation was used between %1 and %2" ).arg( d->mSourceCRS.authid(),
759 d->mDestCRS.authid() );
760 qWarning(
"%s", warning.toLatin1().constData() );
766 for (
const int &pos : zNanPositions )
768 z[pos] = std::numeric_limits<double>::quiet_NaN();
771 if ( projResult != 0 )
776 for (
int i = 0; i < numPoints; ++i )
780 points += QStringLiteral(
"(%1, %2)\n" ).arg( x[i], 0,
'f' ).arg( y[i], 0,
'f' );
784 points += QStringLiteral(
"(%1, %2)\n" ).arg( x[i], 0,
'f' ).arg( y[i], 0,
'f' );
788 QString dir = ( direction ==
ForwardTransform ) ? QObject::tr(
"forward transform" ) : QObject::tr(
"inverse transform" );
790 QString msg = QObject::tr(
"%1 of\n"
795 projResult < 0 ? QString::fromUtf8( proj_errno_string( projResult ) ) : QObject::tr(
"Fallback transform failed" ) );
799 if ( msg != mLastError )
801 QgsDebugMsg(
"Projection failed emitting invalid transform signal: " + msg );
809 #ifdef COORDINATE_TRANSFORM_VERBOSE
810 QgsDebugMsg( QStringLiteral(
"[[[[[[ Projected %1, %2 to %3, %4 ]]]]]]" )
811 .arg( xorg, 0,
'g', 15 ).arg( yorg, 0,
'g', 15 )
812 .arg( *x, 0,
'g', 15 ).arg( *y, 0,
'g', 15 ) );
823 return !d->mIsValid || d->mShortCircuit;
828 return d->mProjCoordinateOperation;
833 ProjData projData = d->threadLocalProjData();
840 d->mProjCoordinateOperation = operation;
841 d->mShouldReverseCoordinateOperation =
false;
847 d->mAllowFallbackTransforms = allowed;
852 return d->mAllowFallbackTransforms;
857 mBallparkTransformsAreAppropriate = appropriate;
862 mDisableFallbackHandler = disabled;
867 return mFallbackOperationOccurred;
874 proj = QApplication::applicationDirPath()
875 +
"/share/proj/" + QString( name );
879 return proj.toUtf8();
887 const QString sourceKey = src.
authid().isEmpty() ?
889 const QString destKey = dest.
authid().isEmpty() ?
892 if ( sourceKey.isEmpty() || destKey.isEmpty() )
899 const QList< QgsCoordinateTransform > values = sTransforms.values( qMakePair( sourceKey, destKey ) );
900 for (
auto valIt = values.constBegin(); valIt != values.constEnd(); ++valIt )
902 if ( ( *valIt ).coordinateOperation() == coordinateOperationProj
903 && ( *valIt ).allowFallbackTransforms() == allowFallback
911 bool hasContext = mHasContext;
918 mHasContext = hasContext;
927 void QgsCoordinateTransform::addToCache()
929 if ( !d->mSourceCRS.isValid() || !d->mDestCRS.isValid() )
932 const QString sourceKey = d->mSourceCRS.authid().isEmpty() ?
934 const QString destKey = d->mDestCRS.authid().isEmpty() ?
937 if ( sourceKey.isEmpty() || destKey.isEmpty() )
944 sTransforms.insert( qMakePair( sourceKey, destKey ), *
this );
950 return d->mSourceDatumTransform;
958 d->mSourceDatumTransform = dt;
965 return d->mDestinationDatumTransform;
973 d->mDestinationDatumTransform = dt;
985 sDisableCache =
true;
991 void QgsCoordinateTransform::removeFromCacheObjectsBelongingToCurrentThread(
void *pj_context )
1002 if ( sDisableCache )
1005 for (
auto it = sTransforms.begin(); it != sTransforms.end(); )
1007 auto &v = it.value();
1008 if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
1009 it = sTransforms.erase( it );
1019 double distSourceUnits = std::sqrt( source1.
sqrDist( source2 ) );
1022 double distDestUnits = std::sqrt( dest1.
sqrDist( dest2 ) );
1023 return distDestUnits / distSourceUnits;
1028 QgsCoordinateTransformPrivate::setCustomMissingRequiredGridHandler( handler );
1033 QgsCoordinateTransformPrivate::setCustomMissingPreferredGridHandler( handler );
1038 QgsCoordinateTransformPrivate::setCustomCoordinateOperationCreationErrorHandler( handler );
1043 QgsCoordinateTransformPrivate::setCustomMissingGridUsedByContextHandler( handler );
1048 sFallbackOperationOccurredHandler = handler;
1053 QgsCoordinateTransformPrivate::setDynamicCrsToDynamicCrsWarningHandler( handler );
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QString authid() const
Returns the authority identifier for the CRS.
@ WKT_PREFERRED
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
double coordinateEpoch() const
Returns the coordinate epoch, as a decimal year.
QString toWkt(WktVariant variant=WKT1_GDAL, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
Contains information about the context in which a coordinate transform is executed.
Custom exception class for Coordinate Reference System related exceptions.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
A class to represent a 2D point.
double sqrDist(double x, double y) const SIP_HOLDGIL
Returns the squared distance between this point a specified x, y coordinate.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QgsCoordinateTransformContext transformContext
The QgsReadWriteLocker class is a convenience class that simplifies locking and unlocking QReadWriteL...
A rectangle specified with double values.
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
bool isNull() const
Test if the rectangle is null (all coordinates zero or after call to setMinimal()).
void setXMaximum(double x) SIP_HOLDGIL
Set the maximum x value.
void setXMinimum(double x) SIP_HOLDGIL
Set the minimum x value.
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
void setMinimal() SIP_HOLDGIL
Set a rectangle so that min corner is at max and max corner is at min.
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
bool isEmpty() const
Returns true if the rectangle is empty.
double y() const
Returns Y coordinate.
double z() const
Returns Z coordinate.
double x() const
Returns X coordinate.
#define Q_NOWARN_DEPRECATED_POP
#define Q_NOWARN_DEPRECATED_PUSH
bool qgsNanCompatibleEquals(double a, double b)
Compare two doubles, treating nan values as equal.
#define QgsDebugMsgLevel(str, level)
const QgsCoordinateReferenceSystem & crs