33using namespace Qt::StringLiterals;
38#include <QApplication>
54QReadWriteLock QgsCoordinateTransform::sCacheLock;
56bool QgsCoordinateTransform::sDisableCache =
false;
60 const QString &desiredOperation )> QgsCoordinateTransform::sFallbackOperationOccurredHandler =
nullptr;
64 d =
new QgsCoordinateTransformPrivate();
70 d =
new QgsCoordinateTransformPrivate( source, destination, mContext );
73 mIgnoreImpossible =
true;
85 if ( !d->checkValidity() )
89 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
97 mBallparkTransformsAreAppropriate =
true;
103 d =
new QgsCoordinateTransformPrivate( source, destination, mContext );
110 mIgnoreImpossible =
true;
118 if ( !d->checkValidity() )
122 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
130 mBallparkTransformsAreAppropriate =
true;
135 d =
new QgsCoordinateTransformPrivate( source, destination, sourceDatumTransform, destinationDatumTransform );
140 if ( !d->checkValidity() )
144 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
153 : mContext( o.mContext )
155 , mHasContext( o.mHasContext )
161 , mIgnoreImpossible( false )
162 , mBallparkTransformsAreAppropriate( false )
163 , mDisableFallbackHandler( false )
164 , mFallbackOperationOccurred( false )
176 mHasContext = o.mHasContext;
178 mContext = o.mContext;
179 mLastError = QString();
187 return d->mSourceCRS == other.d->mSourceCRS
188 && d->mDestCRS == other.d->mDestCRS
189 && mBallparkTransformsAreAppropriate == other.mBallparkTransformsAreAppropriate
190 && d->mProjCoordinateOperation == other.d->mProjCoordinateOperation
196 return !( *
this == other );
221 if ( !d->checkValidity() )
224 d->calculateTransforms( mContext );
226 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
244 if ( !d->checkValidity() )
247 d->calculateTransforms( mContext );
249 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
271 if ( !d->checkValidity() )
274 d->calculateTransforms( mContext );
276 if ( !setFromCache( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation, d->mAllowFallbackTransforms ) )
291 return d->mSourceCRS;
301 if ( !d->mIsValid || d->mShortCircuit )
305 double x = point.
x();
306 double y = point.
y();
339 if ( !d->mIsValid || d->mShortCircuit )
363#ifdef COORDINATE_TRANSFORM_VERBOSE
375 double x = point.
x();
376 double y = point.
y();
377 double z = point.
z();
394 if ( !d->mIsValid || d->mShortCircuit )
415 double xd =
static_cast< double >( x ), yd =
static_cast< double >( y );
424 if ( !d->mIsValid || d->mShortCircuit )
450 if ( !d->mIsValid || d->mShortCircuit )
456 const int nVertices = poly.size();
458 QVector<double> x( nVertices );
459 QVector<double> y( nVertices );
460 QVector<double> z( nVertices );
461 double *destX = x.data();
462 double *destY = y.data();
463 double *destZ = z.data();
465 const QPointF *polyData = poly.constData();
466 for (
int i = 0; i < nVertices; ++i )
468 *destX++ = polyData->x();
469 *destY++ = polyData->y();
485 QPointF *destPoint = poly.data();
486 const double *srcX = x.constData();
487 const double *srcY = y.constData();
488 for (
int i = 0; i < nVertices; ++i )
490 destPoint->rx() = *srcX++;
491 destPoint->ry() = *srcY++;
496 if ( !err.isEmpty() )
504 if ( !d->mIsValid || d->mShortCircuit )
507 Q_ASSERT( x.size() == y.size() );
530 if ( !d->mIsValid || d->mShortCircuit )
533 Q_ASSERT( x.size() == y.size() );
543 const int vectorSize = x.size();
544 QVector<double> xd( x.size() );
545 QVector<double> yd( y.size() );
546 QVector<double> zd( z.size() );
548 double *destX = xd.data();
549 double *destY = yd.data();
550 double *destZ = zd.data();
552 const float *srcX = x.constData();
553 const float *srcY = y.constData();
554 const float *srcZ = z.constData();
556 for (
int i = 0; i < vectorSize; ++i )
558 *destX++ =
static_cast< double >( *srcX++ );
559 *destY++ =
static_cast< double >( *srcY++ );
560 *destZ++ =
static_cast< double >( *srcZ++ );
566 float *destFX = x.data();
567 float *destFY = y.data();
568 float *destFZ = z.data();
569 const double *srcXD = xd.constData();
570 const double *srcYD = yd.constData();
571 const double *srcZD = zd.constData();
572 for (
int i = 0; i < vectorSize; ++i )
574 *destFX++ =
static_cast< float >( *srcXD++ );
575 *destFY++ =
static_cast< float >( *srcYD++ );
576 *destFZ++ =
static_cast< float >( *srcZD++ );
594 if ( !d->mIsValid || d->mShortCircuit )
606 QgsDebugMsgLevel( u
"No QgsCoordinateTransformContext context set for transform"_s, 4 );
614 throw QgsCsException( QObject::tr(
"Could not transform bounding box for geocentric CRS %1" ).arg( d->mSourceCRS.authid() ) );
618 throw QgsCsException( QObject::tr(
"Could not transform bounding box for geocentric CRS %1" ).arg( d->mDestCRS.authid() ) );
621 const double xMin = rect.
xMinimum();
622 const double xMax = rect.
xMaximum();
625 if ( d->mGeographicToWebMercator &&
633 constexpr double EPS = 1e-1;
634 if ( yMin < -90 + EPS )
636 if ( yMax < -90 + EPS )
637 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
640 if ( yMax > 90 - EPS )
642 if ( yMin > 90 - EPS )
643 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
652#if PROJ_VERSION_MAJOR< 9 || (PROJ_VERSION_MAJOR==9 && PROJ_VERSION_MINOR<7)
653 const auto legacyImplementation = [
this, &rect, xMin, yMin, yMax, direction, handle180Crossover]()
661 const int nPoints = 1000;
662 const double dst = std::sqrt( ( rect.
width() * ( yMax - yMin ) ) / std::pow( std::sqrt(
static_cast< double >( nPoints ) ) - 1, 2.0 ) );
663 const int nXPoints =
static_cast<int>( std::clamp( std::ceil( rect.
width() / dst ) + 1, 3.0, 1000.0 ) );
664 const int nYPoints =
static_cast<int>( std::clamp( std::ceil( ( yMax - yMin ) / dst ) + 1, 3.0, 1000.0 ) );
669 std::vector<double> x( nXPoints *
static_cast< std::size_t
>( nYPoints ) );
670 std::vector<double> y( nXPoints *
static_cast< std::size_t
>( nYPoints ) );
671 std::vector<double> z( nXPoints *
static_cast< std::size_t
>( nYPoints ) );
675 const double dx = rect.
width() /
static_cast< double >( nXPoints - 1 );
676 const double dy = ( yMax - yMin ) /
static_cast< double >( nYPoints - 1 );
678 double pointY = yMin;
680 for (
int i = 0; i < nYPoints ; i++ )
684 double pointX = xMin;
686 for (
int j = 0; j < nXPoints; j++ )
688 x[( i * nXPoints ) + j] = pointX;
689 y[( i * nXPoints ) + j] = pointY;
691 z[( i * nXPoints ) + j] = 0.0;
702 transformCoords( nXPoints * nYPoints, x.data(), y.data(), z.data(), direction );
712 bool doHandle180Crossover =
false;
715 const double xMin = std::fmod( x[0], 180.0 );
716 const double xMax = std::fmod( x[nXPoints - 1], 180.0 );
717 if ( handle180Crossover
720 && xMin > 0.0 && xMin <= 180.0 && xMax < 0.0 && xMax >= -180.0 )
722 doHandle180Crossover =
true;
727 for (
int i = 0; i < nXPoints * nYPoints; i++ )
729 if ( !std::isfinite( x[i] ) || !std::isfinite( y[i] ) )
734 if ( doHandle180Crossover )
748 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
751 if ( doHandle180Crossover )
772#if PROJ_VERSION_MAJOR>8 || (PROJ_VERSION_MAJOR==8 && PROJ_VERSION_MINOR>=2)
774#if PROJ_VERSION_MAJOR< 9 || (PROJ_VERSION_MAJOR==9 && PROJ_VERSION_MINOR<7)
782 return legacyImplementation();
786 ProjData projData = d->threadLocalProjData();
789#if PROJ_VERSION_MAJOR< 9 || (PROJ_VERSION_MAJOR==9 && PROJ_VERSION_MINOR<6)
804 transform2D.reset( proj_create_crs_to_crs_from_pj( projContext, srcCrsHorizontal.get(), destCrsHorizontal.get(),
nullptr,
nullptr ) );
807 const QString err = u
"proj_create_crs_to_crs_from_pj(horizontalCrs(%1), horizontalCrs(%2)) failed"_s.arg( d->mSourceCRS.authid(), d->mSourceCRS.authid() );
808 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS: %1" ).arg( err ) );
810 transform2D.reset( proj_normalize_for_visualization( projContext, transform2D.get() ) );
813 const QString err = u
"Cannot normalize transform between horizontalCrs(%1) and horizontalCrs(%2)"_s.arg( d->mSourceCRS.authid(), d->mDestCRS.authid() );
814 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS: %1" ).arg( err ) );
816 projData = transform2D.get();
820 double transXMin = 0;
821 double transYMin = 0;
822 double transXMax = 0;
823 double transYMax = 0;
825 proj_errno_reset( projData );
828 constexpr int DENSIFY_POINTS = 30;
830 xMin, yMin, xMax, yMax,
831 &transXMin, &transYMin, &transXMax, &transYMax, DENSIFY_POINTS );
833 if ( ( projResult != 1
834 || !std::isfinite( transXMin )
835 || !std::isfinite( transXMax )
836 || !std::isfinite( transYMin )
837 || !std::isfinite( transYMax ) )
838 && ( d->mAvailableOpCount > 1 || d->mAvailableOpCount == -1 )
842 if (
PJ *
transform = d->threadLocalFallbackProjData() )
845 xMin, yMin, xMax, yMax,
846 &transXMin, &transYMin, &transXMax, &transYMax, DENSIFY_POINTS );
851 || !std::isfinite( transXMin )
852 || !std::isfinite( transXMax )
853 || !std::isfinite( transYMin )
854 || !std::isfinite( transYMax ) )
856#if PROJ_VERSION_MAJOR< 9 || (PROJ_VERSION_MAJOR==9 && PROJ_VERSION_MINOR<7)
860 return legacyImplementation();
862 const QString projErr = QString::fromUtf8( proj_context_errno_string( projContext, proj_errno( projData ) ) );
864 const QString msg = QObject::tr(
"%1 (%2 to %3) of bounding box failed: %4" )
875 bool doHandle180Crossover =
false;
877 if ( handle180Crossover
880 && ( transXMax < transXMin ) )
883 std::swap( transXMax, transXMin );
888 doHandle180Crossover =
true;
891 QgsRectangle boundingBoxRect{ transXMin, transYMin, transXMax, transYMax };
892 if ( boundingBoxRect.
isNull() )
895 throw QgsCsException( QObject::tr(
"Could not transform bounding box to target CRS" ) );
898 if ( doHandle180Crossover )
901 if ( boundingBoxRect.
xMinimum() > 180.0 )
903 if ( boundingBoxRect.
xMaximum() > 180.0 )
909 if ( boundingBoxRect.
isEmpty() )
914 return boundingBoxRect;
916#if PROJ_VERSION_MAJOR< 9 || (PROJ_VERSION_MAJOR==9 && PROJ_VERSION_MINOR<7)
917 return legacyImplementation();
923 if ( !d->mIsValid || d->mShortCircuit )
926 if ( !d->mSourceCRS.isValid() )
929 "The coordinates can not be reprojected. The CRS is: %1" )
930 .arg( d->mSourceCRS.toProj() ), QObject::tr(
"CRS" ) );
933 if ( !d->mDestCRS.isValid() )
936 "The coordinates can not be reprojected. The CRS is: %1" ).arg( d->mDestCRS.toProj() ), QObject::tr(
"CRS" ) );
940 std::vector< int > zNanPositions;
941 for (
int i = 0; i < numPoints; i++ )
943 if ( std::isnan( z[i] ) )
945 zNanPositions.push_back( i );
950 std::vector< double > xprev( numPoints );
951 memcpy( xprev.data(), x,
sizeof(
double ) * numPoints );
952 std::vector< double > yprev( numPoints );
953 memcpy( yprev.data(), y,
sizeof(
double ) * numPoints );
954 std::vector< double > zprev( numPoints );
955 memcpy( zprev.data(), z,
sizeof(
double ) * numPoints );
957 const bool useTime = !std::isnan( d->mDefaultTime );
958 std::vector< double > t( useTime ? numPoints : 0, d->mDefaultTime );
960#ifdef COORDINATE_TRANSFORM_VERBOSE
963 QgsDebugMsgLevel( u
"[[[[[[ Number of points to transform: %1 ]]]]]]"_s.arg( numPoints ), 2 );
969 QgsDebugMsgLevel( u
"No QgsCoordinateTransformContext context set for transform"_s, 4 );
974 ProjData projData = d->threadLocalProjData();
978 proj_errno_reset( projData );
980 x,
sizeof(
double ), numPoints,
981 y,
sizeof(
double ), numPoints,
982 z,
sizeof(
double ), numPoints,
983 useTime ? t.data() :
nullptr,
sizeof(
double ), useTime ? numPoints : 0 );
993 if ( numPoints == 1 )
995 projResult = proj_errno( projData );
996 actualRes = projResult;
1000 actualRes = proj_errno( projData );
1002 if ( actualRes == 0 )
1006 if ( std::any_of( x, x + numPoints, [](
double v ) {
return std::isinf( v ); } )
1007 || std::any_of( y, y + numPoints, [](
double v ) {
return std::isinf( v ); } )
1008 || std::any_of( z, z + numPoints, [](
double v ) {
return std::isinf( v ); } ) )
1014 mFallbackOperationOccurred =
false;
1015 bool errorOccurredDuringFallbackOperation =
false;
1017 && ( d->mAvailableOpCount > 1 || d->mAvailableOpCount == -1 )
1018 && ( d->mAllowFallbackTransforms || mBallparkTransformsAreAppropriate ) )
1021 if (
PJ *
transform = d->threadLocalFallbackProjData() )
1025 memcpy( x, xprev.data(),
sizeof(
double ) * numPoints );
1026 memcpy( y, yprev.data(),
sizeof(
double ) * numPoints );
1027 memcpy( z, zprev.data(),
sizeof(
double ) * numPoints );
1029 x,
sizeof(
double ), numPoints,
1030 y,
sizeof(
double ), numPoints,
1031 z,
sizeof(
double ), numPoints,
1032 useTime ? t.data() :
nullptr,
sizeof(
double ), useTime ? numPoints : 0 );
1041 if ( numPoints == 1 )
1047 errorOccurredDuringFallbackOperation = std::isinf( x[0] ) || std::isinf( y[0] ) || std::isinf( z[0] );
1050 if ( !errorOccurredDuringFallbackOperation )
1052 mFallbackOperationOccurred =
true;
1055 if ( !mBallparkTransformsAreAppropriate && !mDisableFallbackHandler && sFallbackOperationOccurredHandler )
1057 sFallbackOperationOccurredHandler( d->mSourceCRS, d->mDestCRS, d->mProjCoordinateOperation );
1059 const QString warning = u
"A fallback coordinate operation was used between %1 and %2"_s.arg( d->mSourceCRS.authid(),
1060 d->mDestCRS.authid() );
1061 qWarning(
"%s", warning.toLatin1().constData() );
1067 for (
const int &pos : zNanPositions )
1069 z[pos] = std::numeric_limits<double>::quiet_NaN();
1072 if ( projResult != 0 || errorOccurredDuringFallbackOperation )
1077 const QChar delim = numPoints > 1 ?
'\n' :
' ';
1078 for (
int i = 0; i < numPoints; ++i )
1080 points += u
"(%1, %2)"_s.arg( xprev[i], 0,
'f' ).arg( yprev[i], 0,
'f' ) + delim;
1086 const QString projError = !errorOccurredDuringFallbackOperation ? QString::fromUtf8( proj_context_errno_string( projContext, projResult ) ) : QObject::tr(
"Fallback transform failed" );
1088 const QString msg = QObject::tr(
"%1 (%2 to %3) of%4%5Error: %6" )
1097 if ( msg != mLastError )
1099 QgsDebugError(
"Projection failed emitting invalid transform signal: " + msg );
1107#ifdef COORDINATE_TRANSFORM_VERBOSE
1109 .arg( xorg, 0,
'g', 15 ).arg( yorg, 0,
'g', 15 )
1110 .arg( *x, 0,
'g', 15 ).arg( *y, 0,
'g', 15 ), 2 );
1121 return !d->mIsValid || d->mShortCircuit;
1126 return d->mIsValid && d->mHasVerticalComponent;
1131 return d->mProjCoordinateOperation;
1136 ProjData projData = d->threadLocalProjData();
1143 d->mProjCoordinateOperation = operation;
1144 d->mShouldReverseCoordinateOperation =
false;
1150 d->mAllowFallbackTransforms = allowed;
1155 return d->mAllowFallbackTransforms;
1160 mBallparkTransformsAreAppropriate = appropriate;
1165 mDisableFallbackHandler = disabled;
1170 return mFallbackOperationOccurred;
1177 proj = QApplication::applicationDirPath()
1178 +
"/share/proj/" + QString( name );
1182 return proj.toUtf8();
1190 const QString sourceKey = src.
authid().isEmpty() ?
1192 const QString destKey = dest.
authid().isEmpty() ?
1195 if ( sourceKey.isEmpty() || destKey.isEmpty() )
1199 if ( sDisableCache )
1202 const QList< QgsCoordinateTransform > values = sTransforms.values( qMakePair( sourceKey, destKey ) );
1203 for (
auto valIt = values.constBegin(); valIt != values.constEnd(); ++valIt )
1205 if ( ( *valIt ).coordinateOperation() == coordinateOperationProj
1206 && ( *valIt ).allowFallbackTransforms() == allowFallback
1212 const QgsCoordinateTransformContext
context = mContext;
1214 const bool hasContext = mHasContext;
1221 mHasContext = hasContext;
1230void QgsCoordinateTransform::addToCache()
1232 if ( !d->mSourceCRS.isValid() || !d->mDestCRS.isValid() )
1235 const QString sourceKey = d->mSourceCRS.authid().isEmpty() ?
1237 const QString destKey = d->mDestCRS.authid().isEmpty() ?
1240 if ( sourceKey.isEmpty() || destKey.isEmpty() )
1244 if ( sDisableCache )
1247 sTransforms.insert( qMakePair( sourceKey, destKey ), *
this );
1253 return d->mSourceDatumTransform;
1261 d->mSourceDatumTransform = dt;
1268 return d->mDestinationDatumTransform;
1276 d->mDestinationDatumTransform = dt;
1283 if ( sDisableCache )
1288 sDisableCache =
true;
1291 sTransforms.clear();
1294void QgsCoordinateTransform::removeFromCacheObjectsBelongingToCurrentThread(
void *pj_context )
1300 if ( sDisableCache )
1305 if ( sDisableCache )
1308 for (
auto it = sTransforms.begin(); it != sTransforms.end(); )
1310 auto &v = it.value();
1311 if ( v.d->removeObjectsBelongingToCurrentThread( pj_context ) )
1312 it = sTransforms.erase( it );
1322 const double distSourceUnits = std::sqrt( source1.
sqrDist( source2 ) );
1325 const double distDestUnits = std::sqrt( dest1.
sqrDist( dest2 ) );
1326 return distDestUnits / distSourceUnits;
1331 QgsCoordinateTransformPrivate::setCustomMissingRequiredGridHandler( handler );
1336 QgsCoordinateTransformPrivate::setCustomMissingPreferredGridHandler( handler );
1341 QgsCoordinateTransformPrivate::setCustomCoordinateOperationCreationErrorHandler( handler );
1346 QgsCoordinateTransformPrivate::setCustomMissingGridUsedByContextHandler( handler );
1351 sFallbackOperationOccurredHandler = handler;
1356 QgsCoordinateTransformPrivate::setDynamicCrsToDynamicCrsWarningHandler( handler );
@ Geocentric
Geocentric CRS.
QFlags< CoordinateTransformationFlag > CoordinateTransformationFlags
Coordinate transformation flags.
@ Preferred
Preferred format, matching the most recent WKT ISO standard. Currently an alias to WKT2_2019,...
@ BallparkTransformsAreAppropriate
Indicates that approximate "ballpark" results are appropriate for this coordinate transform....
@ IgnoreImpossibleTransformations
Indicates that impossible transformations (such as those which attempt to transform between two diffe...
TransformDirection
Indicates the direction (forward or inverse) of a transform.
@ Forward
Forward transform (from source to destination).
@ Reverse
Reverse/inverse transform (from destination to source).
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
QString toWkt(Qgis::CrsWktVariant variant=Qgis::CrsWktVariant::Wkt1Gdal, bool multiline=false, int indentationWidth=4) const
Returns a WKT representation of this CRS.
QString celestialBodyName() const
Attempts to retrieve the name of the celestial body associated with the CRS (e.g.
double coordinateEpoch() const
Returns the coordinate epoch, as a decimal year.
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, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
double sqrDist(double x, double y) const
Returns the squared distance between this point a specified x, y coordinate.
static PJ_CONTEXT * get()
Returns a thread local instance of a proj context, safe for use in the current thread.
static proj_pj_unique_ptr crsToHorizontalCrs(const PJ *crs)
Given a PROJ crs (which may be a compound or bound crs, or some other type), extract the horizontal c...
static bool hasVerticalAxis(const PJ *crs)
Returns true if a PROJ crs has a vertical axis.
std::unique_ptr< PJ, ProjPJDeleter > proj_pj_unique_ptr
Scoped Proj PJ object.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
QgsCoordinateTransformContext transformContext
A convenience class that simplifies locking and unlocking QReadWriteLocks.
A rectangle specified with double values.
Q_INVOKABLE QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
void setXMinimum(double x)
Set the minimum x value.
void setXMaximum(double x)
Set the maximum x value.
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
void setNull()
Mark a rectangle as being null (holding no spatial information).
Scoped object for temporary suppression of PROJ logging output.
A 3D vector (similar to QVector3D) with the difference that it uses double precision instead of singl...
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)
#define QgsDebugError(str)