repo_name
stringclasses
10 values
file_path
stringlengths
29
222
content
stringlengths
24
926k
extention
stringclasses
5 values
PROJ
data/projects/PROJ/src/projections/imw_p.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(imw_p, "International Map of the World Polyconic") "\n\tMod. Polyconic, Ell\n\tlat_1= and lat_2= [lon_1=]"; #define TOL 1e-10 #define EPS 1e-10 namespace { // anonymous namespace enum Mode { NONE_IS_ZERO = 0, /* phi_1 and phi_2 != 0 */ PHI_1_IS_ZERO = 1, /* phi_1 = 0 */ PHI_2_IS_ZERO = -1 /* phi_2 = 0 */ }; } // anonymous namespace namespace { // anonymous namespace struct pj_imw_p_data { double P, Pp, Q, Qp, R_1, R_2, sphi_1, sphi_2, C2; double phi_1, phi_2, lam_1; double *en; enum Mode mode; }; } // anonymous namespace static int phi12(PJ *P, double *del, double *sig) { struct pj_imw_p_data *Q = static_cast<struct pj_imw_p_data *>(P->opaque); int err = 0; if (!pj_param(P->ctx, P->params, "tlat_1").i) { proj_log_error(P, _("Missing parameter: lat_1 should be specified")); err = PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE; } else if (!pj_param(P->ctx, P->params, "tlat_2").i) { proj_log_error(P, _("Missing parameter: lat_2 should be specified")); err = PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE; } else { Q->phi_1 = pj_param(P->ctx, P->params, "rlat_1").f; Q->phi_2 = pj_param(P->ctx, P->params, "rlat_2").f; *del = 0.5 * (Q->phi_2 - Q->phi_1); *sig = 0.5 * (Q->phi_2 + Q->phi_1); err = (fabs(*del) < EPS || fabs(*sig) < EPS) ? PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE : 0; if (err) { proj_log_error( P, _("Illegal value for lat_1 and lat_2: |lat_1 - lat_2| " "and |lat_1 + lat_2| should be > 0")); } } return err; } static PJ_XY loc_for(PJ_LP lp, PJ *P, double *yc) { struct pj_imw_p_data *Q = static_cast<struct pj_imw_p_data *>(P->opaque); PJ_XY xy; if (lp.phi == 0.0) { xy.x = lp.lam; xy.y = 0.; } else { double xa, ya, xb, yb, xc, D, B, m, sp, t, R, C; sp = sin(lp.phi); m = pj_mlfn(lp.phi, sp, cos(lp.phi), Q->en); xa = Q->Pp + Q->Qp * m; ya = Q->P + Q->Q * m; R = 1. / (tan(lp.phi) * sqrt(1. - P->es * sp * sp)); C = sqrt(R * R - xa * xa); if (lp.phi < 0.) C = -C; C += ya - R; if (Q->mode == PHI_2_IS_ZERO) { xb = lp.lam; yb = Q->C2; } else { t = lp.lam * Q->sphi_2; xb = Q->R_2 * sin(t); yb = Q->C2 + Q->R_2 * (1. - cos(t)); } if (Q->mode == PHI_1_IS_ZERO) { xc = lp.lam; *yc = 0.; } else { t = lp.lam * Q->sphi_1; xc = Q->R_1 * sin(t); *yc = Q->R_1 * (1. - cos(t)); } D = (xb - xc) / (yb - *yc); B = xc + D * (C + R - *yc); xy.x = D * sqrt(R * R * (1 + D * D) - B * B); if (lp.phi > 0) xy.x = -xy.x; xy.x = (B + xy.x) / (1. + D * D); xy.y = sqrt(R * R - xy.x * xy.x); if (lp.phi > 0) xy.y = -xy.y; xy.y += C + R; } return xy; } static PJ_XY imw_p_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ double yc; PJ_XY xy = loc_for(lp, P, &yc); return (xy); } static PJ_LP imw_p_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_imw_p_data *Q = static_cast<struct pj_imw_p_data *>(P->opaque); PJ_XY t; double yc = 0.0; int i = 0; const int N_MAX_ITER = 1000; /* Arbitrarily chosen number... */ lp.phi = Q->phi_2; lp.lam = xy.x / cos(lp.phi); do { t = loc_for(lp, P, &yc); const double denom = t.y - yc; if (denom != 0 || fabs(t.y - xy.y) > TOL) { if (denom == 0) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().lp; } lp.phi = ((lp.phi - Q->phi_1) * (xy.y - yc) / denom) + Q->phi_1; } if (t.x != 0 && fabs(t.x - xy.x) > TOL) lp.lam = lp.lam * xy.x / t.x; i++; } while (i < N_MAX_ITER && (fabs(t.x - xy.x) > TOL || fabs(t.y - xy.y) > TOL)); if (i == N_MAX_ITER) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().lp; } return lp; } static void xy(PJ *P, double phi, double *x, double *y, double *sp, double *R) { double F; *sp = sin(phi); *R = 1. / (tan(phi) * sqrt(1. - P->es * *sp * *sp)); F = static_cast<struct pj_imw_p_data *>(P->opaque)->lam_1 * *sp; *y = *R * (1 - cos(F)); *x = *R * sin(F); } static PJ *pj_imw_p_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); if (static_cast<struct pj_imw_p_data *>(P->opaque)->en) free(static_cast<struct pj_imw_p_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(imw_p) { double del, sig, s, t, x1, x2, T2, y1, m1, m2, y2; int err; struct pj_imw_p_data *Q = static_cast<struct pj_imw_p_data *>( calloc(1, sizeof(struct pj_imw_p_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (!(Q->en = pj_enfn(P->n))) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); if ((err = phi12(P, &del, &sig)) != 0) { return pj_imw_p_destructor(P, err); } if (Q->phi_2 < Q->phi_1) { /* make sure P->phi_1 most southerly */ del = Q->phi_1; Q->phi_1 = Q->phi_2; Q->phi_2 = del; } if (pj_param(P->ctx, P->params, "tlon_1").i) Q->lam_1 = pj_param(P->ctx, P->params, "rlon_1").f; else { /* use predefined based upon latitude */ sig = fabs(sig * RAD_TO_DEG); if (sig <= 60) sig = 2.; else if (sig <= 76) sig = 4.; else sig = 8.; Q->lam_1 = sig * DEG_TO_RAD; } Q->mode = NONE_IS_ZERO; if (Q->phi_1 != 0.0) xy(P, Q->phi_1, &x1, &y1, &Q->sphi_1, &Q->R_1); else { Q->mode = PHI_1_IS_ZERO; y1 = 0.; x1 = Q->lam_1; } if (Q->phi_2 != 0.0) xy(P, Q->phi_2, &x2, &T2, &Q->sphi_2, &Q->R_2); else { Q->mode = PHI_2_IS_ZERO; T2 = 0.; x2 = Q->lam_1; } m1 = pj_mlfn(Q->phi_1, Q->sphi_1, cos(Q->phi_1), Q->en); m2 = pj_mlfn(Q->phi_2, Q->sphi_2, cos(Q->phi_2), Q->en); t = m2 - m1; s = x2 - x1; y2 = sqrt(t * t - s * s) + y1; Q->C2 = y2 - T2; t = 1. / t; Q->P = (m2 * y1 - m1 * y2) * t; Q->Q = (y2 - y1) * t; Q->Pp = (m2 * x1 - m1 * x2) * t; Q->Qp = (x2 - x1) * t; P->fwd = imw_p_e_forward; P->inv = imw_p_e_inverse; P->destructor = pj_imw_p_destructor; return P; } #undef TOL #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/putp3.cpp
#include <errno.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_putp3_data { double A; }; } // anonymous namespace PROJ_HEAD(putp3, "Putnins P3") "\n\tPCyl, Sph"; PROJ_HEAD(putp3p, "Putnins P3'") "\n\tPCyl, Sph"; #define C 0.79788456 #define RPISQ 0.1013211836 static PJ_XY putp3_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = C * lp.lam * (1. - static_cast<struct pj_putp3_data *>(P->opaque)->A * lp.phi * lp.phi); xy.y = C * lp.phi; return xy; } static PJ_LP putp3_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = xy.y / C; lp.lam = xy.x / (C * (1. - static_cast<struct pj_putp3_data *>(P->opaque)->A * lp.phi * lp.phi)); return lp; } PJ *PJ_PROJECTION(putp3) { struct pj_putp3_data *Q = static_cast<struct pj_putp3_data *>( calloc(1, sizeof(struct pj_putp3_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->A = 4. * RPISQ; P->es = 0.; P->inv = putp3_s_inverse; P->fwd = putp3_s_forward; return P; } PJ *PJ_PROJECTION(putp3p) { struct pj_putp3_data *Q = static_cast<struct pj_putp3_data *>( calloc(1, sizeof(struct pj_putp3_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->A = 2. * RPISQ; P->es = 0.; P->inv = putp3_s_inverse; P->fwd = putp3_s_forward; return P; } #undef C #undef RPISQ
cpp
PROJ
data/projects/PROJ/src/projections/imoll_o.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(imoll_o, "Interrupted Mollweide Oceanic View") "\n\tPCyl, Sph"; /* This projection is a variant of the Interrupted Mollweide projection that emphasizes ocean areas. This projection is a compilation of 6 separate sub-projections. It is related to the Interrupted Goode Homolosine projection, but uses Mollweide at all latitudes. Each sub-projection is assigned an integer label numbered 1 through 6. Most of this code contains logic to assign the labels based on latitude (phi) and longitude (lam) regions. The code is adapted from igh.cpp. Original Reference: J. Paul Goode (1919) STUDIES IN PROJECTIONS: ADAPTING THE HOMOLOGRAPHIC PROJECTION TO THE PORTRAYAL OF THE EARTH'S ENTIRE SURFACE, Bul. Geog. SOC.Phila., Vol. XWIJNO.3. July, 1919, pp. 103-113. */ C_NAMESPACE PJ *pj_moll(PJ *); namespace pj_imoll_o_ns { struct pj_imoll_o_data { struct PJconsts *pj[6]; }; /* SIMPLIFY THIS */ constexpr double d10 = 10 * DEG_TO_RAD; constexpr double d20 = 20 * DEG_TO_RAD; constexpr double d60 = 60 * DEG_TO_RAD; constexpr double d90 = 90 * DEG_TO_RAD; constexpr double d110 = 110 * DEG_TO_RAD; constexpr double d130 = 130 * DEG_TO_RAD; constexpr double d140 = 140 * DEG_TO_RAD; constexpr double d150 = 150 * DEG_TO_RAD; constexpr double d180 = 180 * DEG_TO_RAD; constexpr double EPSLN = 1.e-10; /* allow a little 'slack' on zone edge positions */ } // namespace pj_imoll_o_ns /* Assign an integer index representing each of the 6 sub-projection zones based on latitude (phi) and longitude (lam) ranges. */ static PJ_XY imoll_o_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ using namespace pj_imoll_o_ns; PJ_XY xy; struct pj_imoll_o_data *Q = static_cast<struct pj_imoll_o_data *>(P->opaque); int z; if (lp.phi >= 0) { /* 1|2|3 */ if (lp.lam <= -d90) z = 1; else if (lp.lam >= d60) z = 3; else z = 2; } else { if (lp.lam <= -d60) z = 4; else if (lp.lam >= d90) z = 6; else z = 5; } lp.lam -= Q->pj[z - 1]->lam0; xy = Q->pj[z - 1]->fwd(lp, Q->pj[z - 1]); xy.x += Q->pj[z - 1]->x0; xy.y += Q->pj[z - 1]->y0; return xy; } static PJ_LP imoll_o_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ using namespace pj_imoll_o_ns; PJ_LP lp = {0.0, 0.0}; struct pj_imoll_o_data *Q = static_cast<struct pj_imoll_o_data *>(P->opaque); const double y90 = sqrt(2.0); /* lt=90 corresponds to y=sqrt(2) */ int z = 0; if (xy.y > y90 + EPSLN || xy.y < -y90 + EPSLN) /* 0 */ z = 0; else if (xy.y >= 0) { if (xy.x <= -d90) z = 1; else if (xy.x >= d60) z = 3; else z = 2; } else { if (xy.x <= -d60) z = 4; else if (xy.x >= d90) z = 6; else z = 5; } if (z) { bool ok = false; xy.x -= Q->pj[z - 1]->x0; xy.y -= Q->pj[z - 1]->y0; lp = Q->pj[z - 1]->inv(xy, Q->pj[z - 1]); lp.lam += Q->pj[z - 1]->lam0; switch (z) { case 1: ok = ((lp.lam >= -d180 - EPSLN && lp.lam <= -d90 + EPSLN) && (lp.phi >= 0.0 - EPSLN)); break; case 2: ok = ((lp.lam >= -d90 - EPSLN && lp.lam <= d60 + EPSLN) && (lp.phi >= 0.0 - EPSLN)); break; case 3: ok = ((lp.lam >= d60 - EPSLN && lp.lam <= d180 + EPSLN) && (lp.phi >= 0.0 - EPSLN)); break; case 4: ok = ((lp.lam >= -d180 - EPSLN && lp.lam <= -d60 + EPSLN) && (lp.phi <= 0.0 + EPSLN)); break; case 5: ok = ((lp.lam >= -d60 - EPSLN && lp.lam <= d90 + EPSLN) && (lp.phi <= 0.0 + EPSLN)); break; case 6: ok = ((lp.lam >= d90 - EPSLN && lp.lam <= d180 + EPSLN) && (lp.phi <= 0.0 + EPSLN)); break; } z = (!ok ? 0 : z); /* projectable? */ } if (!z) lp.lam = HUGE_VAL; if (!z) lp.phi = HUGE_VAL; return lp; } static PJ *pj_imoll_o_destructor(PJ *P, int errlev) { using namespace pj_imoll_o_ns; int i; if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); struct pj_imoll_o_data *Q = static_cast<struct pj_imoll_o_data *>(P->opaque); for (i = 0; i < 6; ++i) { if (Q->pj[i]) Q->pj[i]->destructor(Q->pj[i], errlev); } return pj_default_destructor(P, errlev); } /* Zones: -180 -90 60 180 +---------+----------------+-------------+ |1 |2 |3 | | | | | | | | | | | | | | | | | 0 +---------+--+-------------+--+----------+ |4 |5 |6 | | | | | | | | | | | | | | | | | +------------+----------------+----------+ -180 -60 90 180 */ static bool pj_imoll_o_setup_zone(PJ *P, struct pj_imoll_o_ns::pj_imoll_o_data *Q, int n, PJ *(*proj_ptr)(PJ *), double x_0, double y_0, double lon_0) { if (!(Q->pj[n - 1] = proj_ptr(nullptr))) return false; if (!(Q->pj[n - 1] = proj_ptr(Q->pj[n - 1]))) return false; Q->pj[n - 1]->ctx = P->ctx; Q->pj[n - 1]->x0 = x_0; Q->pj[n - 1]->y0 = y_0; Q->pj[n - 1]->lam0 = lon_0; return true; } static double pj_imoll_o_compute_zone_offset(struct pj_imoll_o_ns::pj_imoll_o_data *Q, int zone1, int zone2, double lam, double phi1, double phi2) { PJ_LP lp1, lp2; PJ_XY xy1, xy2; lp1.lam = lam - (Q->pj[zone1 - 1]->lam0); lp1.phi = phi1; lp2.lam = lam - (Q->pj[zone2 - 1]->lam0); lp2.phi = phi2; xy1 = Q->pj[zone1 - 1]->fwd(lp1, Q->pj[zone1 - 1]); xy2 = Q->pj[zone2 - 1]->fwd(lp2, Q->pj[zone2 - 1]); return (xy2.x + Q->pj[zone2 - 1]->x0) - (xy1.x + Q->pj[zone1 - 1]->x0); } PJ *PJ_PROJECTION(imoll_o) { using namespace pj_imoll_o_ns; struct pj_imoll_o_data *Q = static_cast<struct pj_imoll_o_data *>( calloc(1, sizeof(struct pj_imoll_o_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* Setup zones */ if (!pj_imoll_o_setup_zone(P, Q, 1, pj_moll, -d140, 0, -d140) || !pj_imoll_o_setup_zone(P, Q, 2, pj_moll, -d10, 0, -d10) || !pj_imoll_o_setup_zone(P, Q, 3, pj_moll, d130, 0, d130) || !pj_imoll_o_setup_zone(P, Q, 4, pj_moll, -d110, 0, -d110) || !pj_imoll_o_setup_zone(P, Q, 5, pj_moll, d20, 0, d20) || !pj_imoll_o_setup_zone(P, Q, 6, pj_moll, d150, 0, d150)) { return pj_imoll_o_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } /* Adjust zones */ /* Match 2 (center) to 1 (west) */ Q->pj[1]->x0 += pj_imoll_o_compute_zone_offset(Q, 2, 1, -d90, 0.0 + EPSLN, 0.0 + EPSLN); /* Match 3 (east) to 2 (center) */ Q->pj[2]->x0 += pj_imoll_o_compute_zone_offset(Q, 3, 2, d60, 0.0 + EPSLN, 0.0 + EPSLN); /* Match 4 (south) to 1 (north) */ Q->pj[3]->x0 += pj_imoll_o_compute_zone_offset(Q, 4, 1, -d180, 0.0 - EPSLN, 0.0 + EPSLN); /* Match 5 (south) to 2 (north) */ Q->pj[4]->x0 += pj_imoll_o_compute_zone_offset(Q, 5, 2, -d60, 0.0 - EPSLN, 0.0 + EPSLN); /* Match 6 (south) to 3 (north) */ Q->pj[5]->x0 += pj_imoll_o_compute_zone_offset(Q, 6, 3, d90, 0.0 - EPSLN, 0.0 + EPSLN); P->inv = imoll_o_s_inverse; P->fwd = imoll_o_s_forward; P->destructor = pj_imoll_o_destructor; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/mbtfpp.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(mbtfpp, "McBride-Thomas Flat-Polar Parabolic") "\n\tCyl, Sph"; #define CSy .95257934441568037152 #define FXC .92582009977255146156 #define FYC 3.40168025708304504493 #define C23 .66666666666666666666 #define C13 .33333333333333333333 #define ONEEPS 1.0000001 static PJ_XY mbtfpp_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; lp.phi = asin(CSy * sin(lp.phi)); xy.x = FXC * lp.lam * (2. * cos(C23 * lp.phi) - 1.); xy.y = FYC * sin(C13 * lp.phi); return xy; } static PJ_LP mbtfpp_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = xy.y / FYC; if (fabs(lp.phi) >= 1.) { if (fabs(lp.phi) > ONEEPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { lp.phi = (lp.phi < 0.) ? -M_HALFPI : M_HALFPI; } } else lp.phi = asin(lp.phi); lp.phi *= 3.; lp.lam = xy.x / (FXC * (2. * cos(C23 * lp.phi) - 1.)); lp.phi = sin(lp.phi) / CSy; if (fabs(lp.phi) >= 1.) { if (fabs(lp.phi) > ONEEPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { lp.phi = (lp.phi < 0.) ? -M_HALFPI : M_HALFPI; } } else lp.phi = asin(lp.phi); return lp; } PJ *PJ_PROJECTION(mbtfpp) { P->es = 0.; P->inv = mbtfpp_s_inverse; P->fwd = mbtfpp_s_forward; return P; } #undef CSy #undef FXC #undef FYC #undef C23 #undef C13 #undef ONEEPS
cpp
PROJ
data/projects/PROJ/src/projections/bipc.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" #include <math.h> PROJ_HEAD(bipc, "Bipolar conic of western hemisphere") "\n\tConic Sph"; #define EPS 1e-10 #define EPS10 1e-10 #define ONEEPS 1.000000001 #define NITER 10 #define lamB -.34894976726250681539 #define n .63055844881274687180 #define F 1.89724742567461030582 #define Azab .81650043674686363166 #define Azba 1.82261843856185925133 #define T 1.27246578267089012270 #define rhoc 1.20709121521568721927 #define cAzc .69691523038678375519 #define sAzc .71715351331143607555 #define C45 .70710678118654752469 #define S45 .70710678118654752410 #define C20 .93969262078590838411 #define S20 -.34202014332566873287 #define R110 1.91986217719376253360 #define R104 1.81514242207410275904 namespace { // anonymous namespace struct pj_bipc_data { int noskew; }; } // anonymous namespace static PJ_XY bipc_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_bipc_data *Q = static_cast<struct pj_bipc_data *>(P->opaque); double cphi, sphi, tphi, t, al, Az, z, Av, cdlam, sdlam, r; int tag; cphi = cos(lp.phi); sphi = sin(lp.phi); cdlam = cos(sdlam = lamB - lp.lam); sdlam = sin(sdlam); if (fabs(fabs(lp.phi) - M_HALFPI) < EPS10) { Az = lp.phi < 0. ? M_PI : 0.; tphi = HUGE_VAL; } else { tphi = sphi / cphi; Az = atan2(sdlam, C45 * (tphi - cdlam)); } if ((tag = (Az > Azba))) { sdlam = lp.lam + R110; cdlam = cos(sdlam); sdlam = sin(sdlam); z = S20 * sphi + C20 * cphi * cdlam; if (fabs(z) > 1.) { if (fabs(z) > ONEEPS) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } else z = z < 0. ? -1. : 1.; } else z = acos(z); if (tphi != HUGE_VAL) Az = atan2(sdlam, (C20 * tphi - S20 * cdlam)); Av = Azab; xy.y = rhoc; } else { z = S45 * (sphi + cphi * cdlam); if (fabs(z) > 1.) { if (fabs(z) > ONEEPS) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } else z = z < 0. ? -1. : 1.; } else z = acos(z); Av = Azba; xy.y = -rhoc; } if (z < 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } t = pow(tan(.5 * z), n); r = F * t; if ((al = .5 * (R104 - z)) < 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } al = (t + pow(al, n)) / T; if (fabs(al) > 1.) { if (fabs(al) > ONEEPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } else al = al < 0. ? -1. : 1.; } else al = acos(al); t = n * (Av - Az); if (fabs(t) < al) r /= cos(al + (tag ? t : -t)); xy.x = r * sin(t); xy.y += (tag ? -r : r) * cos(t); if (Q->noskew) { t = xy.x; xy.x = -xy.x * cAzc - xy.y * sAzc; xy.y = -xy.y * cAzc + t * sAzc; } return (xy); } static PJ_LP bipc_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_bipc_data *Q = static_cast<struct pj_bipc_data *>(P->opaque); double t, r, rp, rl, al, z = 0.0, fAz, Az, s, c, Av; int neg, i; if (Q->noskew) { t = xy.x; xy.x = -xy.x * cAzc + xy.y * sAzc; xy.y = -xy.y * cAzc - t * sAzc; } if ((neg = (xy.x < 0.))) { xy.y = rhoc - xy.y; s = S20; c = C20; Av = Azab; } else { xy.y += rhoc; s = S45; c = C45; Av = Azba; } r = hypot(xy.x, xy.y); rl = rp = r; Az = atan2(xy.x, xy.y); fAz = fabs(Az); for (i = NITER; i; --i) { z = 2. * atan(pow(r / F, 1 / n)); al = acos((pow(tan(.5 * z), n) + pow(tan(.5 * (R104 - z)), n)) / T); if (fAz < al) r = rp * cos(al + (neg ? Az : -Az)); if (fabs(rl - r) < EPS) break; rl = r; } if (!i) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } Az = Av - Az / n; lp.phi = asin(s * cos(z) + c * sin(z) * cos(Az)); lp.lam = atan2(sin(Az), c / tan(z) - s * cos(Az)); if (neg) lp.lam -= R110; else lp.lam = lamB - lp.lam; return (lp); } PJ *PJ_PROJECTION(bipc) { struct pj_bipc_data *Q = static_cast<struct pj_bipc_data *>( calloc(1, sizeof(struct pj_bipc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->noskew = pj_param(P->ctx, P->params, "bns").i; P->inv = bipc_s_inverse; P->fwd = bipc_s_forward; P->es = 0.; return P; } #undef EPS #undef EPS10 #undef ONEEPS #undef NITER #undef lamB #undef n #undef F #undef Azab #undef Azba #undef T #undef rhoc #undef cAzc #undef sAzc #undef C45 #undef S45 #undef C20 #undef S20 #undef R110 #undef R104
cpp
PROJ
data/projects/PROJ/src/projections/loxim.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(loxim, "Loximuthal") "\n\tPCyl Sph"; #define EPS 1e-8 namespace { // anonymous namespace struct pj_loxim_data { double phi1; double cosphi1; double tanphi1; }; } // anonymous namespace static PJ_XY loxim_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_loxim_data *Q = static_cast<struct pj_loxim_data *>(P->opaque); xy.y = lp.phi - Q->phi1; if (fabs(xy.y) < EPS) xy.x = lp.lam * Q->cosphi1; else { xy.x = M_FORTPI + 0.5 * lp.phi; if (fabs(xy.x) < EPS || fabs(fabs(xy.x) - M_HALFPI) < EPS) xy.x = 0.; else xy.x = lp.lam * xy.y / log(tan(xy.x) / Q->tanphi1); } return xy; } static PJ_LP loxim_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_loxim_data *Q = static_cast<struct pj_loxim_data *>(P->opaque); lp.phi = xy.y + Q->phi1; if (fabs(xy.y) < EPS) { lp.lam = xy.x / Q->cosphi1; } else { lp.lam = M_FORTPI + 0.5 * lp.phi; if (fabs(lp.lam) < EPS || fabs(fabs(lp.lam) - M_HALFPI) < EPS) lp.lam = 0.; else lp.lam = xy.x * log(tan(lp.lam) / Q->tanphi1) / xy.y; } return lp; } PJ *PJ_PROJECTION(loxim) { struct pj_loxim_data *Q = static_cast<struct pj_loxim_data *>( calloc(1, sizeof(struct pj_loxim_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->phi1 = pj_param(P->ctx, P->params, "rlat_1").f; Q->cosphi1 = cos(Q->phi1); if (Q->cosphi1 < EPS) { proj_log_error(P, _("Invalid value for lat_1: |lat_1| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->tanphi1 = tan(M_FORTPI + 0.5 * Q->phi1); P->inv = loxim_s_inverse; P->fwd = loxim_s_forward; P->es = 0.; return P; } #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/nell_h.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(nell_h, "Nell-Hammer") "\n\tPCyl, Sph"; #define NITER 9 #define EPS 1e-7 static PJ_XY nell_h_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = 0.5 * lp.lam * (1. + cos(lp.phi)); xy.y = 2.0 * (lp.phi - tan(0.5 * lp.phi)); return xy; } static PJ_LP nell_h_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; int i; (void)P; const double p = 0.5 * xy.y; for (i = NITER; i; --i) { const double c = cos(0.5 * lp.phi); const double V = (lp.phi - tan(lp.phi / 2) - p) / (1. - 0.5 / (c * c)); lp.phi -= V; if (fabs(V) < EPS) break; } if (!i) { lp.phi = p < 0. ? -M_HALFPI : M_HALFPI; lp.lam = 2. * xy.x; } else lp.lam = 2. * xy.x / (1. + cos(lp.phi)); return lp; } PJ *PJ_PROJECTION(nell_h) { P->es = 0.; P->inv = nell_h_s_inverse; P->fwd = nell_h_s_forward; return P; } #undef NITER #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/eqearth.cpp
/* Equal Earth is a projection inspired by the Robinson projection, but unlike the Robinson projection retains the relative size of areas. The projection was designed in 2018 by Bojan Savric, Tom Patterson and Bernhard Jenny. Publication: Bojan Savric, Tom Patterson & Bernhard Jenny (2018). The Equal Earth map projection, International Journal of Geographical Information Science, DOI: 10.1080/13658816.2018.1504949 Port to PROJ by Juernjakob Dugge, 16 August 2018 Added ellipsoidal equations by Bojan Savric, 22 August 2018 */ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(eqearth, "Equal Earth") "\n\tPCyl, Sph&Ell"; /* A1..A4, polynomial coefficients */ #define A1 1.340264 #define A2 -0.081106 #define A3 0.000893 #define A4 0.003796 #define M (sqrt(3.0) / 2.0) #define MAX_Y 1.3173627591574 /* 90° latitude on a sphere with radius 1 */ #define EPS 1e-11 #define MAX_ITER 12 namespace { // anonymous namespace struct pj_eqearth { double qp; double rqda; double *apa; }; } // anonymous namespace static PJ_XY eqearth_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal/spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_eqearth *Q = static_cast<struct pj_eqearth *>(P->opaque); double sbeta; double psi, psi2, psi6; /* Spheroidal case, using sine latitude */ sbeta = sin(lp.phi); /* In the ellipsoidal case, we convert sbeta to sine of authalic latitude */ if (P->es != 0.0) { sbeta = pj_qsfn(sbeta, P->e, 1.0 - P->es) / Q->qp; /* Rounding error. */ if (fabs(sbeta) > 1) sbeta = sbeta > 0 ? 1 : -1; } /* Equal Earth projection */ psi = asin(M * sbeta); psi2 = psi * psi; psi6 = psi2 * psi2 * psi2; xy.x = lp.lam * cos(psi) / (M * (A1 + 3 * A2 * psi2 + psi6 * (7 * A3 + 9 * A4 * psi2))); xy.y = psi * (A1 + A2 * psi2 + psi6 * (A3 + A4 * psi2)); /* Adjusting x and y for authalic radius */ xy.x *= Q->rqda; xy.y *= Q->rqda; return xy; } static PJ_LP eqearth_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal/spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_eqearth *Q = static_cast<struct pj_eqearth *>(P->opaque); double yc, y2, y6; int i; /* Adjusting x and y for authalic radius */ xy.x /= Q->rqda; xy.y /= Q->rqda; /* Make sure y is inside valid range */ if (xy.y > MAX_Y) xy.y = MAX_Y; else if (xy.y < -MAX_Y) xy.y = -MAX_Y; yc = xy.y; /* Newton-Raphson */ for (i = MAX_ITER; i; --i) { double f, fder, tol; y2 = yc * yc; y6 = y2 * y2 * y2; f = yc * (A1 + A2 * y2 + y6 * (A3 + A4 * y2)) - xy.y; fder = A1 + 3 * A2 * y2 + y6 * (7 * A3 + 9 * A4 * y2); tol = f / fder; yc -= tol; if (fabs(tol) < EPS) break; } if (i == 0) { proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } /* Longitude */ y2 = yc * yc; y6 = y2 * y2 * y2; lp.lam = M * xy.x * (A1 + 3 * A2 * y2 + y6 * (7 * A3 + 9 * A4 * y2)) / cos(yc); /* Latitude (for spheroidal case, this is latitude */ lp.phi = asin(sin(yc) / M); /* Ellipsoidal case, converting auth. latitude */ if (P->es != 0.0) lp.phi = pj_authlat(lp.phi, Q->apa); return lp; } static PJ *destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_eqearth *>(P->opaque)->apa); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(eqearth) { struct pj_eqearth *Q = static_cast<struct pj_eqearth *>(calloc(1, sizeof(struct pj_eqearth))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = destructor; P->fwd = eqearth_e_forward; P->inv = eqearth_e_inverse; Q->rqda = 1.0; /* Ellipsoidal case */ if (P->es != 0.0) { Q->apa = pj_authset(P->es); /* For auth_lat(). */ if (nullptr == Q->apa) return destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->qp = pj_qsfn(1.0, P->e, P->one_es); /* For auth_lat(). */ Q->rqda = sqrt(0.5 * Q->qp); /* Authalic radius divided by major axis */ } return P; } #undef A1 #undef A2 #undef A3 #undef A4 #undef M #undef MAX_Y #undef EPS #undef MAX_ITER
cpp
PROJ
data/projects/PROJ/src/projections/ortho.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(ortho, "Orthographic") "\n\tAzi, Sph&Ell"; namespace pj_ortho_ns { enum Mode { N_POLE = 0, S_POLE = 1, EQUIT = 2, OBLIQ = 3 }; } namespace { // anonymous namespace struct pj_ortho_data { double sinph0; double cosph0; double nu0; double y_shift; double y_scale; enum pj_ortho_ns::Mode mode; }; } // anonymous namespace #define EPS10 1.e-10 static PJ_XY forward_error(PJ *P, PJ_LP lp, PJ_XY xy) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); proj_log_trace(P, "Coordinate (%.3f, %.3f) is on the unprojected hemisphere", proj_todeg(lp.lam), proj_todeg(lp.phi)); return xy; } static PJ_XY ortho_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy; struct pj_ortho_data *Q = static_cast<struct pj_ortho_data *>(P->opaque); double coslam, cosphi, sinphi; xy.x = HUGE_VAL; xy.y = HUGE_VAL; cosphi = cos(lp.phi); coslam = cos(lp.lam); switch (Q->mode) { case pj_ortho_ns::EQUIT: if (cosphi * coslam < -EPS10) return forward_error(P, lp, xy); xy.y = sin(lp.phi); break; case pj_ortho_ns::OBLIQ: sinphi = sin(lp.phi); // Is the point visible from the projection plane ? // From // https://lists.osgeo.org/pipermail/proj/2020-September/009831.html // this is the dot product of the normal of the ellipsoid at the center // of the projection and at the point considered for projection. // [cos(phi)*cos(lambda), cos(phi)*sin(lambda), sin(phi)] // Also from Snyder's Map Projection - A working manual, equation (5-3), // page 149 if (Q->sinph0 * sinphi + Q->cosph0 * cosphi * coslam < -EPS10) return forward_error(P, lp, xy); xy.y = Q->cosph0 * sinphi - Q->sinph0 * cosphi * coslam; break; case pj_ortho_ns::N_POLE: coslam = -coslam; PROJ_FALLTHROUGH; case pj_ortho_ns::S_POLE: if (fabs(lp.phi - P->phi0) - EPS10 > M_HALFPI) return forward_error(P, lp, xy); xy.y = cosphi * coslam; break; } xy.x = cosphi * sin(lp.lam); return xy; } static PJ_LP ortho_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp; struct pj_ortho_data *Q = static_cast<struct pj_ortho_data *>(P->opaque); double sinc; lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; const double rh = hypot(xy.x, xy.y); sinc = rh; if (sinc > 1.) { if ((sinc - 1.) > EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } sinc = 1.; } const double cosc = sqrt(1. - sinc * sinc); /* in this range OK */ if (fabs(rh) <= EPS10) { lp.phi = P->phi0; lp.lam = 0.0; } else { switch (Q->mode) { case pj_ortho_ns::N_POLE: xy.y = -xy.y; lp.phi = acos(sinc); break; case pj_ortho_ns::S_POLE: lp.phi = -acos(sinc); break; case pj_ortho_ns::EQUIT: lp.phi = xy.y * sinc / rh; xy.x *= sinc; xy.y = cosc * rh; goto sinchk; case pj_ortho_ns::OBLIQ: lp.phi = cosc * Q->sinph0 + xy.y * sinc * Q->cosph0 / rh; xy.y = (cosc - Q->sinph0 * lp.phi) * rh; xy.x *= sinc * Q->cosph0; sinchk: if (fabs(lp.phi) >= 1.) lp.phi = lp.phi < 0. ? -M_HALFPI : M_HALFPI; else lp.phi = asin(lp.phi); break; } lp.lam = (xy.y == 0. && (Q->mode == pj_ortho_ns::OBLIQ || Q->mode == pj_ortho_ns::EQUIT)) ? (xy.x == 0. ? 0. : xy.x < 0. ? -M_HALFPI : M_HALFPI) : atan2(xy.x, xy.y); } return lp; } static PJ_XY ortho_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy; struct pj_ortho_data *Q = static_cast<struct pj_ortho_data *>(P->opaque); // From EPSG guidance note 7.2, March 2020, §3.3.5 Orthographic const double cosphi = cos(lp.phi); const double sinphi = sin(lp.phi); const double coslam = cos(lp.lam); const double sinlam = sin(lp.lam); // Is the point visible from the projection plane ? // Same condition as in spherical case if (Q->sinph0 * sinphi + Q->cosph0 * cosphi * coslam < -EPS10) { xy.x = HUGE_VAL; xy.y = HUGE_VAL; return forward_error(P, lp, xy); } const double nu = 1.0 / sqrt(1.0 - P->es * sinphi * sinphi); xy.x = nu * cosphi * sinlam; xy.y = nu * (sinphi * Q->cosph0 - cosphi * Q->sinph0 * coslam) + P->es * (Q->nu0 * Q->sinph0 - nu * sinphi) * Q->cosph0; return xy; } static PJ_LP ortho_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp; struct pj_ortho_data *Q = static_cast<struct pj_ortho_data *>(P->opaque); const auto SQ = [](double x) { return x * x; }; if (Q->mode == pj_ortho_ns::N_POLE || Q->mode == pj_ortho_ns::S_POLE) { // Polar case. Forward case equations can be simplified as: // xy.x = nu * cosphi * sinlam // xy.y = nu * -cosphi * coslam * sign(phi0) // ==> lam = atan2(xy.x, -xy.y * sign(phi0)) // ==> xy.x^2 + xy.y^2 = nu^2 * cosphi^2 // rh^2 = cosphi^2 / (1 - es * sinphi^2) // ==> cosphi^2 = rh^2 * (1 - es) / (1 - es * rh^2) const double rh2 = SQ(xy.x) + SQ(xy.y); if (rh2 >= 1. - 1e-15) { if ((rh2 - 1.) > EPS10) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; return lp; } lp.phi = 0; } else { lp.phi = acos(sqrt(rh2 * P->one_es / (1 - P->es * rh2))) * (Q->mode == pj_ortho_ns::N_POLE ? 1 : -1); } lp.lam = atan2(xy.x, xy.y * (Q->mode == pj_ortho_ns::N_POLE ? -1 : 1)); return lp; } if (Q->mode == pj_ortho_ns::EQUIT) { // Equatorial case. Forward case equations can be simplified as: // xy.x = nu * cosphi * sinlam // xy.y = nu * sinphi * (1 - P->es) // x^2 * (1 - es * sinphi^2) = (1 - sinphi^2) * sinlam^2 // y^2 / ((1 - es)^2 + y^2 * es) = sinphi^2 // Equation of the ellipse if (SQ(xy.x) + SQ(xy.y * (P->a / P->b)) > 1 + 1e-11) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; return lp; } const double sinphi2 = xy.y == 0 ? 0 : 1.0 / (SQ((1 - P->es) / xy.y) + P->es); if (sinphi2 > 1 - 1e-11) { lp.phi = M_PI_2 * (xy.y > 0 ? 1 : -1); lp.lam = 0; return lp; } lp.phi = asin(sqrt(sinphi2)) * (xy.y > 0 ? 1 : -1); const double sinlam = xy.x * sqrt((1 - P->es * sinphi2) / (1 - sinphi2)); if (fabs(sinlam) - 1 > -1e-15) lp.lam = M_PI_2 * (xy.x > 0 ? 1 : -1); else lp.lam = asin(sinlam); return lp; } // Using Q->sinph0 * sinphi + Q->cosph0 * cosphi * coslam == 0 (visibity // condition of the forward case) in the forward equations, and a lot of // substitution games... PJ_XY xy_recentered; xy_recentered.x = xy.x; xy_recentered.y = (xy.y - Q->y_shift) / Q->y_scale; if (SQ(xy.x) + SQ(xy_recentered.y) > 1 + 1e-11) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; return lp; } // From EPSG guidance note 7.2, March 2020, §3.3.5 Orthographic // It suggests as initial guess: // lp.lam = 0; // lp.phi = P->phi0; // But for poles, this will not converge well. Better use: lp = ortho_s_inverse(xy_recentered, P); for (int i = 0; i < 20; i++) { const double cosphi = cos(lp.phi); const double sinphi = sin(lp.phi); const double coslam = cos(lp.lam); const double sinlam = sin(lp.lam); const double one_minus_es_sinphi2 = 1.0 - P->es * sinphi * sinphi; const double nu = 1.0 / sqrt(one_minus_es_sinphi2); PJ_XY xy_new; xy_new.x = nu * cosphi * sinlam; xy_new.y = nu * (sinphi * Q->cosph0 - cosphi * Q->sinph0 * coslam) + P->es * (Q->nu0 * Q->sinph0 - nu * sinphi) * Q->cosph0; const double rho = (1.0 - P->es) * nu / one_minus_es_sinphi2; const double J11 = -rho * sinphi * sinlam; const double J12 = nu * cosphi * coslam; const double J21 = rho * (cosphi * Q->cosph0 + sinphi * Q->sinph0 * coslam); const double J22 = nu * Q->sinph0 * cosphi * sinlam; const double D = J11 * J22 - J12 * J21; const double dx = xy.x - xy_new.x; const double dy = xy.y - xy_new.y; const double dphi = (J22 * dx - J12 * dy) / D; const double dlam = (-J21 * dx + J11 * dy) / D; lp.phi += dphi; if (lp.phi > M_PI_2) { lp.phi = M_PI_2 - (lp.phi - M_PI_2); lp.lam = adjlon(lp.lam + M_PI); } else if (lp.phi < -M_PI_2) { lp.phi = -M_PI_2 + (-M_PI_2 - lp.phi); lp.lam = adjlon(lp.lam + M_PI); } lp.lam += dlam; if (fabs(dphi) < 1e-12 && fabs(dlam) < 1e-12) { return lp; } } proj_context_errno_set(P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } PJ *PJ_PROJECTION(ortho) { struct pj_ortho_data *Q = static_cast<struct pj_ortho_data *>( calloc(1, sizeof(struct pj_ortho_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->sinph0 = sin(P->phi0); Q->cosph0 = cos(P->phi0); if (fabs(fabs(P->phi0) - M_HALFPI) <= EPS10) Q->mode = P->phi0 < 0. ? pj_ortho_ns::S_POLE : pj_ortho_ns::N_POLE; else if (fabs(P->phi0) > EPS10) { Q->mode = pj_ortho_ns::OBLIQ; } else Q->mode = pj_ortho_ns::EQUIT; if (P->es == 0) { P->inv = ortho_s_inverse; P->fwd = ortho_s_forward; } else { Q->nu0 = 1.0 / sqrt(1.0 - P->es * Q->sinph0 * Q->sinph0); Q->y_shift = P->es * Q->nu0 * Q->sinph0 * Q->cosph0; Q->y_scale = 1.0 / sqrt(1.0 - P->es * Q->cosph0 * Q->cosph0); P->inv = ortho_e_inverse; P->fwd = ortho_e_forward; } return P; } #undef EPS10
cpp
PROJ
data/projects/PROJ/src/projections/nsper.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> /* Note: EPSG Guidance 7-2 describes a Vertical Perspective method (EPSG::9838), * that extends 'nsper' with ellipsoidal development, and a ellipsoidal height * of topocentric origin for the projection plan. */ namespace pj_nsper_ns { enum Mode { N_POLE = 0, S_POLE = 1, EQUIT = 2, OBLIQ = 3 }; } namespace { // anonymous namespace struct pj_nsper_data { double height; double sinph0; double cosph0; double p; double rp; double pn1; double pfact; double h; double cg; double sg; double sw; double cw; enum pj_nsper_ns::Mode mode; int tilt; }; } // anonymous namespace PROJ_HEAD(nsper, "Near-sided perspective") "\n\tAzi, Sph\n\th="; PROJ_HEAD(tpers, "Tilted perspective") "\n\tAzi, Sph\n\ttilt= azi= h="; #define EPS10 1.e-10 static PJ_XY nsper_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_nsper_data *Q = static_cast<struct pj_nsper_data *>(P->opaque); double coslam, cosphi, sinphi; sinphi = sin(lp.phi); cosphi = cos(lp.phi); coslam = cos(lp.lam); switch (Q->mode) { case pj_nsper_ns::OBLIQ: xy.y = Q->sinph0 * sinphi + Q->cosph0 * cosphi * coslam; break; case pj_nsper_ns::EQUIT: xy.y = cosphi * coslam; break; case pj_nsper_ns::S_POLE: xy.y = -sinphi; break; case pj_nsper_ns::N_POLE: xy.y = sinphi; break; } if (xy.y < Q->rp) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.y = Q->pn1 / (Q->p - xy.y); xy.x = xy.y * cosphi * sin(lp.lam); switch (Q->mode) { case pj_nsper_ns::OBLIQ: xy.y *= (Q->cosph0 * sinphi - Q->sinph0 * cosphi * coslam); break; case pj_nsper_ns::EQUIT: xy.y *= sinphi; break; case pj_nsper_ns::N_POLE: coslam = -coslam; PROJ_FALLTHROUGH; case pj_nsper_ns::S_POLE: xy.y *= cosphi * coslam; break; } if (Q->tilt) { double yt, ba; yt = xy.y * Q->cg + xy.x * Q->sg; ba = 1. / (yt * Q->sw * Q->h + Q->cw); xy.x = (xy.x * Q->cg - xy.y * Q->sg) * Q->cw * ba; xy.y = yt * ba; } return xy; } static PJ_LP nsper_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_nsper_data *Q = static_cast<struct pj_nsper_data *>(P->opaque); double rh; if (Q->tilt) { double bm, bq, yt; yt = 1. / (Q->pn1 - xy.y * Q->sw); bm = Q->pn1 * xy.x * yt; bq = Q->pn1 * xy.y * Q->cw * yt; xy.x = bm * Q->cg + bq * Q->sg; xy.y = bq * Q->cg - bm * Q->sg; } rh = hypot(xy.x, xy.y); if (fabs(rh) <= EPS10) { lp.lam = 0.; lp.phi = P->phi0; } else { double cosz, sinz; sinz = 1. - rh * rh * Q->pfact; if (sinz < 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } sinz = (Q->p - sqrt(sinz)) / (Q->pn1 / rh + rh / Q->pn1); cosz = sqrt(1. - sinz * sinz); switch (Q->mode) { case pj_nsper_ns::OBLIQ: lp.phi = asin(cosz * Q->sinph0 + xy.y * sinz * Q->cosph0 / rh); xy.y = (cosz - Q->sinph0 * sin(lp.phi)) * rh; xy.x *= sinz * Q->cosph0; break; case pj_nsper_ns::EQUIT: lp.phi = asin(xy.y * sinz / rh); xy.y = cosz * rh; xy.x *= sinz; break; case pj_nsper_ns::N_POLE: lp.phi = asin(cosz); xy.y = -xy.y; break; case pj_nsper_ns::S_POLE: lp.phi = -asin(cosz); break; } lp.lam = atan2(xy.x, xy.y); } return lp; } static PJ *nsper_setup(PJ *P) { struct pj_nsper_data *Q = static_cast<struct pj_nsper_data *>(P->opaque); Q->height = pj_param(P->ctx, P->params, "dh").f; if (fabs(fabs(P->phi0) - M_HALFPI) < EPS10) Q->mode = P->phi0 < 0. ? pj_nsper_ns::S_POLE : pj_nsper_ns::N_POLE; else if (fabs(P->phi0) < EPS10) Q->mode = pj_nsper_ns::EQUIT; else { Q->mode = pj_nsper_ns::OBLIQ; Q->sinph0 = sin(P->phi0); Q->cosph0 = cos(P->phi0); } Q->pn1 = Q->height / P->a; /* normalize by radius */ if (Q->pn1 <= 0 || Q->pn1 > 1e10) { proj_log_error(P, _("Invalid value for h")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->p = 1. + Q->pn1; Q->rp = 1. / Q->p; Q->h = 1. / Q->pn1; Q->pfact = (Q->p + 1.) * Q->h; P->inv = nsper_s_inverse; P->fwd = nsper_s_forward; P->es = 0.; return P; } PJ *PJ_PROJECTION(nsper) { struct pj_nsper_data *Q = static_cast<struct pj_nsper_data *>( calloc(1, sizeof(struct pj_nsper_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->tilt = 0; return nsper_setup(P); } PJ *PJ_PROJECTION(tpers) { double omega, gamma; struct pj_nsper_data *Q = static_cast<struct pj_nsper_data *>( calloc(1, sizeof(struct pj_nsper_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; omega = pj_param(P->ctx, P->params, "rtilt").f; gamma = pj_param(P->ctx, P->params, "razi").f; Q->tilt = 1; Q->cg = cos(gamma); Q->sg = sin(gamma); Q->cw = cos(omega); Q->sw = sin(omega); return nsper_setup(P); } #undef EPS10
cpp
PROJ
data/projects/PROJ/src/projections/rpoly.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_rpoly_data { double phi1; double fxa; double fxb; int mode; }; } // anonymous namespace PROJ_HEAD(rpoly, "Rectangular Polyconic") "\n\tConic, Sph, no inv\n\tlat_ts="; #define EPS 1e-9 static PJ_XY rpoly_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_rpoly_data *Q = static_cast<struct pj_rpoly_data *>(P->opaque); double fa; if (Q->mode) fa = tan(lp.lam * Q->fxb) * Q->fxa; else fa = 0.5 * lp.lam; if (fabs(lp.phi) < EPS) { xy.x = fa + fa; xy.y = -P->phi0; } else { xy.y = 1. / tan(lp.phi); fa = 2. * atan(fa * sin(lp.phi)); xy.x = sin(fa) * xy.y; xy.y = lp.phi - P->phi0 + (1. - cos(fa)) * xy.y; } return xy; } PJ *PJ_PROJECTION(rpoly) { struct pj_rpoly_data *Q = static_cast<struct pj_rpoly_data *>( calloc(1, sizeof(struct pj_rpoly_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->phi1 = fabs(pj_param(P->ctx, P->params, "rlat_ts").f); Q->mode = Q->phi1 > EPS; if (Q->mode) { Q->fxb = 0.5 * sin(Q->phi1); Q->fxa = 0.5 / Q->fxb; } P->es = 0.; P->fwd = rpoly_s_forward; return P; } #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/igh.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(igh, "Interrupted Goode Homolosine") "\n\tPCyl, Sph"; /* This projection is a compilation of 12 separate sub-projections. Sinusoidal projections are found near the equator and Mollweide projections are found at higher latitudes. The transition between the two occurs at 40 degrees latitude and is represented by the constant `igh_phi_boundary`. Each sub-projection is assigned an integer label numbered 1 through 12. Most of this code contains logic to assign the labels based on latitude (phi) and longitude (lam) regions. Original Reference: J. Paul Goode (1925) THE HOMOLOSINE PROJECTION: A NEW DEVICE FOR PORTRAYING THE EARTH'S SURFACE ENTIRE, Annals of the Association of American Geographers, 15:3, 119-125, DOI: 10.1080/00045602509356949 */ C_NAMESPACE PJ *pj_sinu(PJ *), *pj_moll(PJ *); /* Transition from sinusoidal to Mollweide projection Latitude (phi): 40deg 44' 11.8" */ constexpr double igh_phi_boundary = (40 + 44 / 60. + 11.8 / 3600.) * DEG_TO_RAD; namespace pj_igh_ns { struct pj_igh_data { struct PJconsts *pj[12]; double dy0; }; constexpr double d10 = 10 * DEG_TO_RAD; constexpr double d20 = 20 * DEG_TO_RAD; constexpr double d30 = 30 * DEG_TO_RAD; constexpr double d40 = 40 * DEG_TO_RAD; constexpr double d50 = 50 * DEG_TO_RAD; constexpr double d60 = 60 * DEG_TO_RAD; constexpr double d80 = 80 * DEG_TO_RAD; constexpr double d90 = 90 * DEG_TO_RAD; constexpr double d100 = 100 * DEG_TO_RAD; constexpr double d140 = 140 * DEG_TO_RAD; constexpr double d160 = 160 * DEG_TO_RAD; constexpr double d180 = 180 * DEG_TO_RAD; constexpr double EPSLN = 1.e-10; /* allow a little 'slack' on zone edge positions */ } // namespace pj_igh_ns static PJ_XY igh_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ using namespace pj_igh_ns; PJ_XY xy; struct pj_igh_data *Q = static_cast<struct pj_igh_data *>(P->opaque); int z; if (lp.phi >= igh_phi_boundary) { /* 1|2 */ z = (lp.lam <= -d40 ? 1 : 2); } else if (lp.phi >= 0) { /* 3|4 */ z = (lp.lam <= -d40 ? 3 : 4); } else if (lp.phi >= -igh_phi_boundary) { /* 5|6|7|8 */ if (lp.lam <= -d100) z = 5; /* 5 */ else if (lp.lam <= -d20) z = 6; /* 6 */ else if (lp.lam <= d80) z = 7; /* 7 */ else z = 8; /* 8 */ } else { /* 9|10|11|12 */ if (lp.lam <= -d100) z = 9; /* 9 */ else if (lp.lam <= -d20) z = 10; /* 10 */ else if (lp.lam <= d80) z = 11; /* 11 */ else z = 12; /* 12 */ } lp.lam -= Q->pj[z - 1]->lam0; xy = Q->pj[z - 1]->fwd(lp, Q->pj[z - 1]); xy.x += Q->pj[z - 1]->x0; xy.y += Q->pj[z - 1]->y0; return xy; } static PJ_LP igh_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ using namespace pj_igh_ns; PJ_LP lp = {0.0, 0.0}; struct pj_igh_data *Q = static_cast<struct pj_igh_data *>(P->opaque); const double y90 = Q->dy0 + sqrt(2.0); /* lt=90 corresponds to y=y0+sqrt(2) */ int z = 0; if (xy.y > y90 + EPSLN || xy.y < -y90 + EPSLN) /* 0 */ z = 0; else if (xy.y >= igh_phi_boundary) /* 1|2 */ z = (xy.x <= -d40 ? 1 : 2); else if (xy.y >= 0) /* 3|4 */ z = (xy.x <= -d40 ? 3 : 4); else if (xy.y >= -igh_phi_boundary) { /* 5|6|7|8 */ if (xy.x <= -d100) z = 5; /* 5 */ else if (xy.x <= -d20) z = 6; /* 6 */ else if (xy.x <= d80) z = 7; /* 7 */ else z = 8; /* 8 */ } else { /* 9|10|11|12 */ if (xy.x <= -d100) z = 9; /* 9 */ else if (xy.x <= -d20) z = 10; /* 10 */ else if (xy.x <= d80) z = 11; /* 11 */ else z = 12; /* 12 */ } if (z) { bool ok = false; xy.x -= Q->pj[z - 1]->x0; xy.y -= Q->pj[z - 1]->y0; lp = Q->pj[z - 1]->inv(xy, Q->pj[z - 1]); lp.lam += Q->pj[z - 1]->lam0; switch (z) { case 1: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d40 + EPSLN) || ((lp.lam >= -d40 - EPSLN && lp.lam <= -d10 + EPSLN) && (lp.phi >= d60 - EPSLN && lp.phi <= d90 + EPSLN)); break; case 2: ok = (lp.lam >= -d40 - EPSLN && lp.lam <= d180 + EPSLN) || ((lp.lam >= -d180 - EPSLN && lp.lam <= -d160 + EPSLN) && (lp.phi >= d50 - EPSLN && lp.phi <= d90 + EPSLN)) || ((lp.lam >= -d50 - EPSLN && lp.lam <= -d40 + EPSLN) && (lp.phi >= d60 - EPSLN && lp.phi <= d90 + EPSLN)); break; case 3: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d40 + EPSLN); break; case 4: ok = (lp.lam >= -d40 - EPSLN && lp.lam <= d180 + EPSLN); break; case 5: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d100 + EPSLN); break; case 6: ok = (lp.lam >= -d100 - EPSLN && lp.lam <= -d20 + EPSLN); break; case 7: ok = (lp.lam >= -d20 - EPSLN && lp.lam <= d80 + EPSLN); break; case 8: ok = (lp.lam >= d80 - EPSLN && lp.lam <= d180 + EPSLN); break; case 9: ok = (lp.lam >= -d180 - EPSLN && lp.lam <= -d100 + EPSLN); break; case 10: ok = (lp.lam >= -d100 - EPSLN && lp.lam <= -d20 + EPSLN); break; case 11: ok = (lp.lam >= -d20 - EPSLN && lp.lam <= d80 + EPSLN); break; case 12: ok = (lp.lam >= d80 - EPSLN && lp.lam <= d180 + EPSLN); break; } z = (!ok ? 0 : z); /* projectable? */ } if (!z) lp.lam = HUGE_VAL; if (!z) lp.phi = HUGE_VAL; return lp; } static PJ *pj_igh_data_destructor(PJ *P, int errlev) { using namespace pj_igh_ns; int i; if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); struct pj_igh_data *Q = static_cast<struct pj_igh_data *>(P->opaque); for (i = 0; i < 12; ++i) { if (Q->pj[i]) Q->pj[i]->destructor(Q->pj[i], errlev); } return pj_default_destructor(P, errlev); } /* Zones: -180 -40 180 +--------------+-------------------------+ Zones 1,2,9,10,11 & 12: |1 |2 | Mollweide projection | | | +--------------+-------------------------+ Zones 3,4,5,6,7 & 8: |3 |4 | Sinusoidal projection | | | 0 +-------+------+-+-----------+-----------+ |5 |6 |7 |8 | | | | | | +-------+--------+-----------+-----------+ |9 |10 |11 |12 | | | | | | +-------+--------+-----------+-----------+ -180 -100 -20 80 180 */ static bool pj_igh_setup_zone(PJ *P, struct pj_igh_ns::pj_igh_data *Q, int n, PJ *(*proj_ptr)(PJ *), double x_0, double y_0, double lon_0) { if (!(Q->pj[n - 1] = proj_ptr(nullptr))) return false; if (!(Q->pj[n - 1] = proj_ptr(Q->pj[n - 1]))) return false; Q->pj[n - 1]->ctx = P->ctx; Q->pj[n - 1]->x0 = x_0; Q->pj[n - 1]->y0 = y_0; Q->pj[n - 1]->lam0 = lon_0; return true; } PJ *PJ_PROJECTION(igh) { using namespace pj_igh_ns; PJ_XY xy1, xy3; PJ_LP lp = {0, igh_phi_boundary}; struct pj_igh_data *Q = static_cast<struct pj_igh_data *>( calloc(1, sizeof(struct pj_igh_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* sinusoidal zones */ if (!pj_igh_setup_zone(P, Q, 3, pj_sinu, -d100, 0, -d100) || !pj_igh_setup_zone(P, Q, 4, pj_sinu, d30, 0, d30) || !pj_igh_setup_zone(P, Q, 5, pj_sinu, -d160, 0, -d160) || !pj_igh_setup_zone(P, Q, 6, pj_sinu, -d60, 0, -d60) || !pj_igh_setup_zone(P, Q, 7, pj_sinu, d20, 0, d20) || !pj_igh_setup_zone(P, Q, 8, pj_sinu, d140, 0, d140)) { return pj_igh_data_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } /* mollweide zones */ if (!pj_igh_setup_zone(P, Q, 1, pj_moll, -d100, 0, -d100)) { return pj_igh_data_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } /* y0 ? */ xy1 = Q->pj[0]->fwd(lp, Q->pj[0]); /* zone 1 */ xy3 = Q->pj[2]->fwd(lp, Q->pj[2]); /* zone 3 */ /* y0 + xy1.y = xy3.y for lt = 40d44'11.8" */ Q->dy0 = xy3.y - xy1.y; Q->pj[0]->y0 = Q->dy0; /* mollweide zones (cont'd) */ if (!pj_igh_setup_zone(P, Q, 2, pj_moll, d30, Q->dy0, d30) || !pj_igh_setup_zone(P, Q, 9, pj_moll, -d160, -Q->dy0, -d160) || !pj_igh_setup_zone(P, Q, 10, pj_moll, -d60, -Q->dy0, -d60) || !pj_igh_setup_zone(P, Q, 11, pj_moll, d20, -Q->dy0, d20) || !pj_igh_setup_zone(P, Q, 12, pj_moll, d140, -Q->dy0, d140)) { return pj_igh_data_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); } P->inv = igh_s_inverse; P->fwd = igh_s_forward; P->destructor = pj_igh_data_destructor; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/ccon.cpp
/****************************************************************************** * Copyright (c) 2017, Lukasz Komsta * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> #define EPS10 1e-10 namespace { // anonymous namespace struct pj_ccon_data { double phi1; double ctgphi1; double sinphi1; double cosphi1; double *en; }; } // anonymous namespace PROJ_HEAD(ccon, "Central Conic") "\n\tCentral Conic, Sph\n\tlat_1="; static PJ_XY ccon_forward(PJ_LP lp, PJ *P) { PJ_XY xy = {0.0, 0.0}; struct pj_ccon_data *Q = static_cast<struct pj_ccon_data *>(P->opaque); double r; r = Q->ctgphi1 - tan(lp.phi - Q->phi1); xy.x = r * sin(lp.lam * Q->sinphi1); xy.y = Q->ctgphi1 - r * cos(lp.lam * Q->sinphi1); return xy; } static PJ_LP ccon_inverse(PJ_XY xy, PJ *P) { PJ_LP lp = {0.0, 0.0}; struct pj_ccon_data *Q = static_cast<struct pj_ccon_data *>(P->opaque); xy.y = Q->ctgphi1 - xy.y; lp.phi = Q->phi1 - atan(hypot(xy.x, xy.y) - Q->ctgphi1); lp.lam = atan2(xy.x, xy.y) / Q->sinphi1; return lp; } static PJ *pj_ccon_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_ccon_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(ccon) { struct pj_ccon_data *Q = static_cast<struct pj_ccon_data *>( calloc(1, sizeof(struct pj_ccon_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_ccon_destructor; Q->phi1 = pj_param(P->ctx, P->params, "rlat_1").f; if (fabs(Q->phi1) < EPS10) { proj_log_error(P, _("Invalid value for lat_1: |lat_1| should be > 0")); return pj_ccon_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (!(Q->en = pj_enfn(P->n))) return pj_ccon_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->sinphi1 = sin(Q->phi1); Q->cosphi1 = cos(Q->phi1); Q->ctgphi1 = Q->cosphi1 / Q->sinphi1; P->inv = ccon_inverse; P->fwd = ccon_forward; return P; } #undef EPS10
cpp
PROJ
data/projects/PROJ/src/projections/urmfps.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(urmfps, "Urmaev Flat-Polar Sinusoidal") "\n\tPCyl, Sph\n\tn="; PROJ_HEAD(wag1, "Wagner I (Kavrayskiy VI)") "\n\tPCyl, Sph"; namespace { // anonymous namespace struct pj_urmfps { double n, C_y; }; } // anonymous namespace #define C_x 0.8773826753 #define Cy 1.139753528477 static PJ_XY urmfps_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; lp.phi = aasin(P->ctx, static_cast<struct pj_urmfps *>(P->opaque)->n * sin(lp.phi)); xy.x = C_x * lp.lam * cos(lp.phi); xy.y = static_cast<struct pj_urmfps *>(P->opaque)->C_y * lp.phi; return xy; } static PJ_LP urmfps_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; xy.y /= static_cast<struct pj_urmfps *>(P->opaque)->C_y; lp.phi = aasin(P->ctx, sin(xy.y) / static_cast<struct pj_urmfps *>(P->opaque)->n); lp.lam = xy.x / (C_x * cos(xy.y)); return lp; } static PJ *urmfps_setup(PJ *P) { static_cast<struct pj_urmfps *>(P->opaque)->C_y = Cy / static_cast<struct pj_urmfps *>(P->opaque)->n; P->es = 0.; P->inv = urmfps_s_inverse; P->fwd = urmfps_s_forward; return P; } PJ *PJ_PROJECTION(urmfps) { struct pj_urmfps *Q = static_cast<struct pj_urmfps *>(calloc(1, sizeof(struct pj_urmfps))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (!pj_param(P->ctx, P->params, "tn").i) { proj_log_error(P, _("Missing parameter n.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->n = pj_param(P->ctx, P->params, "dn").f; if (Q->n <= 0. || Q->n > 1.) { proj_log_error(P, _("Invalid value for n: it should be in ]0,1] range.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } return urmfps_setup(P); } PJ *PJ_PROJECTION(wag1) { struct pj_urmfps *Q = static_cast<struct pj_urmfps *>(calloc(1, sizeof(struct pj_urmfps))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; static_cast<struct pj_urmfps *>(P->opaque)->n = 0.8660254037844386467637231707; return urmfps_setup(P); } #undef C_x #undef Cy
cpp
PROJ
data/projects/PROJ/src/projections/bacon.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" #define HLFPI2 2.46740110027233965467 /* (pi/2)^2 */ #define EPS 1e-10 namespace { // anonymous namespace struct pj_bacon { int bacn; int ortl; }; } // anonymous namespace PROJ_HEAD(apian, "Apian Globular I") "\n\tMisc Sph, no inv"; PROJ_HEAD(ortel, "Ortelius Oval") "\n\tMisc Sph, no inv"; PROJ_HEAD(bacon, "Bacon Globular") "\n\tMisc Sph, no inv"; static PJ_XY bacon_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_bacon *Q = static_cast<struct pj_bacon *>(P->opaque); double ax, f; xy.y = Q->bacn ? M_HALFPI * sin(lp.phi) : lp.phi; ax = fabs(lp.lam); if (ax >= EPS) { if (Q->ortl && ax >= M_HALFPI) xy.x = sqrt(HLFPI2 - lp.phi * lp.phi + EPS) + ax - M_HALFPI; else { f = 0.5 * (HLFPI2 / ax + ax); xy.x = ax - f + sqrt(f * f - xy.y * xy.y); } if (lp.lam < 0.) xy.x = -xy.x; } else xy.x = 0.; return (xy); } PJ *PJ_PROJECTION(bacon) { struct pj_bacon *Q = static_cast<struct pj_bacon *>(calloc(1, sizeof(struct pj_bacon))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->bacn = 1; Q->ortl = 0; P->es = 0.; P->fwd = bacon_s_forward; return P; } PJ *PJ_PROJECTION(apian) { struct pj_bacon *Q = static_cast<struct pj_bacon *>(calloc(1, sizeof(struct pj_bacon))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->bacn = Q->ortl = 0; P->es = 0.; P->fwd = bacon_s_forward; return P; } PJ *PJ_PROJECTION(ortel) { struct pj_bacon *Q = static_cast<struct pj_bacon *>(calloc(1, sizeof(struct pj_bacon))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->bacn = 0; Q->ortl = 1; P->es = 0.; P->fwd = bacon_s_forward; return P; } #undef HLFPI2 #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/natearth2.cpp
/* The Natural Earth II projection was designed by Tom Patterson, US National Park Service, in 2012, using Flex Projector. The polynomial equation was developed by Bojan Savric and Bernhard Jenny, College of Earth, Ocean, and Atmospheric Sciences, Oregon State University. Port to PROJ.4 by Bojan Savric, 4 April 2016 */ #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(natearth2, "Natural Earth 2") "\n\tPCyl, Sph"; #define A0 0.84719 #define A1 -0.13063 #define A2 -0.04515 #define A3 0.05494 #define A4 -0.02326 #define A5 0.00331 #define B0 1.01183 #define B1 -0.02625 #define B2 0.01926 #define B3 -0.00396 #define C0 B0 #define C1 (9 * B1) #define C2 (11 * B2) #define C3 (13 * B3) #define EPS 1e-11 #define MAX_Y (0.84719 * 0.535117535153096 * M_PI) /* Not sure at all of the appropriate number for MAX_ITER... */ #define MAX_ITER 100 static PJ_XY natearth2_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double phi2, phi4, phi6; (void)P; phi2 = lp.phi * lp.phi; phi4 = phi2 * phi2; phi6 = phi2 * phi4; xy.x = lp.lam * (A0 + A1 * phi2 + phi6 * phi6 * (A2 + A3 * phi2 + A4 * phi4 + A5 * phi6)); xy.y = lp.phi * (B0 + phi4 * phi4 * (B1 + B2 * phi2 + B3 * phi4)); return xy; } static PJ_LP natearth2_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double yc, y2, y4, y6, f, fder; int i; (void)P; /* make sure y is inside valid range */ if (xy.y > MAX_Y) { xy.y = MAX_Y; } else if (xy.y < -MAX_Y) { xy.y = -MAX_Y; } /* latitude */ yc = xy.y; for (i = MAX_ITER; i; --i) { /* Newton-Raphson */ y2 = yc * yc; y4 = y2 * y2; f = (yc * (B0 + y4 * y4 * (B1 + B2 * y2 + B3 * y4))) - xy.y; fder = C0 + y4 * y4 * (C1 + C2 * y2 + C3 * y4); const double tol = f / fder; yc -= tol; if (fabs(tol) < EPS) { break; } } if (i == 0) proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.phi = yc; /* longitude */ y2 = yc * yc; y4 = y2 * y2; y6 = y2 * y4; lp.lam = xy.x / (A0 + A1 * y2 + y6 * y6 * (A2 + A3 * y2 + A4 * y4 + A5 * y6)); return lp; } PJ *PJ_PROJECTION(natearth2) { P->es = 0; P->inv = natearth2_s_inverse; P->fwd = natearth2_s_forward; return P; } #undef A0 #undef A1 #undef A2 #undef A3 #undef A4 #undef A5 #undef B0 #undef B1 #undef B2 #undef B3 #undef C0 #undef C1 #undef C2 #undef C3 #undef EPS #undef MAX_Y #undef MAX_ITER
cpp
PROJ
data/projects/PROJ/src/projections/fahey.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(fahey, "Fahey") "\n\tPcyl, Sph"; #define TOL 1e-6 static PJ_XY fahey_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = tan(0.5 * lp.phi); xy.y = 1.819152 * xy.x; xy.x = 0.819152 * lp.lam * asqrt(1 - xy.x * xy.x); return xy; } static PJ_LP fahey_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; xy.y /= 1.819152; lp.phi = 2. * atan(xy.y); xy.y = 1. - xy.y * xy.y; lp.lam = fabs(xy.y) < TOL ? 0. : xy.x / (0.819152 * sqrt(xy.y)); return lp; } PJ *PJ_PROJECTION(fahey) { P->es = 0.; P->inv = fahey_s_inverse; P->fwd = fahey_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/mbt_fps.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(mbt_fps, "McBryde-Thomas Flat-Pole Sine (No. 2)") "\n\tCyl, Sph"; #define MAX_ITER 10 #define LOOP_TOL 1e-7 #define C1 0.45503 #define C2 1.36509 #define C3 1.41546 #define C_x 0.22248 #define C_y 1.44492 #define C1_2 0.33333333333333333333333333 static PJ_XY mbt_fps_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; const double k = C3 * sin(lp.phi); for (int i = MAX_ITER; i; --i) { const double t = lp.phi / C2; const double V = (C1 * sin(t) + sin(lp.phi) - k) / (C1_2 * cos(t) + cos(lp.phi)); lp.phi -= V; if (fabs(V) < LOOP_TOL) break; } const double t = lp.phi / C2; xy.x = C_x * lp.lam * (1. + 3. * cos(lp.phi) / cos(t)); xy.y = C_y * sin(t); return xy; } static PJ_LP mbt_fps_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; const double t = aasin(P->ctx, xy.y / C_y); lp.phi = C2 * t; lp.lam = xy.x / (C_x * (1. + 3. * cos(lp.phi) / cos(t))); lp.phi = aasin(P->ctx, (C1 * sin(t) + sin(lp.phi)) / C3); return (lp); } PJ *PJ_PROJECTION(mbt_fps) { P->es = 0; P->inv = mbt_fps_s_inverse; P->fwd = mbt_fps_s_forward; return P; } #undef MAX_ITER #undef LOOP_TOL #undef C1 #undef C2 #undef C3 #undef C_x #undef C_y #undef C1_2
cpp
PROJ
data/projects/PROJ/src/projections/aitoff.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the aitoff (Aitoff) and wintri (Winkel Tripel) * projections. * Author: Gerald Evenden (1995) * Drazen Tutic, Lovro Gradiser (2015) - add inverse * Thomas Knudsen (2016) - revise/add regression tests * ****************************************************************************** * Copyright (c) 1995, Gerald Evenden * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace pj_aitoff_ns { enum Mode { AITOFF = 0, WINKEL_TRIPEL = 1 }; } namespace { // anonymous namespace struct pj_aitoff_data { double cosphi1; enum pj_aitoff_ns::Mode mode; }; } // anonymous namespace PROJ_HEAD(aitoff, "Aitoff") "\n\tMisc Sph"; PROJ_HEAD(wintri, "Winkel Tripel") "\n\tMisc Sph\n\tlat_1"; #if 0 FORWARD(aitoff_s_forward); /* spheroid */ #endif static PJ_XY aitoff_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_aitoff_data *Q = static_cast<struct pj_aitoff_data *>(P->opaque); double c, d; #if 0 // Likely domain of validity for wintri in +over mode. Should be confirmed // Cf https://lists.osgeo.org/pipermail/gdal-dev/2023-April/057164.html if (Q->mode == WINKEL_TRIPEL && fabs(lp.lam) > 2 * M_PI) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } #endif c = 0.5 * lp.lam; d = acos(cos(lp.phi) * cos(c)); if (d != 0.0) { /* basic Aitoff */ xy.x = 2. * d * cos(lp.phi) * sin(c) * (xy.y = 1. / sin(d)); xy.y *= d * sin(lp.phi); } else xy.x = xy.y = 0.; if (Q->mode == pj_aitoff_ns::WINKEL_TRIPEL) { xy.x = (xy.x + lp.lam * Q->cosphi1) * 0.5; xy.y = (xy.y + lp.phi) * 0.5; } return (xy); } /*********************************************************************************** * * Inverse functions added by Drazen Tutic and Lovro Gradiser based on paper: * * I.Özbug Biklirici and Cengizhan Ipbüker. A General Algorithm for the Inverse * Transformation of Map Projections Using Jacobian Matrices. In Proceedings of *the Third International Symposium Mathematical & Computational Applications, * pages 175{182, Turkey, September 2002. * * Expected accuracy is defined by EPSILON = 1e-12. Should be appropriate for * most applications of Aitoff and Winkel Tripel projections. * * Longitudes of 180W and 180E can be mixed in solution obtained. * * Inverse for Aitoff projection in poles is undefined, longitude value of 0 is *assumed. * * Contact : [email protected] * Date: 2015-02-16 * ************************************************************************************/ static PJ_LP aitoff_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_aitoff_data *Q = static_cast<struct pj_aitoff_data *>(P->opaque); int iter, MAXITER = 10, round = 0, MAXROUND = 20; double EPSILON = 1e-12, D, C, f1, f2, f1p, f1l, f2p, f2l, dp, dl, sl, sp, cp, cl, x, y; if ((fabs(xy.x) < EPSILON) && (fabs(xy.y) < EPSILON)) { lp.phi = 0.; lp.lam = 0.; return lp; } /* initial values for Newton-Raphson method */ lp.phi = xy.y; lp.lam = xy.x; do { iter = 0; do { sl = sin(lp.lam * 0.5); cl = cos(lp.lam * 0.5); sp = sin(lp.phi); cp = cos(lp.phi); D = cp * cl; C = 1. - D * D; const double denom = pow(C, 1.5); if (denom == 0) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } D = acos(D) / denom; f1 = 2. * D * C * cp * sl; f2 = D * C * sp; f1p = 2. * (sl * cl * sp * cp / C - D * sp * sl); f1l = cp * cp * sl * sl / C + D * cp * cl * sp * sp; f2p = sp * sp * cl / C + D * sl * sl * cp; f2l = 0.5 * (sp * cp * sl / C - D * sp * cp * cp * sl * cl); if (Q->mode == pj_aitoff_ns::WINKEL_TRIPEL) { f1 = 0.5 * (f1 + lp.lam * Q->cosphi1); f2 = 0.5 * (f2 + lp.phi); f1p *= 0.5; f1l = 0.5 * (f1l + Q->cosphi1); f2p = 0.5 * (f2p + 1.); f2l *= 0.5; } f1 -= xy.x; f2 -= xy.y; dp = f1p * f2l - f2p * f1l; dl = (f2 * f1p - f1 * f2p) / dp; dp = (f1 * f2l - f2 * f1l) / dp; dl = fmod(dl, M_PI); /* set to interval [-M_PI, M_PI] */ lp.phi -= dp; lp.lam -= dl; } while ((fabs(dp) > EPSILON || fabs(dl) > EPSILON) && (iter++ < MAXITER)); if (lp.phi > M_PI_2) lp.phi -= 2. * (lp.phi - M_PI_2); /* correct if symmetrical solution for Aitoff */ if (lp.phi < -M_PI_2) lp.phi -= 2. * (lp.phi + M_PI_2); /* correct if symmetrical solution for Aitoff */ if ((fabs(fabs(lp.phi) - M_PI_2) < EPSILON) && (Q->mode == pj_aitoff_ns::AITOFF)) lp.lam = 0.; /* if pole in Aitoff, return longitude of 0 */ /* calculate x,y coordinates with solution obtained */ if ((D = acos(cos(lp.phi) * cos(C = 0.5 * lp.lam))) != 0.0) { /* Aitoff */ y = 1. / sin(D); x = 2. * D * cos(lp.phi) * sin(C) * y; y *= D * sin(lp.phi); } else x = y = 0.; if (Q->mode == pj_aitoff_ns::WINKEL_TRIPEL) { x = (x + lp.lam * Q->cosphi1) * 0.5; y = (y + lp.phi) * 0.5; } /* if too far from given values of x,y, repeat with better approximation * of phi,lam */ } while (((fabs(xy.x - x) > EPSILON) || (fabs(xy.y - y) > EPSILON)) && (round++ < MAXROUND)); if (iter == MAXITER && round == MAXROUND) { proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); /* fprintf(stderr, "Warning: Accuracy of 1e-12 not reached. Last * increments: dlat=%e and dlon=%e\n", dp, dl); */ } return lp; } static PJ *pj_aitoff_setup(PJ *P) { P->inv = aitoff_s_inverse; P->fwd = aitoff_s_forward; P->es = 0.; return P; } PJ *PJ_PROJECTION(aitoff) { struct pj_aitoff_data *Q = static_cast<struct pj_aitoff_data *>( calloc(1, sizeof(struct pj_aitoff_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->mode = pj_aitoff_ns::AITOFF; return pj_aitoff_setup(P); } PJ *PJ_PROJECTION(wintri) { struct pj_aitoff_data *Q = static_cast<struct pj_aitoff_data *>( calloc(1, sizeof(struct pj_aitoff_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->mode = pj_aitoff_ns::WINKEL_TRIPEL; if (pj_param(P->ctx, P->params, "tlat_1").i) { if ((Q->cosphi1 = cos(pj_param(P->ctx, P->params, "rlat_1").f)) == 0.) { proj_log_error( P, _("Invalid value for lat_1: |lat_1| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } else /* 50d28' or acos(2/pi) */ Q->cosphi1 = 0.636619772367581343; return pj_aitoff_setup(P); }
cpp
PROJ
data/projects/PROJ/src/projections/nzmg.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the nzmg (New Zealand Map Grid) projection. * Very loosely based upon DMA code by Bradford W. Drew * Author: Gerald Evenden * ****************************************************************************** * Copyright (c) 1995, Gerald Evenden * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(nzmg, "New Zealand Map Grid") "\n\tfixed Earth"; #define EPSLN 1e-10 #define SEC5_TO_RAD 0.4848136811095359935899141023 #define RAD_TO_SEC5 2.062648062470963551564733573 static const COMPLEX bf[] = { {.7557853228, 0.0}, {.249204646, 0.003371507}, {-.001541739, 0.041058560}, {-.10162907, 0.01727609}, {-.26623489, -0.36249218}, {-.6870983, -1.1651967}}; #define Nbf 5 #define Ntpsi 9 #define Ntphi 8 static PJ_XY nzmg_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; COMPLEX p; const double *C; int i; static const double tpsi[] = { .6399175073, -.1358797613, .063294409, -.02526853, .0117879, -.0055161, .0026906, -.001333, .00067, -.00034}; lp.phi = (lp.phi - P->phi0) * RAD_TO_SEC5; i = Ntpsi; C = tpsi + i; for (p.r = *C; i; --i) { --C; p.r = *C + lp.phi * p.r; } p.r *= lp.phi; p.i = lp.lam; p = pj_zpoly1(p, bf, Nbf); xy.x = p.i; xy.y = p.r; return xy; } static PJ_LP nzmg_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; int nn, i; COMPLEX p, f, fp, dp; double den; const double *C; static const double tphi[] = {1.5627014243, .5185406398, -.03333098, -.1052906, -.0368594, .007317, .01220, .00394, -.0013}; p.r = xy.y; p.i = xy.x; for (nn = 20; nn; --nn) { f = pj_zpolyd1(p, bf, Nbf, &fp); f.r -= xy.y; f.i -= xy.x; den = fp.r * fp.r + fp.i * fp.i; dp.r = -(f.r * fp.r + f.i * fp.i) / den; dp.i = -(f.i * fp.r - f.r * fp.i) / den; p.r += dp.r; p.i += dp.i; if ((fabs(dp.r) + fabs(dp.i)) <= EPSLN) break; } if (nn) { lp.lam = p.i; i = Ntphi; C = tphi + i; for (lp.phi = *C; i; --i) { --C; lp.phi = *C + p.r * lp.phi; } lp.phi = P->phi0 + p.r * lp.phi * SEC5_TO_RAD; } else lp.lam = lp.phi = HUGE_VAL; return lp; } PJ *PJ_PROJECTION(nzmg) { /* force to International major axis */ P->ra = 1. / (P->a = 6378388.0); P->lam0 = DEG_TO_RAD * 173.; P->phi0 = DEG_TO_RAD * -41.; P->x0 = 2510000.; P->y0 = 6023150.; P->inv = nzmg_e_inverse; P->fwd = nzmg_e_forward; return P; } #undef EPSLN #undef SEC5_TO_RAD #undef RAD_TO_SEC5 #undef Nbf #undef Ntpsi #undef Ntphi
cpp
PROJ
data/projects/PROJ/src/projections/mill.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(mill, "Miller Cylindrical") "\n\tCyl, Sph"; static PJ_XY mill_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = lp.lam; xy.y = log(tan(M_FORTPI + lp.phi * .4)) * 1.25; return (xy); } static PJ_LP mill_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; lp.lam = xy.x; lp.phi = 2.5 * (atan(exp(.8 * xy.y)) - M_FORTPI); return (lp); } PJ *PJ_PROJECTION(mill) { P->es = 0.; P->inv = mill_s_inverse; P->fwd = mill_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/tcc.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(tcc, "Transverse Central Cylindrical") "\n\tCyl, Sph, no inv"; #define EPS10 1.e-10 static PJ_XY tcc_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; const double b = cos(lp.phi) * sin(lp.lam); const double bt = 1. - b * b; if (bt < EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.x = b / sqrt(bt); xy.y = atan2(tan(lp.phi), cos(lp.lam)); return xy; } PJ *PJ_PROJECTION(tcc) { P->es = 0.; P->fwd = tcc_s_forward; P->inv = nullptr; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/cass.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(cass, "Cassini") "\n\tCyl, Sph&Ell"; #define C1 .16666666666666666666 #define C2 .00833333333333333333 #define C3 .04166666666666666666 #define C4 .33333333333333333333 #define C5 .06666666666666666666 namespace { // anonymous namespace struct cass_data { double *en; double m0; bool hyperbolic; }; } // anonymous namespace static PJ_XY cass_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct cass_data *Q = static_cast<struct cass_data *>(P->opaque); const double sinphi = sin(lp.phi); const double cosphi = cos(lp.phi); const double M = pj_mlfn(lp.phi, sinphi, cosphi, Q->en); const double nu_square = 1. / (1. - P->es * sinphi * sinphi); const double nu = sqrt(nu_square); const double tanphi = tan(lp.phi); const double T = tanphi * tanphi; const double A = lp.lam * cosphi; const double C = P->es * (cosphi * cosphi) / (1 - P->es); const double A2 = A * A; xy.x = nu * A * (1. - A2 * T * (C1 + (8. - T + 8. * C) * A2 * C2)); xy.y = M - Q->m0 + nu * tanphi * A2 * (.5 + (5. - T + 6. * C) * A2 * C3); if (Q->hyperbolic) { const double rho = nu_square * (1. - P->es) * nu; xy.y -= xy.y * xy.y * xy.y / (6 * rho * nu); } return xy; } static PJ_XY cass_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = asin(cos(lp.phi) * sin(lp.lam)); xy.y = atan2(tan(lp.phi), cos(lp.lam)) - P->phi0; return xy; } static PJ_LP cass_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct cass_data *Q = static_cast<struct cass_data *>(P->opaque); const double phi1 = pj_inv_mlfn(Q->m0 + xy.y, Q->en); const double tanphi1 = tan(phi1); const double T1 = tanphi1 * tanphi1; const double sinphi1 = sin(phi1); const double nu1_square = 1. / (1. - P->es * sinphi1 * sinphi1); const double nu1 = sqrt(nu1_square); const double rho1 = nu1_square * (1. - P->es) * nu1; const double D = xy.x / nu1; const double D2 = D * D; lp.phi = phi1 - (nu1 * tanphi1 / rho1) * D2 * (.5 - (1. + 3. * T1) * D2 * C3); lp.lam = D * (1. + T1 * D2 * (-C4 + (1. + 3. * T1) * D2 * C5)) / cos(phi1); // EPSG guidance note 7-2 suggests a custom approximation for the // 'Vanua Levu 1915 / Vanua Levu Grid' case, but better use the // generic inversion method // Actually use it in the non-hyperbolic case. It enables to make the // 5108.gie roundtripping tests to success, with at most 2 iterations. constexpr double deltaXYTolerance = 1e-12; lp = pj_generic_inverse_2d(xy, P, lp, deltaXYTolerance); return lp; } static PJ_LP cass_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double dd; lp.phi = asin(sin(dd = xy.y + P->phi0) * cos(xy.x)); lp.lam = atan2(tan(xy.x), cos(dd)); return lp; } static PJ *pj_cass_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct cass_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(cass) { /* Spheroidal? */ if (0 == P->es) { P->inv = cass_s_inverse; P->fwd = cass_s_forward; return P; } /* otherwise it's ellipsoidal */ auto Q = static_cast<struct cass_data *>(calloc(1, sizeof(struct cass_data))); P->opaque = Q; if (nullptr == P->opaque) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->destructor = pj_cass_destructor; Q->en = pj_enfn(P->n); if (nullptr == Q->en) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->m0 = pj_mlfn(P->phi0, sin(P->phi0), cos(P->phi0), Q->en); if (pj_param_exists(P->params, "hyperbolic")) Q->hyperbolic = true; P->inv = cass_e_inverse; P->fwd = cass_e_forward; return P; } #undef C1 #undef C2 #undef C3 #undef C4 #undef C5
cpp
PROJ
data/projects/PROJ/src/projections/wag2.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(wag2, "Wagner II") "\n\tPCyl, Sph"; #define C_x 0.92483 #define C_y 1.38725 #define C_p1 0.88022 #define C_p2 0.88550 static PJ_XY wag2_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; lp.phi = aasin(P->ctx, C_p1 * sin(C_p2 * lp.phi)); xy.x = C_x * lp.lam * cos(lp.phi); xy.y = C_y * lp.phi; return (xy); } static PJ_LP wag2_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = xy.y / C_y; lp.lam = xy.x / (C_x * cos(lp.phi)); lp.phi = aasin(P->ctx, sin(lp.phi) / C_p1) / C_p2; return (lp); } PJ *PJ_PROJECTION(wag2) { P->es = 0.; P->inv = wag2_s_inverse; P->fwd = wag2_s_forward; return P; } #undef C_x #undef C_y #undef C_p1 #undef C_p2
cpp
PROJ
data/projects/PROJ/src/projections/natearth.cpp
/* The Natural Earth projection was designed by Tom Patterson, US National Park Service, in 2007, using Flex Projector. The shape of the original projection was defined at every 5 degrees and piece-wise cubic spline interpolation was used to compute the complete graticule. The code here uses polynomial functions instead of cubic splines and is therefore much simpler to program. The polynomial approximation was developed by Bojan Savric, in collaboration with Tom Patterson and Bernhard Jenny, Institute of Cartography, ETH Zurich. It slightly deviates from Patterson's original projection by adding additional curvature to meridians where they meet the horizontal pole line. This improvement is by intention and designed in collaboration with Tom Patterson. Port to PROJ.4 by Bernhard Jenny, 6 June 2011 */ #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(natearth, "Natural Earth") "\n\tPCyl, Sph"; #define A0 0.8707 #define A1 -0.131979 #define A2 -0.013791 #define A3 0.003971 #define A4 -0.001529 #define B0 1.007226 #define B1 0.015085 #define B2 -0.044475 #define B3 0.028874 #define B4 -0.005916 #define C0 B0 #define C1 (3 * B1) #define C2 (7 * B2) #define C3 (9 * B3) #define C4 (11 * B4) #define EPS 1e-11 #define MAX_Y (0.8707 * 0.52 * M_PI) /* Not sure at all of the appropriate number for MAX_ITER... */ #define MAX_ITER 100 static PJ_XY natearth_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double phi2, phi4; (void)P; phi2 = lp.phi * lp.phi; phi4 = phi2 * phi2; xy.x = lp.lam * (A0 + phi2 * (A1 + phi2 * (A2 + phi4 * phi2 * (A3 + phi2 * A4)))); xy.y = lp.phi * (B0 + phi2 * (B1 + phi4 * (B2 + B3 * phi2 + B4 * phi4))); return xy; } static PJ_LP natearth_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double yc, y2, y4, f, fder; int i; (void)P; /* make sure y is inside valid range */ if (xy.y > MAX_Y) { xy.y = MAX_Y; } else if (xy.y < -MAX_Y) { xy.y = -MAX_Y; } /* latitude */ yc = xy.y; for (i = MAX_ITER; i; --i) { /* Newton-Raphson */ y2 = yc * yc; y4 = y2 * y2; f = (yc * (B0 + y2 * (B1 + y4 * (B2 + B3 * y2 + B4 * y4)))) - xy.y; fder = C0 + y2 * (C1 + y4 * (C2 + C3 * y2 + C4 * y4)); const double tol = f / fder; yc -= tol; if (fabs(tol) < EPS) { break; } } if (i == 0) proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.phi = yc; /* longitude */ y2 = yc * yc; lp.lam = xy.x / (A0 + y2 * (A1 + y2 * (A2 + y2 * y2 * y2 * (A3 + y2 * A4)))); return lp; } PJ *PJ_PROJECTION(natearth) { P->es = 0; P->inv = natearth_s_inverse; P->fwd = natearth_s_forward; return P; } #undef A0 #undef A1 #undef A2 #undef A3 #undef A4 #undef A5 #undef B0 #undef B1 #undef B2 #undef B3 #undef C0 #undef C1 #undef C2 #undef C3 #undef EPS #undef MAX_Y #undef MAX_ITER
cpp
PROJ
data/projects/PROJ/src/projections/gnom.cpp
#include <errno.h> #include <float.h> #include <math.h> #include "geodesic.h" #include "proj.h" #include "proj_internal.h" PROJ_HEAD(gnom, "Gnomonic") "\n\tAzi, Sph"; #define EPS10 1.e-10 namespace pj_gnom_ns { enum Mode { N_POLE = 0, S_POLE = 1, EQUIT = 2, OBLIQ = 3 }; } namespace { // anonymous namespace struct pj_gnom_data { double sinph0; double cosph0; enum pj_gnom_ns::Mode mode; struct geod_geodesic g; }; } // anonymous namespace static PJ_XY gnom_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_gnom_data *Q = static_cast<struct pj_gnom_data *>(P->opaque); double coslam, cosphi, sinphi; sinphi = sin(lp.phi); cosphi = cos(lp.phi); coslam = cos(lp.lam); switch (Q->mode) { case pj_gnom_ns::EQUIT: xy.y = cosphi * coslam; break; case pj_gnom_ns::OBLIQ: xy.y = Q->sinph0 * sinphi + Q->cosph0 * cosphi * coslam; break; case pj_gnom_ns::S_POLE: xy.y = -sinphi; break; case pj_gnom_ns::N_POLE: xy.y = sinphi; break; } if (xy.y <= EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.x = (xy.y = 1. / xy.y) * cosphi * sin(lp.lam); switch (Q->mode) { case pj_gnom_ns::EQUIT: xy.y *= sinphi; break; case pj_gnom_ns::OBLIQ: xy.y *= Q->cosph0 * sinphi - Q->sinph0 * cosphi * coslam; break; case pj_gnom_ns::N_POLE: coslam = -coslam; PROJ_FALLTHROUGH; case pj_gnom_ns::S_POLE: xy.y *= cosphi * coslam; break; } return xy; } static PJ_LP gnom_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_gnom_data *Q = static_cast<struct pj_gnom_data *>(P->opaque); double rh, cosz, sinz; rh = hypot(xy.x, xy.y); sinz = sin(lp.phi = atan(rh)); cosz = sqrt(1. - sinz * sinz); if (fabs(rh) <= EPS10) { lp.phi = P->phi0; lp.lam = 0.; } else { switch (Q->mode) { case pj_gnom_ns::OBLIQ: lp.phi = cosz * Q->sinph0 + xy.y * sinz * Q->cosph0 / rh; if (fabs(lp.phi) >= 1.) lp.phi = lp.phi > 0. ? M_HALFPI : -M_HALFPI; else lp.phi = asin(lp.phi); xy.y = (cosz - Q->sinph0 * sin(lp.phi)) * rh; xy.x *= sinz * Q->cosph0; break; case pj_gnom_ns::EQUIT: lp.phi = xy.y * sinz / rh; if (fabs(lp.phi) >= 1.) lp.phi = lp.phi > 0. ? M_HALFPI : -M_HALFPI; else lp.phi = asin(lp.phi); xy.y = cosz * rh; xy.x *= sinz; break; case pj_gnom_ns::S_POLE: lp.phi -= M_HALFPI; break; case pj_gnom_ns::N_POLE: lp.phi = M_HALFPI - lp.phi; xy.y = -xy.y; break; } lp.lam = atan2(xy.x, xy.y); } return lp; } static PJ_XY gnom_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_gnom_data *Q = static_cast<struct pj_gnom_data *>(P->opaque); double lat0 = P->phi0 / DEG_TO_RAD, lon0 = 0, lat1 = lp.phi / DEG_TO_RAD, lon1 = lp.lam / DEG_TO_RAD, azi0, m, M; geod_geninverse(&Q->g, lat0, lon0, lat1, lon1, nullptr, &azi0, nullptr, &m, &M, nullptr, nullptr); if (M <= 0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); xy.x = xy.y = HUGE_VAL; } else { double rho = m / M; azi0 *= DEG_TO_RAD; xy.x = rho * sin(azi0); xy.y = rho * cos(azi0); } return xy; } static PJ_LP gnom_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ constexpr int numit_ = 10; static const double eps_ = 0.01 * sqrt(DBL_EPSILON); PJ_LP lp = {0.0, 0.0}; struct pj_gnom_data *Q = static_cast<struct pj_gnom_data *>(P->opaque); double lat0 = P->phi0 / DEG_TO_RAD, lon0 = 0, azi0 = atan2(xy.x, xy.y) / DEG_TO_RAD, // Clockwise from north rho = hypot(xy.x, xy.y), s = atan(rho); bool little = rho <= 1; if (!little) rho = 1 / rho; struct geod_geodesicline l; geod_lineinit(&l, &Q->g, lat0, lon0, azi0, GEOD_LATITUDE | GEOD_LONGITUDE | GEOD_DISTANCE_IN | GEOD_REDUCEDLENGTH | GEOD_GEODESICSCALE); int count = numit_, trip = 0; double lat1 = 0, lon1 = 0; while (count--) { double m, M; geod_genposition(&l, 0, s, &lat1, &lon1, nullptr, &s, &m, &M, nullptr, nullptr); if (trip) break; // If little, solve rho(s) = rho with drho(s)/ds = 1/M^2 // else solve 1/rho(s) = 1/rho with d(1/rho(s))/ds = -1/m^2 double ds = little ? (m - rho * M) * M : (rho * m - M) * m; s -= ds; // Reversed test to allow escape with NaNs if (!(fabs(ds) >= eps_)) ++trip; } if (trip) { lp.phi = lat1 * DEG_TO_RAD; lp.lam = lon1 * DEG_TO_RAD; } else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.phi = lp.lam = HUGE_VAL; } return lp; } PJ *PJ_PROJECTION(gnom) { struct pj_gnom_data *Q = static_cast<struct pj_gnom_data *>( calloc(1, sizeof(struct pj_gnom_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (P->es == 0) { if (fabs(fabs(P->phi0) - M_HALFPI) < EPS10) { Q->mode = P->phi0 < 0. ? pj_gnom_ns::S_POLE : pj_gnom_ns::N_POLE; } else if (fabs(P->phi0) < EPS10) { Q->mode = pj_gnom_ns::EQUIT; } else { Q->mode = pj_gnom_ns::OBLIQ; Q->sinph0 = sin(P->phi0); Q->cosph0 = cos(P->phi0); } P->inv = gnom_s_inverse; P->fwd = gnom_s_forward; } else { geod_init(&Q->g, 1, P->f); P->inv = gnom_e_inverse; P->fwd = gnom_e_forward; } P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/comill.cpp
/* The Compact Miller projection was designed by Tom Patterson, US National Park Service, in 2014. The polynomial equation was developed by Bojan Savric and Bernhard Jenny, College of Earth, Ocean, and Atmospheric Sciences, Oregon State University. Port to PROJ.4 by Bojan Savric, 4 April 2016 */ #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(comill, "Compact Miller") "\n\tCyl, Sph"; #define K1 0.9902 #define K2 0.1604 #define K3 -0.03054 #define C1 K1 #define C2 (3 * K2) #define C3 (5 * K3) #define EPS 1e-11 #define MAX_Y (0.6000207669862655 * M_PI) /* Not sure at all of the appropriate number for MAX_ITER... */ #define MAX_ITER 100 static PJ_XY comill_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double lat_sq; (void)P; /* silence unused parameter warnings */ lat_sq = lp.phi * lp.phi; xy.x = lp.lam; xy.y = lp.phi * (K1 + lat_sq * (K2 + K3 * lat_sq)); return xy; } static PJ_LP comill_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double yc, tol, y2, f, fder; int i; (void)P; /* silence unused parameter warnings */ /* make sure y is inside valid range */ if (xy.y > MAX_Y) { xy.y = MAX_Y; } else if (xy.y < -MAX_Y) { xy.y = -MAX_Y; } /* latitude */ yc = xy.y; for (i = MAX_ITER; i; --i) { /* Newton-Raphson */ y2 = yc * yc; f = (yc * (K1 + y2 * (K2 + K3 * y2))) - xy.y; fder = C1 + y2 * (C2 + C3 * y2); tol = f / fder; yc -= tol; if (fabs(tol) < EPS) { break; } } if (i == 0) proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.phi = yc; /* longitude */ lp.lam = xy.x; return lp; } PJ *PJ_PROJECTION(comill) { P->es = 0; P->inv = comill_s_inverse; P->fwd = comill_s_forward; return P; } #undef K1 #undef K2 #undef K3 #undef C1 #undef C2 #undef C3 #undef EPS #undef MAX_Y #undef MAX_ITER
cpp
PROJ
data/projects/PROJ/src/projections/sch.cpp
/****************************************************************************** * Project: SCH Coordinate system * Purpose: Implementation of SCH Coordinate system * References : * 1. Hensley. Scott. SCH Coordinates and various transformations. June 15, *2000. * 2. Buckley, Sean Monroe. Radar interferometry measurement of land *subsidence. 2000.. PhD Thesis. UT Austin. (Appendix) * 3. Hensley, Scott, Elaine Chapin, and T. Michel. "Improved processing of *AIRSAR data based on the GeoSAR processor." Airsar earth science and *applications workshop, March. 2002. *(http://airsar.jpl.nasa.gov/documents/workshop2002/papers/T3.pdf) * * Author: Piyush Agram ([email protected]) * Copyright (c) 2015 California Institute of Technology. * Government sponsorship acknowledged. * * NOTE: The SCH coordinate system is a sensor aligned coordinate system * developed at JPL for radar mapping missions. Details pertaining to the * coordinate system have been release in the public domain (see references *above). This code is an independent implementation of the SCH coordinate *system that conforms to the PROJ.4 conventions and uses the details presented *in these publicly released documents. All credit for the development of the *coordinate system and its use should be directed towards the original *developers at JPL. ****************************************************************************** * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_sch_data { double plat; /*Peg Latitude */ double plon; /*Peg Longitude*/ double phdg; /*Peg heading */ double h0; /*Average altitude */ double transMat[9]; double xyzoff[3]; double rcurv; PJ *cart; PJ *cart_sph; }; } // anonymous namespace PROJ_HEAD(sch, "Spherical Cross-track Height") "\n\tMisc\n\tplat_0= plon_0= phdg_0= [h_0=]"; static PJ_LPZ sch_inverse3d(PJ_XYZ xyz, PJ *P) { struct pj_sch_data *Q = static_cast<struct pj_sch_data *>(P->opaque); PJ_LPZ lpz; lpz.lam = xyz.x * (P->a / Q->rcurv); lpz.phi = xyz.y * (P->a / Q->rcurv); lpz.z = xyz.z; xyz = Q->cart_sph->fwd3d(lpz, Q->cart_sph); /* Apply rotation */ xyz = {Q->transMat[0] * xyz.x + Q->transMat[1] * xyz.y + Q->transMat[2] * xyz.z, Q->transMat[3] * xyz.x + Q->transMat[4] * xyz.y + Q->transMat[5] * xyz.z, Q->transMat[6] * xyz.x + Q->transMat[7] * xyz.y + Q->transMat[8] * xyz.z}; /* Apply offset */ xyz.x += Q->xyzoff[0]; xyz.y += Q->xyzoff[1]; xyz.z += Q->xyzoff[2]; /* Convert geocentric coordinates to lat long */ return Q->cart->inv3d(xyz, Q->cart); } static PJ_XYZ sch_forward3d(PJ_LPZ lpz, PJ *P) { struct pj_sch_data *Q = static_cast<struct pj_sch_data *>(P->opaque); /* Convert lat long to geocentric coordinates */ PJ_XYZ xyz = Q->cart->fwd3d(lpz, Q->cart); /* Adjust for offset */ xyz.x -= Q->xyzoff[0]; xyz.y -= Q->xyzoff[1]; xyz.z -= Q->xyzoff[2]; /* Apply rotation */ xyz = {Q->transMat[0] * xyz.x + Q->transMat[3] * xyz.y + Q->transMat[6] * xyz.z, Q->transMat[1] * xyz.x + Q->transMat[4] * xyz.y + Q->transMat[7] * xyz.z, Q->transMat[2] * xyz.x + Q->transMat[5] * xyz.y + Q->transMat[8] * xyz.z}; /* Convert to local lat,long */ lpz = Q->cart_sph->inv3d(xyz, Q->cart_sph); /* Scale by radius */ xyz.x = lpz.lam * (Q->rcurv / P->a); xyz.y = lpz.phi * (Q->rcurv / P->a); xyz.z = lpz.z; return xyz; } static PJ *pj_sch_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; auto Q = static_cast<struct pj_sch_data *>(P->opaque); if (Q) { if (Q->cart) Q->cart->destructor(Q->cart, errlev); if (Q->cart_sph) Q->cart_sph->destructor(Q->cart_sph, errlev); } return pj_default_destructor(P, errlev); } static PJ *pj_sch_setup(PJ *P) { /* general initialization */ struct pj_sch_data *Q = static_cast<struct pj_sch_data *>(P->opaque); /* Setup original geocentric system */ // Pass a dummy ellipsoid definition that will be overridden just afterwards Q->cart = proj_create(P->ctx, "+proj=cart +a=1"); if (Q->cart == nullptr) return pj_sch_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); /* inherit ellipsoid definition from P to Q->cart */ pj_inherit_ellipsoid_def(P, Q->cart); const double clt = cos(Q->plat); const double slt = sin(Q->plat); const double clo = cos(Q->plon); const double slo = sin(Q->plon); /* Estimate the radius of curvature for given peg */ const double temp = sqrt(1.0 - (P->es) * slt * slt); const double reast = (P->a) / temp; const double rnorth = (P->a) * (1.0 - (P->es)) / pow(temp, 3); const double chdg = cos(Q->phdg); const double shdg = sin(Q->phdg); Q->rcurv = Q->h0 + (reast * rnorth) / (reast * chdg * chdg + rnorth * shdg * shdg); /* Set up local sphere at the given peg point */ Q->cart_sph = proj_create(P->ctx, "+proj=cart +a=1"); if (Q->cart_sph == nullptr) return pj_sch_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); pj_calc_ellipsoid_params(Q->cart_sph, Q->rcurv, 0); /* Set up the transformation matrices */ Q->transMat[0] = clt * clo; Q->transMat[1] = -shdg * slo - slt * clo * chdg; Q->transMat[2] = slo * chdg - slt * clo * shdg; Q->transMat[3] = clt * slo; Q->transMat[4] = clo * shdg - slt * slo * chdg; Q->transMat[5] = -clo * chdg - slt * slo * shdg; Q->transMat[6] = slt; Q->transMat[7] = clt * chdg; Q->transMat[8] = clt * shdg; PJ_LPZ lpz; lpz.lam = Q->plon; lpz.phi = Q->plat; lpz.z = Q->h0; PJ_XYZ xyz = Q->cart->fwd3d(lpz, Q->cart); Q->xyzoff[0] = xyz.x - (Q->rcurv) * clt * clo; Q->xyzoff[1] = xyz.y - (Q->rcurv) * clt * slo; Q->xyzoff[2] = xyz.z - (Q->rcurv) * slt; P->fwd3d = sch_forward3d; P->inv3d = sch_inverse3d; return P; } PJ *PJ_PROJECTION(sch) { struct pj_sch_data *Q = static_cast<struct pj_sch_data *>( calloc(1, sizeof(struct pj_sch_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_sch_destructor; Q->h0 = 0.0; /* Check if peg latitude was defined */ if (pj_param(P->ctx, P->params, "tplat_0").i) Q->plat = pj_param(P->ctx, P->params, "rplat_0").f; else { proj_log_error(P, _("Missing parameter plat_0.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } /* Check if peg longitude was defined */ if (pj_param(P->ctx, P->params, "tplon_0").i) Q->plon = pj_param(P->ctx, P->params, "rplon_0").f; else { proj_log_error(P, _("Missing parameter plon_0.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } /* Check if peg heading is defined */ if (pj_param(P->ctx, P->params, "tphdg_0").i) Q->phdg = pj_param(P->ctx, P->params, "rphdg_0").f; else { proj_log_error(P, _("Missing parameter phdg_0.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } /* Check if average height was defined - If so read it in */ if (pj_param(P->ctx, P->params, "th_0").i) Q->h0 = pj_param(P->ctx, P->params, "dh_0").f; return pj_sch_setup(P); }
cpp
PROJ
data/projects/PROJ/src/projections/poly.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(poly, "Polyconic (American)") "\n\tConic, Sph&Ell"; namespace { // anonymous namespace struct pj_poly_data { double ml0; double *en; }; } // anonymous namespace #define TOL 1e-10 #define CONV 1e-10 #define N_ITER 10 #define I_ITER 20 #define ITOL 1.e-12 static PJ_XY poly_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_poly_data *Q = static_cast<struct pj_poly_data *>(P->opaque); double ms, sp, cp; if (fabs(lp.phi) <= TOL) { xy.x = lp.lam; xy.y = -Q->ml0; } else { sp = sin(lp.phi); cp = cos(lp.phi); ms = fabs(cp) > TOL ? pj_msfn(sp, cp, P->es) / sp : 0.; lp.lam *= sp; xy.x = ms * sin(lp.lam); xy.y = (pj_mlfn(lp.phi, sp, cp, Q->en) - Q->ml0) + ms * (1. - cos(lp.lam)); } return xy; } static PJ_XY poly_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_poly_data *Q = static_cast<struct pj_poly_data *>(P->opaque); if (fabs(lp.phi) <= TOL) { xy.x = lp.lam; xy.y = Q->ml0; } else { const double cot = 1. / tan(lp.phi); const double E = lp.lam * sin(lp.phi); xy.x = sin(E) * cot; xy.y = lp.phi - P->phi0 + cot * (1. - cos(E)); } return xy; } static PJ_LP poly_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_poly_data *Q = static_cast<struct pj_poly_data *>(P->opaque); xy.y += Q->ml0; if (fabs(xy.y) <= TOL) { lp.lam = xy.x; lp.phi = 0.; } else { int i; const double r = xy.y * xy.y + xy.x * xy.x; lp.phi = xy.y; for (i = I_ITER; i; --i) { const double sp = sin(lp.phi); const double cp = cos(lp.phi); const double s2ph = sp * cp; if (fabs(cp) < ITOL) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } double mlp = sqrt(1. - P->es * sp * sp); const double c = sp * mlp / cp; const double ml = pj_mlfn(lp.phi, sp, cp, Q->en); const double mlb = ml * ml + r; mlp = P->one_es / (mlp * mlp * mlp); const double dPhi = (ml + ml + c * mlb - 2. * xy.y * (c * ml + 1.)) / (P->es * s2ph * (mlb - 2. * xy.y * ml) / c + 2. * (xy.y - ml) * (c * mlp - 1. / s2ph) - mlp - mlp); lp.phi += dPhi; if (fabs(dPhi) <= ITOL) break; } if (!i) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } const double c = sin(lp.phi); lp.lam = asin(xy.x * tan(lp.phi) * sqrt(1. - P->es * c * c)) / sin(lp.phi); } return lp; } static PJ_LP poly_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; if (fabs(xy.y = P->phi0 + xy.y) <= TOL) { lp.lam = xy.x; lp.phi = 0.; } else { lp.phi = xy.y; const double B = xy.x * xy.x + xy.y * xy.y; int i = N_ITER; while (true) { const double tp = tan(lp.phi); const double dphi = (xy.y * (lp.phi * tp + 1.) - lp.phi - .5 * (lp.phi * lp.phi + B) * tp) / ((lp.phi - xy.y) / tp - 1.); lp.phi -= dphi; if (!(fabs(dphi) > CONV)) break; --i; if (i == 0) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } } lp.lam = asin(xy.x * tan(lp.phi)) / sin(lp.phi); } return lp; } static PJ *pj_poly_destructor(PJ *P, int errlev) { if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); if (static_cast<struct pj_poly_data *>(P->opaque)->en) free(static_cast<struct pj_poly_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(poly) { struct pj_poly_data *Q = static_cast<struct pj_poly_data *>( calloc(1, sizeof(struct pj_poly_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_poly_destructor; if (P->es != 0.0) { if (!(Q->en = pj_enfn(P->n))) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->ml0 = pj_mlfn(P->phi0, sin(P->phi0), cos(P->phi0), Q->en); P->inv = poly_e_inverse; P->fwd = poly_e_forward; } else { Q->ml0 = -P->phi0; P->inv = poly_s_inverse; P->fwd = poly_s_forward; } return P; } #undef TOL #undef CONV #undef N_ITER #undef I_ITER #undef ITOL
cpp
PROJ
data/projects/PROJ/src/projections/eck1.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(eck1, "Eckert I") "\n\tPCyl, Sph"; #define FC 0.92131773192356127802 #define RP 0.31830988618379067154 static PJ_XY eck1_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = FC * lp.lam * (1. - RP * fabs(lp.phi)); xy.y = FC * lp.phi; return xy; } static PJ_LP eck1_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; lp.phi = xy.y / FC; lp.lam = xy.x / (FC * (1. - RP * fabs(lp.phi))); return (lp); } PJ *PJ_PROJECTION(eck1) { P->es = 0.0; P->inv = eck1_s_inverse; P->fwd = eck1_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/lagrng.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(lagrng, "Lagrange") "\n\tMisc Sph\n\tW="; #define TOL 1e-10 namespace { // anonymous namespace struct pj_lagrng { double a1; double a2; double hrw; double hw; double rw; double w; }; } // anonymous namespace static PJ_XY lagrng_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_lagrng *Q = static_cast<struct pj_lagrng *>(P->opaque); double v, c; const double sin_phi = sin(lp.phi); if (fabs(fabs(sin_phi) - 1) < TOL) { xy.x = 0; xy.y = lp.phi < 0 ? -2. : 2.; } else { v = Q->a1 * pow((1. + sin_phi) / (1. - sin_phi), Q->hrw); lp.lam *= Q->rw; c = 0.5 * (v + 1. / v) + cos(lp.lam); if (c < TOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.x = 2. * sin(lp.lam) / c; xy.y = (v - 1. / v) / c; } return xy; } static PJ_LP lagrng_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_lagrng *Q = static_cast<struct pj_lagrng *>(P->opaque); double c, x2, y2p, y2m; if (fabs(fabs(xy.y) - 2.) < TOL) { lp.phi = xy.y < 0 ? -M_HALFPI : M_HALFPI; lp.lam = 0; } else { x2 = xy.x * xy.x; y2p = 2. + xy.y; y2m = 2. - xy.y; c = y2p * y2m - x2; if (fabs(c) < TOL) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } lp.phi = 2. * atan(pow((y2p * y2p + x2) / (Q->a2 * (y2m * y2m + x2)), Q->hw)) - M_HALFPI; lp.lam = Q->w * atan2(4. * xy.x, c); } return lp; } PJ *PJ_PROJECTION(lagrng) { double sin_phi1; struct pj_lagrng *Q = static_cast<struct pj_lagrng *>(calloc(1, sizeof(struct pj_lagrng))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (pj_param(P->ctx, P->params, "tW").i) Q->w = pj_param(P->ctx, P->params, "dW").f; else Q->w = 2; if (Q->w <= 0) { proj_log_error(P, _("Invalid value for W: it should be > 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->hw = 0.5 * Q->w; Q->rw = 1. / Q->w; Q->hrw = 0.5 * Q->rw; sin_phi1 = sin(pj_param(P->ctx, P->params, "rlat_1").f); if (fabs(fabs(sin_phi1) - 1.) < TOL) { proj_log_error(P, _("Invalid value for lat_1: |lat_1| should be < 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->a1 = pow((1. - sin_phi1) / (1. + sin_phi1), Q->hrw); Q->a2 = Q->a1 * Q->a1; P->es = 0.; P->inv = lagrng_s_inverse; P->fwd = lagrng_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/vandg4.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(vandg4, "van der Grinten IV") "\n\tMisc Sph, no inv"; #define TOL 1e-10 static PJ_XY vandg4_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double x1, t, bt, ct, ft, bt2, ct2, dt, dt2; (void)P; if (fabs(lp.phi) < TOL) { xy.x = lp.lam; xy.y = 0.; } else if (fabs(lp.lam) < TOL || fabs(fabs(lp.phi) - M_HALFPI) < TOL) { xy.x = 0.; xy.y = lp.phi; } else { bt = fabs(M_TWO_D_PI * lp.phi); bt2 = bt * bt; ct = 0.5 * (bt * (8. - bt * (2. + bt2)) - 5.) / (bt2 * (bt - 1.)); ct2 = ct * ct; dt = M_TWO_D_PI * lp.lam; dt = dt + 1. / dt; dt = sqrt(dt * dt - 4.); if ((fabs(lp.lam) - M_HALFPI) < 0.) dt = -dt; dt2 = dt * dt; x1 = bt + ct; x1 *= x1; t = bt + 3. * ct; ft = x1 * (bt2 + ct2 * dt2 - 1.) + (1. - bt2) * (bt2 * (t * t + 4. * ct2) + ct2 * (12. * bt * ct + 4. * ct2)); x1 = (dt * (x1 + ct2 - 1.) + 2. * sqrt(ft)) / (4. * x1 + dt2); xy.x = M_HALFPI * x1; xy.y = M_HALFPI * sqrt(1. + dt * fabs(x1) - x1 * x1); if (lp.lam < 0.) xy.x = -xy.x; if (lp.phi < 0.) xy.y = -xy.y; } return xy; } PJ *PJ_PROJECTION(vandg4) { P->es = 0.; P->fwd = vandg4_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/s2.cpp
/****************************************************************************** * Project: PROJ * Purpose: Implementing the S2 family of projections in PROJ * Author: Marcus Elia, <marcus at geopi.pe> * ****************************************************************************** * Copyright (c) 2021, Marcus Elia, <marcus at geopi.pe> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ***************************************************************************** * * This implements the S2 projection. This code is similar * to the QSC projection. * * * You have to choose one of the following projection centers, * corresponding to the centers of the six cube faces: * phi0 = 0.0, lam0 = 0.0 ("front" face) * phi0 = 0.0, lam0 = 90.0 ("right" face) * phi0 = 0.0, lam0 = 180.0 ("back" face) * phi0 = 0.0, lam0 = -90.0 ("left" face) * phi0 = 90.0 ("top" face) * phi0 = -90.0 ("bottom" face) * Other projection centers will not work! * * You must also choose which conversion from UV to ST coordinates * is used (linear, quadratic, tangent). Read about them in * https://github.com/google/s2geometry/blob/0c4c460bdfe696da303641771f9def900b3e440f/src/s2/s2coords.h * The S2 projection functions are adapted from the above link and the S2 * Math util functions are adapted from * https://github.com/google/s2geometry/blob/0c4c460bdfe696da303641771f9def900b3e440f/src/s2/util/math/vector.h ****************************************************************************/ /* enable predefined math constants M_* for MS Visual Studio */ #if defined(_MSC_VER) || defined(_WIN32) #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES #endif #endif #include <cmath> #include <cstdint> #include <errno.h> #include "proj.h" #include "proj_internal.h" /* The six cube faces. */ namespace { // anonymous namespace enum Face { FACE_FRONT = 0, FACE_RIGHT = 1, FACE_TOP = 2, FACE_BACK = 3, FACE_LEFT = 4, FACE_BOTTOM = 5 }; } // anonymous namespace enum S2ProjectionType { Linear, Quadratic, Tangent, NoUVtoST }; static std::map<std::string, S2ProjectionType> stringToS2ProjectionType{ {"linear", Linear}, {"quadratic", Quadratic}, {"tangent", Tangent}, {"none", NoUVtoST}}; namespace { // anonymous namespace struct pj_s2 { enum Face face; double a_squared; double one_minus_f; double one_minus_f_squared; S2ProjectionType UVtoST; }; } // anonymous namespace PROJ_HEAD(s2, "S2") "\n\tMisc, Sph&Ell"; /* The four areas on a cube face. AREA_0 is the area of definition, * the other three areas are counted counterclockwise. */ namespace { // anonymous namespace enum Area { AREA_0 = 0, AREA_1 = 1, AREA_2 = 2, AREA_3 = 3 }; } // anonymous namespace // ================================================= // // S2 Math Util // // ================================================= static PJ_XYZ Abs(const PJ_XYZ &p) { return {std::fabs(p.x), std::fabs(p.y), std::fabs(p.z)}; } // return the index of the largest component (fabs) static int LargestAbsComponent(const PJ_XYZ &p) { PJ_XYZ temp = Abs(p); return temp.x > temp.y ? temp.x > temp.z ? 0 : 2 : temp.y > temp.z ? 1 : 2; } // ================================================= // // S2 Projection Functions // // ================================================= // Unfortunately, tan(M_PI_4) is slightly less than 1.0. This isn't due to // a flaw in the implementation of tan(), it's because the derivative of // tan(x) at x=pi/4 is 2, and it happens that the two adjacent floating // point numbers on either side of the infinite-precision value of pi/4 have // tangents that are slightly below and slightly above 1.0 when rounded to // the nearest double-precision result. static double STtoUV(double s, S2ProjectionType s2_projection) { switch (s2_projection) { case Linear: return 2 * s - 1; break; case Quadratic: if (s >= 0.5) return (1 / 3.) * (4 * s * s - 1); else return (1 / 3.) * (1 - 4 * (1 - s) * (1 - s)); break; case Tangent: s = std::tan(M_PI_2 * s - M_PI_4); return s + (1.0 / static_cast<double>(static_cast<std::int64_t>(1) << 53)) * s; break; default: return s; } } static double UVtoST(double u, S2ProjectionType s2_projection) { switch (s2_projection) { case Linear: return 0.5 * (u + 1); break; case Quadratic: if (u >= 0) return 0.5 * std::sqrt(1 + 3 * u); else return 1 - 0.5 * std::sqrt(1 - 3 * u); break; case Tangent: { volatile double a = std::atan(u); return (2 * M_1_PI) * (a + M_PI_4); } break; default: return u; } } inline PJ_XYZ FaceUVtoXYZ(int face, double u, double v) { switch (face) { case 0: return {1, u, v}; case 1: return {-u, 1, v}; case 2: return {-u, -v, 1}; case 3: return {-1, -v, -u}; case 4: return {v, -1, -u}; default: return {v, u, -1}; } } inline PJ_XYZ FaceUVtoXYZ(int face, const PJ_XY &uv) { return FaceUVtoXYZ(face, uv.x, uv.y); } inline void ValidFaceXYZtoUV(int face, const PJ_XYZ &p, double *pu, double *pv) { switch (face) { case 0: *pu = p.y / p.x; *pv = p.z / p.x; break; case 1: *pu = -p.x / p.y; *pv = p.z / p.y; break; case 2: *pu = -p.x / p.z; *pv = -p.y / p.z; break; case 3: *pu = p.z / p.x; *pv = p.y / p.x; break; case 4: *pu = p.z / p.y; *pv = -p.x / p.y; break; default: *pu = -p.y / p.z; *pv = -p.x / p.z; break; } } inline void ValidFaceXYZtoUV(int face, const PJ_XYZ &p, PJ_XY *puv) { ValidFaceXYZtoUV(face, p, &(*puv).x, &(*puv).y); } inline int GetFace(const PJ_XYZ &p) { int face = LargestAbsComponent(p); double pFace; switch (face) { case 0: pFace = p.x; break; case 1: pFace = p.y; break; default: pFace = p.z; break; } if (pFace < 0) face += 3; return face; } inline int XYZtoFaceUV(const PJ_XYZ &p, double *pu, double *pv) { int face = GetFace(p); ValidFaceXYZtoUV(face, p, pu, pv); return face; } inline int XYZtoFaceUV(const PJ_XYZ &p, PJ_XY *puv) { return XYZtoFaceUV(p, &(*puv).x, &(*puv).y); } inline bool FaceXYZtoUV(int face, const PJ_XYZ &p, double *pu, double *pv) { double pFace; switch (face) { case 0: pFace = p.x; break; case 1: pFace = p.y; break; case 2: pFace = p.z; break; case 3: pFace = p.x; break; case 4: pFace = p.y; break; default: pFace = p.z; break; } if (face < 3) { if (pFace <= 0) return false; } else { if (pFace >= 0) return false; } ValidFaceXYZtoUV(face, p, pu, pv); return true; } inline bool FaceXYZtoUV(int face, const PJ_XYZ &p, PJ_XY *puv) { return FaceXYZtoUV(face, p, &(*puv).x, &(*puv).y); } // This function inverts ValidFaceXYZtoUV() inline bool UVtoSphereXYZ(int face, double u, double v, PJ_XYZ *xyz) { double major_coord = 1 / sqrt(1 + u * u + v * v); double minor_coord_1 = u * major_coord; double minor_coord_2 = v * major_coord; switch (face) { case 0: xyz->x = major_coord; xyz->y = minor_coord_1; xyz->z = minor_coord_2; break; case 1: xyz->x = -minor_coord_1; xyz->y = major_coord; xyz->z = minor_coord_2; break; case 2: xyz->x = -minor_coord_1; xyz->y = -minor_coord_2; xyz->z = major_coord; break; case 3: xyz->x = -major_coord; xyz->y = -minor_coord_2; xyz->z = -minor_coord_1; break; case 4: xyz->x = minor_coord_2; xyz->y = -major_coord; xyz->z = -minor_coord_1; break; default: xyz->x = minor_coord_2; xyz->y = minor_coord_1; xyz->z = -major_coord; break; } return true; } // ============================================ // // The Forward and Inverse Functions // // ============================================ static PJ_XY s2_forward(PJ_LP lp, PJ *P) { struct pj_s2 *Q = static_cast<struct pj_s2 *>(P->opaque); double lat; /* Convert the geodetic latitude to a geocentric latitude. * This corresponds to the shift from the ellipsoid to the sphere * described in [LK12]. */ if (P->es != 0.0) { lat = atan(Q->one_minus_f_squared * tan(lp.phi)); } else { lat = lp.phi; } // Convert the lat/long to x,y,z on the unit sphere double x, y, z; double sinlat, coslat; double sinlon, coslon; sinlat = sin(lat); coslat = cos(lat); sinlon = sin(lp.lam); coslon = cos(lp.lam); x = coslat * coslon; y = coslat * sinlon; z = sinlat; PJ_XYZ spherePoint{x, y, z}; PJ_XY uvCoords; ValidFaceXYZtoUV(Q->face, spherePoint, &uvCoords.x, &uvCoords.y); double s = UVtoST(uvCoords.x, Q->UVtoST); double t = UVtoST(uvCoords.y, Q->UVtoST); return {s, t}; } static PJ_LP s2_inverse(PJ_XY xy, PJ *P) { PJ_LP lp = {0.0, 0.0}; struct pj_s2 *Q = static_cast<struct pj_s2 *>(P->opaque); // Do the S2 projections to get from s,t to u,v to x,y,z double u = STtoUV(xy.x, Q->UVtoST); double v = STtoUV(xy.y, Q->UVtoST); PJ_XYZ sphereCoords; UVtoSphereXYZ(Q->face, u, v, &sphereCoords); double q = sphereCoords.x; double r = sphereCoords.y; double s = sphereCoords.z; // Get the spherical angles from the x y z lp.phi = acos(-s) - M_HALFPI; lp.lam = atan2(r, q); /* Apply the shift from the sphere to the ellipsoid as described * in [LK12]. */ if (P->es != 0.0) { int invert_sign; volatile double tanphi, xa; invert_sign = (lp.phi < 0.0 ? 1 : 0); tanphi = tan(lp.phi); xa = P->b / sqrt(tanphi * tanphi + Q->one_minus_f_squared); lp.phi = atan(sqrt(Q->a_squared - xa * xa) / (Q->one_minus_f * xa)); if (invert_sign) { lp.phi = -lp.phi; } } return lp; } PJ *PJ_PROJECTION(s2) { struct pj_s2 *Q = static_cast<struct pj_s2 *>(calloc(1, sizeof(struct pj_s2))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* Determine which UVtoST function is to be used */ PROJVALUE maybeUVtoST = pj_param(P->ctx, P->params, "sUVtoST"); if (nullptr != maybeUVtoST.s) { try { Q->UVtoST = stringToS2ProjectionType.at(maybeUVtoST.s); } catch (const std::out_of_range &) { proj_log_error( P, _("Invalid value for s2 parameter: should be linear, " "quadratic, tangent, or none.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } else { Q->UVtoST = Quadratic; } P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_PROJECTED; P->from_greenwich = -P->lam0; P->inv = s2_inverse; P->fwd = s2_forward; /* Determine the cube face from the center of projection. */ if (P->phi0 >= M_HALFPI - M_FORTPI / 2.0) { Q->face = FACE_TOP; } else if (P->phi0 <= -(M_HALFPI - M_FORTPI / 2.0)) { Q->face = FACE_BOTTOM; } else if (fabs(P->lam0) <= M_FORTPI) { Q->face = FACE_FRONT; } else if (fabs(P->lam0) <= M_HALFPI + M_FORTPI) { Q->face = (P->lam0 > 0.0 ? FACE_RIGHT : FACE_LEFT); } else { Q->face = FACE_BACK; } /* Fill in useful values for the ellipsoid <-> sphere shift * described in [LK12]. */ if (P->es != 0.0) { Q->a_squared = P->a * P->a; Q->one_minus_f = 1.0 - (P->a - P->b) / P->a; Q->one_minus_f_squared = Q->one_minus_f * Q->one_minus_f; } return P; }
cpp
PROJ
data/projects/PROJ/src/projections/isea.cpp
/* * This code was entirely written by Nathan Wagner * and is in the public domain. */ #include <errno.h> #include <float.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits> #include "proj.h" #include "proj_internal.h" #include <math.h> #define DEG36 0.62831853071795864768 #define DEG72 1.25663706143591729537 #define DEG90 M_PI_2 #define DEG108 1.88495559215387594306 #define DEG120 2.09439510239319549229 #define DEG144 2.51327412287183459075 #define DEG180 M_PI /* sqrt(5)/M_PI */ #define ISEA_SCALE 0.8301572857837594396028083 /* 26.565051177 degrees */ #define V_LAT 0.46364760899944494524 /* 52.62263186 */ #define E_RAD 0.91843818702186776133 /* 10.81231696 */ #define F_RAD 0.18871053072122403508 /* R tan(g) sin(60) */ #define TABLE_G 0.6615845383 /* H = 0.25 R tan g = */ #define TABLE_H 0.1909830056 /* in radians */ #define ISEA_STD_LAT 1.01722196792335072101 #define ISEA_STD_LONG .19634954084936207740 namespace { // anonymous namespace struct hex { int iso; long x, y, z; }; } // anonymous namespace /* y *must* be positive down as the xy /iso conversion assumes this */ static void hex_xy(struct hex *h) { if (!h->iso) return; if (h->x >= 0) { h->y = -h->y - (h->x + 1) / 2; } else { /* need to round toward -inf, not toward zero, so x-1 */ h->y = -h->y - h->x / 2; } h->iso = 0; } static void hex_iso(struct hex *h) { if (h->iso) return; if (h->x >= 0) { h->y = (-h->y - (h->x + 1) / 2); } else { /* need to round toward -inf, not toward zero, so x-1 */ h->y = (-h->y - (h->x) / 2); } h->z = -h->x - h->y; h->iso = 1; } static void hexbin2(double width, double x, double y, long *i, long *j) { double z, rx, ry, rz; double abs_dx, abs_dy, abs_dz; long ix, iy, iz, s; struct hex h; x = x / cos(30 * M_PI / 180.0); /* rotated X coord */ y = y - x / 2.0; /* adjustment for rotated X */ /* adjust for actual hexwidth */ if (width == 0) { throw "Division by zero"; } x /= width; y /= width; z = -x - y; rx = floor(x + 0.5); ix = lround(rx); ry = floor(y + 0.5); iy = lround(ry); rz = floor(z + 0.5); iz = lround(rz); if (fabs((double)ix + iy) > std::numeric_limits<int>::max() || fabs((double)ix + iy + iz) > std::numeric_limits<int>::max()) { throw "Integer overflow"; } s = ix + iy + iz; if (s) { abs_dx = fabs(rx - x); abs_dy = fabs(ry - y); abs_dz = fabs(rz - z); if (abs_dx >= abs_dy && abs_dx >= abs_dz) { ix -= s; } else if (abs_dy >= abs_dx && abs_dy >= abs_dz) { iy -= s; } else { iz -= s; } } h.x = ix; h.y = iy; h.z = iz; h.iso = 1; hex_xy(&h); *i = h.x; *j = h.y; } namespace { // anonymous namespace enum isea_poly { ISEA_NONE, ISEA_ICOSAHEDRON = 20 }; enum isea_topology { ISEA_HEXAGON = 6, ISEA_TRIANGLE = 3, ISEA_DIAMOND = 4 }; enum isea_address_form { ISEA_GEO, ISEA_Q2DI, ISEA_SEQNUM, ISEA_INTERLEAVE, ISEA_PLANE, ISEA_Q2DD, ISEA_PROJTRI, ISEA_VERTEX2DD, ISEA_HEX }; } // anonymous namespace namespace { // anonymous namespace struct isea_dgg { int polyhedron; /* ignored, icosahedron */ double o_lat, o_lon, o_az; /* orientation, radians */ int topology; /* ignored, hexagon */ int aperture; /* valid values depend on partitioning method */ int resolution; double radius; /* radius of the earth in meters, ignored 1.0 */ int output; /* an isea_address_form */ int triangle; /* triangle of last transformed point */ int quad; /* quad of last transformed point */ unsigned long serial; }; } // anonymous namespace namespace { // anonymous namespace struct isea_pt { double x, y; }; } // anonymous namespace namespace { // anonymous namespace struct isea_geo { double longitude, lat; }; } // anonymous namespace /* ENDINC */ namespace { // anonymous namespace enum snyder_polyhedron { SNYDER_POLY_HEXAGON, SNYDER_POLY_PENTAGON, SNYDER_POLY_TETRAHEDRON, SNYDER_POLY_CUBE, SNYDER_POLY_OCTAHEDRON, SNYDER_POLY_DODECAHEDRON, SNYDER_POLY_ICOSAHEDRON }; } // anonymous namespace namespace { // anonymous namespace struct snyder_constants { double g, G, theta; /* cppcheck-suppress unusedStructMember */ double ea_w, ea_a, ea_b, g_w, g_a, g_b; }; } // anonymous namespace /* TODO put these in radians to avoid a later conversion */ static const struct snyder_constants constants[] = { {23.80018260, 62.15458023, 60.0, 3.75, 1.033, 0.968, 5.09, 1.195, 1.0}, {20.07675127, 55.69063953, 54.0, 2.65, 1.030, 0.983, 3.59, 1.141, 1.027}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, {37.37736814, 36.0, 30.0, 17.27, 1.163, 0.860, 13.14, 1.584, 1.0}, }; static struct isea_geo vertex[] = { {0.0, DEG90}, {DEG180, V_LAT}, {-DEG108, V_LAT}, {-DEG36, V_LAT}, {DEG36, V_LAT}, {DEG108, V_LAT}, {-DEG144, -V_LAT}, {-DEG72, -V_LAT}, {0.0, -V_LAT}, {DEG72, -V_LAT}, {DEG144, -V_LAT}, {0.0, -DEG90}}; /* TODO make an isea_pt array of the vertices as well */ static int tri_v1[] = {0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 2, 3, 4, 5, 1, 11, 11, 11, 11, 11}; /* triangle Centers */ static const struct isea_geo icostriangles[] = { {0.0, 0.0}, {-DEG144, E_RAD}, {-DEG72, E_RAD}, {0.0, E_RAD}, {DEG72, E_RAD}, {DEG144, E_RAD}, {-DEG144, F_RAD}, {-DEG72, F_RAD}, {0.0, F_RAD}, {DEG72, F_RAD}, {DEG144, F_RAD}, {-DEG108, -F_RAD}, {-DEG36, -F_RAD}, {DEG36, -F_RAD}, {DEG108, -F_RAD}, {DEG180, -F_RAD}, {-DEG108, -E_RAD}, {-DEG36, -E_RAD}, {DEG36, -E_RAD}, {DEG108, -E_RAD}, {DEG180, -E_RAD}, }; static double az_adjustment(int triangle) { double adj; struct isea_geo v; struct isea_geo c; v = vertex[tri_v1[triangle]]; c = icostriangles[triangle]; /* TODO looks like the adjustment is always either 0 or 180 */ /* at least if you pick your vertex carefully */ adj = atan2(cos(v.lat) * sin(v.longitude - c.longitude), cos(c.lat) * sin(v.lat) - sin(c.lat) * cos(v.lat) * cos(v.longitude - c.longitude)); return adj; } static struct isea_pt isea_triangle_xy(int triangle) { struct isea_pt c; const double Rprime = 0.91038328153090290025; triangle = (triangle - 1) % 20; c.x = TABLE_G * ((triangle % 5) - 2) * 2.0; if (triangle > 9) { c.x += TABLE_G; } switch (triangle / 5) { case 0: c.y = 5.0 * TABLE_H; break; case 1: c.y = TABLE_H; break; case 2: c.y = -TABLE_H; break; case 3: c.y = -5.0 * TABLE_H; break; default: /* should be impossible */ exit(EXIT_FAILURE); } c.x *= Rprime; c.y *= Rprime; return c; } /* snyder eq 14 */ static double sph_azimuth(double f_lon, double f_lat, double t_lon, double t_lat) { double az; az = atan2(cos(t_lat) * sin(t_lon - f_lon), cos(f_lat) * sin(t_lat) - sin(f_lat) * cos(t_lat) * cos(t_lon - f_lon)); return az; } #ifdef _MSC_VER #pragma warning(push) /* disable unreachable code warning for return 0 */ #pragma warning(disable : 4702) #endif /* coord needs to be in radians */ static int isea_snyder_forward(struct isea_geo *ll, struct isea_pt *out) { int i; /* * spherical distance from center of polygon face to any of its * vertices on the globe */ double g; /* * spherical angle between radius vector to center and adjacent edge * of spherical polygon on the globe */ double G; /* * plane angle between radius vector to center and adjacent edge of * plane polygon */ double theta; /* additional variables from snyder */ double q, H, Ag, Azprime, Az, dprime, f, rho, x, y; /* variables used to store intermediate results */ double cot_theta, tan_g, az_offset; /* how many multiples of 60 degrees we adjust the azimuth */ int Az_adjust_multiples; struct snyder_constants c; /* * TODO by locality of reference, start by trying the same triangle * as last time */ /* TODO put these constants in as radians to begin with */ c = constants[SNYDER_POLY_ICOSAHEDRON]; theta = PJ_TORAD(c.theta); g = PJ_TORAD(c.g); G = PJ_TORAD(c.G); for (i = 1; i <= 20; i++) { double z; struct isea_geo center; center = icostriangles[i]; /* step 1 */ z = acos(sin(center.lat) * sin(ll->lat) + cos(center.lat) * cos(ll->lat) * cos(ll->longitude - center.longitude)); /* not on this triangle */ if (z > g + 0.000005) { /* TODO DBL_EPSILON */ continue; } Az = sph_azimuth(center.longitude, center.lat, ll->longitude, ll->lat); /* step 2 */ /* This calculates "some" vertex coordinate */ az_offset = az_adjustment(i); Az -= az_offset; /* TODO I don't know why we do this. It's not in snyder */ /* maybe because we should have picked a better vertex */ if (Az < 0.0) { Az += 2.0 * M_PI; } /* * adjust Az for the point to fall within the range of 0 to * 2(90 - theta) or 60 degrees for the hexagon, by * and therefore 120 degrees for the triangle * of the icosahedron * subtracting or adding multiples of 60 degrees to Az and * recording the amount of adjustment */ Az_adjust_multiples = 0; while (Az < 0.0) { Az += DEG120; Az_adjust_multiples--; } while (Az > DEG120 + DBL_EPSILON) { Az -= DEG120; Az_adjust_multiples++; } /* step 3 */ cot_theta = 1.0 / tan(theta); tan_g = tan(g); /* TODO this is a constant */ /* Calculate q from eq 9. */ /* TODO cot_theta is cot(30) */ q = atan2(tan_g, cos(Az) + sin(Az) * cot_theta); /* not in this triangle */ if (z > q + 0.000005) { continue; } /* step 4 */ /* Apply equations 5-8 and 10-12 in order */ /* eq 5 */ /* Rprime = 0.9449322893 * R; */ /* R' in the paper is for the truncated */ const double Rprime = 0.91038328153090290025; /* eq 6 */ H = acos(sin(Az) * sin(G) * cos(g) - cos(Az) * cos(G)); /* eq 7 */ /* Ag = (Az + G + H - DEG180) * M_PI * R * R / DEG180; */ Ag = Az + G + H - DEG180; /* eq 8 */ Azprime = atan2(2.0 * Ag, Rprime * Rprime * tan_g * tan_g - 2.0 * Ag * cot_theta); /* eq 10 */ /* cot(theta) = 1.73205080756887729355 */ dprime = Rprime * tan_g / (cos(Azprime) + sin(Azprime) * cot_theta); /* eq 11 */ f = dprime / (2.0 * Rprime * sin(q / 2.0)); /* eq 12 */ rho = 2.0 * Rprime * f * sin(z / 2.0); /* * add back the same 60 degree multiple adjustment from step * 2 to Azprime */ Azprime += DEG120 * Az_adjust_multiples; /* calculate rectangular coordinates */ x = rho * sin(Azprime); y = rho * cos(Azprime); /* * TODO * translate coordinates to the origin for the particular * hexagon on the flattened polyhedral map plot */ out->x = x; out->y = y; return i; } /* * should be impossible, this implies that the coordinate is not on * any triangle */ fprintf(stderr, "impossible transform: %f %f is not on any triangle\n", PJ_TODEG(ll->longitude), PJ_TODEG(ll->lat)); exit(EXIT_FAILURE); } #ifdef _MSC_VER #pragma warning(pop) #endif /* * return the new coordinates of any point in original coordinate system. * Define a point (newNPold) in original coordinate system as the North Pole in * new coordinate system, and the great circle connect the original and new * North Pole as the lon0 longitude in new coordinate system, given any point * in original coordinate system, this function return the new coordinates. */ /* formula from Snyder, Map Projections: A working manual, p31 */ /* * old north pole at np in new coordinates * could be simplified a bit with fewer intermediates * * TODO take a result pointer */ static struct isea_geo snyder_ctran(struct isea_geo *np, struct isea_geo *pt) { struct isea_geo npt; double alpha, phi, lambda, lambda0, beta, lambdap, phip; double sin_phip; double lp_b; /* lambda prime minus beta */ double cos_p, sin_a; phi = pt->lat; lambda = pt->longitude; alpha = np->lat; beta = np->longitude; lambda0 = beta; cos_p = cos(phi); sin_a = sin(alpha); /* mpawm 5-7 */ sin_phip = sin_a * sin(phi) - cos(alpha) * cos_p * cos(lambda - lambda0); /* mpawm 5-8b */ /* use the two argument form so we end up in the right quadrant */ lp_b = atan2(cos_p * sin(lambda - lambda0), (sin_a * cos_p * cos(lambda - lambda0) + cos(alpha) * sin(phi))); lambdap = lp_b + beta; /* normalize longitude */ /* TODO can we just do a modulus ? */ lambdap = fmod(lambdap, 2 * M_PI); while (lambdap > M_PI) lambdap -= 2 * M_PI; while (lambdap < -M_PI) lambdap += 2 * M_PI; phip = asin(sin_phip); npt.lat = phip; npt.longitude = lambdap; return npt; } static struct isea_geo isea_ctran(struct isea_geo *np, struct isea_geo *pt, double lon0) { struct isea_geo npt; np->longitude += M_PI; npt = snyder_ctran(np, pt); np->longitude -= M_PI; npt.longitude -= (M_PI - lon0 + np->longitude); /* * snyder is down tri 3, isea is along side of tri1 from vertex 0 to * vertex 1 these are 180 degrees apart */ npt.longitude += M_PI; /* normalize longitude */ npt.longitude = fmod(npt.longitude, 2 * M_PI); while (npt.longitude > M_PI) npt.longitude -= 2 * M_PI; while (npt.longitude < -M_PI) npt.longitude += 2 * M_PI; return npt; } /* fuller's at 5.2454 west, 2.3009 N, adjacent at 7.46658 deg */ static int isea_grid_init(struct isea_dgg *g) { if (!g) return 0; g->polyhedron = 20; g->o_lat = ISEA_STD_LAT; g->o_lon = ISEA_STD_LONG; g->o_az = 0.0; g->aperture = 4; g->resolution = 6; g->radius = 1.0; g->topology = 6; return 1; } static void isea_orient_isea(struct isea_dgg *g) { if (!g) return; g->o_lat = ISEA_STD_LAT; g->o_lon = ISEA_STD_LONG; g->o_az = 0.0; } static void isea_orient_pole(struct isea_dgg *g) { if (!g) return; g->o_lat = M_PI / 2.0; g->o_lon = 0.0; g->o_az = 0; } static int isea_transform(struct isea_dgg *g, struct isea_geo *in, struct isea_pt *out) { struct isea_geo i, pole; int tri; pole.lat = g->o_lat; pole.longitude = g->o_lon; i = isea_ctran(&pole, in, g->o_az); tri = isea_snyder_forward(&i, out); out->x *= g->radius; out->y *= g->radius; g->triangle = tri; return tri; } #define DOWNTRI(tri) (((tri - 1) / 5) % 2 == 1) static void isea_rotate(struct isea_pt *pt, double degrees) { double rad; double x, y; rad = -degrees * M_PI / 180.0; while (rad >= 2.0 * M_PI) rad -= 2.0 * M_PI; while (rad <= -2.0 * M_PI) rad += 2.0 * M_PI; x = pt->x * cos(rad) + pt->y * sin(rad); y = -pt->x * sin(rad) + pt->y * cos(rad); pt->x = x; pt->y = y; } static int isea_tri_plane(int tri, struct isea_pt *pt, double radius) { struct isea_pt tc; /* center of triangle */ if (DOWNTRI(tri)) { isea_rotate(pt, 180.0); } tc = isea_triangle_xy(tri); tc.x *= radius; tc.y *= radius; pt->x += tc.x; pt->y += tc.y; return tri; } /* convert projected triangle coords to quad xy coords, return quad number */ static int isea_ptdd(int tri, struct isea_pt *pt) { int downtri, quadz; downtri = (((tri - 1) / 5) % 2 == 1); quadz = ((tri - 1) % 5) + ((tri - 1) / 10) * 5 + 1; isea_rotate(pt, downtri ? 240.0 : 60.0); if (downtri) { pt->x += 0.5; /* pt->y += cos(30.0 * M_PI / 180.0); */ pt->y += .86602540378443864672; } return quadz; } static int isea_dddi_ap3odd(struct isea_dgg *g, int quadz, struct isea_pt *pt, struct isea_pt *di) { struct isea_pt v; double hexwidth; double sidelength; /* in hexes */ long d, i; long maxcoord; struct hex h; /* This is the number of hexes from apex to base of a triangle */ sidelength = (pow(2.0, g->resolution) + 1.0) / 2.0; /* apex to base is cos(30deg) */ hexwidth = cos(M_PI / 6.0) / sidelength; /* TODO I think sidelength is always x.5, so * (int)sidelength * 2 + 1 might be just as good */ maxcoord = lround((sidelength * 2.0)); v = *pt; hexbin2(hexwidth, v.x, v.y, &h.x, &h.y); h.iso = 0; hex_iso(&h); d = h.x - h.z; i = h.x + h.y + h.y; /* * you want to test for max coords for the next quad in the same * "row" first to get the case where both are max */ if (quadz <= 5) { if (d == 0 && i == maxcoord) { /* north pole */ quadz = 0; d = 0; i = 0; } else if (i == maxcoord) { /* upper right in next quad */ quadz += 1; if (quadz == 6) quadz = 1; i = maxcoord - d; d = 0; } else if (d == maxcoord) { /* lower right in quad to lower right */ quadz += 5; d = 0; } } else /* if (quadz >= 6) */ { if (i == 0 && d == maxcoord) { /* south pole */ quadz = 11; d = 0; i = 0; } else if (d == maxcoord) { /* lower right in next quad */ quadz += 1; if (quadz == 11) quadz = 6; d = maxcoord - i; i = 0; } else if (i == maxcoord) { /* upper right in quad to upper right */ quadz = (quadz - 4) % 5; i = 0; } } di->x = d; di->y = i; g->quad = quadz; return quadz; } static int isea_dddi(struct isea_dgg *g, int quadz, struct isea_pt *pt, struct isea_pt *di) { struct isea_pt v; double hexwidth; long sidelength; /* in hexes */ struct hex h; if (g->aperture == 3 && g->resolution % 2 != 0) { return isea_dddi_ap3odd(g, quadz, pt, di); } /* todo might want to do this as an iterated loop */ if (g->aperture > 0) { double sidelengthDouble = pow(g->aperture, g->resolution / 2.0); if (fabs(sidelengthDouble) > std::numeric_limits<int>::max()) { throw "Integer overflow"; } sidelength = lround(sidelengthDouble); } else { sidelength = g->resolution; } if (sidelength == 0) { throw "Division by zero"; } hexwidth = 1.0 / sidelength; v = *pt; isea_rotate(&v, -30.0); hexbin2(hexwidth, v.x, v.y, &h.x, &h.y); h.iso = 0; hex_iso(&h); /* we may actually be on another quad */ if (quadz <= 5) { if (h.x == 0 && h.z == -sidelength) { /* north pole */ quadz = 0; h.z = 0; h.y = 0; h.x = 0; } else if (h.z == -sidelength) { quadz = quadz + 1; if (quadz == 6) quadz = 1; h.y = sidelength - h.x; h.z = h.x - sidelength; h.x = 0; } else if (h.x == sidelength) { quadz += 5; h.y = -h.z; h.x = 0; } } else /* if (quadz >= 6) */ { if (h.z == 0 && h.x == sidelength) { /* south pole */ quadz = 11; h.x = 0; h.y = 0; h.z = 0; } else if (h.x == sidelength) { quadz = quadz + 1; if (quadz == 11) quadz = 6; h.x = h.y + sidelength; h.y = 0; h.z = -h.x; } else if (h.y == -sidelength) { quadz -= 4; h.y = 0; h.z = -h.x; } } di->x = h.x; di->y = -h.z; g->quad = quadz; return quadz; } static int isea_ptdi(struct isea_dgg *g, int tri, struct isea_pt *pt, struct isea_pt *di) { struct isea_pt v; int quadz; v = *pt; quadz = isea_ptdd(tri, &v); quadz = isea_dddi(g, quadz, &v, di); return quadz; } /* q2di to seqnum */ static long isea_disn(struct isea_dgg *g, int quadz, struct isea_pt *di) { long sidelength; long sn, height; long hexes; if (quadz == 0) { g->serial = 1; return g->serial; } /* hexes in a quad */ hexes = lround(pow(static_cast<double>(g->aperture), static_cast<double>(g->resolution))); if (quadz == 11) { g->serial = 1 + 10 * hexes + 1; return g->serial; } if (g->aperture == 3 && g->resolution % 2 == 1) { height = lround(floor((pow(g->aperture, (g->resolution - 1) / 2.0)))); sn = ((long)di->x) * height; sn += ((long)di->y) / height; sn += (quadz - 1) * hexes; sn += 2; } else { sidelength = lround((pow(g->aperture, g->resolution / 2.0))); sn = lround( floor(((quadz - 1) * hexes + sidelength * di->x + di->y + 2))); } g->serial = sn; return sn; } /* TODO just encode the quad in the d or i coordinate * quad is 0-11, which can be four bits. * d' = d << 4 + q, d = d' >> 4, q = d' & 0xf */ /* convert a q2di to global hex coord */ static int isea_hex(struct isea_dgg *g, int tri, struct isea_pt *pt, struct isea_pt *hex) { struct isea_pt v; #ifdef FIXME long sidelength; long d, i, x, y; #endif int quadz; quadz = isea_ptdi(g, tri, pt, &v); if (v.x < (INT_MIN >> 4) || v.x > (INT_MAX >> 4)) { throw "Invalid shift"; } hex->x = ((int)v.x * 16) + quadz; hex->y = v.y; return 1; #ifdef FIXME d = lround(floor(v.x)); i = lround(floor(v.y)); /* Aperture 3 odd resolutions */ if (g->aperture == 3 && g->resolution % 2 != 0) { long offset = lround((pow(3.0, g->resolution - 1) + 0.5)); d += offset * ((g->quadz - 1) % 5); i += offset * ((g->quadz - 1) % 5); if (quadz == 0) { d = 0; i = offset; } else if (quadz == 11) { d = 2 * offset; i = 0; } else if (quadz > 5) { d += offset; } x = (2 * d - i) / 3; y = (2 * i - d) / 3; hex->x = x + offset / 3; hex->y = y + 2 * offset / 3; return 1; } /* aperture 3 even resolutions and aperture 4 */ sidelength = lround((pow(g->aperture, g->resolution / 2.0))); if (g->quad == 0) { hex->x = 0; hex->y = sidelength; } else if (g->quad == 11) { hex->x = sidelength * 2; hex->y = 0; } else { hex->x = d + sidelength * ((g->quad - 1) % 5); if (g->quad > 5) hex->x += sidelength; hex->y = i + sidelength * ((g->quad - 1) % 5); } return 1; #endif } static struct isea_pt isea_forward(struct isea_dgg *g, struct isea_geo *in) { int tri; struct isea_pt out, coord; tri = isea_transform(g, in, &out); if (g->output == ISEA_PLANE) { isea_tri_plane(tri, &out, g->radius); return out; } /* convert to isea standard triangle size */ out.x = out.x / g->radius * ISEA_SCALE; out.y = out.y / g->radius * ISEA_SCALE; out.x += 0.5; out.y += 2.0 * .14433756729740644112; switch (g->output) { case ISEA_PROJTRI: /* nothing to do, already in projected triangle */ break; case ISEA_VERTEX2DD: g->quad = isea_ptdd(tri, &out); break; case ISEA_Q2DD: /* Same as above, we just don't print as much */ g->quad = isea_ptdd(tri, &out); break; case ISEA_Q2DI: g->quad = isea_ptdi(g, tri, &out, &coord); return coord; break; case ISEA_SEQNUM: isea_ptdi(g, tri, &out, &coord); /* disn will set g->serial */ isea_disn(g, g->quad, &coord); return coord; break; case ISEA_HEX: isea_hex(g, tri, &out, &coord); return coord; break; } return out; } /* * Proj 4 integration code follows */ PROJ_HEAD(isea, "Icosahedral Snyder Equal Area") "\n\tSph"; namespace { // anonymous namespace struct pj_isea_data { struct isea_dgg dgg; }; } // anonymous namespace static PJ_XY isea_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_isea_data *Q = static_cast<struct pj_isea_data *>(P->opaque); struct isea_pt out; struct isea_geo in; in.longitude = lp.lam; in.lat = lp.phi; try { out = isea_forward(&Q->dgg, &in); } catch (const char *) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } xy.x = out.x; xy.y = out.y; return xy; } PJ *PJ_PROJECTION(isea) { char *opt; struct pj_isea_data *Q = static_cast<struct pj_isea_data *>( calloc(1, sizeof(struct pj_isea_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; // NOTE: if a inverse was needed, there is some material at // https://brsr.github.io/2021/08/31/snyder-equal-area.html P->fwd = isea_s_forward; isea_grid_init(&Q->dgg); Q->dgg.output = ISEA_PLANE; /* P->dgg.radius = P->a; / * otherwise defaults to 1 */ /* calling library will scale, I think */ opt = pj_param(P->ctx, P->params, "sorient").s; if (opt) { if (!strcmp(opt, "isea")) { isea_orient_isea(&Q->dgg); } else if (!strcmp(opt, "pole")) { isea_orient_pole(&Q->dgg); } else { proj_log_error( P, _("Invalid value for orient: only isea or pole are supported")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (pj_param(P->ctx, P->params, "tazi").i) { Q->dgg.o_az = pj_param(P->ctx, P->params, "razi").f; } if (pj_param(P->ctx, P->params, "tlon_0").i) { Q->dgg.o_lon = pj_param(P->ctx, P->params, "rlon_0").f; } if (pj_param(P->ctx, P->params, "tlat_0").i) { Q->dgg.o_lat = pj_param(P->ctx, P->params, "rlat_0").f; } opt = pj_param(P->ctx, P->params, "smode").s; if (opt) { if (!strcmp(opt, "plane")) { Q->dgg.output = ISEA_PLANE; } else if (!strcmp(opt, "di")) { Q->dgg.output = ISEA_Q2DI; } else if (!strcmp(opt, "dd")) { Q->dgg.output = ISEA_Q2DD; } else if (!strcmp(opt, "hex")) { Q->dgg.output = ISEA_HEX; } else { proj_log_error(P, _("Invalid value for mode: only plane, di, dd or " "hex are supported")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (pj_param(P->ctx, P->params, "trescale").i) { Q->dgg.radius = ISEA_SCALE; } if (pj_param(P->ctx, P->params, "tresolution").i) { Q->dgg.resolution = pj_param(P->ctx, P->params, "iresolution").i; } else { Q->dgg.resolution = 4; } if (pj_param(P->ctx, P->params, "taperture").i) { Q->dgg.aperture = pj_param(P->ctx, P->params, "iaperture").i; } else { Q->dgg.aperture = 3; } return P; } #undef DEG36 #undef DEG72 #undef DEG90 #undef DEG108 #undef DEG120 #undef DEG144 #undef DEG180 #undef ISEA_SCALE #undef V_LAT #undef E_RAD #undef F_RAD #undef TABLE_G #undef TABLE_H #undef ISEA_STD_LAT #undef ISEA_STD_LONG
cpp
PROJ
data/projects/PROJ/src/projections/adams.cpp
/* * Implementation of the Guyou, Pierce Quincuncial, Adams Hemisphere in a * Square, Adams World in a Square I & II projections. * * Based on original code from libproj4 written by Gerald Evenden. Adapted to * modern PROJ by Kristian Evers. Original code found in file src/proj_guyou.c, * see * https://github.com/rouault/libproj4/blob/master/libproject-1.01/src/proj_guyou.c * for reference. * Fix for Peirce Quincuncial projection to diamond or square by Toby C. * Wilkinson to correctly flip out southern hemisphere into the four triangles * of Peirce's quincunx. The fix inspired by a similar rotate and translate * solution applied by Jonathan Feinberg for cartopy, see * https://github.com/jonathf/cartopy/blob/8172cac7fc45cafc86573d408ce85b74258a9c28/lib/cartopy/peircequincuncial.py * Added original code for horizontal and vertical arrangement of hemispheres by * Toby C. Wilkinson to allow creation of lateral quincuncial projections, such * as Grieger's Triptychial, see, e.g.: * - Grieger, B. (2020). “Optimized global map projections for specific * applications: the triptychial projection and the Spilhaus projection”. * EGU2020-9885. https://doi.org/10.5194/egusphere-egu2020-9885 * * Copyright (c) 2005, 2006, 2009 Gerald I. Evenden * Copyright (c) 2020 Kristian Evers * Copyright (c) 2021 Toby C Wilkinson * * Related material * ---------------- * * CONFORMAL PROJECTION OF THE SPHERE WITHIN A SQUARE, 1929, OSCAR S. ADAMS, * U.S. COAST AND GEODETIC SURVEY, Special Publication No.153, * ftp://ftp.library.noaa.gov/docs.lib/htdocs/rescue/cgs_specpubs/QB275U35no1531929.pdf * * https://en.wikipedia.org/wiki/Guyou_hemisphere-in-a-square_projection * https://en.wikipedia.org/wiki/Adams_hemisphere-in-a-square_projection * https://en.wikipedia.org/wiki/Peirce_quincuncial_projection */ #include <errno.h> #include <math.h> #include <algorithm> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(guyou, "Guyou") "\n\tMisc Sph No inv"; PROJ_HEAD(peirce_q, "Peirce Quincuncial") "\n\tMisc Sph No inv"; PROJ_HEAD(adams_hemi, "Adams Hemisphere in a Square") "\n\tMisc Sph No inv"; PROJ_HEAD(adams_ws1, "Adams World in a Square I") "\n\tMisc Sph No inv"; PROJ_HEAD(adams_ws2, "Adams World in a Square II") "\n\tMisc Sph No inv"; namespace { // anonymous namespace enum projection_type { GUYOU, PEIRCE_Q, ADAMS_HEMI, ADAMS_WS1, ADAMS_WS2, }; enum peirce_shape { PEIRCE_Q_SQUARE, PEIRCE_Q_DIAMOND, PEIRCE_Q_NHEMISPHERE, PEIRCE_Q_SHEMISPHERE, PEIRCE_Q_HORIZONTAL, PEIRCE_Q_VERTICAL, }; struct pj_adams_data { projection_type mode; peirce_shape pqshape; double scrollx = 0.0; double scrolly = 0.0; }; } // anonymous namespace #define TOL 1e-9 #define RSQRT2 0.7071067811865475244008443620 static double ell_int_5(double phi) { /* Procedure to compute elliptic integral of the first kind * where k^2=0.5. Precision good to better than 1e-7 * The approximation is performed with an even Chebyshev * series, thus the coefficients below are the even values * and where series evaluation must be multiplied by the argument. */ constexpr double C0 = 2.19174570831038; static const double C[] = { -8.58691003636495e-07, 2.02692115653689e-07, 3.12960480765314e-05, 5.30394739921063e-05, -0.0012804644680613, -0.00575574836830288, 0.0914203033408211, }; double y = phi * M_2_PI; y = 2. * y * y - 1.; double y2 = 2. * y; double d1 = 0.0; double d2 = 0.0; for (double c : C) { double temp = d1; d1 = y2 * d1 - d2 + c; d2 = temp; } return phi * (y * d1 - d2 + 0.5 * C0); } static PJ_XY adams_forward(PJ_LP lp, PJ *P) { double a = 0., b = 0.; bool sm = false, sn = false; PJ_XY xy; const struct pj_adams_data *Q = static_cast<const struct pj_adams_data *>(P->opaque); switch (Q->mode) { case GUYOU: if ((fabs(lp.lam) - TOL) > M_PI_2) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } if (fabs(fabs(lp.phi) - M_PI_2) < TOL) { xy.x = 0; xy.y = lp.phi < 0 ? -1.85407 : 1.85407; return xy; } else { const double sl = sin(lp.lam); const double sp = sin(lp.phi); const double cp = cos(lp.phi); a = aacos(P->ctx, (cp * sl - sp) * RSQRT2); b = aacos(P->ctx, (cp * sl + sp) * RSQRT2); sm = lp.lam < 0.; sn = lp.phi < 0.; } break; case PEIRCE_Q: { /* lam0 - note that the original Peirce model used a central meridian of * around -70deg, but the default within proj is +lon0=0 */ if (Q->pqshape == PEIRCE_Q_NHEMISPHERE) { if (lp.phi < -TOL) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } } if (Q->pqshape == PEIRCE_Q_SHEMISPHERE) { if (lp.phi > -TOL) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } } const double sl = sin(lp.lam); const double cl = cos(lp.lam); const double cp = cos(lp.phi); a = aacos(P->ctx, cp * (sl + cl) * RSQRT2); b = aacos(P->ctx, cp * (sl - cl) * RSQRT2); sm = sl < 0.; sn = cl > 0.; } break; case ADAMS_HEMI: { const double sp = sin(lp.phi); if ((fabs(lp.lam) - TOL) > M_PI_2) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } a = cos(lp.phi) * sin(lp.lam); sm = (sp + a) < 0.; sn = (sp - a) < 0.; a = aacos(P->ctx, a); b = M_PI_2 - lp.phi; } break; case ADAMS_WS1: { const double sp = tan(0.5 * lp.phi); b = cos(aasin(P->ctx, sp)) * sin(0.5 * lp.lam); a = aacos(P->ctx, (b - sp) * RSQRT2); b = aacos(P->ctx, (b + sp) * RSQRT2); sm = lp.lam < 0.; sn = lp.phi < 0.; } break; case ADAMS_WS2: { const double spp = tan(0.5 * lp.phi); a = cos(aasin(P->ctx, spp)) * sin(0.5 * lp.lam); sm = (spp + a) < 0.; sn = (spp - a) < 0.; b = aacos(P->ctx, spp); a = aacos(P->ctx, a); } break; } double m = aasin(P->ctx, sqrt((1. + std::min(0.0, cos(a + b))))); if (sm) m = -m; double n = aasin(P->ctx, sqrt(fabs(1. - std::max(0.0, cos(a - b))))); if (sn) n = -n; xy.x = ell_int_5(m); xy.y = ell_int_5(n); if (Q->mode == PEIRCE_Q) { /* Constant complete elliptic integral of the first kind with m=0.5, * calculated using * https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ellipk.html * . Used as basic as scaled shift distance */ constexpr double shd = 1.8540746773013719 * 2; /* For square and diamond Quincuncial projections, spin out southern * hemisphere to triangular segments of quincunx (before rotation for * square)*/ if (Q->pqshape == PEIRCE_Q_SQUARE || (Q->pqshape == PEIRCE_Q_DIAMOND)) { if (lp.phi < 0.) { /* fold out segments */ if (lp.lam < (-0.75 * M_PI)) xy.y = shd - xy.y; /* top left segment, shift up and reflect y */ if ((lp.lam < (-0.25 * M_PI)) && (lp.lam >= (-0.75 * M_PI))) xy.x = -shd - xy.x; /* left segment, shift left and reflect x */ if ((lp.lam < (0.25 * M_PI)) && (lp.lam >= (-0.25 * M_PI))) xy.y = -shd - xy.y; /* bottom segment, shift down and reflect y */ if ((lp.lam < (0.75 * M_PI)) && (lp.lam >= (0.25 * M_PI))) xy.x = shd - xy.x; /* right segment, shift right and reflect x */ if (lp.lam >= (0.75 * M_PI)) xy.y = shd - xy.y; /* top right segment, shift up and reflect y */ } } /* For square types rotate xy by 45 deg */ if (Q->pqshape == PEIRCE_Q_SQUARE) { const double temp = xy.x; xy.x = RSQRT2 * (xy.x - xy.y); xy.y = RSQRT2 * (temp + xy.y); } /* For rectangle Quincuncial projs, spin out southern hemisphere to east * (horizontal) or north (vertical) after rotation */ if (Q->pqshape == PEIRCE_Q_HORIZONTAL) { if (lp.phi < 0.) { xy.x = shd - xy.x; /* reflect x to east */ } xy.x = xy.x - (shd / 2); /* shift everything so origin is in middle of two hemispheres */ } if (Q->pqshape == PEIRCE_Q_VERTICAL) { if (lp.phi < 0.) { xy.y = shd - xy.y; /* reflect y to north */ } xy.y = xy.y - (shd / 2); /* shift everything so origin is in middle of two hemispheres */ } // if o_scrollx param present, scroll x if (!(Q->scrollx == 0.0) && (Q->pqshape == PEIRCE_Q_HORIZONTAL)) { double xscale = 2.0; double xthresh = shd / 2; xy.x = xy.x + (Q->scrollx * (xthresh * 2 * xscale)); /*shift relative to proj width*/ if (xy.x >= (xthresh * xscale)) { xy.x = xy.x - (shd * xscale); } else if (xy.x < -(xthresh * xscale)) { xy.x = xy.x + (shd * xscale); } } // if o_scrolly param present, scroll y if (!(Q->scrolly == 0.0) && (Q->pqshape == PEIRCE_Q_VERTICAL)) { double yscale = 2.0; double ythresh = shd / 2; xy.y = xy.y + (Q->scrolly * (ythresh * 2 * yscale)); /*shift relative to proj height*/ if (xy.y >= (ythresh * yscale)) { xy.y = xy.y - (shd * yscale); } else if (xy.y < -(ythresh * yscale)) { xy.y = xy.y + (shd * yscale); } } } if (Q->mode == ADAMS_HEMI || Q->mode == ADAMS_WS2) { /* rotate by 45deg. */ const double temp = xy.x; xy.x = RSQRT2 * (xy.x - xy.y); xy.y = RSQRT2 * (temp + xy.y); } return xy; } static PJ_LP adams_inverse(PJ_XY xy, PJ *P) { PJ_LP lp; // Only implemented for ADAMS_WS2 // Uses Newton-Raphson method on the following pair of functions: // f_x(lam,phi) = adams_forward(lam, phi).x - xy.x // f_y(lam,phi) = adams_forward(lam, phi).y - xy.y // Initial guess (very rough, especially at high northings) // The magic values are got with: // echo 0 90 | src/proj -f "%.8f" +proj=adams_ws2 +R=1 // echo 180 0 | src/proj -f "%.8f" +proj=adams_ws2 +R=1 lp.phi = std::max(std::min(xy.y / 2.62181347, 1.0), -1.0) * M_HALFPI; lp.lam = fabs(lp.phi) >= M_HALFPI ? 0 : std::max(std::min(xy.x / 2.62205760 / cos(lp.phi), 1.0), -1.0) * M_PI; constexpr double deltaXYTolerance = 1e-10; return pj_generic_inverse_2d(xy, P, lp, deltaXYTolerance); } static PJ_LP peirce_q_square_inverse(PJ_XY xy, PJ *P) { /* Heuristics based on trial and repeat process */ PJ_LP lp; lp.phi = 0; if (xy.x == 0 && xy.y < 0) { lp.lam = -M_PI / 4; if (fabs(xy.y) < 2.622057580396) lp.phi = M_PI / 4; } else if (xy.x > 0 && fabs(xy.y) < 1e-7) lp.lam = M_PI / 4; else if (xy.x < 0 && fabs(xy.y) < 1e-7) { lp.lam = -3 * M_PI / 4; lp.phi = M_PI / 2 / 2.622057574224 * xy.x + M_PI / 2; } else if (fabs(xy.x) < 1e-7 && xy.y > 0) lp.lam = 3 * M_PI / 4; else if (xy.x >= 0 && xy.y <= 0) { lp.lam = 0; if (xy.x == 0 && xy.y == 0) { lp.phi = M_PI / 2; return lp; } } else if (xy.x >= 0 && xy.y >= 0) lp.lam = M_PI / 2; else if (xy.x <= 0 && xy.y >= 0) { if (fabs(xy.x) < fabs(xy.y)) lp.lam = M_PI * 0.9; else lp.lam = -M_PI * 0.9; } else /* if( xy.x <= 0 && xy.y <= 0 ) */ lp.lam = -M_PI / 2; constexpr double deltaXYTolerance = 1e-10; return pj_generic_inverse_2d(xy, P, lp, deltaXYTolerance); } static PJ_LP peirce_q_diamond_inverse(PJ_XY xy, PJ *P) { /* Heuristics based on a trial and repeat process */ PJ_LP lp; lp.phi = 0; if (xy.x >= 0 && xy.y <= 0) { lp.lam = M_PI / 4; if (xy.x > 0 && xy.y == 0) { lp.lam = M_PI / 2; lp.phi = 0; } else if (xy.x == 0 && xy.y == 0) { lp.lam = 0; lp.phi = M_PI / 2; return lp; } else if (xy.x == 0 && xy.y < 0) { lp.lam = 0; lp.phi = M_PI / 4; } } else if (xy.x >= 0 && xy.y >= 0) lp.lam = 3 * M_PI / 4; else if (xy.x <= 0 && xy.y >= 0) { lp.lam = -3 * M_PI / 4; } else /* if( xy.x <= 0 && xy.y <= 0 ) */ lp.lam = -M_PI / 4; if (fabs(xy.x) > 1.8540746773013719 + 1e-3 || fabs(xy.y) > 1.8540746773013719 + 1e-3) { lp.phi = -M_PI / 4; } constexpr double deltaXYTolerance = 1e-10; return pj_generic_inverse_2d(xy, P, lp, deltaXYTolerance); } static PJ *pj_adams_setup(PJ *P, projection_type mode) { struct pj_adams_data *Q = static_cast<struct pj_adams_data *>( calloc(1, sizeof(struct pj_adams_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->es = 0; P->fwd = adams_forward; Q->mode = mode; if (mode == ADAMS_WS2) P->inv = adams_inverse; if (mode == PEIRCE_Q) { // Quincuncial projections shape options: square, diamond, hemisphere, // horizontal (rectangle) or vertical (rectangle) const char *pqshape = pj_param(P->ctx, P->params, "sshape").s; if (!pqshape) pqshape = "diamond"; /* default if shape value not supplied */ if (strcmp(pqshape, "square") == 0) { Q->pqshape = PEIRCE_Q_SQUARE; P->inv = peirce_q_square_inverse; } else if (strcmp(pqshape, "diamond") == 0) { Q->pqshape = PEIRCE_Q_DIAMOND; P->inv = peirce_q_diamond_inverse; } else if (strcmp(pqshape, "nhemisphere") == 0) { Q->pqshape = PEIRCE_Q_NHEMISPHERE; } else if (strcmp(pqshape, "shemisphere") == 0) { Q->pqshape = PEIRCE_Q_SHEMISPHERE; } else if (strcmp(pqshape, "horizontal") == 0) { Q->pqshape = PEIRCE_Q_HORIZONTAL; if (pj_param(P->ctx, P->params, "tscrollx").i) { double scrollx; scrollx = pj_param(P->ctx, P->params, "dscrollx").f; if (scrollx > 1 || scrollx < -1) { proj_log_error( P, _("Invalid value for scrollx: |scrollx| should " "between -1 and 1")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->scrollx = scrollx; } } else if (strcmp(pqshape, "vertical") == 0) { Q->pqshape = PEIRCE_Q_VERTICAL; if (pj_param(P->ctx, P->params, "tscrolly").i) { double scrolly; scrolly = pj_param(P->ctx, P->params, "dscrolly").f; if (scrolly > 1 || scrolly < -1) { proj_log_error( P, _("Invalid value for scrolly: |scrolly| should " "between -1 and 1")); return pj_default_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->scrolly = scrolly; } } else { proj_log_error(P, _("peirce_q: invalid value for 'shape' parameter")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } return P; } PJ *PJ_PROJECTION(guyou) { return pj_adams_setup(P, GUYOU); } PJ *PJ_PROJECTION(peirce_q) { return pj_adams_setup(P, PEIRCE_Q); } PJ *PJ_PROJECTION(adams_hemi) { return pj_adams_setup(P, ADAMS_HEMI); } PJ *PJ_PROJECTION(adams_ws1) { return pj_adams_setup(P, ADAMS_WS1); } PJ *PJ_PROJECTION(adams_ws2) { return pj_adams_setup(P, ADAMS_WS2); } #undef TOL #undef RSQRT2
cpp
PROJ
data/projects/PROJ/src/projections/chamb.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" typedef struct { double r, Az; } VECT; namespace { // anonymous namespace struct pj_chamb { struct { /* control point data */ double phi, lam; double cosphi, sinphi; VECT v; PJ_XY p; } c[3]; PJ_XY p; double beta_0, beta_1, beta_2; }; } // anonymous namespace PROJ_HEAD(chamb, "Chamberlin Trimetric") "\n\tMisc Sph, no inv" "\n\tlat_1= lon_1= lat_2= lon_2= lat_3= lon_3="; #include <stdio.h> #define THIRD 0.333333333333333333 #define TOL 1e-9 /* distance and azimuth from point 1 to point 2 */ static VECT vect(PJ_CONTEXT *ctx, double dphi, double c1, double s1, double c2, double s2, double dlam) { VECT v; double cdl, dp, dl; cdl = cos(dlam); if (fabs(dphi) > 1. || fabs(dlam) > 1.) v.r = aacos(ctx, s1 * s2 + c1 * c2 * cdl); else { /* more accurate for smaller distances */ dp = sin(.5 * dphi); dl = sin(.5 * dlam); v.r = 2. * aasin(ctx, sqrt(dp * dp + c1 * c2 * dl * dl)); } if (fabs(v.r) > TOL) v.Az = atan2(c2 * sin(dlam), c1 * s2 - s1 * c2 * cdl); else v.r = v.Az = 0.; return v; } /* law of cosines */ static double lc(PJ_CONTEXT *ctx, double b, double c, double a) { return aacos(ctx, .5 * (b * b + c * c - a * a) / (b * c)); } static PJ_XY chamb_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy; struct pj_chamb *Q = static_cast<struct pj_chamb *>(P->opaque); double sinphi, cosphi, a; VECT v[3]; int i, j; sinphi = sin(lp.phi); cosphi = cos(lp.phi); for (i = 0; i < 3; ++i) { /* dist/azimiths from control */ v[i] = vect(P->ctx, lp.phi - Q->c[i].phi, Q->c[i].cosphi, Q->c[i].sinphi, cosphi, sinphi, lp.lam - Q->c[i].lam); if (v[i].r == 0.0) break; v[i].Az = adjlon(v[i].Az - Q->c[i].v.Az); } if (i < 3) /* current point at control point */ xy = Q->c[i].p; else { /* point mean of intersepts */ xy = Q->p; for (i = 0; i < 3; ++i) { j = i == 2 ? 0 : i + 1; a = lc(P->ctx, Q->c[i].v.r, v[i].r, v[j].r); if (v[i].Az < 0.) a = -a; if (!i) { /* coord comp unique to each arc */ xy.x += v[i].r * cos(a); xy.y -= v[i].r * sin(a); } else if (i == 1) { a = Q->beta_1 - a; xy.x -= v[i].r * cos(a); xy.y -= v[i].r * sin(a); } else { a = Q->beta_2 - a; xy.x += v[i].r * cos(a); xy.y += v[i].r * sin(a); } } xy.x *= THIRD; /* mean of arc intercepts */ xy.y *= THIRD; } return xy; } PJ *PJ_PROJECTION(chamb) { int i, j; char line[10]; struct pj_chamb *Q = static_cast<struct pj_chamb *>(calloc(1, sizeof(struct pj_chamb))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; for (i = 0; i < 3; ++i) { /* get control point locations */ (void)snprintf(line, sizeof(line), "rlat_%d", i + 1); Q->c[i].phi = pj_param(P->ctx, P->params, line).f; (void)snprintf(line, sizeof(line), "rlon_%d", i + 1); Q->c[i].lam = pj_param(P->ctx, P->params, line).f; Q->c[i].lam = adjlon(Q->c[i].lam - P->lam0); Q->c[i].cosphi = cos(Q->c[i].phi); Q->c[i].sinphi = sin(Q->c[i].phi); } for (i = 0; i < 3; ++i) { /* inter ctl pt. distances and azimuths */ j = i == 2 ? 0 : i + 1; Q->c[i].v = vect(P->ctx, Q->c[j].phi - Q->c[i].phi, Q->c[i].cosphi, Q->c[i].sinphi, Q->c[j].cosphi, Q->c[j].sinphi, Q->c[j].lam - Q->c[i].lam); if (Q->c[i].v.r == 0.0) { proj_log_error( P, _("Invalid value for control points: they should be distinct")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } /* co-linearity problem ignored for now */ } Q->beta_0 = lc(P->ctx, Q->c[0].v.r, Q->c[2].v.r, Q->c[1].v.r); Q->beta_1 = lc(P->ctx, Q->c[0].v.r, Q->c[1].v.r, Q->c[2].v.r); Q->beta_2 = M_PI - Q->beta_0; Q->c[0].p.y = Q->c[2].v.r * sin(Q->beta_0); Q->c[1].p.y = Q->c[0].p.y; Q->p.y = 2. * Q->c[0].p.y; Q->c[2].p.y = 0.; Q->c[1].p.x = 0.5 * Q->c[0].v.r; Q->c[0].p.x = -Q->c[1].p.x; Q->c[2].p.x = Q->c[0].p.x + Q->c[2].v.r * cos(Q->beta_0); Q->p.x = Q->c[2].p.x; P->es = 0.; P->fwd = chamb_s_forward; return P; } #undef THIRD #undef TOL
cpp
PROJ
data/projects/PROJ/src/projections/fouc_s.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(fouc_s, "Foucaut Sinusoidal") "\n\tPCyl, Sph"; #define MAX_ITER 10 #define LOOP_TOL 1e-7 namespace { // anonymous namespace struct pj_fouc_s_data { double n, n1; }; } // anonymous namespace static PJ_XY fouc_s_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_fouc_s_data *Q = static_cast<struct pj_fouc_s_data *>(P->opaque); double t; t = cos(lp.phi); xy.x = lp.lam * t / (Q->n + Q->n1 * t); xy.y = Q->n * lp.phi + Q->n1 * sin(lp.phi); return xy; } static PJ_LP fouc_s_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_fouc_s_data *Q = static_cast<struct pj_fouc_s_data *>(P->opaque); int i; if (Q->n != 0.0) { lp.phi = xy.y; for (i = MAX_ITER; i; --i) { const double V = (Q->n * lp.phi + Q->n1 * sin(lp.phi) - xy.y) / (Q->n + Q->n1 * cos(lp.phi)); lp.phi -= V; if (fabs(V) < LOOP_TOL) break; } if (!i) lp.phi = xy.y < 0. ? -M_HALFPI : M_HALFPI; } else lp.phi = aasin(P->ctx, xy.y); const double V = cos(lp.phi); lp.lam = xy.x * (Q->n + Q->n1 * V) / V; return lp; } PJ *PJ_PROJECTION(fouc_s) { struct pj_fouc_s_data *Q = static_cast<struct pj_fouc_s_data *>( calloc(1, sizeof(struct pj_fouc_s_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->n = pj_param(P->ctx, P->params, "dn").f; if (Q->n < 0. || Q->n > 1.) { proj_log_error(P, _("Invalid value for n: it should be in [0,1] range.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->n1 = 1. - Q->n; P->es = 0; P->inv = fouc_s_s_inverse; P->fwd = fouc_s_s_forward; return P; } #undef MAX_ITER #undef LOOP_TOL
cpp
PROJ
data/projects/PROJ/src/projections/cc.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(cc, "Central Cylindrical") "\n\tCyl, Sph"; #define EPS10 1.e-10 static PJ_XY cc_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; if (fabs(fabs(lp.phi) - M_HALFPI) <= EPS10) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } xy.x = lp.lam; xy.y = tan(lp.phi); return xy; } static PJ_LP cc_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; lp.phi = atan(xy.y); lp.lam = xy.x; return lp; } PJ *PJ_PROJECTION(cc) { P->es = 0.; P->inv = cc_s_inverse; P->fwd = cc_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/col_urban.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(col_urban, "Colombia Urban") "\n\tMisc\n\th_0="; // Notations and formulas taken from IOGP Publication 373-7-2 - // Geomatics Guidance Note number 7, part 2 - March 2020 namespace { // anonymous namespace struct pj_col_urban { double h0; // height of projection origin, divided by semi-major axis (a) double rho0; // adimensional value, contrary to Guidance note 7.2 double A; double B; // adimensional value, contrary to Guidance note 7.2 double C; double D; // adimensional value, contrary to Guidance note 7.2 }; } // anonymous namespace static PJ_XY col_urban_forward(PJ_LP lp, PJ *P) { PJ_XY xy; struct pj_col_urban *Q = static_cast<struct pj_col_urban *>(P->opaque); const double cosphi = cos(lp.phi); const double sinphi = sin(lp.phi); const double nu = 1. / sqrt(1 - P->es * sinphi * sinphi); const double lam_nu_cosphi = lp.lam * nu * cosphi; xy.x = Q->A * lam_nu_cosphi; const double sinphi_m = sin(0.5 * (lp.phi + P->phi0)); const double rho_m = (1 - P->es) / pow(1 - P->es * sinphi_m * sinphi_m, 1.5); const double G = 1 + Q->h0 / rho_m; xy.y = G * Q->rho0 * ((lp.phi - P->phi0) + Q->B * lam_nu_cosphi * lam_nu_cosphi); return xy; } static PJ_LP col_urban_inverse(PJ_XY xy, PJ *P) { PJ_LP lp; struct pj_col_urban *Q = static_cast<struct pj_col_urban *>(P->opaque); lp.phi = P->phi0 + xy.y / Q->D - Q->B * (xy.x / Q->C) * (xy.x / Q->C); const double sinphi = sin(lp.phi); const double nu = 1. / sqrt(1 - P->es * sinphi * sinphi); lp.lam = xy.x / (Q->C * nu * cos(lp.phi)); return lp; } PJ *PJ_PROJECTION(col_urban) { struct pj_col_urban *Q = static_cast<struct pj_col_urban *>( calloc(1, sizeof(struct pj_col_urban))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; const double h0_unscaled = pj_param(P->ctx, P->params, "dh_0").f; Q->h0 = h0_unscaled / P->a; const double sinphi0 = sin(P->phi0); const double nu0 = 1. / sqrt(1 - P->es * sinphi0 * sinphi0); Q->A = 1 + Q->h0 / nu0; Q->rho0 = (1 - P->es) / pow(1 - P->es * sinphi0 * sinphi0, 1.5); Q->B = tan(P->phi0) / (2 * Q->rho0 * nu0); Q->C = 1 + Q->h0; Q->D = Q->rho0 * (1 + Q->h0 / (1 - P->es)); P->fwd = col_urban_forward; P->inv = col_urban_inverse; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/nell.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(nell, "Nell") "\n\tPCyl, Sph"; #define MAX_ITER 10 #define LOOP_TOL 1e-7 static PJ_XY nell_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; int i; (void)P; const double k = 2. * sin(lp.phi); const double phi_pow_2 = lp.phi * lp.phi; lp.phi *= 1.00371 + phi_pow_2 * (-0.0935382 + phi_pow_2 * -0.011412); for (i = MAX_ITER; i; --i) { const double V = (lp.phi + sin(lp.phi) - k) / (1. + cos(lp.phi)); lp.phi -= V; if (fabs(V) < LOOP_TOL) break; } xy.x = 0.5 * lp.lam * (1. + cos(lp.phi)); xy.y = lp.phi; return xy; } static PJ_LP nell_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.lam = 2. * xy.x / (1. + cos(xy.y)); lp.phi = aasin(P->ctx, 0.5 * (xy.y + sin(xy.y))); return lp; } PJ *PJ_PROJECTION(nell) { P->es = 0; P->inv = nell_s_inverse; P->fwd = nell_s_forward; return P; } #undef MAX_ITER #undef LOOP_TOL
cpp
PROJ
data/projects/PROJ/src/projections/putp6.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_putp6 { double C_x, C_y, A, B, D; }; } // anonymous namespace PROJ_HEAD(putp6, "Putnins P6") "\n\tPCyl, Sph"; PROJ_HEAD(putp6p, "Putnins P6'") "\n\tPCyl, Sph"; #define EPS 1e-10 #define NITER 10 #define CON_POLE 1.732050807568877 /* sqrt(3) */ static PJ_XY putp6_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_putp6 *Q = static_cast<struct pj_putp6 *>(P->opaque); int i; const double p = Q->B * sin(lp.phi); lp.phi *= 1.10265779; for (i = NITER; i; --i) { const double r = sqrt(1. + lp.phi * lp.phi); const double V = ((Q->A - r) * lp.phi - log(lp.phi + r) - p) / (Q->A - 2. * r); lp.phi -= V; if (fabs(V) < EPS) break; } double sqrt_1_plus_phi2; if (!i) { // Note: it seems this case is rarely reached as from experimenting, // i seems to be >= 6 lp.phi = p < 0. ? -CON_POLE : CON_POLE; // the formula of the else case would also work, but this makes // some cppcheck versions happier. sqrt_1_plus_phi2 = 2; } else { sqrt_1_plus_phi2 = sqrt(1. + lp.phi * lp.phi); } xy.x = Q->C_x * lp.lam * (Q->D - sqrt_1_plus_phi2); xy.y = Q->C_y * lp.phi; return xy; } static PJ_LP putp6_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_putp6 *Q = static_cast<struct pj_putp6 *>(P->opaque); double r; lp.phi = xy.y / Q->C_y; r = sqrt(1. + lp.phi * lp.phi); lp.lam = xy.x / (Q->C_x * (Q->D - r)); lp.phi = aasin(P->ctx, ((Q->A - r) * lp.phi - log(lp.phi + r)) / Q->B); return lp; } PJ *PJ_PROJECTION(putp6) { struct pj_putp6 *Q = static_cast<struct pj_putp6 *>(calloc(1, sizeof(struct pj_putp6))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->C_x = 1.01346; Q->C_y = 0.91910; Q->A = 4.; Q->B = 2.1471437182129378784; Q->D = 2.; P->es = 0.; P->inv = putp6_s_inverse; P->fwd = putp6_s_forward; return P; } PJ *PJ_PROJECTION(putp6p) { struct pj_putp6 *Q = static_cast<struct pj_putp6 *>(calloc(1, sizeof(struct pj_putp6))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->C_x = 0.44329; Q->C_y = 0.80404; Q->A = 6.; Q->B = 5.61125; Q->D = 3.; P->es = 0.; P->inv = putp6_s_inverse; P->fwd = putp6_s_forward; return P; } #undef EPS #undef NITER #undef CON_POLE
cpp
PROJ
data/projects/PROJ/src/projections/larr.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(larr, "Larrivee") "\n\tMisc Sph, no inv"; #define SIXTH .16666666666666666 static PJ_XY larr_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = 0.5 * lp.lam * (1. + sqrt(cos(lp.phi))); xy.y = lp.phi / (cos(0.5 * lp.phi) * cos(SIXTH * lp.lam)); return xy; } PJ *PJ_PROJECTION(larr) { P->es = 0; P->fwd = larr_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/oea.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(oea, "Oblated Equal Area") "\n\tMisc Sph\n\tn= m= theta="; namespace { // anonymous namespace struct pj_oea { double theta; double m, n; double two_r_m, two_r_n, rm, rn, hm, hn; double cp0, sp0; }; } // anonymous namespace static PJ_XY oea_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_oea *Q = static_cast<struct pj_oea *>(P->opaque); const double cp = cos(lp.phi); const double sp = sin(lp.phi); const double cl = cos(lp.lam); const double Az = aatan2(cp * sin(lp.lam), Q->cp0 * sp - Q->sp0 * cp * cl) + Q->theta; const double shz = sin(0.5 * aacos(P->ctx, Q->sp0 * sp + Q->cp0 * cp * cl)); const double M = aasin(P->ctx, shz * sin(Az)); const double N = aasin(P->ctx, shz * cos(Az) * cos(M) / cos(M * Q->two_r_m)); xy.y = Q->n * sin(N * Q->two_r_n); xy.x = Q->m * sin(M * Q->two_r_m) * cos(N) / cos(N * Q->two_r_n); return xy; } static PJ_LP oea_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_oea *Q = static_cast<struct pj_oea *>(P->opaque); const double N = Q->hn * aasin(P->ctx, xy.y * Q->rn); const double M = Q->hm * aasin(P->ctx, xy.x * Q->rm * cos(N * Q->two_r_n) / cos(N)); const double xp = 2. * sin(M); const double yp = 2. * sin(N) * cos(M * Q->two_r_m) / cos(M); const double Az = aatan2(xp, yp) - Q->theta; const double cAz = cos(Az); const double z = 2. * aasin(P->ctx, 0.5 * hypot(xp, yp)); const double sz = sin(z); const double cz = cos(z); lp.phi = aasin(P->ctx, Q->sp0 * cz + Q->cp0 * sz * cAz); lp.lam = aatan2(sz * sin(Az), Q->cp0 * cz - Q->sp0 * sz * cAz); return lp; } PJ *PJ_PROJECTION(oea) { struct pj_oea *Q = static_cast<struct pj_oea *>(calloc(1, sizeof(struct pj_oea))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (((Q->n = pj_param(P->ctx, P->params, "dn").f) <= 0.)) { proj_log_error(P, _("Invalid value for n: it should be > 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (((Q->m = pj_param(P->ctx, P->params, "dm").f) <= 0.)) { proj_log_error(P, _("Invalid value for m: it should be > 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->theta = pj_param(P->ctx, P->params, "rtheta").f; Q->sp0 = sin(P->phi0); Q->cp0 = cos(P->phi0); Q->rn = 1. / Q->n; Q->rm = 1. / Q->m; Q->two_r_n = 2. * Q->rn; Q->two_r_m = 2. * Q->rm; Q->hm = 0.5 * Q->m; Q->hn = 0.5 * Q->n; P->fwd = oea_s_forward; P->inv = oea_s_inverse; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/urm5.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(urm5, "Urmaev V") "\n\tPCyl, Sph, no inv\n\tn= q= alpha="; namespace { // anonymous namespace struct pj_urm5 { double m, rmn, q3, n; }; } // anonymous namespace static PJ_XY urm5_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_urm5 *Q = static_cast<struct pj_urm5 *>(P->opaque); double t; t = lp.phi = aasin(P->ctx, Q->n * sin(lp.phi)); xy.x = Q->m * lp.lam * cos(lp.phi); t *= t; xy.y = lp.phi * (1. + t * Q->q3) * Q->rmn; return xy; } PJ *PJ_PROJECTION(urm5) { double alpha, t; struct pj_urm5 *Q = static_cast<struct pj_urm5 *>(calloc(1, sizeof(struct pj_urm5))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (!pj_param(P->ctx, P->params, "tn").i) { proj_log_error(P, _("Missing parameter n.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_MISSING_ARG); } Q->n = pj_param(P->ctx, P->params, "dn").f; if (Q->n <= 0. || Q->n > 1.) { proj_log_error(P, _("Invalid value for n: it should be in ]0,1] range.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->q3 = pj_param(P->ctx, P->params, "dq").f / 3.; alpha = pj_param(P->ctx, P->params, "ralpha").f; t = Q->n * sin(alpha); const double denom = sqrt(1. - t * t); if (denom == 0) { proj_log_error( P, _("Invalid value for n / alpha: n * sin(|alpha|) should be < 1.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->m = cos(alpha) / denom; Q->rmn = 1. / (Q->m * Q->n); P->es = 0.; P->inv = nullptr; P->fwd = urm5_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/mod_ster.cpp
/* based upon Snyder and Linck, USGS-NMD */ #include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(mil_os, "Miller Oblated Stereographic") "\n\tAzi(mod)"; PROJ_HEAD(lee_os, "Lee Oblated Stereographic") "\n\tAzi(mod)"; PROJ_HEAD(gs48, "Modified Stereographic of 48 U.S.") "\n\tAzi(mod)"; PROJ_HEAD(alsk, "Modified Stereographic of Alaska") "\n\tAzi(mod)"; PROJ_HEAD(gs50, "Modified Stereographic of 50 U.S.") "\n\tAzi(mod)"; #define EPSLN 1e-12 namespace { // anonymous namespace struct pj_mod_ster_data { const COMPLEX *zcoeff; double cchio, schio; int n; }; } // anonymous namespace static PJ_XY mod_ster_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>(P->opaque); double sinlon, coslon, esphi, chi, schi, cchi, s; COMPLEX p; sinlon = sin(lp.lam); coslon = cos(lp.lam); esphi = P->e * sin(lp.phi); chi = 2. * atan(tan((M_HALFPI + lp.phi) * .5) * pow((1. - esphi) / (1. + esphi), P->e * .5)) - M_HALFPI; schi = sin(chi); cchi = cos(chi); const double denom = 1. + Q->schio * schi + Q->cchio * cchi * coslon; if (denom == 0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } s = 2. / denom; p.r = s * cchi * sinlon; p.i = s * (Q->cchio * schi - Q->schio * cchi * coslon); p = pj_zpoly1(p, Q->zcoeff, Q->n); xy.x = p.r; xy.y = p.i; return xy; } static PJ_LP mod_ster_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>(P->opaque); int nn; COMPLEX p, fxy, fpxy, dp; double den, rh = 0.0, z, sinz = 0.0, cosz = 0.0, chi, phi = 0.0, esphi; p.r = xy.x; p.i = xy.y; for (nn = 20; nn; --nn) { fxy = pj_zpolyd1(p, Q->zcoeff, Q->n, &fpxy); fxy.r -= xy.x; fxy.i -= xy.y; den = fpxy.r * fpxy.r + fpxy.i * fpxy.i; dp.r = -(fxy.r * fpxy.r + fxy.i * fpxy.i) / den; dp.i = -(fxy.i * fpxy.r - fxy.r * fpxy.i) / den; p.r += dp.r; p.i += dp.i; if ((fabs(dp.r) + fabs(dp.i)) <= EPSLN) break; } if (nn) { rh = hypot(p.r, p.i); z = 2. * atan(.5 * rh); sinz = sin(z); cosz = cos(z); if (fabs(rh) <= EPSLN) { /* if we end up here input coordinates were (0,0). * pj_inv() adds P->lam0 to lp.lam, this way we are * sure to get the correct offset */ lp.lam = 0.0; lp.phi = P->phi0; return lp; } chi = aasin(P->ctx, cosz * Q->schio + p.i * sinz * Q->cchio / rh); phi = chi; for (nn = 20; nn; --nn) { double dphi; esphi = P->e * sin(phi); dphi = 2. * atan(tan((M_HALFPI + chi) * .5) * pow((1. + esphi) / (1. - esphi), P->e * .5)) - M_HALFPI - phi; phi += dphi; if (fabs(dphi) <= EPSLN) break; } } if (nn) { lp.phi = phi; lp.lam = atan2(p.r * sinz, rh * Q->cchio * cosz - p.i * Q->schio * sinz); } else lp.lam = lp.phi = HUGE_VAL; return lp; } static PJ *mod_ster_setup(PJ *P) { /* general initialization */ struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>(P->opaque); double esphi, chio; if (P->es != 0.0) { esphi = P->e * sin(P->phi0); chio = 2. * atan(tan((M_HALFPI + P->phi0) * .5) * pow((1. - esphi) / (1. + esphi), P->e * .5)) - M_HALFPI; } else chio = P->phi0; Q->schio = sin(chio); Q->cchio = cos(chio); P->inv = mod_ster_e_inverse; P->fwd = mod_ster_e_forward; return P; } /* Miller Oblated Stereographic */ PJ *PJ_PROJECTION(mil_os) { static const COMPLEX AB[] = {{0.924500, 0.}, {0., 0.}, {0.019430, 0.}}; struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>( calloc(1, sizeof(struct pj_mod_ster_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->n = 2; P->lam0 = DEG_TO_RAD * 20.; P->phi0 = DEG_TO_RAD * 18.; Q->zcoeff = AB; P->es = 0.; return mod_ster_setup(P); } /* Lee Oblated Stereographic */ PJ *PJ_PROJECTION(lee_os) { static const COMPLEX AB[] = { {0.721316, 0.}, {0., 0.}, {-0.0088162, -0.00617325}}; struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>( calloc(1, sizeof(struct pj_mod_ster_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->n = 2; P->lam0 = DEG_TO_RAD * -165.; P->phi0 = DEG_TO_RAD * -10.; Q->zcoeff = AB; P->es = 0.; return mod_ster_setup(P); } PJ *PJ_PROJECTION(gs48) { static const COMPLEX /* 48 United States */ AB[] = { {0.98879, 0.}, {0., 0.}, {-0.050909, 0.}, {0., 0.}, {0.075528, 0.}}; struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>( calloc(1, sizeof(struct pj_mod_ster_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->n = 4; P->lam0 = DEG_TO_RAD * -96.; P->phi0 = DEG_TO_RAD * 39.; Q->zcoeff = AB; P->es = 0.; P->a = 6370997.; return mod_ster_setup(P); } PJ *PJ_PROJECTION(alsk) { static const COMPLEX ABe[] = { /* Alaska ellipsoid */ {.9945303, 0.}, {.0052083, -.0027404}, {.0072721, .0048181}, {-.0151089, -.1932526}, {.0642675, -.1381226}, {.3582802, -.2884586}, }; static const COMPLEX ABs[] = {/* Alaska sphere */ {.9972523, 0.}, {.0052513, -.0041175}, {.0074606, .0048125}, {-.0153783, -.1968253}, {.0636871, -.1408027}, {.3660976, -.2937382}}; struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>( calloc(1, sizeof(struct pj_mod_ster_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->n = 5; P->lam0 = DEG_TO_RAD * -152.; P->phi0 = DEG_TO_RAD * 64.; if (P->es != 0.0) { /* fixed ellipsoid/sphere */ Q->zcoeff = ABe; P->a = 6378206.4; P->e = sqrt(P->es = 0.00676866); } else { Q->zcoeff = ABs; P->a = 6370997.; } return mod_ster_setup(P); } PJ *PJ_PROJECTION(gs50) { static const COMPLEX ABe[] = { /* GS50 ellipsoid */ {.9827497, 0.}, {.0210669, .0053804}, {-.1031415, -.0571664}, {-.0323337, -.0322847}, {.0502303, .1211983}, {.0251805, .0895678}, {-.0012315, -.1416121}, {.0072202, -.1317091}, {-.0194029, .0759677}, {-.0210072, .0834037}}; static const COMPLEX ABs[] = { /* GS50 sphere */ {.9842990, 0.}, {.0211642, .0037608}, {-.1036018, -.0575102}, {-.0329095, -.0320119}, {.0499471, .1223335}, {.0260460, .0899805}, {.0007388, -.1435792}, {.0075848, -.1334108}, {-.0216473, .0776645}, {-.0225161, .0853673}}; struct pj_mod_ster_data *Q = static_cast<struct pj_mod_ster_data *>( calloc(1, sizeof(struct pj_mod_ster_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->n = 9; P->lam0 = DEG_TO_RAD * -120.; P->phi0 = DEG_TO_RAD * 45.; if (P->es != 0.0) { /* fixed ellipsoid/sphere */ Q->zcoeff = ABe; P->a = 6378206.4; P->e = sqrt(P->es = 0.00676866); } else { Q->zcoeff = ABs; P->a = 6370997.; } return mod_ster_setup(P); } #undef EPSLN
cpp
PROJ
data/projects/PROJ/src/projections/krovak.cpp
/* * Project: PROJ * Purpose: Implementation of the krovak (Krovak) projection. * Definition: http://www.ihsenergy.com/epsg/guid7.html#1.4.3 * Author: Thomas Flemming, [email protected] * ****************************************************************************** * Copyright (c) 2001, Thomas Flemming, [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ****************************************************************************** * A description of the (forward) projection is found in: * * Bohuslav Veverka, * * KROVAK’S PROJECTION AND ITS USE FOR THE * CZECH REPUBLIC AND THE SLOVAK REPUBLIC, * * 50 years of the Research Institute of * and the Slovak Republic Geodesy, Topography and Cartography * * which can be found via the Wayback Machine: * * https://web.archive.org/web/20150216143806/https://www.vugtk.cz/odis/sborniky/sb2005/Sbornik_50_let_VUGTK/Part_1-Scientific_Contribution/16-Veverka.pdf * * Further info, including the inverse projection, is given by EPSG: * * Guidance Note 7 part 2 * Coordinate Conversions and Transformations including Formulas * * http://www.iogp.org/pubs/373-07-2.pdf * * Variable names in this file mostly follows what is used in the * paper by Veverka. * * According to EPSG the full Krovak projection method should have * the following parameters. Within PROJ the azimuth, and pseudo * standard parallel are hardcoded in the algorithm and can't be * altered from outside. The others all have defaults to match the * common usage with Krovak projection. * * lat_0 = latitude of centre of the projection * * lon_0 = longitude of centre of the projection * * ** = azimuth (true) of the centre line passing through the * centre of the projection * * ** = latitude of pseudo standard parallel * * k = scale factor on the pseudo standard parallel * * x_0 = False Easting of the centre of the projection at the * apex of the cone * * y_0 = False Northing of the centre of the projection at * the apex of the cone * *****************************************************************************/ #include <errno.h> #include <math.h> #include <algorithm> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(krovak, "Krovak") "\n\tPCyl, Ell"; PROJ_HEAD(mod_krovak, "Modified Krovak") "\n\tPCyl, Ell"; #define EPS 1e-15 #define UQ 1.04216856380474 /* DU(2, 59, 42, 42.69689) */ #define S0 \ 1.37008346281555 /* Latitude of pseudo standard parallel 78deg 30'00" N */ /* Not sure at all of the appropriate number for MAX_ITER... */ #define MAX_ITER 100 namespace { // anonymous namespace struct pj_krovak_data { double alpha; double k; double n; double rho0; double ad; bool easting_northing; // true, in default mode. false when using +czech bool modified; }; } // anonymous namespace namespace pj_modified_krovak { constexpr double X0 = 1089000.0; constexpr double Y0 = 654000.0; constexpr double C1 = 2.946529277E-02; constexpr double C2 = 2.515965696E-02; constexpr double C3 = 1.193845912E-07; constexpr double C4 = -4.668270147E-07; constexpr double C5 = 9.233980362E-12; constexpr double C6 = 1.523735715E-12; constexpr double C7 = 1.696780024E-18; constexpr double C8 = 4.408314235E-18; constexpr double C9 = -8.331083518E-24; constexpr double C10 = -3.689471323E-24; // Correction terms to be applied to regular Krovak to obtain Modified Krovak. // Note that Xr is a Southing in metres and Yr a Westing in metres, // and output (dX, dY) is a corrective term in (Southing, Westing) in metres // Reference: // https://www.cuzk.cz/Zememerictvi/Geodeticke-zaklady-na-uzemi-CR/GNSS/Nova-realizace-systemu-ETRS89-v-CR/Metodika-prevodu-ETRF2000-vs-S-JTSK-var2(101208).aspx static void mod_krovak_compute_dx_dy(const double Xr, const double Yr, double &dX, double &dY) { const double Xr2 = Xr * Xr; const double Yr2 = Yr * Yr; const double Xr4 = Xr2 * Xr2; const double Yr4 = Yr2 * Yr2; dX = C1 + C3 * Xr - C4 * Yr - 2 * C6 * Xr * Yr + C5 * (Xr2 - Yr2) + C7 * Xr * (Xr2 - 3 * Yr2) - C8 * Yr * (3 * Xr2 - Yr2) + 4 * C9 * Xr * Yr * (Xr2 - Yr2) + C10 * (Xr4 + Yr4 - 6 * Xr2 * Yr2); dY = C2 + C3 * Yr + C4 * Xr + 2 * C5 * Xr * Yr + C6 * (Xr2 - Yr2) + C8 * Xr * (Xr2 - 3 * Yr2) + C7 * Yr * (3 * Xr2 - Yr2) - 4 * C10 * Xr * Yr * (Xr2 - Yr2) + C9 * (Xr4 + Yr4 - 6 * Xr2 * Yr2); } } // namespace pj_modified_krovak static PJ_XY krovak_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ struct pj_krovak_data *Q = static_cast<struct pj_krovak_data *>(P->opaque); PJ_XY xy = {0.0, 0.0}; const double gfi = pow((1. + P->e * sin(lp.phi)) / (1. - P->e * sin(lp.phi)), Q->alpha * P->e / 2.); const double u = 2. * (atan(Q->k * pow(tan(lp.phi / 2. + M_PI_4), Q->alpha) / gfi) - M_PI_4); const double deltav = -lp.lam * Q->alpha; const double s = asin(cos(Q->ad) * sin(u) + sin(Q->ad) * cos(u) * cos(deltav)); const double cos_s = cos(s); if (cos_s < 1e-12) { xy.x = 0; xy.y = 0; return xy; } const double d = asin(cos(u) * sin(deltav) / cos_s); const double eps = Q->n * d; const double rho = Q->rho0 * pow(tan(S0 / 2. + M_PI_4), Q->n) / pow(tan(s / 2. + M_PI_4), Q->n); xy.x = rho * cos(eps); xy.y = rho * sin(eps); // At this point, xy.x is a southing and xy.y is a westing if (Q->modified) { using namespace pj_modified_krovak; const double Xp = xy.x; const double Yp = xy.y; // Reduced X and Y const double Xr = Xp * P->a - X0; const double Yr = Yp * P->a - Y0; double dX, dY; mod_krovak_compute_dx_dy(Xr, Yr, dX, dY); xy.x = Xp - dX / P->a; xy.y = Yp - dY / P->a; } // PROJ always return values in (easting, northing) (default mode) // or (westing, southing) (+czech mode), so swap X/Y std::swap(xy.x, xy.y); if (Q->easting_northing) { // The default non-Czech convention uses easting, northing, so we have // to reverse the sign of the coordinates. But to do so, we have to take // into account the false easting/northing. xy.x = -xy.x - 2 * P->x0 / P->a; xy.y = -xy.y - 2 * P->y0 / P->a; } return xy; } static PJ_LP krovak_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ struct pj_krovak_data *Q = static_cast<struct pj_krovak_data *>(P->opaque); PJ_LP lp = {0.0, 0.0}; if (Q->easting_northing) { // The default non-Czech convention uses easting, northing, so we have // to reverse the sign of the coordinates. But to do so, we have to take // into account the false easting/northing. xy.y = -xy.y - 2 * P->x0 / P->a; xy.x = -xy.x - 2 * P->y0 / P->a; } std::swap(xy.x, xy.y); if (Q->modified) { using namespace pj_modified_krovak; // Note: in EPSG guidance node 7-2, below Xr/Yr/dX/dY are actually // Xr'/Yr'/dX'/dY' const double Xr = xy.x * P->a - X0; const double Yr = xy.y * P->a - Y0; double dX, dY; mod_krovak_compute_dx_dy(Xr, Yr, dX, dY); xy.x = xy.x + dX / P->a; xy.y = xy.y + dY / P->a; } const double rho = sqrt(xy.x * xy.x + xy.y * xy.y); const double eps = atan2(xy.y, xy.x); const double d = eps / sin(S0); double s; if (rho == 0.0) { s = M_PI_2; } else { s = 2. * (atan(pow(Q->rho0 / rho, 1. / Q->n) * tan(S0 / 2. + M_PI_4)) - M_PI_4); } const double u = asin(cos(Q->ad) * sin(s) - sin(Q->ad) * cos(s) * cos(d)); const double deltav = asin(cos(s) * sin(d) / cos(u)); lp.lam = P->lam0 - deltav / Q->alpha; /* ITERATION FOR lp.phi */ double fi1 = u; int i; for (i = MAX_ITER; i; --i) { lp.phi = 2. * (atan(pow(Q->k, -1. / Q->alpha) * pow(tan(u / 2. + M_PI_4), 1. / Q->alpha) * pow((1. + P->e * sin(fi1)) / (1. - P->e * sin(fi1)), P->e / 2.)) - M_PI_4); if (fabs(fi1 - lp.phi) < EPS) break; fi1 = lp.phi; } if (i == 0) proj_context_errno_set( P->ctx, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); lp.lam -= P->lam0; return lp; } static PJ *krovak_setup(PJ *P, bool modified) { double u0, n0, g; struct pj_krovak_data *Q = static_cast<struct pj_krovak_data *>( calloc(1, sizeof(struct pj_krovak_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* we want Bessel as fixed ellipsoid */ P->a = 6377397.155; P->es = 0.006674372230614; P->e = sqrt(P->es); /* if latitude of projection center is not set, use 49d30'N */ if (!pj_param(P->ctx, P->params, "tlat_0").i) P->phi0 = 0.863937979737193; /* if center long is not set use 42d30'E of Ferro - 17d40' for Ferro */ /* that will correspond to using longitudes relative to greenwich */ /* as input and output, instead of lat/long relative to Ferro */ if (!pj_param(P->ctx, P->params, "tlon_0").i) P->lam0 = 0.7417649320975901 - 0.308341501185665; /* if scale not set default to 0.9999 */ if (!pj_param(P->ctx, P->params, "tk").i && !pj_param(P->ctx, P->params, "tk_0").i) P->k0 = 0.9999; Q->modified = modified; Q->easting_northing = true; if (pj_param(P->ctx, P->params, "tczech").i) Q->easting_northing = false; /* Set up shared parameters between forward and inverse */ Q->alpha = sqrt(1. + (P->es * pow(cos(P->phi0), 4)) / (1. - P->es)); u0 = asin(sin(P->phi0) / Q->alpha); g = pow((1. + P->e * sin(P->phi0)) / (1. - P->e * sin(P->phi0)), Q->alpha * P->e / 2.); double tan_half_phi0_plus_pi_4 = tan(P->phi0 / 2. + M_PI_4); if (tan_half_phi0_plus_pi_4 == 0.0) { proj_log_error(P, _("Invalid value for lat_0: lat_0 + PI/4 should be " "different from 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->k = tan(u0 / 2. + M_PI_4) / pow(tan_half_phi0_plus_pi_4, Q->alpha) * g; n0 = sqrt(1. - P->es) / (1. - P->es * pow(sin(P->phi0), 2)); Q->n = sin(S0); Q->rho0 = P->k0 * n0 / tan(S0); Q->ad = M_PI_2 - UQ; P->inv = krovak_e_inverse; P->fwd = krovak_e_forward; return P; } PJ *PJ_PROJECTION(krovak) { return krovak_setup(P, false); } PJ *PJ_PROJECTION(mod_krovak) { return krovak_setup(P, true); } #undef EPS #undef UQ #undef S0 #undef MAX_ITER
cpp
PROJ
data/projects/PROJ/src/projections/tcea.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(tcea, "Transverse Cylindrical Equal Area") "\n\tCyl, Sph"; static PJ_XY tcea_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = cos(lp.phi) * sin(lp.lam) / P->k0; xy.y = P->k0 * (atan2(tan(lp.phi), cos(lp.lam)) - P->phi0); return xy; } static PJ_LP tcea_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double t; xy.y = xy.y / P->k0 + P->phi0; xy.x *= P->k0; t = sqrt(1. - xy.x * xy.x); lp.phi = asin(t * sin(xy.y)); lp.lam = atan2(xy.x, t * cos(xy.y)); return lp; } PJ *PJ_PROJECTION(tcea) { P->inv = tcea_s_inverse; P->fwd = tcea_s_forward; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/latlong.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Stub projection implementation for lat/long coordinates. We * don't actually change the coordinates, but we want proj=latlong * to act sort of like a projection. * Author: Frank Warmerdam, [email protected] * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ /* very loosely based upon DMA code by Bradford W. Drew */ #include "proj_internal.h" PROJ_HEAD(lonlat, "Lat/long (Geodetic)") "\n\t"; PROJ_HEAD(latlon, "Lat/long (Geodetic alias)") "\n\t"; PROJ_HEAD(latlong, "Lat/long (Geodetic alias)") "\n\t"; PROJ_HEAD(longlat, "Lat/long (Geodetic alias)") "\n\t"; static PJ_XY latlong_forward(PJ_LP lp, PJ *P) { PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = lp.lam; xy.y = lp.phi; return xy; } static PJ_LP latlong_inverse(PJ_XY xy, PJ *P) { PJ_LP lp = {0.0, 0.0}; (void)P; lp.phi = xy.y; lp.lam = xy.x; return lp; } static PJ_XYZ latlong_forward_3d(PJ_LPZ lpz, PJ *P) { PJ_XYZ xyz = {0, 0, 0}; (void)P; xyz.x = lpz.lam; xyz.y = lpz.phi; xyz.z = lpz.z; return xyz; } static PJ_LPZ latlong_inverse_3d(PJ_XYZ xyz, PJ *P) { PJ_LPZ lpz = {0, 0, 0}; (void)P; lpz.lam = xyz.x; lpz.phi = xyz.y; lpz.z = xyz.z; return lpz; } static void latlong_forward_4d(PJ_COORD &, PJ *) {} static void latlong_inverse_4d(PJ_COORD &, PJ *) {} static PJ *latlong_setup(PJ *P) { P->is_latlong = 1; P->x0 = 0; P->y0 = 0; P->inv = latlong_inverse; P->fwd = latlong_forward; P->inv3d = latlong_inverse_3d; P->fwd3d = latlong_forward_3d; P->inv4d = latlong_inverse_4d; P->fwd4d = latlong_forward_4d; P->left = PJ_IO_UNITS_RADIANS; P->right = PJ_IO_UNITS_RADIANS; return P; } PJ *PJ_PROJECTION(latlong) { return latlong_setup(P); } PJ *PJ_PROJECTION(longlat) { return latlong_setup(P); } PJ *PJ_PROJECTION(latlon) { return latlong_setup(P); } PJ *PJ_PROJECTION(lonlat) { return latlong_setup(P); }
cpp
PROJ
data/projects/PROJ/src/projections/august.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(august, "August Epicycloidal") "\n\tMisc Sph, no inv"; #define M 1.333333333333333 static PJ_XY august_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double t, c1, c, x1, x12, y1, y12; (void)P; t = tan(.5 * lp.phi); c1 = sqrt(1. - t * t); lp.lam *= .5; c = 1. + c1 * cos(lp.lam); x1 = sin(lp.lam) * c1 / c; y1 = t / c; x12 = x1 * x1; y12 = y1 * y1; xy.x = M * x1 * (3. + x12 - 3. * y12); xy.y = M * y1 * (3. + 3. * x12 - y12); return (xy); } PJ *PJ_PROJECTION(august) { P->inv = nullptr; P->fwd = august_s_forward; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/aea.cpp
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the aea (Albers Equal Area) projection. * and the leac (Lambert Equal Area Conic) projection * Author: Gerald Evenden (1995) * Thomas Knudsen (2016) - revise/add regression tests * ****************************************************************************** * Copyright (c) 1995, Gerald Evenden * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> #define EPS10 1.e-10 #define TOL7 1.e-7 PROJ_HEAD(aea, "Albers Equal Area") "\n\tConic Sph&Ell\n\tlat_1= lat_2="; PROJ_HEAD(leac, "Lambert Equal Area Conic") "\n\tConic, Sph&Ell\n\tlat_1= south"; /* determine latitude angle phi-1 */ #define N_ITER 15 #define EPSILON 1.0e-7 #define TOL 1.0e-10 static double phi1_(double qs, double Te, double Tone_es) { int i; double Phi, sinpi, cospi, con, com, dphi; Phi = asin(.5 * qs); if (Te < EPSILON) return (Phi); i = N_ITER; do { sinpi = sin(Phi); cospi = cos(Phi); con = Te * sinpi; com = 1. - con * con; dphi = .5 * com * com / cospi * (qs / Tone_es - sinpi / com + .5 / Te * log((1. - con) / (1. + con))); Phi += dphi; if (!(fabs(dphi) > TOL)) return Phi; --i; } while (i >= 0); return HUGE_VAL; } namespace { // anonymous namespace struct pj_aea { double ec; double n; double c; double dd; double n2; double rho0; double rho; double phi1; double phi2; double *en; int ellips; }; } // anonymous namespace static PJ *pj_aea_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_aea *>(P->opaque)->en); return pj_default_destructor(P, errlev); } static PJ_XY aea_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoid/spheroid, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_aea *Q = static_cast<struct pj_aea *>(P->opaque); Q->rho = Q->c - (Q->ellips ? Q->n * pj_qsfn(sin(lp.phi), P->e, P->one_es) : Q->n2 * sin(lp.phi)); if (Q->rho < 0.) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } Q->rho = Q->dd * sqrt(Q->rho); lp.lam *= Q->n; xy.x = Q->rho * sin(lp.lam); xy.y = Q->rho0 - Q->rho * cos(lp.lam); return xy; } static PJ_LP aea_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoid/spheroid, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_aea *Q = static_cast<struct pj_aea *>(P->opaque); xy.y = Q->rho0 - xy.y; Q->rho = hypot(xy.x, xy.y); if (Q->rho != 0.0) { if (Q->n < 0.) { Q->rho = -Q->rho; xy.x = -xy.x; xy.y = -xy.y; } lp.phi = Q->rho / Q->dd; if (Q->ellips) { lp.phi = (Q->c - lp.phi * lp.phi) / Q->n; if (fabs(Q->ec - fabs(lp.phi)) > TOL7) { if (fabs(lp.phi) > 2) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } lp.phi = phi1_(lp.phi, P->e, P->one_es); if (lp.phi == HUGE_VAL) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } } else lp.phi = lp.phi < 0. ? -M_HALFPI : M_HALFPI; } else { lp.phi = (Q->c - lp.phi * lp.phi) / Q->n2; if (fabs(lp.phi) <= 1.) lp.phi = asin(lp.phi); else lp.phi = lp.phi < 0. ? -M_HALFPI : M_HALFPI; } lp.lam = atan2(xy.x, xy.y) / Q->n; } else { lp.lam = 0.; lp.phi = Q->n > 0. ? M_HALFPI : -M_HALFPI; } return lp; } static PJ *setup(PJ *P) { struct pj_aea *Q = static_cast<struct pj_aea *>(P->opaque); P->inv = aea_e_inverse; P->fwd = aea_e_forward; if (fabs(Q->phi1) > M_HALFPI) { proj_log_error(P, _("Invalid value for lat_1: |lat_1| should be <= 90°")); return pj_aea_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(Q->phi2) > M_HALFPI) { proj_log_error(P, _("Invalid value for lat_2: |lat_2| should be <= 90°")); return pj_aea_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(Q->phi1 + Q->phi2) < EPS10) { proj_log_error(P, _("Invalid value for lat_1 and lat_2: |lat_1 + " "lat_2| should be > 0")); return pj_aea_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } double sinphi = sin(Q->phi1); Q->n = sinphi; double cosphi = cos(Q->phi1); const int secant = fabs(Q->phi1 - Q->phi2) >= EPS10; Q->ellips = (P->es > 0.); if (Q->ellips) { double ml1, m1; Q->en = pj_enfn(P->n); if (Q->en == nullptr) return pj_aea_destructor(P, 0); m1 = pj_msfn(sinphi, cosphi, P->es); ml1 = pj_qsfn(sinphi, P->e, P->one_es); if (secant) { /* secant cone */ double ml2, m2; sinphi = sin(Q->phi2); cosphi = cos(Q->phi2); m2 = pj_msfn(sinphi, cosphi, P->es); ml2 = pj_qsfn(sinphi, P->e, P->one_es); if (ml2 == ml1) return pj_aea_destructor(P, 0); Q->n = (m1 * m1 - m2 * m2) / (ml2 - ml1); if (Q->n == 0) { // Not quite, but es is very close to 1... proj_log_error(P, _("Invalid value for eccentricity")); return pj_aea_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } Q->ec = 1. - .5 * P->one_es * log((1. - P->e) / (1. + P->e)) / P->e; Q->c = m1 * m1 + Q->n * ml1; Q->dd = 1. / Q->n; Q->rho0 = Q->dd * sqrt(Q->c - Q->n * pj_qsfn(sin(P->phi0), P->e, P->one_es)); } else { if (secant) Q->n = .5 * (Q->n + sin(Q->phi2)); Q->n2 = Q->n + Q->n; Q->c = cosphi * cosphi + Q->n2 * sinphi; Q->dd = 1. / Q->n; Q->rho0 = Q->dd * sqrt(Q->c - Q->n2 * sin(P->phi0)); } return P; } PJ *PJ_PROJECTION(aea) { struct pj_aea *Q = static_cast<struct pj_aea *>(calloc(1, sizeof(struct pj_aea))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_aea_destructor; Q->phi1 = pj_param(P->ctx, P->params, "rlat_1").f; Q->phi2 = pj_param(P->ctx, P->params, "rlat_2").f; return setup(P); } PJ *PJ_PROJECTION(leac) { struct pj_aea *Q = static_cast<struct pj_aea *>(calloc(1, sizeof(struct pj_aea))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_aea_destructor; Q->phi2 = pj_param(P->ctx, P->params, "rlat_1").f; Q->phi1 = pj_param(P->ctx, P->params, "bsouth").i ? -M_HALFPI : M_HALFPI; return setup(P); } #undef EPS10 #undef TOL7 #undef N_ITER #undef EPSILON #undef TOL
cpp
PROJ
data/projects/PROJ/src/projections/eqdc.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" #include <math.h> namespace { // anonymous namespace struct pj_eqdc_data { double phi1; double phi2; double n; double rho; double rho0; double c; double *en; int ellips; }; } // anonymous namespace PROJ_HEAD(eqdc, "Equidistant Conic") "\n\tConic, Sph&Ell\n\tlat_1= lat_2="; #define EPS10 1.e-10 static PJ_XY eqdc_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_eqdc_data *Q = static_cast<struct pj_eqdc_data *>(P->opaque); Q->rho = Q->c - (Q->ellips ? pj_mlfn(lp.phi, sin(lp.phi), cos(lp.phi), Q->en) : lp.phi); const double lam_mul_n = lp.lam * Q->n; xy.x = Q->rho * sin(lam_mul_n); xy.y = Q->rho0 - Q->rho * cos(lam_mul_n); return xy; } static PJ_LP eqdc_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_eqdc_data *Q = static_cast<struct pj_eqdc_data *>(P->opaque); if ((Q->rho = hypot(xy.x, xy.y = Q->rho0 - xy.y)) != 0.0) { if (Q->n < 0.) { Q->rho = -Q->rho; xy.x = -xy.x; xy.y = -xy.y; } lp.phi = Q->c - Q->rho; if (Q->ellips) lp.phi = pj_inv_mlfn(lp.phi, Q->en); lp.lam = atan2(xy.x, xy.y) / Q->n; } else { lp.lam = 0.; lp.phi = Q->n > 0. ? M_HALFPI : -M_HALFPI; } return lp; } static PJ *pj_eqdc_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_eqdc_data *>(P->opaque)->en); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(eqdc) { double cosphi, sinphi; int secant; struct pj_eqdc_data *Q = static_cast<struct pj_eqdc_data *>( calloc(1, sizeof(struct pj_eqdc_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_eqdc_destructor; Q->phi1 = pj_param(P->ctx, P->params, "rlat_1").f; Q->phi2 = pj_param(P->ctx, P->params, "rlat_2").f; if (fabs(Q->phi1) > M_HALFPI) { proj_log_error(P, _("Invalid value for lat_1: |lat_1| should be <= 90°")); return pj_eqdc_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(Q->phi2) > M_HALFPI) { proj_log_error(P, _("Invalid value for lat_2: |lat_2| should be <= 90°")); return pj_eqdc_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (fabs(Q->phi1 + Q->phi2) < EPS10) { proj_log_error(P, _("Invalid value for lat_1 and lat_2: |lat_1 + " "lat_2| should be > 0")); return pj_eqdc_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } if (!(Q->en = pj_enfn(P->n))) return pj_eqdc_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); sinphi = sin(Q->phi1); Q->n = sinphi; cosphi = cos(Q->phi1); secant = fabs(Q->phi1 - Q->phi2) >= EPS10; Q->ellips = (P->es > 0.); if (Q->ellips) { double ml1, m1; m1 = pj_msfn(sinphi, cosphi, P->es); ml1 = pj_mlfn(Q->phi1, sinphi, cosphi, Q->en); if (secant) { /* secant cone */ sinphi = sin(Q->phi2); cosphi = cos(Q->phi2); const double ml2 = pj_mlfn(Q->phi2, sinphi, cosphi, Q->en); if (ml1 == ml2) { proj_log_error(P, _("Eccentricity too close to 1")); return pj_eqdc_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->n = (m1 - pj_msfn(sinphi, cosphi, P->es)) / (ml2 - ml1); if (Q->n == 0) { // Not quite, but es is very close to 1... proj_log_error(P, _("Invalid value for eccentricity")); return pj_eqdc_destructor( P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } Q->c = ml1 + m1 / Q->n; Q->rho0 = Q->c - pj_mlfn(P->phi0, sin(P->phi0), cos(P->phi0), Q->en); } else { if (secant) Q->n = (cosphi - cos(Q->phi2)) / (Q->phi2 - Q->phi1); if (Q->n == 0) { proj_log_error(P, _("Invalid value for lat_1 and lat_2: lat_1 + " "lat_2 should be > 0")); return pj_eqdc_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->c = Q->phi1 + cos(Q->phi1) / Q->n; Q->rho0 = Q->c - P->phi0; } P->inv = eqdc_e_inverse; P->fwd = eqdc_e_forward; return P; } #undef EPS10
cpp
PROJ
data/projects/PROJ/src/projections/tobmerc.cpp
#include <float.h> #include <math.h> #include "proj.h" #include "proj_internal.h" #include <math.h> PROJ_HEAD(tobmerc, "Tobler-Mercator") "\n\tCyl, Sph"; static PJ_XY tobmerc_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; double cosphi; if (fabs(lp.phi) >= M_HALFPI) { // builtins.gie tests "Test expected failure at the poles:". However // given that M_HALFPI is strictly less than pi/2 in double precision, // it's not clear why shouldn't just return a large result for xy.y (and // it's not even that large, merely 38.025...). Even if the logic was // such that phi was strictly equal to pi/2, allowing xy.y = inf would // be a reasonable result. proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return xy; } cosphi = cos(lp.phi); xy.x = P->k0 * lp.lam * cosphi * cosphi; xy.y = P->k0 * asinh(tan(lp.phi)); return xy; } static PJ_LP tobmerc_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; double cosphi; lp.phi = atan(sinh(xy.y / P->k0)); cosphi = cos(lp.phi); lp.lam = xy.x / P->k0 / (cosphi * cosphi); return lp; } PJ *PJ_PROJECTION(tobmerc) { P->inv = tobmerc_s_inverse; P->fwd = tobmerc_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/putp5.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_putp5_data { double A, B; }; } // anonymous namespace PROJ_HEAD(putp5, "Putnins P5") "\n\tPCyl, Sph"; PROJ_HEAD(putp5p, "Putnins P5'") "\n\tPCyl, Sph"; #define C 1.01346 #define D 1.2158542 static PJ_XY putp5_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_putp5_data *Q = static_cast<struct pj_putp5_data *>(P->opaque); xy.x = C * lp.lam * (Q->A - Q->B * sqrt(1. + D * lp.phi * lp.phi)); xy.y = C * lp.phi; return xy; } static PJ_LP putp5_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_putp5_data *Q = static_cast<struct pj_putp5_data *>(P->opaque); lp.phi = xy.y / C; lp.lam = xy.x / (C * (Q->A - Q->B * sqrt(1. + D * lp.phi * lp.phi))); return lp; } PJ *PJ_PROJECTION(putp5) { struct pj_putp5_data *Q = static_cast<struct pj_putp5_data *>( calloc(1, sizeof(struct pj_putp5_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->A = 2.; Q->B = 1.; P->es = 0.; P->inv = putp5_s_inverse; P->fwd = putp5_s_forward; return P; } PJ *PJ_PROJECTION(putp5p) { struct pj_putp5_data *Q = static_cast<struct pj_putp5_data *>( calloc(1, sizeof(struct pj_putp5_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; Q->A = 1.5; Q->B = 0.5; P->es = 0.; P->inv = putp5_s_inverse; P->fwd = putp5_s_forward; return P; } #undef C #undef D
cpp
PROJ
data/projects/PROJ/src/projections/wink1.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(wink1, "Winkel I") "\n\tPCyl, Sph\n\tlat_ts="; namespace { // anonymous namespace struct pj_wink1_data { double cosphi1; }; } // anonymous namespace static PJ_XY wink1_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = .5 * lp.lam * (static_cast<struct pj_wink1_data *>(P->opaque)->cosphi1 + cos(lp.phi)); xy.y = lp.phi; return (xy); } static PJ_LP wink1_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = xy.y; lp.lam = 2. * xy.x / (static_cast<struct pj_wink1_data *>(P->opaque)->cosphi1 + cos(lp.phi)); return (lp); } PJ *PJ_PROJECTION(wink1) { struct pj_wink1_data *Q = static_cast<struct pj_wink1_data *>( calloc(1, sizeof(struct pj_wink1_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; static_cast<struct pj_wink1_data *>(P->opaque)->cosphi1 = cos(pj_param(P->ctx, P->params, "rlat_ts").f); P->es = 0.; P->inv = wink1_s_inverse; P->fwd = wink1_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/tpeqd.cpp
#include "proj.h" #include "proj_internal.h" #include <errno.h> #include <math.h> PROJ_HEAD(tpeqd, "Two Point Equidistant") "\n\tMisc Sph\n\tlat_1= lon_1= lat_2= lon_2="; namespace { // anonymous namespace struct pj_tpeqd { double cp1, sp1, cp2, sp2, ccs, cs, sc, r2z0, z02, dlam2; double hz0, thz0, rhshz0, ca, sa, lp, lamc; }; } // anonymous namespace static PJ_XY tpeqd_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pj_tpeqd *Q = static_cast<struct pj_tpeqd *>(P->opaque); double t, z1, z2, dl1, dl2, sp, cp; sp = sin(lp.phi); cp = cos(lp.phi); z1 = aacos(P->ctx, Q->sp1 * sp + Q->cp1 * cp * cos(dl1 = lp.lam + Q->dlam2)); z2 = aacos(P->ctx, Q->sp2 * sp + Q->cp2 * cp * cos(dl2 = lp.lam - Q->dlam2)); z1 *= z1; z2 *= z2; t = z1 - z2; xy.x = Q->r2z0 * t; t = Q->z02 - t; xy.y = Q->r2z0 * asqrt(4. * Q->z02 * z2 - t * t); if ((Q->ccs * sp - cp * (Q->cs * sin(dl1) - Q->sc * sin(dl2))) < 0.) xy.y = -xy.y; return xy; } static PJ_LP tpeqd_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pj_tpeqd *Q = static_cast<struct pj_tpeqd *>(P->opaque); double cz1, cz2, s, d, cp, sp; cz1 = cos(hypot(xy.y, xy.x + Q->hz0)); cz2 = cos(hypot(xy.y, xy.x - Q->hz0)); s = cz1 + cz2; d = cz1 - cz2; lp.lam = -atan2(d, (s * Q->thz0)); lp.phi = aacos(P->ctx, hypot(Q->thz0 * s, d) * Q->rhshz0); if (xy.y < 0.) lp.phi = -lp.phi; /* lam--phi now in system relative to P1--P2 base equator */ sp = sin(lp.phi); cp = cos(lp.phi); lp.lam -= Q->lp; s = cos(lp.lam); lp.phi = aasin(P->ctx, Q->sa * sp + Q->ca * cp * s); lp.lam = atan2(cp * sin(lp.lam), Q->sa * cp * s - Q->ca * sp) + Q->lamc; return lp; } PJ *PJ_PROJECTION(tpeqd) { double lam_1, lam_2, phi_1, phi_2, A12; struct pj_tpeqd *Q = static_cast<struct pj_tpeqd *>(calloc(1, sizeof(struct pj_tpeqd))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; /* get control point locations */ phi_1 = pj_param(P->ctx, P->params, "rlat_1").f; lam_1 = pj_param(P->ctx, P->params, "rlon_1").f; phi_2 = pj_param(P->ctx, P->params, "rlat_2").f; lam_2 = pj_param(P->ctx, P->params, "rlon_2").f; if (phi_1 == phi_2 && lam_1 == lam_2) { proj_log_error(P, _("Invalid value for lat_1/lon_1/lat_2/lon_2: the 2 " "points should be distinct.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } P->lam0 = adjlon(0.5 * (lam_1 + lam_2)); Q->dlam2 = adjlon(lam_2 - lam_1); Q->cp1 = cos(phi_1); Q->cp2 = cos(phi_2); Q->sp1 = sin(phi_1); Q->sp2 = sin(phi_2); Q->cs = Q->cp1 * Q->sp2; Q->sc = Q->sp1 * Q->cp2; Q->ccs = Q->cp1 * Q->cp2 * sin(Q->dlam2); const auto SQ = [](double x) { return x * x; }; // Numerically stable formula for computing the central angle from // (phi_1, lam_1) to (phi_2, lam_2). // Special case of Vincenty formula on the sphere. // https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulae const double cs_minus_sc_cos_dlam = Q->cs - Q->sc * cos(Q->dlam2); Q->z02 = atan2(sqrt(SQ(Q->cp2 * sin(Q->dlam2)) + SQ(cs_minus_sc_cos_dlam)), Q->sp1 * Q->sp2 + Q->cp1 * Q->cp2 * cos(Q->dlam2)); if (Q->z02 == 0.0) { // Actually happens when both lat_1 = lat_2 and |lat_1| = 90 proj_log_error(P, _("Invalid value for lat_1 and lat_2: their absolute " "value should be < 90°.")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } Q->hz0 = .5 * Q->z02; A12 = atan2(Q->cp2 * sin(Q->dlam2), cs_minus_sc_cos_dlam); const double pp = aasin(P->ctx, Q->cp1 * sin(A12)); Q->ca = cos(pp); Q->sa = sin(pp); Q->lp = adjlon(atan2(Q->cp1 * cos(A12), Q->sp1) - Q->hz0); Q->dlam2 *= .5; Q->lamc = M_HALFPI - atan2(sin(A12) * Q->sp1, cos(A12)) - Q->dlam2; Q->thz0 = tan(Q->hz0); Q->rhshz0 = .5 / sin(Q->hz0); Q->r2z0 = 0.5 / Q->z02; Q->z02 *= Q->z02; P->inv = tpeqd_s_inverse; P->fwd = tpeqd_s_forward; P->es = 0.; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/eck2.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(eck2, "Eckert II") "\n\tPCyl, Sph"; #define FXC 0.46065886596178063902 #define FYC 1.44720250911653531871 #define C13 0.33333333333333333333 #define ONEEPS 1.0000001 static PJ_XY eck2_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; (void)P; xy.x = FXC * lp.lam * (xy.y = sqrt(4. - 3. * sin(fabs(lp.phi)))); xy.y = FYC * (2. - xy.y); if (lp.phi < 0.) xy.y = -xy.y; return (xy); } static PJ_LP eck2_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; (void)P; lp.phi = 2. - fabs(xy.y) / FYC; lp.lam = xy.x / (FXC * lp.phi); lp.phi = (4. - lp.phi * lp.phi) * C13; if (fabs(lp.phi) >= 1.) { if (fabs(lp.phi) > ONEEPS) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { lp.phi = lp.phi < 0. ? -M_HALFPI : M_HALFPI; } } else lp.phi = asin(lp.phi); if (xy.y < 0) lp.phi = -lp.phi; return (lp); } PJ *PJ_PROJECTION(eck2) { P->es = 0.; P->inv = eck2_s_inverse; P->fwd = eck2_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/src/projections/hammer.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(hammer, "Hammer & Eckert-Greifendorff") "\n\tMisc Sph, \n\tW= M="; #define EPS 1.0e-10 namespace { // anonymous namespace struct pq_hammer { double w; double m, rm; }; } // anonymous namespace static PJ_XY hammer_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; struct pq_hammer *Q = static_cast<struct pq_hammer *>(P->opaque); double cosphi, d; cosphi = cos(lp.phi); lp.lam *= Q->w; double denom = 1. + cosphi * cos(lp.lam); if (denom == 0.0) { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return proj_coord_error().xy; } d = sqrt(2. / denom); xy.x = Q->m * d * cosphi * sin(lp.lam); xy.y = Q->rm * d * sin(lp.phi); return xy; } static PJ_LP hammer_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; struct pq_hammer *Q = static_cast<struct pq_hammer *>(P->opaque); double z; z = sqrt(1. - 0.25 * Q->w * Q->w * xy.x * xy.x - 0.25 * xy.y * xy.y); if (fabs(2. * z * z - 1.) < EPS) { lp.lam = HUGE_VAL; lp.phi = HUGE_VAL; proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); } else { lp.lam = aatan2(Q->w * xy.x * z, 2. * z * z - 1) / Q->w; lp.phi = aasin(P->ctx, z * xy.y); } return lp; } PJ *PJ_PROJECTION(hammer) { struct pq_hammer *Q = static_cast<struct pq_hammer *>(calloc(1, sizeof(struct pq_hammer))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; if (pj_param(P->ctx, P->params, "tW").i) { Q->w = fabs(pj_param(P->ctx, P->params, "dW").f); if (Q->w <= 0.) { proj_log_error(P, _("Invalid value for W: it should be > 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } else Q->w = .5; if (pj_param(P->ctx, P->params, "tM").i) { Q->m = fabs(pj_param(P->ctx, P->params, "dM").f); if (Q->m <= 0.) { proj_log_error(P, _("Invalid value for M: it should be > 0")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } else Q->m = 1.; Q->rm = 1. / Q->m; Q->m /= Q->w; P->es = 0.; P->fwd = hammer_s_forward; P->inv = hammer_s_inverse; return P; } #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/cea.cpp
#include <errno.h> #include <math.h> #include "proj.h" #include "proj_internal.h" namespace { // anonymous namespace struct pj_cea_data { double qp; double *apa; }; } // anonymous namespace PROJ_HEAD(cea, "Equal Area Cylindrical") "\n\tCyl, Sph&Ell\n\tlat_ts="; #define EPS 1e-10 static PJ_XY cea_e_forward(PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = P->k0 * lp.lam; xy.y = 0.5 * pj_qsfn(sin(lp.phi), P->e, P->one_es) / P->k0; return xy; } static PJ_XY cea_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; xy.x = P->k0 * lp.lam; xy.y = sin(lp.phi) / P->k0; return xy; } static PJ_LP cea_e_inverse(PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */ PJ_LP lp = {0.0, 0.0}; lp.phi = pj_authlat(asin(2. * xy.y * P->k0 / static_cast<struct pj_cea_data *>(P->opaque)->qp), static_cast<struct pj_cea_data *>(P->opaque)->apa); lp.lam = xy.x / P->k0; return lp; } static PJ_LP cea_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; xy.y *= P->k0; const double t = fabs(xy.y); if (t - EPS <= 1.) { if (t >= 1.) lp.phi = xy.y < 0. ? -M_HALFPI : M_HALFPI; else lp.phi = asin(xy.y); lp.lam = xy.x / P->k0; } else { proj_errno_set(P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } return (lp); } static PJ *pj_cea_destructor(PJ *P, int errlev) { /* Destructor */ if (nullptr == P) return nullptr; if (nullptr == P->opaque) return pj_default_destructor(P, errlev); free(static_cast<struct pj_cea_data *>(P->opaque)->apa); return pj_default_destructor(P, errlev); } PJ *PJ_PROJECTION(cea) { double t = 0.0; struct pj_cea_data *Q = static_cast<struct pj_cea_data *>( calloc(1, sizeof(struct pj_cea_data))); if (nullptr == Q) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); P->opaque = Q; P->destructor = pj_cea_destructor; if (pj_param(P->ctx, P->params, "tlat_ts").i) { t = pj_param(P->ctx, P->params, "rlat_ts").f; P->k0 = cos(t); if (P->k0 < 0.) { proj_log_error( P, _("Invalid value for lat_ts: |lat_ts| should be <= 90°")); return pj_default_destructor(P, PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); } } if (P->es != 0.0) { t = sin(t); P->k0 /= sqrt(1. - P->es * t * t); P->e = sqrt(P->es); Q->apa = pj_authset(P->es); if (!(Q->apa)) return pj_default_destructor(P, PROJ_ERR_OTHER /*ENOMEM*/); Q->qp = pj_qsfn(1., P->e, P->one_es); P->inv = cea_e_inverse; P->fwd = cea_e_forward; } else { P->inv = cea_s_inverse; P->fwd = cea_s_forward; } return P; } #undef EPS
cpp
PROJ
data/projects/PROJ/src/projections/eck4.cpp
#include <math.h> #include "proj.h" #include "proj_internal.h" PROJ_HEAD(eck4, "Eckert IV") "\n\tPCyl, Sph"; // C_x = 2 / sqrt(4 * M_PI + M_PI * M_PI) constexpr double C_x = .42223820031577120149; // C_y = 2 * sqrt(M_PI / (4 + M_PI)) constexpr double C_y = 1.32650042817700232218; // RC_y = 1. / C_y constexpr double RC_y = .75386330736002178205; // C_p = 2 + M_PI / 2 constexpr double C_p = 3.57079632679489661922; // RC_p = 1. / C_p constexpr double RC_p = .28004957675577868795; static PJ_XY eck4_s_forward(PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0, 0.0}; int i; (void)P; // Newton's iterative method to find theta such as // theta + sin(theta) * cos(theta) + 2 * sin(theta) == C_p * sin(phi) const double p = C_p * sin(lp.phi); double V = lp.phi * lp.phi; double theta = lp.phi * (0.895168 + V * (0.0218849 + V * 0.00826809)); constexpr int NITER = 6; for (i = NITER; i; --i) { const double c = cos(theta); const double s = sin(theta); V = (theta + s * (c + 2.) - p) / (1. + c * (c + 2.) - s * s); theta -= V; constexpr double EPS = 1e-7; if (fabs(V) < EPS) break; } if (!i) { xy.x = C_x * lp.lam; xy.y = theta < 0. ? -C_y : C_y; } else { xy.x = C_x * lp.lam * (1. + cos(theta)); xy.y = C_y * sin(theta); } return xy; } static PJ_LP eck4_s_inverse(PJ_XY xy, PJ *P) { /* Spheroidal, inverse */ PJ_LP lp = {0.0, 0.0}; const double sin_theta = xy.y * RC_y; const double one_minus_abs_sin_theta = 1.0 - fabs(sin_theta); if (one_minus_abs_sin_theta >= 0.0 && one_minus_abs_sin_theta <= 1e-12) { lp.lam = xy.x / C_x; lp.phi = sin_theta > 0 ? M_PI / 2 : -M_PI / 2; } else { const double theta = aasin(P->ctx, sin_theta); const double cos_theta = cos(theta); lp.lam = xy.x / (C_x * (1. + cos_theta)); const double sin_phi = (theta + sin_theta * (cos_theta + 2.)) * RC_p; lp.phi = aasin(P->ctx, sin_phi); } if (!P->over) { const double fabs_lam_minus_pi = fabs(lp.lam) - M_PI; if (fabs_lam_minus_pi > 0.0) { if (fabs_lam_minus_pi > 1e-10) { proj_errno_set( P, PROJ_ERR_COORD_TRANSFM_OUTSIDE_PROJECTION_DOMAIN); return lp; } else { lp.lam = lp.lam > 0 ? M_PI : -M_PI; } } } return lp; } PJ *PJ_PROJECTION(eck4) { P->es = 0.0; P->inv = eck4_s_inverse; P->fwd = eck4_s_forward; return P; }
cpp
PROJ
data/projects/PROJ/test/fuzzers/proj_crs_to_crs_fuzzer.cpp
/****************************************************************************** * * Project: proj.4 * Purpose: Fuzzer * Author: Even Rouault, even.rouault at spatialys.com * ****************************************************************************** * Copyright (c) 2017, Even Rouault <even.rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include "proj.h" /* Standalone build: g++ -g -std=c++11 proj_crs_to_crs_fuzzer.cpp -o proj_crs_to_crs_fuzzer -fvisibility=hidden -DSTANDALONE ../../build/lib/libproj.a -lpthread -lsqlite3 -I../../src -I../../include */ extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv); extern "C" int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len); int LLVMFuzzerInitialize(int * /*argc*/, char ***argv) { const char *argv0 = (*argv)[0]; char *path = strdup(argv0); char *lastslash = strrchr(path, '/'); if (lastslash) { *lastslash = '\0'; setenv("PROJ_DATA", path, 1); } else { setenv("PROJ_DATA", ".", 1); } free(path); return 0; } int LLVMFuzzerTestOneInput(const uint8_t *buf, size_t len) { if (len > 1000) { #ifdef STANDALONE fprintf(stderr, "Input too large\n"); #endif return -1; } /* We expect the blob to be 2 lines: */ /* source_string\ndestination_string */ char *buf_dup = (char *)malloc(len + 1); memcpy(buf_dup, buf, len); buf_dup[len] = 0; char *first_line = buf_dup; char *first_newline = strchr(first_line, '\n'); if (!first_newline) { free(buf_dup); return -1; } first_newline[0] = 0; char *second_line = first_newline + 1; #ifdef STANDALONE fprintf(stderr, "src=%s\n", first_line); fprintf(stderr, "dst=%s\n", second_line); #endif proj_destroy( proj_create_crs_to_crs(nullptr, first_line, second_line, nullptr)); free(buf_dup); proj_cleanup(); return 0; } #ifdef STANDALONE int main(int argc, char *argv[]) { if (argc < 2) { const char str[] = "+proj=longlat +datum=WGS84 +nodefs\n+proj=longlat " "+datum=WGS84 +nodefs"; int ret = LLVMFuzzerTestOneInput((const uint8_t *)(str), sizeof(str) - 1); if (ret) return ret; return 0; } else { int nRet = 0; void *buf = nullptr; int nLen = 0; FILE *f = fopen(argv[1], "rb"); if (!f) { fprintf(stderr, "%s does not exist.\n", argv[1]); exit(1); } fseek(f, 0, SEEK_END); nLen = (int)ftell(f); fseek(f, 0, SEEK_SET); buf = malloc(nLen); if (!buf) { fprintf(stderr, "malloc failed.\n"); fclose(f); exit(1); } if (fread(buf, nLen, 1, f) != 1) { fprintf(stderr, "fread failed.\n"); fclose(f); free(buf); exit(1); } fclose(f); nRet = LLVMFuzzerTestOneInput((const uint8_t *)(buf), nLen); free(buf); return nRet; } } #endif // STANDALONE
cpp
PROJ
data/projects/PROJ/test/postinstall/c_app/c_app.c
#include <proj.h> #include <stdio.h> int test_transform() { PJ *P; PJ_COORD a, b; P = proj_create_crs_to_crs( PJ_DEFAULT_CTX, "EPSG:4326", "+proj=utm +zone=32 +datum=WGS84", /* or EPSG:32632 */ NULL); if (0 == P) { fprintf(stderr, "Oops\n"); return 1; } /* Copenhagen: 55d N, 12d E */ a = proj_coord(55, 12, 0, 0); b = proj_trans(P, PJ_FWD, a); printf("easting: %.2f, northing: %.2f, ", b.enu.e, b.enu.n); b = proj_trans(P, PJ_INV, b); printf("latitude: %.2f, longitude: %.2f\n", b.lp.lam, b.lp.phi); proj_destroy(P); return 0; } int main(int argc, char *argv[]) { PJ_INFO info; info = proj_info(); if (argc == 2 && argv[1][0] == '-') { switch (argv[1][1]) { case 't': return (test_transform()); case 's': printf("%s\n", info.searchpath); return (0); case 'v': printf("%d.%d.%d\n", info.major, info.minor, info.patch); return (0); } } fprintf(stderr, "Use option -t, -s or -v\n"); return (1); }
c
PROJ
data/projects/PROJ/test/postinstall/cpp_app/cpp_app.cpp
#include <iostream> #include <proj.h> int test_transform() { PJ *P; PJ_COORD a, b; P = proj_create_crs_to_crs( PJ_DEFAULT_CTX, "EPSG:4326", "+proj=utm +zone=32 +datum=WGS84", // or EPSG:32632 NULL); if (0 == P) { std::cerr << "Oops" << std::endl; return 1; } // Copenhagen: 55d N, 12d E a = proj_coord(55, 12, 0, 0); b = proj_trans(P, PJ_FWD, a); std::cout.precision(2); std::cout.setf(std::ios::fixed, std::ios::floatfield); std::cout << "easting: " << b.enu.e << ", northing: " << b.enu.n; b = proj_trans(P, PJ_INV, b); std::cout << ", latitude: " << b.lp.lam << ", longitude: " << b.lp.phi << std::endl; proj_destroy(P); return 0; } int main(int argc, char *argv[]) { PJ_INFO info; info = proj_info(); if (argc == 2 && argv[1][0] == '-') { switch (argv[1][1]) { case 't': return (test_transform()); case 's': std::cout << info.searchpath << std::endl; return (0); case 'v': std::cout << info.major << '.' << info.minor << '.' << info.patch << std::endl; return (0); } } std::cerr << "Use option -t, -s or -v" << std::endl; return (1); }
cpp
PROJ
data/projects/PROJ/test/unit/test_coordinates.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2023, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" // to be able to use internal::replaceAll #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinates.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include <cmath> #include <string> #include <vector> using namespace osgeo::proj::common; using namespace osgeo::proj::coordinates; using namespace osgeo::proj::crs; using namespace osgeo::proj::cs; using namespace osgeo::proj::datum; using namespace osgeo::proj::io; using namespace osgeo::proj::metadata; using namespace osgeo::proj::util; namespace { struct ObjectKeeper { PJ *m_obj = nullptr; explicit ObjectKeeper(PJ *obj) : m_obj(obj) {} ~ObjectKeeper() { proj_destroy(m_obj); } void clear() { proj_destroy(m_obj); m_obj = nullptr; } ObjectKeeper(const ObjectKeeper &) = delete; ObjectKeeper &operator=(const ObjectKeeper &) = delete; }; struct PjContextKeeper { PJ_CONTEXT *m_ctxt = nullptr; explicit PjContextKeeper(PJ_CONTEXT *ctxt) : m_ctxt(ctxt) {} ~PjContextKeeper() { proj_context_destroy(m_ctxt); } PjContextKeeper(const PjContextKeeper &) = delete; PjContextKeeper &operator=(const PjContextKeeper &) = delete; }; } // namespace // --------------------------------------------------------------------------- static VerticalCRSNNPtr createVerticalCRS() { PropertyMap propertiesVDatum; propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5101) .set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn"); auto vdatum = VerticalReferenceFrame::create(propertiesVDatum); PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5701) .set(IdentifiedObject::NAME_KEY, "ODN height"); return VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(coordinateMetadata, static_crs) { auto coordinateMetadata = CoordinateMetadata::create(GeographicCRS::EPSG_4326); EXPECT_TRUE(coordinateMetadata->crs()->isEquivalentTo( GeographicCRS::EPSG_4326.get())); EXPECT_FALSE(coordinateMetadata->coordinateEpoch().has_value()); // We tolerate coordinate epochs for EPSG:4326 EXPECT_NO_THROW( CoordinateMetadata::create(GeographicCRS::EPSG_4326, 2025.0)); // A coordinate epoch should NOT be provided EXPECT_THROW(CoordinateMetadata::create(createVerticalCRS(), 2025.0), Exception); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); auto wkt = coordinateMetadata->exportToWKT(f.get()); auto obj = WKTParser().createFromWKT(wkt); auto coordinateMetadataFromWkt = nn_dynamic_pointer_cast<CoordinateMetadata>(obj); ASSERT_TRUE(coordinateMetadataFromWkt != nullptr); EXPECT_TRUE(coordinateMetadataFromWkt->crs()->isEquivalentTo( GeographicCRS::EPSG_4326.get())); EXPECT_FALSE(coordinateMetadataFromWkt->coordinateEpoch().has_value()); auto ctxt = proj_context_create(); PjContextKeeper ctxtKeeper(ctxt); auto pjObj = proj_create(ctxt, wkt.c_str()); ObjectKeeper objKeeper(pjObj); ASSERT_TRUE(pjObj != nullptr); EXPECT_EQ(proj_get_type(pjObj), PJ_TYPE_COORDINATE_METADATA); EXPECT_TRUE(std::isnan(proj_coordinate_metadata_get_epoch(ctxt, pjObj))); auto pjObj2 = proj_get_source_crs(ctxt, pjObj); ObjectKeeper objKeeper2(pjObj2); EXPECT_TRUE(pjObj2 != nullptr); auto projjson = coordinateMetadata->exportToJSON(JSONFormatter::create(nullptr).get()); auto obj2 = createFromUserInput(projjson, nullptr); auto coordinateMetadataFromJson = nn_dynamic_pointer_cast<CoordinateMetadata>(obj2); ASSERT_TRUE(coordinateMetadataFromJson != nullptr); EXPECT_TRUE(coordinateMetadataFromJson->crs()->isEquivalentTo( GeographicCRS::EPSG_4326.get())); EXPECT_FALSE(coordinateMetadataFromJson->coordinateEpoch().has_value()); } // --------------------------------------------------------------------------- TEST(coordinateMetadata, dynamic_crs) { auto drf = DynamicGeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), Ellipsoid::WGS84, optional<std::string>("My anchor"), PrimeMeridian::GREENWICH, Measure(2018.5, UnitOfMeasure::YEAR), optional<std::string>("My model")); auto crs = GeographicCRS::create( PropertyMap(), drf, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto coordinateMetadata = CoordinateMetadata::create(crs, 2023.5); EXPECT_TRUE(coordinateMetadata->crs()->isEquivalentTo(crs.get())); EXPECT_TRUE(coordinateMetadata->coordinateEpoch().has_value()); EXPECT_NEAR(coordinateMetadata->coordinateEpochAsDecimalYear(), 2023.5, 1e-10); // A coordinate epoch should be provided EXPECT_THROW(CoordinateMetadata::create(crs), Exception); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); auto wkt = coordinateMetadata->exportToWKT(f.get()); auto obj = WKTParser().createFromWKT(wkt); auto coordinateMetadataFromWkt = nn_dynamic_pointer_cast<CoordinateMetadata>(obj); EXPECT_TRUE(coordinateMetadataFromWkt->crs()->isEquivalentTo(crs.get())); EXPECT_TRUE(coordinateMetadataFromWkt->coordinateEpoch().has_value()); EXPECT_NEAR(coordinateMetadataFromWkt->coordinateEpochAsDecimalYear(), 2023.5, 1e-10); auto ctxt = proj_context_create(); PjContextKeeper ctxtKeeper(ctxt); auto pjObj = proj_create(ctxt, wkt.c_str()); ObjectKeeper objKeeper(pjObj); ASSERT_TRUE(pjObj != nullptr); EXPECT_EQ(proj_get_type(pjObj), PJ_TYPE_COORDINATE_METADATA); EXPECT_NEAR(proj_coordinate_metadata_get_epoch(ctxt, pjObj), 2023.5, 1e-10); auto projjson = coordinateMetadata->exportToJSON(JSONFormatter::create(nullptr).get()); auto obj2 = createFromUserInput(projjson, nullptr); auto coordinateMetadataFromJson = nn_dynamic_pointer_cast<CoordinateMetadata>(obj2); EXPECT_TRUE(coordinateMetadataFromJson->crs()->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(coordinateMetadataFromJson->coordinateEpoch().has_value()); EXPECT_NEAR(coordinateMetadataFromJson->coordinateEpochAsDecimalYear(), 2023.5, 1e-10); } // --------------------------------------------------------------------------- TEST(coordinateMetadata, crs_with_point_motion_operation_and_promote_to_3D) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); { // "NAD83(CSRS)v7" auto crs = factory->createCoordinateReferenceSystem("8255"); EXPECT_THROW(CoordinateMetadata::create(crs, 2023.5), Exception); EXPECT_NO_THROW(CoordinateMetadata::create(crs, 2023.5, dbContext)); auto cm = CoordinateMetadata::create(crs, 2023.5, dbContext) ->promoteTo3D(std::string(), dbContext); EXPECT_TRUE(cm->crs()->isEquivalentTo( crs->promoteTo3D(std::string(), dbContext).get())); EXPECT_TRUE(cm->coordinateEpoch().has_value()); EXPECT_NEAR(cm->coordinateEpochAsDecimalYear(), 2023.5, 1e-10); } { auto crs = factory->createCoordinateReferenceSystem("4267"); EXPECT_THROW(CoordinateMetadata::create(crs, 2023.5, dbContext), Exception); auto cm = CoordinateMetadata::create(crs)->promoteTo3D(std::string(), dbContext); EXPECT_TRUE(cm->crs()->isEquivalentTo( crs->promoteTo3D(std::string(), dbContext).get())); EXPECT_TRUE(!cm->coordinateEpoch().has_value()); } }
cpp
PROJ
data/projects/PROJ/test/unit/main.cpp
/****************************************************************************** * * Project: PROJ * Purpose: gtest main * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <locale> #include "gtest_include.h" GTEST_API_ int main(int argc, char **argv) { // Use a potentially non-C locale to make sure we are robust setlocale(LC_ALL, ""); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
cpp
PROJ
data/projects/PROJ/test/unit/pj_phi2_test.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test pj_phi2 function. * Author: Kurt Schwehr <[email protected]> * ****************************************************************************** * Copyright (c) 2018, Google Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "proj.h" #include "proj_internal.h" #include <cmath> #include <limits> #include "gtest_include.h" namespace { TEST(PjPhi2Test, Basic) { PJ_CONTEXT *ctx = pj_get_default_ctx(); // Expectation is that only sane values of e (and nan is here reckoned to // be sane) are passed to pj_phi2. Thus the return value with other values // of e is "implementation dependent". constexpr auto inf = std::numeric_limits<double>::infinity(); constexpr auto nan = std::numeric_limits<double>::quiet_NaN(); // Strict equality is demanded here. EXPECT_EQ(M_PI_2, pj_phi2(ctx, +0.0, 0.0)); EXPECT_EQ(0.0, pj_phi2(ctx, 1.0, 0.0)); EXPECT_EQ(-M_PI_2, pj_phi2(ctx, inf, 0.0)); // We don't expect pj_phi2 to be called with negative ts (since ts = // exp(-psi)). However, in the current implementation it is odd in ts. // N.B. ts = +0.0 and ts = -0.0 return different results. EXPECT_EQ(-M_PI_2, pj_phi2(ctx, -0.0, 0.0)); EXPECT_EQ(0.0, pj_phi2(ctx, -1.0, 0.0)); EXPECT_EQ(+M_PI_2, pj_phi2(ctx, -inf, 0.0)); constexpr double e = 0.2; EXPECT_EQ(M_PI_2, pj_phi2(ctx, +0.0, e)); EXPECT_EQ(0.0, pj_phi2(ctx, 1.0, e)); EXPECT_EQ(-M_PI_2, pj_phi2(ctx, inf, e)); EXPECT_EQ(-M_PI_2, pj_phi2(ctx, -0.0, e)); EXPECT_EQ(0.0, pj_phi2(ctx, -1.0, e)); EXPECT_EQ(+M_PI_2, pj_phi2(ctx, -inf, e)); EXPECT_TRUE(std::isnan(pj_phi2(ctx, nan, 0.0))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, nan, e))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, +0.0, nan))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, 1.0, nan))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, inf, nan))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, -0.0, nan))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, -1.0, nan))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, -inf, nan))); EXPECT_TRUE(std::isnan(pj_phi2(ctx, nan, nan))); EXPECT_DOUBLE_EQ(M_PI / 3, pj_phi2(ctx, 1 / (sqrt(3.0) + 2), 0.0)); EXPECT_DOUBLE_EQ(M_PI / 4, pj_phi2(ctx, 1 / (sqrt(2.0) + 1), 0.0)); EXPECT_DOUBLE_EQ(M_PI / 6, pj_phi2(ctx, 1 / sqrt(3.0), 0.0)); EXPECT_DOUBLE_EQ(-M_PI / 3, pj_phi2(ctx, sqrt(3.0) + 2, 0.0)); EXPECT_DOUBLE_EQ(-M_PI / 4, pj_phi2(ctx, sqrt(2.0) + 1, 0.0)); EXPECT_DOUBLE_EQ(-M_PI / 6, pj_phi2(ctx, sqrt(3.0), 0.0)); // Generated with exp(e * atanh(e * sin(phi))) / (tan(phi) + sec(phi)) EXPECT_DOUBLE_EQ(M_PI / 3, pj_phi2(ctx, 0.27749174377027023413, e)); EXPECT_DOUBLE_EQ(M_PI / 4, pj_phi2(ctx, 0.42617788119104192995, e)); EXPECT_DOUBLE_EQ(M_PI / 6, pj_phi2(ctx, 0.58905302448626726064, e)); EXPECT_DOUBLE_EQ(-M_PI / 3, pj_phi2(ctx, 3.6037108218537833089, e)); EXPECT_DOUBLE_EQ(-M_PI / 4, pj_phi2(ctx, 2.3464380582241712935, e)); EXPECT_DOUBLE_EQ(-M_PI / 6, pj_phi2(ctx, 1.6976400399134411849, e)); } } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_operation.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" // to be able to use internal::replaceAll #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj_constants.h" #include <string> #include <vector> using namespace osgeo::proj::common; using namespace osgeo::proj::crs; using namespace osgeo::proj::cs; using namespace osgeo::proj::datum; using namespace osgeo::proj::io; using namespace osgeo::proj::internal; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; namespace { struct UnrelatedObject : public IComparable { UnrelatedObject() = default; bool _isEquivalentTo(const IComparable *, Criterion, const DatabaseContextPtr &) const override { assert(false); return false; } }; static nn<std::shared_ptr<UnrelatedObject>> createUnrelatedObject() { return nn_make_shared<UnrelatedObject>(); } } // namespace // --------------------------------------------------------------------------- TEST(operation, method) { auto method = OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>{}); EXPECT_TRUE(method->isEquivalentTo(method.get())); EXPECT_FALSE(method->isEquivalentTo(createUnrelatedObject().get())); auto otherMethod = OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}); EXPECT_TRUE(otherMethod->isEquivalentTo(otherMethod.get())); EXPECT_FALSE(method->isEquivalentTo(otherMethod.get())); auto otherMethod2 = OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2"))}); EXPECT_FALSE(otherMethod->isEquivalentTo(otherMethod2.get())); EXPECT_FALSE(otherMethod->isEquivalentTo( otherMethod2.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, method_parameter_different_order) { auto method1 = OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>{ OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "paramName")), OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "paramName2"))}); auto method2 = OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>{ OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "paramName2")), OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "paramName"))}); auto method3 = OperationMethod::create( PropertyMap(), std::vector<OperationParameterNNPtr>{ OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "paramName3")), OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "paramName"))}); EXPECT_FALSE(method1->isEquivalentTo(method2.get())); EXPECT_TRUE(method1->isEquivalentTo(method2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(method1->isEquivalentTo(method3.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, ParameterValue) { auto valStr1 = ParameterValue::create("str1"); auto valStr2 = ParameterValue::create("str2"); EXPECT_TRUE(valStr1->isEquivalentTo(valStr1.get())); EXPECT_FALSE(valStr1->isEquivalentTo(createUnrelatedObject().get())); EXPECT_FALSE(valStr1->isEquivalentTo(valStr2.get())); auto valMeasure1 = ParameterValue::create(Angle(-90.0)); auto valMeasure1Eps = ParameterValue::create(Angle(-90.0 - 1e-11)); auto valMeasure2 = ParameterValue::create(Angle(-89.0)); EXPECT_TRUE(valMeasure1->isEquivalentTo(valMeasure1.get())); EXPECT_TRUE(valMeasure1->isEquivalentTo( valMeasure1.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(valMeasure1->isEquivalentTo(valMeasure1Eps.get())); EXPECT_TRUE(valMeasure1->isEquivalentTo( valMeasure1Eps.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(valMeasure1->isEquivalentTo(valStr1.get())); EXPECT_FALSE(valMeasure1->isEquivalentTo(valMeasure2.get())); EXPECT_FALSE(valMeasure1->isEquivalentTo( valMeasure2.get(), IComparable::Criterion::EQUIVALENT)); auto valInt1 = ParameterValue::create(1); auto valInt2 = ParameterValue::create(2); EXPECT_TRUE(valInt1->isEquivalentTo(valInt1.get())); EXPECT_FALSE(valInt1->isEquivalentTo(valInt2.get())); auto valTrue = ParameterValue::create(true); auto valFalse = ParameterValue::create(false); EXPECT_TRUE(valTrue->isEquivalentTo(valTrue.get())); EXPECT_FALSE(valTrue->isEquivalentTo(valFalse.get())); } // --------------------------------------------------------------------------- TEST(operation, OperationParameter) { auto op1 = OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName")); auto op2 = OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2")); EXPECT_TRUE(op1->isEquivalentTo(op1.get())); EXPECT_FALSE(op1->isEquivalentTo(createUnrelatedObject().get())); EXPECT_FALSE(op1->isEquivalentTo(op2.get())); } // --------------------------------------------------------------------------- TEST(operation, OperationParameterValue) { auto op1 = OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName")); auto op2 = OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2")); auto valStr1 = ParameterValue::create("str1"); auto valStr2 = ParameterValue::create("str2"); auto opv11 = OperationParameterValue::create(op1, valStr1); EXPECT_TRUE(opv11->isEquivalentTo(opv11.get())); EXPECT_FALSE(opv11->isEquivalentTo(createUnrelatedObject().get())); auto opv12 = OperationParameterValue::create(op1, valStr2); EXPECT_FALSE(opv11->isEquivalentTo(opv12.get())); auto opv21 = OperationParameterValue::create(op2, valStr1); EXPECT_FALSE(opv11->isEquivalentTo(opv12.get())); } // --------------------------------------------------------------------------- TEST(operation, SingleOperation) { auto sop1 = Transformation::create( PropertyMap(), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), static_cast<CRSPtr>(GeographicCRS::EPSG_4979.as_nullable()), PropertyMap(), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); EXPECT_TRUE(sop1->isEquivalentTo(sop1.get())); EXPECT_FALSE(sop1->isEquivalentTo(createUnrelatedObject().get())); EXPECT_TRUE( sop1->isEquivalentTo(sop1->CoordinateOperation::shallowClone().get())); EXPECT_TRUE(sop1->inverse()->isEquivalentTo( sop1->inverse()->CoordinateOperation::shallowClone().get())); auto sop2 = Transformation::create( PropertyMap(), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), static_cast<CRSPtr>(GeographicCRS::EPSG_4979.as_nullable()), PropertyMap(), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); EXPECT_FALSE(sop1->isEquivalentTo(sop2.get())); auto sop3 = Transformation::create( PropertyMap(), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), static_cast<CRSPtr>(GeographicCRS::EPSG_4979.as_nullable()), PropertyMap(), std::vector<OperationParameterNNPtr>{ OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName")), OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin"), ParameterValue::createFilename("foo2.bin")}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); EXPECT_FALSE(sop1->isEquivalentTo(sop3.get())); auto sop4 = Transformation::create( PropertyMap(), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), static_cast<CRSPtr>(GeographicCRS::EPSG_4979.as_nullable()), PropertyMap(), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo2.bin")}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); EXPECT_FALSE(sop1->isEquivalentTo(sop4.get())); } // --------------------------------------------------------------------------- TEST(operation, SingleOperation_different_order) { auto sop1 = Transformation::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "ignored1"), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4807, nullptr, PropertyMap(), std::vector<OperationParameterNNPtr>{ OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName")), OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin"), ParameterValue::createFilename("foo2.bin")}, {}); auto sop2 = Transformation::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "ignored2"), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4807, nullptr, PropertyMap(), std::vector<OperationParameterNNPtr>{ OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2")), OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo2.bin"), ParameterValue::createFilename("foo.bin")}, {}); auto sop3 = Transformation::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "ignored3"), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4807, nullptr, PropertyMap(), std::vector<OperationParameterNNPtr>{ OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName")), OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName2"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo2.bin"), ParameterValue::createFilename("foo.bin")}, {}); EXPECT_FALSE(sop1->isEquivalentTo(sop2.get())); EXPECT_TRUE( sop1->isEquivalentTo(sop2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( sop1->isEquivalentTo(sop3.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, transformation_to_wkt) { PropertyMap propertiesTransformation; propertiesTransformation .set(Identifier::CODESPACE_KEY, "codeSpaceTransformation") .set(Identifier::CODE_KEY, "codeTransformation") .set(IdentifiedObject::NAME_KEY, "transformationName") .set(IdentifiedObject::REMARKS_KEY, "my remarks"); auto transf = Transformation::create( propertiesTransformation, nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), static_cast<CRSPtr>(GeographicCRS::EPSG_4979.as_nullable()), PropertyMap() .set(Identifier::CODESPACE_KEY, "codeSpaceOperationMethod") .set(Identifier::CODE_KEY, "codeOperationMethod") .set(IdentifiedObject::NAME_KEY, "operationMethodName"), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); std::string src_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); src_wkt = GeographicCRS::EPSG_4326->exportToWKT(formatter.get()); } std::string dst_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); dst_wkt = GeographicCRS::EPSG_4807->exportToWKT(formatter.get()); } std::string interpolation_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); interpolation_wkt = GeographicCRS::EPSG_4979->exportToWKT(formatter.get()); } auto expected = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[" + dst_wkt + "],\n" " METHOD[\"operationMethodName\",\n" " ID[\"codeSpaceOperationMethod\",\"codeOperationMethod\"]],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"],\n" " INTERPOLATIONCRS[" + interpolation_wkt + "],\n" " OPERATIONACCURACY[0.1],\n" " ID[\"codeSpaceTransformation\",\"codeTransformation\"],\n" " REMARK[\"my remarks\"]]"; EXPECT_EQ( replaceAll(replaceAll(transf->exportToWKT(WKTFormatter::create().get()), " ", ""), "\n", ""), replaceAll(replaceAll(expected, " ", ""), "\n", "")); EXPECT_THROW( transf->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); EXPECT_TRUE(transf->isEquivalentTo(transf.get())); EXPECT_FALSE(transf->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(operation, concatenated_operation) { PropertyMap propertiesTransformation; propertiesTransformation .set(Identifier::CODESPACE_KEY, "codeSpaceTransformation") .set(Identifier::CODE_KEY, "codeTransformation") .set(IdentifiedObject::NAME_KEY, "transformationName") .set(IdentifiedObject::REMARKS_KEY, "my remarks"); auto transf_1 = Transformation::create( propertiesTransformation, nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), nullptr, PropertyMap().set(IdentifiedObject::NAME_KEY, "operationMethodName"), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>()); auto transf_2 = Transformation::create( propertiesTransformation, nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4979), nullptr, PropertyMap().set(IdentifiedObject::NAME_KEY, "operationMethodName"), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>()); auto concat = ConcatenatedOperation::create( PropertyMap() .set(Identifier::CODESPACE_KEY, "codeSpace") .set(Identifier::CODE_KEY, "code") .set(IdentifiedObject::NAME_KEY, "name") .set(IdentifiedObject::REMARKS_KEY, "my remarks"), std::vector<CoordinateOperationNNPtr>{transf_1, transf_2}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); std::string src_wkt; { auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); src_wkt = GeographicCRS::EPSG_4326->exportToWKT(formatter.get()); } std::string dst_wkt; { auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); dst_wkt = GeographicCRS::EPSG_4979->exportToWKT(formatter.get()); } std::string step1_wkt; { auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); step1_wkt = transf_1->exportToWKT(formatter.get()); } std::string step2_wkt; { auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); step2_wkt = transf_2->exportToWKT(formatter.get()); } auto expected = "CONCATENATEDOPERATION[\"name\",\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[" + dst_wkt + "],\n" " STEP[" + step1_wkt + "],\n" " STEP[" + step2_wkt + "],\n" " OPERATIONACCURACY[0.1],\n" " ID[\"codeSpace\",\"code\"],\n" " REMARK[\"my remarks\"]]"; EXPECT_EQ(replaceAll(replaceAll(concat->exportToWKT( WKTFormatter::create( WKTFormatter::Convention::WKT2_2019) .get()), " ", ""), "\n", ""), replaceAll(replaceAll(expected, " ", ""), "\n", "")); EXPECT_THROW(concat->exportToWKT(WKTFormatter::create().get()), FormattingException); EXPECT_THROW(ConcatenatedOperation::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "name"), std::vector<CoordinateOperationNNPtr>{transf_1, transf_1}, std::vector<PositionalAccuracyNNPtr>()), InvalidOperation); auto inv = concat->inverse(); EXPECT_EQ(inv->nameStr(), "Inverse of name"); EXPECT_EQ(inv->sourceCRS()->nameStr(), concat->targetCRS()->nameStr()); EXPECT_EQ(inv->targetCRS()->nameStr(), concat->sourceCRS()->nameStr()); auto inv_as_concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(inv); ASSERT_TRUE(inv_as_concat != nullptr); ASSERT_EQ(inv_as_concat->operations().size(), 2U); EXPECT_EQ(inv_as_concat->operations()[0]->nameStr(), "Inverse of transformationName"); EXPECT_EQ(inv_as_concat->operations()[1]->nameStr(), "Inverse of transformationName"); EXPECT_TRUE(concat->isEquivalentTo(concat.get())); EXPECT_FALSE(concat->isEquivalentTo(createUnrelatedObject().get())); EXPECT_TRUE(concat->isEquivalentTo( concat->CoordinateOperation::shallowClone().get())); EXPECT_FALSE( ConcatenatedOperation::create(PropertyMap(), std::vector<CoordinateOperationNNPtr>{ transf_1, transf_1->inverse()}, std::vector<PositionalAccuracyNNPtr>()) ->isEquivalentTo(ConcatenatedOperation::create( PropertyMap(), std::vector<CoordinateOperationNNPtr>{ transf_1->inverse(), transf_1}, std::vector<PositionalAccuracyNNPtr>()) .get())); EXPECT_FALSE( ConcatenatedOperation::create(PropertyMap(), std::vector<CoordinateOperationNNPtr>{ transf_1, transf_1->inverse()}, std::vector<PositionalAccuracyNNPtr>()) ->isEquivalentTo(ConcatenatedOperation::create( PropertyMap(), std::vector<CoordinateOperationNNPtr>{ transf_1, transf_1->inverse(), transf_1}, std::vector<PositionalAccuracyNNPtr>()) .get())); } // --------------------------------------------------------------------------- TEST(operation, transformation_createGeocentricTranslations) { auto transf = Transformation::createGeocentricTranslations( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_TRUE(transf->validateParameters().empty()); auto params = transf->getTOWGS84Parameters(); auto expected = std::vector<double>{1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0}; EXPECT_EQ(params, expected); auto inv_transf = transf->inverse(); auto inv_transf_as_transf = nn_dynamic_pointer_cast<Transformation>(inv_transf); ASSERT_TRUE(inv_transf_as_transf != nullptr); EXPECT_EQ(transf->sourceCRS()->nameStr(), inv_transf_as_transf->targetCRS()->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), inv_transf_as_transf->sourceCRS()->nameStr()); auto expected_inv = std::vector<double>{-1.0, -2.0, -3.0, 0.0, 0.0, 0.0, 0.0}; EXPECT_EQ(inv_transf_as_transf->getTOWGS84Parameters(), expected_inv); EXPECT_EQ(transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=GRS80 +step +proj=helmert +x=1 +y=2 " "+z=3 +step +inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg +step " "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- static GeodeticCRSNNPtr createGeocentricDatumWGS84() { PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 4328) .set(IdentifiedObject::NAME_KEY, "WGS 84"); return GeodeticCRS::create( propertiesCRS, GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- static GeodeticCRSNNPtr createGeocentricKM() { PropertyMap propertiesCRS; propertiesCRS.set(IdentifiedObject::NAME_KEY, "Based on WGS 84"); return GeodeticCRS::create( propertiesCRS, GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric( UnitOfMeasure("kilometre", 1000.0, UnitOfMeasure::Type::LINEAR))); } // --------------------------------------------------------------------------- TEST(operation, transformation_createGeocentricTranslations_between_geocentricCRS) { auto transf1 = Transformation::createGeocentricTranslations( PropertyMap(), createGeocentricDatumWGS84(), createGeocentricKM(), 1.0, 2.0, 3.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_EQ(transf1->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=helmert +x=1 +y=2 +z=3 +step " "+proj=unitconvert +xy_in=m +z_in=m +xy_out=km +z_out=km"); auto transf2 = Transformation::createGeocentricTranslations( PropertyMap(), createGeocentricKM(), createGeocentricDatumWGS84(), 1.0, 2.0, 3.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_EQ(transf2->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=km +z_in=km " "+xy_out=m +z_out=m +step +proj=helmert +x=1 +y=2 +z=3"); auto transf3 = Transformation::createGeocentricTranslations( PropertyMap(), createGeocentricKM(), createGeocentricKM(), 1.0, 2.0, 3.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_EQ(transf3->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=km +z_in=km " "+xy_out=m +z_out=m +step +proj=helmert +x=1 +y=2 +z=3 +step " "+proj=unitconvert +xy_in=m +z_in=m +xy_out=km +z_out=km"); } // --------------------------------------------------------------------------- TEST(operation, transformation_createGeocentricTranslations_null) { auto transf = Transformation::createGeocentricTranslations( PropertyMap(), createGeocentricDatumWGS84(), createGeocentricDatumWGS84(), 0.0, 0.0, 0.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_EQ(transf->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, transformation_createGeocentricTranslations_neg_zero) { auto transf = Transformation::createGeocentricTranslations( PropertyMap(), createGeocentricDatumWGS84(), createGeocentricDatumWGS84(), 1.0, -0.0, 0.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_EQ(transf->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=helmert +x=-1 +y=0 +z=0"); } // --------------------------------------------------------------------------- TEST(operation, transformation_createPositionVector) { auto transf = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("100")}); EXPECT_TRUE(transf->validateParameters().empty()); ASSERT_EQ(transf->coordinateOperationAccuracies().size(), 1U); auto expected = std::vector<double>{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}; EXPECT_EQ(transf->getTOWGS84Parameters(), expected); EXPECT_EQ(transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=GRS80 +step +proj=helmert +x=1 +y=2 " "+z=3 +rx=4 +ry=5 +rz=6 +s=7 +convention=position_vector +step " "+inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); auto inv_transf = transf->inverse(); ASSERT_EQ(inv_transf->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(transf->sourceCRS()->nameStr(), inv_transf->targetCRS()->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), inv_transf->sourceCRS()->nameStr()); #ifdef USE_APPROXIMATE_HELMERT_INVERSE auto inv_transf_as_transf = nn_dynamic_pointer_cast<Transformation>(inv_transf); ASSERT_TRUE(inv_transf_as_transf != nullptr); #else EXPECT_EQ( inv_transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 +step " "+proj=cart +ellps=WGS84 +step +inv +proj=helmert +x=1 +y=2 +z=3 +rx=4 " "+ry=5 +rz=6 +s=7 +convention=position_vector +step +inv +proj=cart " "+ellps=GRS80 +step +proj=pop +v_3 +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); // In WKT, use approximate formula auto wkt = inv_transf->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE( wkt.find("Transformation from WGS 84 to NAD83 (approx. inversion)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("Position Vector transformation (geog2D domain)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("ID[\"EPSG\",9606]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis translation\",-1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis translation\",-2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis translation\",-3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis rotation\",-4") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis rotation\",-5") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis rotation\",-6") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Scale difference\",-7") != std::string::npos) << wkt; #endif } // --------------------------------------------------------------------------- TEST(operation, transformation_createCoordinateFrameRotation) { auto transf = Transformation::createCoordinateFrameRotation( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, -4.0, -5.0, -6.0, 7.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_TRUE(transf->validateParameters().empty()); auto params = transf->getTOWGS84Parameters(); auto expected = std::vector<double>{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}; EXPECT_EQ(params, expected); EXPECT_EQ(transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=GRS80 +step +proj=helmert +x=1 +y=2 " "+z=3 +rx=-4 +ry=-5 +rz=-6 +s=7 +convention=coordinate_frame " "+step +inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); auto inv_transf = transf->inverse(); ASSERT_EQ(inv_transf->coordinateOperationAccuracies().size(), 0U); EXPECT_EQ(transf->sourceCRS()->nameStr(), inv_transf->targetCRS()->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), inv_transf->sourceCRS()->nameStr()); #ifdef USE_APPROXIMATE_HELMERT_INVERSE auto inv_transf_as_transf = nn_dynamic_pointer_cast<Transformation>(inv_transf); ASSERT_TRUE(inv_transf_as_transf != nullptr); #else EXPECT_EQ( inv_transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 +step " "+proj=cart +ellps=WGS84 +step +inv +proj=helmert +x=1 +y=2 +z=3 " "+rx=-4 +ry=-5 +rz=-6 +s=7 +convention=coordinate_frame +step +inv " "+proj=cart +ellps=GRS80 +step +proj=pop +v_3 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); // In WKT, use approximate formula auto wkt = inv_transf->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE( wkt.find("Transformation from WGS 84 to NAD83 (approx. inversion)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("Coordinate Frame rotation (geog2D domain)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("ID[\"EPSG\",9607]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis translation\",-1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis translation\",-2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis translation\",-3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis rotation\",4") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis rotation\",5") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis rotation\",6") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Scale difference\",-7") != std::string::npos) << wkt; #endif } // --------------------------------------------------------------------------- TEST(operation, transformation_createTimeDependentPositionVector) { auto transf = Transformation::createTimeDependentPositionVector( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 2018.5, std::vector<PositionalAccuracyNNPtr>()); EXPECT_TRUE(transf->validateParameters().empty()); auto inv_transf = transf->inverse(); EXPECT_EQ(transf->sourceCRS()->nameStr(), inv_transf->targetCRS()->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), inv_transf->sourceCRS()->nameStr()); auto projString = inv_transf->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_TRUE(projString.find("+proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 " "+rz=6 +s=7 +dx=0.1 +dy=0.2 +dz=0.3 +drx=0.4 " "+dry=0.5 +drz=0.6 +ds=0.7 +t_epoch=2018.5 " "+convention=position_vector") != std::string::npos) << projString; // In WKT, use approximate formula auto wkt = inv_transf->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE( wkt.find("Transformation from WGS 84 to NAD83 (approx. inversion)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("Time-dependent Position Vector tfm (geog2D)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("ID[\"EPSG\",1054]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis translation\",-1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis translation\",-2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis translation\",-3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis rotation\",-4") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis rotation\",-5") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis rotation\",-6") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Scale difference\",-7") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of X-axis translation\",-0.1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Y-axis translation\",-0.2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Z-axis translation\",-0.3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of X-axis rotation\",-0.4") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Y-axis rotation\",-0.5") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Z-axis rotation\",-0.6") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Scale difference\",-0.7") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Parameter reference epoch\",2018.5") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(operation, transformation_createTimeDependentCoordinateFrameRotation) { auto transf = Transformation::createTimeDependentCoordinateFrameRotation( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 2018.5, std::vector<PositionalAccuracyNNPtr>()); EXPECT_TRUE(transf->validateParameters().empty()); auto inv_transf = transf->inverse(); EXPECT_EQ(transf->sourceCRS()->nameStr(), inv_transf->targetCRS()->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), inv_transf->sourceCRS()->nameStr()); auto projString = inv_transf->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_TRUE(projString.find("+proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 " "+rz=6 +s=7 +dx=0.1 +dy=0.2 +dz=0.3 +drx=0.4 " "+dry=0.5 +drz=0.6 +ds=0.7 +t_epoch=2018.5 " "+convention=coordinate_frame") != std::string::npos) << projString; // In WKT, use approximate formula auto wkt = inv_transf->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE( wkt.find("Transformation from WGS 84 to NAD83 (approx. inversion)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("Time-dependent Coordinate Frame rotation (geog2D)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("ID[\"EPSG\",1057]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis translation\",-1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis translation\",-2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis translation\",-3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"X-axis rotation\",-4") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Y-axis rotation\",-5") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Z-axis rotation\",-6") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Scale difference\",-7") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of X-axis translation\",-0.1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Y-axis translation\",-0.2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Z-axis translation\",-0.3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of X-axis rotation\",-0.4") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Y-axis rotation\",-0.5") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Z-axis rotation\",-0.6") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Rate of change of Scale difference\",-0.7") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Parameter reference epoch\",2018.5") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(operation, transformation_successive_helmert_noop) { auto transf_1 = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4269, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, std::vector<PositionalAccuracyNNPtr>()); auto transf_2 = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, -1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, std::vector<PositionalAccuracyNNPtr>()); auto concat = ConcatenatedOperation::create( PropertyMap(), std::vector<CoordinateOperationNNPtr>{transf_1, transf_2}, std::vector<PositionalAccuracyNNPtr>{}); EXPECT_EQ(concat->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, transformation_successive_helmert_non_trivial_1) { auto transf_1 = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4269, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, std::vector<PositionalAccuracyNNPtr>()); auto transf_2 = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, -1.0, -2.0, -3.0, -4.0, -5.0, -6.0, 7.0, std::vector<PositionalAccuracyNNPtr>()); auto concat = ConcatenatedOperation::create( PropertyMap(), std::vector<CoordinateOperationNNPtr>{transf_1, transf_2}, std::vector<PositionalAccuracyNNPtr>{}); EXPECT_NE(concat->exportToPROJString(PROJStringFormatter::create().get()), ""); } // --------------------------------------------------------------------------- TEST(operation, transformation_successive_helmert_non_trivial_2) { auto transf_1 = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4269, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, std::vector<PositionalAccuracyNNPtr>()); auto transf_2 = Transformation::createCoordinateFrameRotation( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, -1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, std::vector<PositionalAccuracyNNPtr>()); auto concat = ConcatenatedOperation::create( PropertyMap(), std::vector<CoordinateOperationNNPtr>{transf_1, transf_2}, std::vector<PositionalAccuracyNNPtr>{}); EXPECT_NE(concat->exportToPROJString(PROJStringFormatter::create().get()), ""); } // --------------------------------------------------------------------------- TEST(operation, transformation_createMolodensky) { auto transf = Transformation::createMolodensky( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4269, 1.0, 2.0, 3.0, 4.0, 5.0, std::vector<PositionalAccuracyNNPtr>()); EXPECT_TRUE(transf->validateParameters().empty()); auto wkt = transf->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(replaceAll(replaceAll(wkt, " ", ""), "\n", "") .find("METHOD[\"Molodensky\",ID[\"EPSG\",9604]]") != std::string::npos) << wkt; auto inv_transf = transf->inverse(); auto inv_transf_as_transf = nn_dynamic_pointer_cast<Transformation>(inv_transf); ASSERT_TRUE(inv_transf_as_transf != nullptr); EXPECT_EQ(transf->sourceCRS()->nameStr(), inv_transf_as_transf->targetCRS()->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), inv_transf_as_transf->sourceCRS()->nameStr()); auto projString = inv_transf_as_transf->exportToPROJString( PROJStringFormatter::create().get()); EXPECT_EQ(projString, "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=molodensky +ellps=GRS80 +dx=-1 +dy=-2 " "+dz=-3 +da=-4 +df=-5 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_createAbridgedMolodensky) { auto transf = Transformation::createAbridgedMolodensky( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4269, 1.0, 2.0, 3.0, 4.0, 5.0, std::vector<PositionalAccuracyNNPtr>()); auto wkt = transf->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(replaceAll(replaceAll(wkt, " ", ""), "\n", "") .find(replaceAll( "METHOD[\"Abridged Molodensky\",ID[\"EPSG\",9605]]", " ", "")) != std::string::npos) << wkt; auto inv_transf = transf->inverse(); auto inv_transf_as_transf = nn_dynamic_pointer_cast<Transformation>(inv_transf); ASSERT_TRUE(inv_transf_as_transf != nullptr); EXPECT_EQ(transf->sourceCRS()->nameStr(), inv_transf_as_transf->targetCRS()->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), inv_transf_as_transf->sourceCRS()->nameStr()); auto projString = inv_transf_as_transf->exportToPROJString( PROJStringFormatter::create().get()); EXPECT_EQ(projString, "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=molodensky +ellps=GRS80 +dx=-1 +dy=-2 " "+dz=-3 +da=-4 +df=-5 +abridged +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step " "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_inverse) { auto transf = Transformation::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "my transformation") .set(Identifier::CODESPACE_KEY, "my codeSpace") .set(Identifier::CODE_KEY, "my code"), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4269, nullptr, PropertyMap() .set(IdentifiedObject::NAME_KEY, "my operation") .set(Identifier::CODESPACE_KEY, "my codeSpace") .set(Identifier::CODE_KEY, "my code"), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); auto inv = transf->inverse(); EXPECT_EQ(inv->inverse(), transf); EXPECT_EQ( inv->exportToWKT(WKTFormatter::create().get()), "COORDINATEOPERATION[\"Inverse of my transformation\",\n" " SOURCECRS[\n" " GEODCRS[\"NAD83\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]],\n" " TARGETCRS[\n" " GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]],\n" " METHOD[\"Inverse of my operation\",\n" " ID[\"INVERSE(my codeSpace)\",\"my code\"]],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"],\n" " OPERATIONACCURACY[0.1],\n" " ID[\"INVERSE(my codeSpace)\",\"my code\"]]"); EXPECT_THROW(inv->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); } // --------------------------------------------------------------------------- static VerticalCRSNNPtr createVerticalCRS() { PropertyMap propertiesVDatum; propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5101) .set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn"); auto vdatum = VerticalReferenceFrame::create(propertiesVDatum); PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5701) .set(IdentifiedObject::NAME_KEY, "ODN height"); return VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(operation, transformation_createTOWGS84) { EXPECT_THROW(Transformation::createTOWGS84(GeographicCRS::EPSG_4326, std::vector<double>()), InvalidOperation); EXPECT_THROW(Transformation::createTOWGS84(createVerticalCRS(), std::vector<double>(7, 0)), InvalidOperation); } // --------------------------------------------------------------------------- TEST(operation, createAxisOrderReversal) { { auto conv = Conversion::createAxisOrderReversal(false); EXPECT_TRUE(conv->validateParameters().empty()); } { auto conv = Conversion::createAxisOrderReversal(true); EXPECT_TRUE(conv->validateParameters().empty()); } auto latLongDeg = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto longLatDeg = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLongitudeLatitude(UnitOfMeasure::DEGREE)); { auto op = CoordinateOperationFactory::create()->createOperation( latLongDeg, longLatDeg); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=2,1"); } { auto longLatRad = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLongitudeLatitude(UnitOfMeasure::RADIAN)); auto op = CoordinateOperationFactory::create()->createOperation( longLatRad, latLongDeg); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } } // --------------------------------------------------------------------------- TEST(operation, utm_export) { auto conv = Conversion::createUTM(PropertyMap(), 1, false); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=1 +south"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"UTM zone 1S\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-177,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",10000000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",17001]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Transverse_Mercator\"],\n" "PARAMETER[\"latitude_of_origin\",0],\n" "PARAMETER[\"central_meridian\",-177],\n" "PARAMETER[\"scale_factor\",0.9996],\n" "PARAMETER[\"false_easting\",500000],\n" "PARAMETER[\"false_northing\",10000000]"); } // --------------------------------------------------------------------------- TEST(operation, tmerc_export) { auto conv = Conversion::createTransverseMercator( PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=tmerc +lat_0=1 +lon_0=2 +k=3 +x_0=4 +y_0=5"); { auto formatter = PROJStringFormatter::create(); formatter->setUseApproxTMerc(true); EXPECT_EQ(conv->exportToPROJString(formatter.get()), "+proj=tmerc +approx +lat_0=1 +lon_0=2 +k=3 +x_0=4 +y_0=5"); } EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Transverse Mercator\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Transverse_Mercator\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"scale_factor\",3],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, gstmerc_export) { auto conv = Conversion::createGaussSchreiberTransverseMercator( PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=gstmerc +lat_0=1 +lon_0=2 +k_0=3 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Gauss Schreiber Transverse Mercator\",\n" " METHOD[\"Gauss Schreiber Transverse Mercator\"],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Gauss_Schreiber_Transverse_Mercator\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"scale_factor\",3],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, tmerc_south_oriented_export) { auto conv = Conversion::createTransverseMercatorSouthOriented( PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); // False easting/northing != 0 not supported EXPECT_THROW(conv->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Transverse Mercator (South Orientated)\",\n" " METHOD[\"Transverse Mercator (South Orientated)\",\n" " ID[\"EPSG\",9808]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Transverse_Mercator_South_Orientated\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"scale_factor\",3],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); auto wkt = "PROJCRS[\"Hartebeesthoek94 / Lo29\"," " BASEGEODCRS[\"Hartebeesthoek94\"," " DATUM[\"Hartebeesthoek94\"," " ELLIPSOID[\"WGS " "84\",6378137,298.257223563,LENGTHUNIT[\"metre\",1.0]]]]," " CONVERSION[\"South African Survey Grid zone 29\"," " METHOD[\"Transverse Mercator (South " "Orientated)\",ID[\"EPSG\",9808]]," " PARAMETER[\"Latitude of natural " "origin\",0,ANGLEUNIT[\"degree\",0.01745329252]]," " PARAMETER[\"Longitude of natural " "origin\",29,ANGLEUNIT[\"degree\",0.01745329252]]," " PARAMETER[\"Scale factor at natural " "origin\",1,SCALEUNIT[\"unity\",1.0]]," " PARAMETER[\"False easting\",0,LENGTHUNIT[\"metre\",1.0]]," " PARAMETER[\"False northing\",0,LENGTHUNIT[\"metre\",1.0]]]," " CS[cartesian,2]," " AXIS[\"westing (Y)\",west,ORDER[1]]," " AXIS[\"southing (X)\",south,ORDER[2]]," " LENGTHUNIT[\"metre\",1.0]," " ID[\"EPSG\",2053]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=tmerc +axis=wsu +lat_0=0 +lon_0=29 +k=1 +x_0=0 +y_0=0 " "+ellps=WGS84 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(operation, tped_export) { auto conv = Conversion::createTwoPointEquidistant( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=tpeqd +lat_1=1 +lon_1=2 +lat_2=3 +lon_2=4 +x_0=5 +y_0=6"); auto formatter = WKTFormatter::create(); formatter->simulCurNodeHasId(); EXPECT_EQ(conv->exportToWKT(formatter.get()), "CONVERSION[\"Two Point Equidistant\",\n" " METHOD[\"Two Point Equidistant\"],\n" " PARAMETER[\"Latitude of 1st point\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Longitude of 1st point\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Latitude of 2nd point\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Longitude of 2nd point\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"False easting\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Two_Point_Equidistant\"],\n" "PARAMETER[\"Latitude_Of_1st_Point\",1],\n" "PARAMETER[\"Longitude_Of_1st_Point\",2],\n" "PARAMETER[\"Latitude_Of_2nd_Point\",3],\n" "PARAMETER[\"Longitude_Of_2nd_Point\",4],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, tmg_export) { auto conv = Conversion::createTunisiaMiningGrid( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_THROW(conv->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Tunisia Mining Grid\",\n" " METHOD[\"Tunisia Mining Grid\",\n" " ID[\"EPSG\",9816]],\n" " PARAMETER[\"Latitude of false origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Easting at false origin\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Tunisia_Mining_Grid\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, aea_export) { auto conv = Conversion::createAlbersEqualArea(PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=aea +lat_0=1 +lon_0=2 +lat_1=3 +lat_2=4 +x_0=5 +y_0=6"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Albers Equal Area\",\n" " METHOD[\"Albers Equal Area\",\n" " ID[\"EPSG\",9822]],\n" " PARAMETER[\"Latitude of false origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Albers_Conic_Equal_Area\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"standard_parallel_1\",3],\n" "PARAMETER[\"standard_parallel_2\",4],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, azimuthal_equidistant_export) { auto conv = Conversion::createAzimuthalEquidistant( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=aeqd +lat_0=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Azimuthal Equidistant\",\n" " METHOD[\"Azimuthal Equidistant\",\n" " ID[\"EPSG\",1125]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Azimuthal_Equidistant\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, guam_projection_export) { auto conv = Conversion::createGuamProjection( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=aeqd +guam +lat_0=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Guam Projection\",\n" " METHOD[\"Guam Projection\",\n" " ID[\"EPSG\",9831]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_THROW( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(operation, bonne_export) { auto conv = Conversion::createBonne(PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=bonne +lat_1=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Bonne\",\n" " METHOD[\"Bonne\",\n" " ID[\"EPSG\",9827]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Bonne\"],\n" "PARAMETER[\"standard_parallel_1\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); auto obj = WKTParser().createFromWKT( "PROJCS[\"unnamed\"," "GEOGCS[\"unnamed ellipse\"," " DATUM[\"unknown\"," " SPHEROID[\"unnamed\",6378137,298.257223563]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"degree\",0.0174532925199433]]," "PROJECTION[\"Bonne\"]," "PARAMETER[\"standard_parallel_1\",1]," "PARAMETER[\"central_meridian\",2]," "PARAMETER[\"false_easting\",3]," "PARAMETER[\"false_northing\",4]," "UNIT[\"metre\",1]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=bonne +lat_1=1 +lon_0=2 +x_0=3 +y_0=4 +ellps=WGS84 " "+units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(operation, lambert_cylindrical_equal_area_spherical_export) { auto conv = Conversion::createLambertCylindricalEqualAreaSpherical( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=cea +R_A +lat_ts=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Cylindrical Equal Area (Spherical)\",\n" " METHOD[\"Lambert Cylindrical Equal Area (Spherical)\",\n" " ID[\"EPSG\",9834]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Cylindrical_Equal_Area\"],\n" "PARAMETER[\"standard_parallel_1\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, lambert_cylindrical_equal_area_export) { auto conv = Conversion::createLambertCylindricalEqualArea( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=cea +lat_ts=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Cylindrical Equal Area\",\n" " METHOD[\"Lambert Cylindrical Equal Area\",\n" " ID[\"EPSG\",9835]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Cylindrical_Equal_Area\"],\n" "PARAMETER[\"standard_parallel_1\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, lcc1sp_export) { auto conv = Conversion::createLambertConicConformal_1SP( PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=lcc +lat_1=1 +lat_0=1 +lon_0=2 +k_0=3 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Conic Conformal (1SP)\",\n" " METHOD[\"Lambert Conic Conformal (1SP)\",\n" " ID[\"EPSG\",9801]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Lambert_Conformal_Conic_1SP\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"scale_factor\",3],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, lcc1sp_variant_b_export) { auto conv = Conversion::createLambertConicConformal_1SP_VariantB( PropertyMap(), Angle(1), Scale(2), Angle(3), Angle(4), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=lcc +lat_1=1 +k_0=2 +lat_0=3 +lon_0=4 +x_0=5 +y_0=6"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Conic Conformal (1SP variant B)\",\n" " METHOD[\"Lambert Conic Conformal (1SP variant B)\",\n" " ID[\"EPSG\",1102]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Scale factor at natural origin\",2,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"Latitude of false origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Easting at false origin\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]]"); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_export) { auto conv = Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=lcc +lat_0=1 +lon_0=2 +lat_1=3 +lat_2=4 +x_0=5 +y_0=6"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Conic Conformal (2SP)\",\n" " METHOD[\"Lambert Conic Conformal (2SP)\",\n" " ID[\"EPSG\",9802]],\n" " PARAMETER[\"Latitude of false origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Lambert_Conformal_Conic_2SP\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"standard_parallel_1\",3],\n" "PARAMETER[\"standard_parallel_2\",4],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_isEquivalentTo_parallels_switched) { auto conv1 = Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Length(5), Length(6)); auto conv2 = Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(1), Angle(2), Angle(4), Angle(3), Length(5), Length(6)); EXPECT_TRUE( conv1->isEquivalentTo(conv2.get(), IComparable::Criterion::EQUIVALENT)); auto conv3 = Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(3), Length(5), Length(6)); EXPECT_FALSE( conv1->isEquivalentTo(conv3.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_michigan_export) { auto conv = Conversion::createLambertConicConformal_2SP_Michigan( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Length(5), Length(6), Scale(7)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ( conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=lcc +lat_0=1 +lon_0=2 +lat_1=3 +lat_2=4 +x_0=5 +y_0=6 +k_0=7"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Conic Conformal (2SP Michigan)\",\n" " METHOD[\"Lambert Conic Conformal (2SP Michigan)\",\n" " ID[\"EPSG\",1051]],\n" " PARAMETER[\"Latitude of false origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]],\n" " PARAMETER[\"Ellipsoid scaling factor\",7,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",1038]]]"); EXPECT_THROW( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_belgium_export) { auto conv = Conversion::createLambertConicConformal_2SP_Belgium( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Length(5), Length(6)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=lcc +lat_0=1 +lon_0=2 +lat_1=3 +lat_2=4 +x_0=5 +y_0=6"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Conic Conformal (2SP Belgium)\",\n" " METHOD[\"Lambert Conic Conformal (2SP Belgium)\",\n" " ID[\"EPSG\",9803]],\n" " PARAMETER[\"Latitude of false origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Lambert_Conformal_Conic_2SP_Belgium\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"standard_parallel_1\",3],\n" "PARAMETER[\"standard_parallel_2\",4],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, cassini_soldner_export) { auto conv = Conversion::createCassiniSoldner( PropertyMap(), Angle(1), Angle(2), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=cass +lat_0=1 +lon_0=2 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Cassini-Soldner\",\n" " METHOD[\"Cassini-Soldner\",\n" " ID[\"EPSG\",9806]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Cassini_Soldner\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, equidistant_conic_export) { auto conv = Conversion::createEquidistantConic(PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=eqdc +lat_0=1 +lon_0=2 +lat_1=3 +lat_2=4 +x_0=5 +y_0=6"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Equidistant Conic\",\n" " METHOD[\"Equidistant Conic\",\n" " ID[\"EPSG\",1119]],\n" " PARAMETER[\"Latitude of false origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Equidistant_Conic\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"standard_parallel_1\",3],\n" "PARAMETER[\"standard_parallel_2\",4],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, eckert_export) { std::vector<std::string> numbers{"", "1", "2", "3", "4", "5", "6"}; std::vector<std::string> latinNumbers{"", "I", "II", "III", "IV", "V", "VI"}; for (int i = 1; i <= 6; i++) { auto conv = (i == 1) ? Conversion::createEckertI(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 2) ? Conversion::createEckertII(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 3) ? Conversion::createEckertIII(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 4) ? Conversion::createEckertIV(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 5) ? Conversion::createEckertV(PropertyMap(), Angle(1), Length(2), Length(3)) : Conversion::createEckertVI(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=eck" + numbers[i] + " +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Eckert " + latinNumbers[i] + "\",\n" " METHOD[\"Eckert " + latinNumbers[i] + "\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ(conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL) .get()), "PROJECTION[\"Eckert_" + latinNumbers[i] + "\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } } // --------------------------------------------------------------------------- TEST(operation, createEquidistantCylindrical) { auto conv = Conversion::createEquidistantCylindrical( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=eqc +lat_ts=1 +lat_0=0 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Equidistant Cylindrical\",\n" " METHOD[\"Equidistant Cylindrical\",\n" " ID[\"EPSG\",1028]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Equirectangular\"],\n" "PARAMETER[\"standard_parallel_1\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); EXPECT_TRUE(conv->validateParameters().empty()); } // --------------------------------------------------------------------------- TEST(operation, createEquidistantCylindricalSpherical) { auto conv = Conversion::createEquidistantCylindricalSpherical( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=eqc +lat_ts=1 +lat_0=0 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Equidistant Cylindrical (Spherical)\",\n" " METHOD[\"Equidistant Cylindrical (Spherical)\",\n" " ID[\"EPSG\",1029]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Equirectangular\"],\n" "PARAMETER[\"standard_parallel_1\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); EXPECT_TRUE(conv->validateParameters().empty()); } // --------------------------------------------------------------------------- TEST(operation, equidistant_cylindrical_lat_0) { auto obj = PROJStringParser().createFromPROJString( "+proj=eqc +ellps=sphere +lat_0=-2 +lat_ts=1 +lon_0=-10 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto wkt = crs->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt.find("PARAMETER[\"Latitude of natural origin\",-2") != std::string::npos) << wkt; auto projString = crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()); EXPECT_EQ(projString, "+proj=eqc +lat_ts=1 +lat_0=-2 +lon_0=-10 +x_0=0 +y_0=0 " "+ellps=sphere +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(operation, gall_export) { auto conv = Conversion::createGall(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=gall +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Gall Stereographic\",\n" " METHOD[\"Gall Stereographic\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Gall_Stereographic\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } // --------------------------------------------------------------------------- TEST(operation, goode_homolosine_export) { auto conv = Conversion::createGoodeHomolosine(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=goode +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Goode Homolosine\",\n" " METHOD[\"Goode Homolosine\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Goode_Homolosine\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } // --------------------------------------------------------------------------- TEST(operation, interrupted_goode_homolosine_export) { auto conv = Conversion::createInterruptedGoodeHomolosine( PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=igh +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Interrupted Goode Homolosine\",\n" " METHOD[\"Interrupted Goode Homolosine\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Interrupted_Goode_Homolosine\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } // --------------------------------------------------------------------------- TEST(operation, geostationary_satellite_sweep_x_export) { auto conv = Conversion::createGeostationarySatelliteSweepX( PropertyMap(), Angle(1), Length(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=geos +sweep=x +lon_0=1 +h=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Geostationary Satellite (Sweep X)\",\n" " METHOD[\"Geostationary Satellite (Sweep X)\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Satellite Height\",2,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); auto crs = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, conv, CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto wkt1 = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(wkt1.find("PROJECTION[\"Geostationary_Satellite\"]") != std::string::npos) << wkt1; EXPECT_TRUE(wkt1.find("EXTENSION[\"PROJ4\",\"+proj=geos +sweep=x +lon_0=1 " "+h=2 +x_0=3 +y_0=4 +datum=WGS84 +units=m " "+no_defs\"]]") != std::string::npos) << wkt1; } // --------------------------------------------------------------------------- TEST(operation, geostationary_satellite_sweep_y_export) { auto conv = Conversion::createGeostationarySatelliteSweepY( PropertyMap(), Angle(1), Length(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=geos +lon_0=1 +h=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Geostationary Satellite (Sweep Y)\",\n" " METHOD[\"Geostationary Satellite (Sweep Y)\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Satellite Height\",2,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Geostationary_Satellite\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"satellite_height\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, gnomonic_export) { auto conv = Conversion::createGnomonic(PropertyMap(), Angle(1), Angle(2), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=gnom +lat_0=1 +lon_0=2 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Gnomonic\",\n" " METHOD[\"Gnomonic\"],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Gnomonic\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, hotine_oblique_mercator_variant_A_export) { auto conv = Conversion::createHotineObliqueMercatorVariantA( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Scale(5), Length(6), Length(7)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=omerc +no_uoff +lat_0=1 +lonc=2 +alpha=3 +gamma=4 +k=5 " "+x_0=6 +y_0=7"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Hotine Oblique Mercator (variant A)\",\n" " METHOD[\"Hotine Oblique Mercator (variant A)\",\n" " ID[\"EPSG\",9812]],\n" " PARAMETER[\"Latitude of projection centre\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of projection centre\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8812]],\n" " PARAMETER[\"Azimuth of initial line\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8813]],\n" " PARAMETER[\"Angle from Rectified to Skew Grid\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8814]],\n" " PARAMETER[\"Scale factor on initial line\",5,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]],\n" " PARAMETER[\"False easting\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",7,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Hotine_Oblique_Mercator\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"azimuth\",3],\n" "PARAMETER[\"rectified_grid_angle\",4],\n" "PARAMETER[\"scale_factor\",5],\n" "PARAMETER[\"false_easting\",6],\n" "PARAMETER[\"false_northing\",7]"); } // --------------------------------------------------------------------------- TEST(operation, hotine_oblique_mercator_variant_A_export_swiss_mercator) { auto conv = Conversion::createHotineObliqueMercatorVariantA( PropertyMap(), Angle(1), Angle(2), Angle(90), Angle(90), Scale(5), Length(6), Length(7)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=somerc +lat_0=1 +lon_0=2 +k_0=5 " "+x_0=6 +y_0=7"); } // --------------------------------------------------------------------------- TEST(operation, hotine_oblique_mercator_variant_B_export) { auto conv = Conversion::createHotineObliqueMercatorVariantB( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Scale(5), Length(6), Length(7)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=omerc +lat_0=1 +lonc=2 +alpha=3 +gamma=4 +k=5 " "+x_0=6 +y_0=7"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Hotine Oblique Mercator (variant B)\",\n" " METHOD[\"Hotine Oblique Mercator (variant B)\",\n" " ID[\"EPSG\",9815]],\n" " PARAMETER[\"Latitude of projection centre\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of projection centre\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8812]],\n" " PARAMETER[\"Azimuth of initial line\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8813]],\n" " PARAMETER[\"Angle from Rectified to Skew Grid\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8814]],\n" " PARAMETER[\"Scale factor on initial line\",5,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]],\n" " PARAMETER[\"Easting at projection centre\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8816]],\n" " PARAMETER[\"Northing at projection centre\",7,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8817]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Hotine_Oblique_Mercator_Azimuth_Center\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"azimuth\",3],\n" "PARAMETER[\"rectified_grid_angle\",4],\n" "PARAMETER[\"scale_factor\",5],\n" "PARAMETER[\"false_easting\",6],\n" "PARAMETER[\"false_northing\",7]"); } // --------------------------------------------------------------------------- TEST(operation, hotine_oblique_mercator_variant_B_export_swiss_mercator) { auto conv = Conversion::createHotineObliqueMercatorVariantB( PropertyMap(), Angle(1), Angle(2), Angle(90), Angle(90), Scale(5), Length(6), Length(7)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=somerc +lat_0=1 +lon_0=2 +k_0=5 " "+x_0=6 +y_0=7"); } // --------------------------------------------------------------------------- TEST(operation, hotine_oblique_mercator_two_point_natural_origin_export) { auto conv = Conversion::createHotineObliqueMercatorTwoPointNaturalOrigin( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Angle(5), Scale(6), Length(7), Length(8)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=omerc +lat_0=1 +lat_1=2 +lon_1=3 +lat_2=4 +lon_2=5 +k=6 " "+x_0=7 +y_0=8"); auto formatter = WKTFormatter::create(); formatter->simulCurNodeHasId(); EXPECT_EQ( conv->exportToWKT(formatter.get()), "CONVERSION[\"Hotine Oblique Mercator Two Point Natural Origin\",\n" " METHOD[\"Hotine Oblique Mercator Two Point Natural Origin\"],\n" " PARAMETER[\"Latitude of projection centre\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Latitude of 1st point\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Longitude of 1st point\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Latitude of 2nd point\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Longitude of 2nd point\",5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Scale factor on initial line\",6,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]],\n" " PARAMETER[\"Easting at projection centre\",7,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8816]],\n" " PARAMETER[\"Northing at projection centre\",8,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8817]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Hotine_Oblique_Mercator_Two_Point_Natural_Origin\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"latitude_of_point_1\",2],\n" "PARAMETER[\"longitude_of_point_1\",3],\n" "PARAMETER[\"latitude_of_point_2\",4],\n" "PARAMETER[\"longitude_of_point_2\",5],\n" "PARAMETER[\"scale_factor\",6],\n" "PARAMETER[\"false_easting\",7],\n" "PARAMETER[\"false_northing\",8]"); } // --------------------------------------------------------------------------- TEST(operation, laborde_oblique_mercator_export) { auto conv = Conversion::createLabordeObliqueMercator( PropertyMap(), Angle(1), Angle(2), Angle(3), Scale(4), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=labrd +lat_0=1 +lon_0=2 +azi=3 +k=4 +x_0=5 +y_0=6"); auto formatter = WKTFormatter::create(); formatter->simulCurNodeHasId(); EXPECT_EQ(conv->exportToWKT(formatter.get()), "CONVERSION[\"Laborde Oblique Mercator\",\n" " METHOD[\"Laborde Oblique Mercator\",\n" " ID[\"EPSG\",9813]],\n" " PARAMETER[\"Latitude of projection centre\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of projection centre\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8812]],\n" " PARAMETER[\"Azimuth of initial line\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8813]],\n" " PARAMETER[\"Scale factor on initial line\",4,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]],\n" " PARAMETER[\"False easting\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Laborde_Oblique_Mercator\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"azimuth\",3],\n" "PARAMETER[\"scale_factor\",4],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, imw_polyconic_export) { auto conv = Conversion::createInternationalMapWorldPolyconic( PropertyMap(), Angle(1), Angle(3), Angle(4), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=imw_p +lon_0=1 +lat_1=3 +lat_2=4 +x_0=5 +y_0=6"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"International Map of the World Polyconic\",\n" " METHOD[\"International Map of the World Polyconic\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Latitude of 1st point\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Latitude of 2nd point\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"False easting\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"International_Map_of_the_World_Polyconic\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"Latitude_Of_1st_Point\",3],\n" "PARAMETER[\"Latitude_Of_2nd_Point\",4],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, krovak_north_oriented_export) { auto conv = Conversion::createKrovakNorthOriented( PropertyMap(), Angle(49.5), Angle(42.5), Angle(30.2881397527778), Angle(78.5), Scale(0.9999), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=krovak +lat_0=49.5 +lon_0=42.5 +alpha=30.2881397527778 " "+k=0.9999 +x_0=5 +y_0=6"); EXPECT_EQ( conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Krovak (North Orientated)\",\n" " METHOD[\"Krovak (North Orientated)\",\n" " ID[\"EPSG\",1041]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",42.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Krovak\"],\n" "PARAMETER[\"latitude_of_center\",49.5],\n" "PARAMETER[\"longitude_of_center\",42.5],\n" "PARAMETER[\"azimuth\",30.2881397527778],\n" "PARAMETER[\"pseudo_standard_parallel_1\",78.5],\n" "PARAMETER[\"scale_factor\",0.9999],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, krovak_export) { auto conv = Conversion::createKrovak( PropertyMap(), Angle(49.5), Angle(42.5), Angle(30.2881397527778), Angle(78.5), Scale(0.9999), Length(5), Length(6)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=krovak +axis=swu +lat_0=49.5 +lon_0=42.5 " "+alpha=30.2881397527778 +k=0.9999 +x_0=5 " "+y_0=6"); EXPECT_EQ( conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Krovak\",\n" " METHOD[\"Krovak\",\n" " ID[\"EPSG\",9819]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",42.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Krovak\"],\n" "PARAMETER[\"latitude_of_center\",49.5],\n" "PARAMETER[\"longitude_of_center\",42.5],\n" "PARAMETER[\"azimuth\",30.2881397527778],\n" "PARAMETER[\"pseudo_standard_parallel_1\",78.5],\n" "PARAMETER[\"scale_factor\",0.9999],\n" "PARAMETER[\"false_easting\",5],\n" "PARAMETER[\"false_northing\",6]"); } // --------------------------------------------------------------------------- TEST(operation, lambert_azimuthal_equal_area_export) { auto conv = Conversion::createLambertAzimuthalEqualArea( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=laea +lat_0=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Lambert Azimuthal Equal Area\",\n" " METHOD[\"Lambert Azimuthal Equal Area\",\n" " ID[\"EPSG\",9820]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Lambert_Azimuthal_Equal_Area\"],\n" "PARAMETER[\"latitude_of_center\",1],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, miller_cylindrical_export) { auto conv = Conversion::createMillerCylindrical(PropertyMap(), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=mill +R_A +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Miller Cylindrical\",\n" " METHOD[\"Miller Cylindrical\"],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Miller_Cylindrical\"],\n" "PARAMETER[\"longitude_of_center\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_A_export) { auto conv = Conversion::createMercatorVariantA( PropertyMap(), Angle(0), Angle(1), Scale(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +lon_0=1 +k=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Mercator (variant A)\",\n" " METHOD[\"Mercator (variant A)\",\n" " ID[\"EPSG\",9804]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",2,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Mercator_1SP\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"scale_factor\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_A_export_latitude_origin_non_zero) { auto conv = Conversion::createMercatorVariantA( PropertyMap(), Angle(10), Angle(1), Scale(2), Length(3), Length(4)); EXPECT_THROW(conv->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); } // --------------------------------------------------------------------------- TEST(operation, wkt1_import_mercator_variant_A) { auto wkt = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"central_meridian\",1],\n" " PARAMETER[\"scale_factor\",2],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto conversion = crs->derivingConversion(); auto convRef = Conversion::createMercatorVariantA( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(0), Angle(1), Scale(2), Length(3), Length(4)); EXPECT_EQ(conversion->exportToWKT(WKTFormatter::create().get()), convRef->exportToWKT(WKTFormatter::create().get())); } // --------------------------------------------------------------------------- TEST(operation, wkt1_import_mercator_variant_A_that_is_variant_B) { // Addresses https://trac.osgeo.org/gdal/ticket/3026 auto wkt = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"latitude_of_origin\",-1],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto conversion = crs->derivingConversion(); auto convRef = Conversion::createMercatorVariantB( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(-1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conversion->isEquivalentTo(convRef.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_B_export) { auto conv = Conversion::createMercatorVariantB( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +lat_ts=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Mercator (variant B)\",\n" " METHOD[\"Mercator (variant B)\",\n" " ID[\"EPSG\",9805]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Mercator_2SP\"],\n" "PARAMETER[\"standard_parallel_1\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, odd_mercator_1sp_with_non_null_latitude) { auto obj = WKTParser().createFromWKT( "PROJCS[\"unnamed\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"latitude_of_origin\",30],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"scale_factor\",0.99],\n" " PARAMETER[\"false_easting\",0],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_THROW(crs->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); } // --------------------------------------------------------------------------- TEST(operation, odd_mercator_2sp_with_latitude_of_origin) { auto obj = WKTParser().createFromWKT( "PROJCS[\"unnamed\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Mercator_2SP\"],\n" " PARAMETER[\"standard_parallel_1\",30],\n" " PARAMETER[\"latitude_of_origin\",40],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"false_easting\",0],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_THROW(crs->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); } // --------------------------------------------------------------------------- TEST(operation, webmerc_export) { auto conv = Conversion::createPopularVisualisationPseudoMercator( PropertyMap(), Angle(0), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=webmerc +lat_0=0 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Popular Visualisation Pseudo Mercator\",\n" " METHOD[\"Popular Visualisation Pseudo Mercator\",\n" " ID[\"EPSG\",1024]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); auto projCRS = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Pseudo-Mercator"), GeographicCRS::EPSG_4326, conv, CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); EXPECT_EQ( projCRS->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJCS[\"Pseudo-Mercator\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " EXTENSION[\"PROJ4\",\"+proj=merc " "+a=6378137 +b=6378137 +lat_ts=0 +lon_0=2 " "+x_0=3 +y_0=4 +k=1 +units=m " "+nadgrids=@null +wktext +no_defs\"]]"); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, projCRS); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=webmerc " "+lat_0=0 +lon_0=2 +x_0=3 +y_0=4 +ellps=WGS84"); EXPECT_EQ( projCRS->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=2 +x_0=3 " "+y_0=4 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(operation, webmerc_import_from_GDAL_wkt1) { auto projCRS = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Pseudo-Mercator"), GeographicCRS::EPSG_4326, Conversion::createPopularVisualisationPseudoMercator( PropertyMap(), Angle(0), Angle(0), Length(0), Length(0)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto wkt1 = projCRS->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); auto obj = WKTParser().createFromWKT(wkt1); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto convGot = crs->derivingConversion(); EXPECT_EQ(convGot->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"unnamed\",\n" " METHOD[\"Popular Visualisation Pseudo Mercator\",\n" " ID[\"EPSG\",1024]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); } // --------------------------------------------------------------------------- TEST(operation, webmerc_import_from_GDAL_wkt1_with_EPSG_code) { auto projCRS = ProjectedCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "Pseudo-Mercator") .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, "3857"), GeographicCRS::EPSG_4326, Conversion::createPopularVisualisationPseudoMercator( PropertyMap(), Angle(0), Angle(0), Length(0), Length(0)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto wkt1 = projCRS->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(wkt1.find("3857") != std::string::npos) << wkt1; auto obj = WKTParser().createFromWKT(wkt1); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->identifiers().size(), 1U); } // --------------------------------------------------------------------------- TEST(operation, webmerc_import_from_GDAL_wkt1_EPSG_3785_deprecated) { auto wkt1 = "PROJCS[\"Popular Visualisation CRS / Mercator (deprecated)\"," " GEOGCS[\"Popular Visualisation CRS\"," " DATUM[\"Popular_Visualisation_Datum\"," " SPHEROID[\"Popular Visualisation Sphere\",6378137,0," " AUTHORITY[\"EPSG\",\"7059\"]]," " TOWGS84[0,0,0,0,0,0,0]," " AUTHORITY[\"EPSG\",\"6055\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9122\"]]," " AUTHORITY[\"EPSG\",\"4055\"]]," " PROJECTION[\"Mercator_1SP\"]," " PARAMETER[\"central_meridian\",0]," " PARAMETER[\"scale_factor\",1]," " PARAMETER[\"false_easting\",0]," " PARAMETER[\"false_northing\",0]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"X\",EAST]," " AXIS[\"Y\",NORTH]," " EXTENSION[\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 " "+lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m " "+nadgrids=@null +wktext +no_defs\"]]"; auto obj = WKTParser().createFromWKT(wkt1); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 " "+y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs"); auto convGot = crs->derivingConversion(); EXPECT_EQ(convGot->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"unnamed\",\n" " METHOD[\"Popular Visualisation Pseudo Mercator\",\n" " ID[\"EPSG\",1024]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); } // --------------------------------------------------------------------------- TEST(operation, webmerc_import_from_WKT2_EPSG_3785_deprecated) { auto wkt2 = "PROJCRS[\"Popular Visualisation CRS / Mercator\",\n" " BASEGEODCRS[\"Popular Visualisation CRS\",\n" " DATUM[\"Popular Visualisation Datum\",\n" " ELLIPSOID[\"Popular Visualisation Sphere\",6378137,0,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"Popular Visualisation Mercator\",\n" " METHOD[\"Mercator (1SP) (Spherical)\",\n" " ID[\"EPSG\",9841]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",1,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (X)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (Y)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]"; auto obj = WKTParser().createFromWKT(wkt2); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 " "+y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs +type=crs"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2015).get()), wkt2); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, DatabaseContext::create()) .get()), "PROJCS[\"Popular Visualisation CRS / Mercator\",\n" " GEOGCS[\"Popular Visualisation CRS\",\n" " DATUM[\"Popular_Visualisation_Datum\",\n" " SPHEROID[\"Popular Visualisation Sphere\",6378137,0],\n" " TOWGS84[0,0,0,0,0,0,0]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",0],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " EXTENSION[\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0 " "+lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext " "+no_defs\"]]"); } // --------------------------------------------------------------------------- TEST(operation, webmerc_import_from_broken_esri_WGS_84_Pseudo_Mercator) { // Likely the result of a broken export of GDAL morphToESRI() auto wkt1 = "PROJCS[\"WGS_84_Pseudo_Mercator\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137,298.257223563]],PRIMEM[\"Greenwich\",0]," "UNIT[\"Degree\",0.017453292519943295]]," "PROJECTION[\"Mercator\"],PARAMETER[\"central_meridian\",0]," "PARAMETER[\"false_easting\",0]," "PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]," "PARAMETER[\"standard_parallel_1\",0.0]]"; auto obj = WKTParser().setStrict(false).createFromWKT(wkt1); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto convGot = crs->derivingConversion(); EXPECT_EQ(convGot->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"unnamed\",\n" " METHOD[\"Popular Visualisation Pseudo Mercator\",\n" " ID[\"EPSG\",1024]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); } // --------------------------------------------------------------------------- TEST(operation, mercator_spherical_export) { auto conv = Conversion::createMercatorSpherical( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +R_C +lat_0=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Mercator (Spherical)\",\n" " METHOD[\"Mercator (Spherical)\",\n" " ID[\"EPSG\",1026]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); } // --------------------------------------------------------------------------- TEST(operation, mercator_spherical_import) { auto wkt2 = "PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Mercator (Spherical)\",\n" " ID[\"EPSG\",1026]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt2); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +R_C +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 " "+units=m +no_defs +type=crs"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt2); } // --------------------------------------------------------------------------- TEST(operation, mollweide_export) { auto conv = Conversion::createMollweide(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=moll +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Mollweide\",\n" " METHOD[\"Mollweide\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Mollweide\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } // --------------------------------------------------------------------------- TEST(operation, nzmg_export) { auto conv = Conversion::createNewZealandMappingGrid( PropertyMap(), Angle(1), Angle(2), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=nzmg +lat_0=1 +lon_0=2 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"New Zealand Map Grid\",\n" " METHOD[\"New Zealand Map Grid\",\n" " ID[\"EPSG\",9811]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"New_Zealand_Map_Grid\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, oblique_stereographic_export) { auto conv = Conversion::createObliqueStereographic( PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=sterea +lat_0=1 +lon_0=2 +k=3 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Oblique Stereographic\",\n" " METHOD[\"Oblique Stereographic\",\n" " ID[\"EPSG\",9809]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Oblique_Stereographic\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"scale_factor\",3],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, orthographic_export) { auto conv = Conversion::createOrthographic(PropertyMap(), Angle(1), Angle(2), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=ortho +lat_0=1 +lon_0=2 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Orthographic\",\n" " METHOD[\"Orthographic\",\n" " ID[\"EPSG\",9840]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Orthographic\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, american_polyconic_export) { auto conv = Conversion::createAmericanPolyconic( PropertyMap(), Angle(1), Angle(2), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=poly +lat_0=1 +lon_0=2 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"American Polyconic\",\n" " METHOD[\"American Polyconic\",\n" " ID[\"EPSG\",9818]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Polyconic\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, polar_stereographic_variant_A_export) { auto conv = Conversion::createPolarStereographicVariantA( PropertyMap(), Angle(90), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=stere +lat_0=90 +lon_0=2 +k=3 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Polar Stereographic (variant A)\",\n" " METHOD[\"Polar Stereographic (variant A)\",\n" " ID[\"EPSG\",9810]],\n" " PARAMETER[\"Latitude of natural origin\",90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Polar_Stereographic\"],\n" "PARAMETER[\"latitude_of_origin\",90],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"scale_factor\",3],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, polar_stereographic_variant_B_export_positive_lat) { auto conv = Conversion::createPolarStereographicVariantB( PropertyMap(), Angle(70), Angle(2), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=2 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Polar Stereographic (variant B)\",\n" " METHOD[\"Polar Stereographic (variant B)\",\n" " ID[\"EPSG\",9829]],\n" " PARAMETER[\"Latitude of standard parallel\",70,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8832]],\n" " PARAMETER[\"Longitude of origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Polar_Stereographic\"],\n" "PARAMETER[\"latitude_of_origin\",70],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, polar_stereographic_variant_B_export_negative_lat) { auto conv = Conversion::createPolarStereographicVariantB( PropertyMap(), Angle(-70), Angle(2), Length(4), Length(5)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=stere +lat_0=-90 +lat_ts=-70 +lon_0=2 +x_0=4 +y_0=5"); } // --------------------------------------------------------------------------- TEST(operation, wkt1_import_polar_stereographic_variantA) { auto wkt = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",-90],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",3],\n" " PARAMETER[\"false_easting\",4],\n" " PARAMETER[\"false_northing\",5],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto conversion = crs->derivingConversion(); auto convRef = Conversion::createPolarStereographicVariantA( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(-90), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_EQ(conversion->exportToWKT(WKTFormatter::create().get()), convRef->exportToWKT(WKTFormatter::create().get())); } // --------------------------------------------------------------------------- TEST(operation, wkt1_import_polar_stereographic_variantB) { auto wkt = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",-70],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",4],\n" " PARAMETER[\"false_northing\",5],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto conversion = crs->derivingConversion(); auto convRef = Conversion::createPolarStereographicVariantB( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(-70), Angle(2), Length(4), Length(5)); EXPECT_EQ(conversion->exportToWKT(WKTFormatter::create().get()), convRef->exportToWKT(WKTFormatter::create().get())); } // --------------------------------------------------------------------------- TEST(operation, wkt1_import_polar_stereographic_ambiguous) { auto wkt = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",-70],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",3],\n" " PARAMETER[\"false_easting\",4],\n" " PARAMETER[\"false_northing\",5],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto conversion = crs->derivingConversion(); EXPECT_EQ(conversion->method()->nameStr(), "Polar_Stereographic"); } // --------------------------------------------------------------------------- TEST(operation, wkt1_import_equivalent_parameters) { auto wkt = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Hotine Oblique Mercator Two Point Natural " "Origin\"],\n" " PARAMETER[\"latitude_of_origin\",1],\n" " PARAMETER[\"Latitude_Of_1st_Point\",2],\n" " PARAMETER[\"Longitude_Of_1st_Point\",3],\n" " PARAMETER[\"Latitude_Of_2nd_Point\",4],\n" " PARAMETER[\"Longitude_Of 2nd_Point\",5],\n" " PARAMETER[\"scale_factor\",6],\n" " PARAMETER[\"false_easting\",7],\n" " PARAMETER[\"false_northing\",8],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto conversion = crs->derivingConversion(); auto convRef = Conversion::createHotineObliqueMercatorTwoPointNaturalOrigin( PropertyMap(), Angle(1), Angle(2), Angle(3), Angle(4), Angle(5), Scale(6), Length(7), Length(8)); EXPECT_EQ( conversion->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), convRef->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get())); } // --------------------------------------------------------------------------- TEST(operation, robinson_export) { auto conv = Conversion::createRobinson(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=robin +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Robinson\",\n" " METHOD[\"Robinson\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Robinson\"],\n" "PARAMETER[\"longitude_of_center\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } // --------------------------------------------------------------------------- TEST(operation, sinusoidal_export) { auto conv = Conversion::createSinusoidal(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=sinu +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Sinusoidal\",\n" " METHOD[\"Sinusoidal\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Sinusoidal\"],\n" "PARAMETER[\"longitude_of_center\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } // --------------------------------------------------------------------------- TEST(operation, stereographic_export) { auto conv = Conversion::createStereographic( PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=stere +lat_0=1 +lon_0=2 +k=3 +x_0=4 +y_0=5"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Stereographic\",\n" " METHOD[\"Stereographic\"],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Stereographic\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"scale_factor\",3],\n" "PARAMETER[\"false_easting\",4],\n" "PARAMETER[\"false_northing\",5]"); } // --------------------------------------------------------------------------- TEST(operation, vandergrinten_export) { auto conv = Conversion::createVanDerGrinten(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=vandg +R_A +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Van Der Grinten\",\n" " METHOD[\"Van Der Grinten\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"VanDerGrinten\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } // --------------------------------------------------------------------------- TEST(operation, wagner_export) { std::vector<std::string> numbers{"", "1", "2", "3", "4", "5", "6", "7"}; std::vector<std::string> latinNumbers{"", "I", "II", "III", "IV", "V", "VI", "VII"}; for (int i = 1; i <= 7; i++) { if (i == 3) continue; auto conv = (i == 1) ? Conversion::createWagnerI(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 2) ? Conversion::createWagnerII(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 4) ? Conversion::createWagnerIV(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 5) ? Conversion::createWagnerV(PropertyMap(), Angle(1), Length(2), Length(3)) : (i == 6) ? Conversion::createWagnerVI(PropertyMap(), Angle(1), Length(2), Length(3)) : Conversion::createWagnerVII(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=wag" + numbers[i] + " +lon_0=1 +x_0=2 +y_0=3"); auto formatter = WKTFormatter::create(); formatter->simulCurNodeHasId(); EXPECT_EQ(conv->exportToWKT(formatter.get()), "CONVERSION[\"Wagner " + latinNumbers[i] + "\",\n" " METHOD[\"Wagner " + latinNumbers[i] + "\"],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ(conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL) .get()), "PROJECTION[\"Wagner_" + latinNumbers[i] + "\"],\n" "PARAMETER[\"central_meridian\",1],\n" "PARAMETER[\"false_easting\",2],\n" "PARAMETER[\"false_northing\",3]"); } } // --------------------------------------------------------------------------- TEST(operation, wagnerIII_export) { auto conv = Conversion::createWagnerIII(PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=wag3 +lat_ts=1 +lon_0=2 +x_0=3 +y_0=4"); auto formatter = WKTFormatter::create(); formatter->simulCurNodeHasId(); EXPECT_EQ(conv->exportToWKT(formatter.get()), "CONVERSION[\"Wagner III\",\n" " METHOD[\"Wagner III\"],\n" " PARAMETER[\"Latitude of true scale\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Wagner_III\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, qsc_export) { auto conv = Conversion::createQuadrilateralizedSphericalCube( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=qsc +lat_0=1 +lon_0=2 +x_0=3 +y_0=4"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Quadrilateralized Spherical Cube\",\n" " METHOD[\"Quadrilateralized Spherical Cube\"],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Quadrilateralized_Spherical_Cube\"],\n" "PARAMETER[\"latitude_of_origin\",1],\n" "PARAMETER[\"central_meridian\",2],\n" "PARAMETER[\"false_easting\",3],\n" "PARAMETER[\"false_northing\",4]"); } // --------------------------------------------------------------------------- TEST(operation, sch_export) { auto conv = Conversion::createSphericalCrossTrackHeight( PropertyMap(), Angle(1), Angle(2), Angle(3), Length(4)); EXPECT_TRUE(conv->validateParameters().empty()); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=sch +plat_0=1 +plon_0=2 +phdg_0=3 +h_0=4"); auto formatter = WKTFormatter::create(); formatter->simulCurNodeHasId(); EXPECT_EQ(conv->exportToWKT(formatter.get()), "CONVERSION[\"Spherical Cross-Track Height\",\n" " METHOD[\"Spherical Cross-Track Height\"],\n" " PARAMETER[\"Peg point latitude\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Peg point longitude\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Peg point heading\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Peg point height\",4,\n" " LENGTHUNIT[\"metre\",1]]]"); EXPECT_EQ( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), "PROJECTION[\"Spherical_Cross_Track_Height\"],\n" "PARAMETER[\"peg_point_latitude\",1],\n" "PARAMETER[\"peg_point_longitude\",2],\n" "PARAMETER[\"peg_point_heading\",3],\n" "PARAMETER[\"peg_point_height\",4]"); } // --------------------------------------------------------------------------- TEST(operation, conversion_inverse) { auto conv = Conversion::createTransverseMercator( PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)); auto inv = conv->inverse(); EXPECT_EQ(inv->inverse(), conv); EXPECT_EQ(inv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Inverse of Transverse Mercator\",\n" " METHOD[\"Inverse of Transverse Mercator\",\n" " ID[\"INVERSE(EPSG)\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",3,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); EXPECT_EQ(inv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=tmerc +lat_0=1 +lon_0=2 +k=3 " "+x_0=4 +y_0=5"); EXPECT_TRUE(inv->isEquivalentTo(inv.get())); EXPECT_FALSE(inv->isEquivalentTo(createUnrelatedObject().get())); EXPECT_TRUE( conv->isEquivalentTo(conv->CoordinateOperation::shallowClone().get())); EXPECT_TRUE( inv->isEquivalentTo(inv->CoordinateOperation::shallowClone().get())); } // --------------------------------------------------------------------------- TEST(operation, eqearth_export) { auto conv = Conversion::createEqualEarth(PropertyMap(), Angle(1), Length(2), Length(3)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=eqearth +lon_0=1 +x_0=2 +y_0=3"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Equal Earth\",\n" " METHOD[\"Equal Earth\",\n" " ID[\"EPSG\",1078]],\n" " PARAMETER[\"Longitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",2,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); } // --------------------------------------------------------------------------- TEST(operation, vertical_perspective_export) { auto conv = Conversion::createVerticalPerspective( PropertyMap(), Angle(1), Angle(2), Length(3), Length(4), Length(5), Length(6)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=nsper +lat_0=1 +lon_0=2 +h=4 +x_0=5 +y_0=6"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Vertical Perspective\",\n" " METHOD[\"Vertical Perspective\",\n" " ID[\"EPSG\",9838]],\n" " PARAMETER[\"Latitude of topocentric origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8834]],\n" " PARAMETER[\"Longitude of topocentric origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8835]],\n" " PARAMETER[\"Ellipsoidal height of topocentric origin\",3,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8836]],\n" " PARAMETER[\"Viewpoint height\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8840]],\n" " PARAMETER[\"False easting\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]"); } // --------------------------------------------------------------------------- TEST( operation, vertical_perspective_export_no_topocentric_height_and_false_easting_northing) { auto conv = Conversion::createVerticalPerspective( PropertyMap(), Angle(1), Angle(2), Length(0), Length(4), Length(0), Length(0)); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=nsper +lat_0=1 +lon_0=2 +h=4 +x_0=0 +y_0=0"); // Check that False esting and False northing are not exported, when they // are 0. EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"Vertical Perspective\",\n" " METHOD[\"Vertical Perspective\",\n" " ID[\"EPSG\",9838]],\n" " PARAMETER[\"Latitude of topocentric origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8834]],\n" " PARAMETER[\"Longitude of topocentric origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8835]],\n" " PARAMETER[\"Ellipsoidal height of topocentric origin\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8836]],\n" " PARAMETER[\"Viewpoint height\",4,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8840]]]"); } // --------------------------------------------------------------------------- TEST(operation, laborde_oblique_mercator) { // Content of EPSG:29701 "Tananarive (Paris) / Laborde Grid" auto projString = "+proj=labrd +lat_0=-18.9 +lon_0=44.1 +azi=18.9 " "+k=0.9995 +x_0=400000 +y_0=800000 +ellps=intl +pm=paris " "+units=m +no_defs +type=crs"; auto obj = PROJStringParser().createFromPROJString(projString); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), projString); } // --------------------------------------------------------------------------- TEST(operation, adams_ws2_export) { auto dbContext = DatabaseContext::create(); // ESRI:54098 WGS_1984_Adams_Square_II auto crs = AuthorityFactory::create(dbContext, "ESRI") ->createProjectedCRS("54098"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=adams_ws2 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m " "+no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(operation, adams_ws2_export_failure) { auto dbContext = DatabaseContext::create(); // ESRI:54099 WGS_1984_Spilhaus_Ocean_Map_in_Square auto crs = AuthorityFactory::create(dbContext, "ESRI") ->createProjectedCRS("54099"); EXPECT_THROW(crs->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); } // --------------------------------------------------------------------------- TEST(operation, hyperbolic_cassini_soldner) { auto dbContext = DatabaseContext::create(); auto crs = AuthorityFactory::create(dbContext, "EPSG")->createProjectedCRS("3139"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=cass +hyperbolic +lat_0=-16.25 +lon_0=179.333333333333 " "+x_0=251727.9155424 +y_0=334519.953768 " "+a=6378306.3696 +b=6356571.996 +units=link +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(operation, PROJ_based) { auto conv = SingleOperation::createPROJBased(PropertyMap(), "+proj=merc", nullptr, nullptr); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"PROJ-based coordinate operation\",\n" " METHOD[\"PROJ-based operation method: +proj=merc\"]]"); EXPECT_EQ(conv->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=merc"); auto str = "+proj=pipeline +step +proj=unitconvert +xy_in=grad +xy_out=rad " "+step +proj=axisswap +order=2,1 +step +proj=longlat " "+ellps=clrk80ign +pm=paris +step +proj=axisswap +order=2,1"; EXPECT_EQ( SingleOperation::createPROJBased(PropertyMap(), str, nullptr, nullptr) ->exportToPROJString(PROJStringFormatter::create().get()), str); EXPECT_THROW(SingleOperation::createPROJBased( PropertyMap(), "+proj=pipeline +step +proj=pipeline", nullptr, nullptr) ->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); } // --------------------------------------------------------------------------- TEST(operation, PROJ_based_empty) { auto conv = SingleOperation::createPROJBased(PropertyMap(), "", nullptr, nullptr); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); EXPECT_EQ(conv->exportToWKT(WKTFormatter::create().get()), "CONVERSION[\"PROJ-based coordinate operation\",\n" " METHOD[\"PROJ-based operation method: \"]]"); EXPECT_THROW( conv->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); EXPECT_EQ(conv->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, PROJ_based_with_global_parameters) { auto conv = SingleOperation::createPROJBased( PropertyMap(), "+proj=pipeline +ellps=WGS84 +step +proj=longlat", nullptr, nullptr); EXPECT_EQ(conv->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +ellps=WGS84 +step +proj=longlat"); } // --------------------------------------------------------------------------- TEST(operation, geographic_topocentric) { auto wkt = "PROJCRS[\"EPSG topocentric example A\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4979]],\n" " CONVERSION[\"EPSG topocentric example A\",\n" " METHOD[\"Geographic/topocentric conversions\",\n" " ID[\"EPSG\",9837]],\n" " PARAMETER[\"Latitude of topocentric origin\",55,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8834]],\n" " PARAMETER[\"Longitude of topocentric origin\",5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8835]],\n" " PARAMETER[\"Ellipsoidal height of topocentric origin\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8836]]],\n" " CS[Cartesian,3],\n" " AXIS[\"topocentric East (U)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"topocentric North (V)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"topocentric height (W)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"Example only (fictitious).\"],\n" " AREA[\"Description of the extent of the CRS.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",5819]]"; auto obj = WKTParser().createFromWKT(wkt); auto dst = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4979, NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=WGS84 " "+step +proj=topocentric +lat_0=55 +lon_0=5 +h_0=0 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, geocentric_topocentric) { auto wkt = "PROJCRS[\"EPSG topocentric example B\",\n" " BASEGEODCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4978]],\n" " CONVERSION[\"EPSG topocentric example B\",\n" " METHOD[\"Geocentric/topocentric conversions\",\n" " ID[\"EPSG\",9836]],\n" " PARAMETER[\"Geocentric X of topocentric origin\",3771793.97,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8837]],\n" " PARAMETER[\"Geocentric Y of topocentric origin\",140253.34,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8838]],\n" " PARAMETER[\"Geocentric Z of topocentric origin\",5124304.35,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8839]]],\n" " CS[Cartesian,3],\n" " AXIS[\"topocentric East (U)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"topocentric North (V)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"topocentric height (W)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"Example only (fictitious).\"],\n" " AREA[\"Description of the extent of the CRS.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",5820]]"; auto dbContext = DatabaseContext::create(); // Need a database so that EPSG:4978 is resolved auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto dst = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(dst != nullptr); auto f(NS_PROJ::io::WKTFormatter::create( NS_PROJ::io::WKTFormatter::Convention::WKT2_2019)); auto op = CoordinateOperationFactory::create()->createOperation( GeodeticCRS::EPSG_4978, NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=topocentric +X_0=3771793.97 +Y_0=140253.34 " "+Z_0=5124304.35 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_A_to_variant_B) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createMercatorVariantA(PropertyMap(), Angle(0), Angle(1), Scale(0.9), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto conv = projCRS->derivingConversion(); auto sameConv = conv->convertToOtherMethod(EPSG_CODE_METHOD_MERCATOR_VARIANT_A); ASSERT_TRUE(sameConv); EXPECT_TRUE(sameConv->isEquivalentTo(conv.get())); auto targetConv = conv->convertToOtherMethod(EPSG_CODE_METHOD_MERCATOR_VARIANT_B); ASSERT_TRUE(targetConv); auto lat_1 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_EQ(lat_1, 25.917499691810534) << lat_1; EXPECT_EQ(targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE), 1); EXPECT_EQ(targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_EASTING, UnitOfMeasure::METRE), 3); EXPECT_EQ(targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_NORTHING, UnitOfMeasure::METRE), 4); EXPECT_FALSE( conv->isEquivalentTo(targetConv.get(), IComparable::Criterion::STRICT)); EXPECT_TRUE(conv->isEquivalentTo(targetConv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(targetConv->isEquivalentTo(conv.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_A_to_variant_B_scale_1) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createMercatorVariantA(PropertyMap(), Angle(0), Angle(1), Scale(1.0), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_MERCATOR_VARIANT_B); ASSERT_TRUE(targetConv); auto lat_1 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_EQ(lat_1, 0.0) << lat_1; } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_A_to_variant_B_no_crs) { auto targetConv = Conversion::createMercatorVariantA(PropertyMap(), Angle(0), Angle(1), Scale(1.0), Length(3), Length(4)) ->convertToOtherMethod(EPSG_CODE_METHOD_MERCATOR_VARIANT_B); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_A_to_variant_B_invalid_scale) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createMercatorVariantA(PropertyMap(), Angle(0), Angle(1), Scale(0.0), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_MERCATOR_VARIANT_B); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- static GeographicCRSNNPtr geographicCRSInvalidEccentricity() { return GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::create( PropertyMap(), Ellipsoid::createFlattenedSphere(PropertyMap(), Length(6378137), Scale(0.1)), optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_A_to_variant_B_invalid_eccentricity) { auto projCRS = ProjectedCRS::create( PropertyMap(), geographicCRSInvalidEccentricity(), Conversion::createMercatorVariantA(PropertyMap(), Angle(0), Angle(1), Scale(1.0), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_MERCATOR_VARIANT_B); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_B_to_variant_A) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createMercatorVariantB(PropertyMap(), Angle(25.917499691810534), Angle(1), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_MERCATOR_VARIANT_A); ASSERT_TRUE(targetConv); EXPECT_EQ(targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE), 0); EXPECT_EQ(targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE), 1); auto k_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, UnitOfMeasure::SCALE_UNITY); EXPECT_EQ(k_0, 0.9) << k_0; EXPECT_EQ(targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_EASTING, UnitOfMeasure::METRE), 3); EXPECT_EQ(targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_NORTHING, UnitOfMeasure::METRE), 4); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_B_to_variant_A_invalid_std1) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createMercatorVariantB(PropertyMap(), Angle(100), Angle(1), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_MERCATOR_VARIANT_A); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, mercator_variant_B_to_variant_A_invalid_eccentricity) { auto projCRS = ProjectedCRS::create( PropertyMap(), geographicCRSInvalidEccentricity(), Conversion::createMercatorVariantB(PropertyMap(), Angle(0), Angle(1), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_MERCATOR_VARIANT_A); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp) { // equivalent to EPSG:2154 auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4269, // something using GRS80 Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.5), Angle(3), Angle(49), Angle(44), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto conv = projCRS->derivingConversion(); auto targetConv = conv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); ASSERT_TRUE(targetConv); { auto lat_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_0, 46.519430223986866, 1e-12) << lat_0; auto lon_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lon_0, 3.0, 1e-15) << lon_0; auto k_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, UnitOfMeasure::SCALE_UNITY); EXPECT_NEAR(k_0, 0.9990510286374692, 1e-15) << k_0; auto x_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_EASTING, UnitOfMeasure::METRE); EXPECT_NEAR(x_0, 700000, 1e-15) << x_0; auto y_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_NORTHING, UnitOfMeasure::METRE); EXPECT_NEAR(y_0, 6602157.8388103368, 1e-7) << y_0; } auto _2sp_from_1sp = targetConv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); ASSERT_TRUE(_2sp_from_1sp); { auto lat_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_0, 46.5, 1e-15) << lat_0; auto lon_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lon_0, 3, 1e-15) << lon_0; auto lat_1 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_1, 49, 1e-15) << lat_1; auto lat_2 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_2, 44, 1e-15) << lat_2; auto x_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, UnitOfMeasure::METRE); EXPECT_NEAR(x_0, 700000, 1e-15) << x_0; auto y_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, UnitOfMeasure::METRE); EXPECT_NEAR(y_0, 6600000, 1e-15) << y_0; } EXPECT_FALSE( conv->isEquivalentTo(targetConv.get(), IComparable::Criterion::STRICT)); EXPECT_TRUE(conv->isEquivalentTo(targetConv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(targetConv->isEquivalentTo(conv.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_phi0_eq_phi1_eq_phi2) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4269, // something using GRS80 Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.5), Angle(3), Angle(46.5), Angle(46.5), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto conv = projCRS->derivingConversion(); auto targetConv = conv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); ASSERT_TRUE(targetConv); { auto lat_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_0, 46.5, 1e-15) << lat_0; auto lon_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lon_0, 3.0, 1e-15) << lon_0; auto k_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, UnitOfMeasure::SCALE_UNITY); EXPECT_NEAR(k_0, 1.0, 1e-15) << k_0; auto x_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_EASTING, UnitOfMeasure::METRE); EXPECT_NEAR(x_0, 700000, 1e-15) << x_0; auto y_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_NORTHING, UnitOfMeasure::METRE); EXPECT_NEAR(y_0, 6600000, 1e-15) << y_0; } auto _2sp_from_1sp = targetConv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); ASSERT_TRUE(_2sp_from_1sp); { auto lat_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_0, 46.5, 1e-15) << lat_0; auto lon_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lon_0, 3, 1e-15) << lon_0; auto lat_1 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_1, 46.5, 1e-15) << lat_1; auto lat_2 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_2, 46.5, 1e-15) << lat_2; auto x_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, UnitOfMeasure::METRE); EXPECT_NEAR(x_0, 700000, 1e-15) << x_0; auto y_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, UnitOfMeasure::METRE); EXPECT_NEAR(y_0, 6600000, 1e-15) << y_0; } EXPECT_TRUE(conv->isEquivalentTo(targetConv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(targetConv->isEquivalentTo(conv.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_phi0_diff_phi1_and_phi1_eq_phi2) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4269, // something using GRS80 Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.123), Angle(3), Angle(46.4567), Angle(46.4567), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto conv = projCRS->derivingConversion(); auto targetConv = conv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); ASSERT_TRUE(targetConv); { auto lat_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_0, 46.4567, 1e-14) << lat_0; auto lon_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lon_0, 3.0, 1e-15) << lon_0; auto k_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, UnitOfMeasure::SCALE_UNITY); EXPECT_NEAR(k_0, 1.0, 1e-15) << k_0; auto x_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_EASTING, UnitOfMeasure::METRE); EXPECT_NEAR(x_0, 700000, 1e-15) << x_0; auto y_0 = targetConv->parameterValueNumeric( EPSG_CODE_PARAMETER_FALSE_NORTHING, UnitOfMeasure::METRE); EXPECT_NEAR(y_0, 6637093.292952879, 1e-8) << y_0; } auto _2sp_from_1sp = targetConv->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); ASSERT_TRUE(_2sp_from_1sp); { auto lat_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_0, 46.4567, 1e-14) << lat_0; auto lon_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, UnitOfMeasure::DEGREE); EXPECT_NEAR(lon_0, 3, 1e-15) << lon_0; auto lat_1 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_1, 46.4567, 1e-14) << lat_1; auto lat_2 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, UnitOfMeasure::DEGREE); EXPECT_NEAR(lat_2, 46.4567, 1e-14) << lat_2; auto x_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, UnitOfMeasure::METRE); EXPECT_NEAR(x_0, 700000, 1e-15) << x_0; auto y_0 = _2sp_from_1sp->parameterValueNumeric( EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, UnitOfMeasure::METRE); EXPECT_NEAR(y_0, 6637093.292952879, 1e-8) << y_0; } EXPECT_TRUE(conv->isEquivalentTo(targetConv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(targetConv->isEquivalentTo(conv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(_2sp_from_1sp->isEquivalentTo( targetConv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(targetConv->isEquivalentTo(_2sp_from_1sp.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(conv->isEquivalentTo(_2sp_from_1sp.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, lcc1sp_to_lcc2sp_invalid_eccentricity) { auto projCRS = ProjectedCRS::create( PropertyMap(), geographicCRSInvalidEccentricity(), Conversion::createLambertConicConformal_1SP(PropertyMap(), Angle(40), Angle(1), Scale(0.99), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc1sp_to_lcc2sp_invalid_scale) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_1SP( PropertyMap(), Angle(40), Angle(1), Scale(0), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc1sp_to_lcc2sp_invalid_lat0) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_1SP(PropertyMap(), Angle(100), Angle(1), Scale(0.99), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc1sp_to_lcc2sp_null_lat0) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_1SP(PropertyMap(), Angle(0), Angle(1), Scale(0.99), Length(3), Length(4)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_invalid_lat0) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(100), Angle(3), Angle(44), Angle(49), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_invalid_lat1) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.5), Angle(3), Angle(100), Angle(49), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_invalid_lat2) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.5), Angle(3), Angle(44), Angle(100), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_invalid_lat1_opposite_lat2) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.5), Angle(3), Angle(-49), Angle(49), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_invalid_lat1_and_lat2_close_to_zero) { auto projCRS = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.5), Angle(3), Angle(.0000000000000001), Angle(.0000000000000002), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, lcc2sp_to_lcc1sp_invalid_eccentricity) { auto projCRS = ProjectedCRS::create( PropertyMap(), geographicCRSInvalidEccentricity(), Conversion::createLambertConicConformal_2SP( PropertyMap(), Angle(46.5), Angle(3), Angle(44), Angle(49), Length(700000), Length(6600000)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto targetConv = projCRS->derivingConversion()->convertToOtherMethod( EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP); EXPECT_FALSE(targetConv != nullptr); } // --------------------------------------------------------------------------- TEST(operation, three_param_equivalent_to_seven_param) { auto three_param = Transformation::createGeocentricTranslations( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, {}); auto seven_param_pv = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, {}); auto seven_param_cf = Transformation::createCoordinateFrameRotation( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, {}); auto seven_param_non_eq = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 1.0, 0.0, 0.0, 0.0, {}); EXPECT_TRUE(three_param->isEquivalentTo( seven_param_pv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(three_param->isEquivalentTo( seven_param_cf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(seven_param_cf->isEquivalentTo( three_param.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(seven_param_pv->isEquivalentTo( three_param.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(three_param->isEquivalentTo( seven_param_non_eq.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, position_vector_equivalent_coordinate_frame) { auto pv = Transformation::createPositionVector( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, {}); auto cf = Transformation::createCoordinateFrameRotation( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, -4 + 1e-11, -5.0, -6.0, 7.0, {}); auto cf_non_eq = Transformation::createCoordinateFrameRotation( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, {}); EXPECT_TRUE( pv->isEquivalentTo(cf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( cf->isEquivalentTo(pv.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(pv->isEquivalentTo(cf_non_eq.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, conversion_missing_parameter) { auto wkt1 = "PROJCS[\"NAD83(CSRS98) / UTM zone 20N (deprecated)\"," " GEOGCS[\"NAD83(CSRS98)\"," " DATUM[\"NAD83_Canadian_Spatial_Reference_System\"," " SPHEROID[\"GRS 1980\",6378137,298.257222101," " AUTHORITY[\"EPSG\",\"7019\"]]," " AUTHORITY[\"EPSG\",\"6140\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9108\"]]," " AUTHORITY[\"EPSG\",\"4140\"]]," " PROJECTION[\"Transverse_Mercator\"]," " PARAMETER[\"latitude_of_origin\",0]," " PARAMETER[\"central_meridian\",-63]," " PARAMETER[\"scale_factor\",0.9996]," " PARAMETER[\"false_easting\",500000]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Easting\",EAST]," " AXIS[\"Northing\",NORTH]," " AUTHORITY[\"EPSG\",\"2038\"]]"; auto obj1 = WKTParser().createFromWKT(wkt1); auto crs1 = nn_dynamic_pointer_cast<ProjectedCRS>(obj1); ASSERT_TRUE(crs1 != nullptr); // Difference with wkt1: latitude_of_origin missing, but false_northing // added to 0 auto wkt2 = "PROJCS[\"NAD83(CSRS98) / UTM zone 20N (deprecated)\"," " GEOGCS[\"NAD83(CSRS98)\"," " DATUM[\"NAD83_Canadian_Spatial_Reference_System\"," " SPHEROID[\"GRS 1980\",6378137,298.257222101," " AUTHORITY[\"EPSG\",\"7019\"]]," " AUTHORITY[\"EPSG\",\"6140\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9108\"]]," " AUTHORITY[\"EPSG\",\"4140\"]]," " PROJECTION[\"Transverse_Mercator\"]," " PARAMETER[\"central_meridian\",-63]," " PARAMETER[\"scale_factor\",0.9996]," " PARAMETER[\"false_easting\",500000]," " PARAMETER[\"false_northing\",0]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Easting\",EAST]," " AXIS[\"Northing\",NORTH]," " AUTHORITY[\"EPSG\",\"2038\"]]"; auto obj2 = WKTParser().createFromWKT(wkt2); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); // Difference with wkt1: false_northing added to 0 auto wkt3 = "PROJCS[\"NAD83(CSRS98) / UTM zone 20N (deprecated)\"," " GEOGCS[\"NAD83(CSRS98)\"," " DATUM[\"NAD83_Canadian_Spatial_Reference_System\"," " SPHEROID[\"GRS 1980\",6378137,298.257222101," " AUTHORITY[\"EPSG\",\"7019\"]]," " AUTHORITY[\"EPSG\",\"6140\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9108\"]]," " AUTHORITY[\"EPSG\",\"4140\"]]," " PROJECTION[\"Transverse_Mercator\"]," " PARAMETER[\"latitude_of_origin\",0]," " PARAMETER[\"central_meridian\",-63]," " PARAMETER[\"scale_factor\",0.9996]," " PARAMETER[\"false_easting\",500000]," " PARAMETER[\"false_northing\",0]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Easting\",EAST]," " AXIS[\"Northing\",NORTH]," " AUTHORITY[\"EPSG\",\"2038\"]]"; auto obj3 = WKTParser().createFromWKT(wkt3); auto crs3 = nn_dynamic_pointer_cast<ProjectedCRS>(obj3); ASSERT_TRUE(crs3 != nullptr); // Difference with wkt1: UNKNOWN added to non-zero auto wkt4 = "PROJCS[\"NAD83(CSRS98) / UTM zone 20N (deprecated)\"," " GEOGCS[\"NAD83(CSRS98)\"," " DATUM[\"NAD83_Canadian_Spatial_Reference_System\"," " SPHEROID[\"GRS 1980\",6378137,298.257222101," " AUTHORITY[\"EPSG\",\"7019\"]]," " AUTHORITY[\"EPSG\",\"6140\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9108\"]]," " AUTHORITY[\"EPSG\",\"4140\"]]," " PROJECTION[\"Transverse_Mercator\"]," " PARAMETER[\"latitude_of_origin\",0]," " PARAMETER[\"central_meridian\",-63]," " PARAMETER[\"scale_factor\",0.9996]," " PARAMETER[\"false_easting\",500000]," " PARAMETER[\"false_northing\",0]," " PARAMETER[\"UNKNOWN\",13]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Easting\",EAST]," " AXIS[\"Northing\",NORTH]," " AUTHORITY[\"EPSG\",\"2038\"]]"; auto obj4 = WKTParser().createFromWKT(wkt4); auto crs4 = nn_dynamic_pointer_cast<ProjectedCRS>(obj4); ASSERT_TRUE(crs4 != nullptr); // Difference with wkt1: latitude_of_origin missing, but false_northing // added to non-zero auto wkt5 = "PROJCS[\"NAD83(CSRS98) / UTM zone 20N (deprecated)\"," " GEOGCS[\"NAD83(CSRS98)\"," " DATUM[\"NAD83_Canadian_Spatial_Reference_System\"," " SPHEROID[\"GRS 1980\",6378137,298.257222101," " AUTHORITY[\"EPSG\",\"7019\"]]," " AUTHORITY[\"EPSG\",\"6140\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9108\"]]," " AUTHORITY[\"EPSG\",\"4140\"]]," " PROJECTION[\"Transverse_Mercator\"]," " PARAMETER[\"central_meridian\",-63]," " PARAMETER[\"scale_factor\",0.9996]," " PARAMETER[\"false_easting\",500000]," " PARAMETER[\"false_northing\",-99999]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Easting\",EAST]," " AXIS[\"Northing\",NORTH]," " AUTHORITY[\"EPSG\",\"2038\"]]"; auto obj5 = WKTParser().createFromWKT(wkt5); auto crs5 = nn_dynamic_pointer_cast<ProjectedCRS>(obj5); ASSERT_TRUE(crs5 != nullptr); EXPECT_TRUE( crs1->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs2->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs1->isEquivalentTo(crs3.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs3->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs2->isEquivalentTo(crs3.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs3->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs1->isEquivalentTo(crs4.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs4->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs1->isEquivalentTo(crs5.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs5->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, conversion_missing_parameter_scale) { auto wkt1 = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"latitude_of_origin\",-1],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1]]"; auto obj1 = WKTParser().createFromWKT(wkt1); auto crs1 = nn_dynamic_pointer_cast<ProjectedCRS>(obj1); ASSERT_TRUE(crs1 != nullptr); // Difference with wkt1: scale_factor missing auto wkt2 = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"latitude_of_origin\",-1],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1]]"; auto obj2 = WKTParser().createFromWKT(wkt2); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); // Difference with wkt1: scale_factor set to non-1 auto wkt3 = "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"latitude_of_origin\",-1],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",-1],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1]]"; auto obj3 = WKTParser().createFromWKT(wkt3); auto crs3 = nn_dynamic_pointer_cast<ProjectedCRS>(obj3); ASSERT_TRUE(crs3 != nullptr); EXPECT_TRUE( crs1->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs2->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs1->isEquivalentTo(crs3.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs3->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs2->isEquivalentTo(crs3.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE( crs3->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, hotine_oblique_mercator_variant_A_export_equivalent_modulo_360) { auto conv1 = Conversion::createHotineObliqueMercatorVariantA( PropertyMap(), Angle(1), Angle(2), Angle(-3), Angle(-4), Scale(5), Length(6), Length(7)); auto conv2 = Conversion::createHotineObliqueMercatorVariantA( PropertyMap(), Angle(1), Angle(2), Angle(-3 + 360), Angle(-4 + 360), Scale(5), Length(6), Length(7)); EXPECT_TRUE( conv1->isEquivalentTo(conv2.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(operation, createChangeVerticalUnit) { auto conv = Conversion::createChangeVerticalUnit(PropertyMap(), Scale(1)); EXPECT_TRUE(conv->validateParameters().empty()); } // --------------------------------------------------------------------------- TEST(operation, createChangeVerticalUnitNoconvFactor) { auto conv = Conversion::createChangeVerticalUnit(PropertyMap()); EXPECT_TRUE(conv->validateParameters().empty()); } // --------------------------------------------------------------------------- TEST(operation, createGeographicGeocentric) { auto conv = Conversion::createGeographicGeocentric(PropertyMap()); EXPECT_TRUE(conv->validateParameters().empty()); } // --------------------------------------------------------------------------- TEST(operation, validateParameters) { { auto conv = Conversion::create( PropertyMap(), PropertyMap().set(IdentifiedObject::NAME_KEY, "unknown"), {}, {}); auto validation = conv->validateParameters(); EXPECT_EQ(validation, std::list<std::string>{"Unknown method unknown"}); } { auto conv = Conversion::create(PropertyMap(), PropertyMap().set(IdentifiedObject::NAME_KEY, "change of vertical unit"), {}, {}); auto validation = conv->validateParameters(); auto expected = std::list<std::string>{ "Method name change of vertical unit is equivalent to official " "Change of Vertical Unit but not strictly equal", "Cannot find expected parameter Unit conversion scalar"}; EXPECT_EQ(validation, expected); } { auto conv = Conversion::create( PropertyMap(), PropertyMap() .set(IdentifiedObject::NAME_KEY, EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT) .set(Identifier::CODESPACE_KEY, Identifier::EPSG) .set(Identifier::CODE_KEY, "1234"), {}, {}); auto validation = conv->validateParameters(); auto expected = std::list<std::string>{ "Method of EPSG code 1234 does not match official code (1069)", "Cannot find expected parameter Unit conversion scalar"}; EXPECT_EQ(validation, expected); } { auto conv = Conversion::create( PropertyMap(), PropertyMap() .set(IdentifiedObject::NAME_KEY, "some fancy name") .set(Identifier::CODESPACE_KEY, Identifier::EPSG) .set(Identifier::CODE_KEY, EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT), {}, {}); auto validation = conv->validateParameters(); auto expected = std::list<std::string>{ "Method name some fancy name, matched to Change of Vertical Unit, " "through its EPSG code has not an equivalent name", "Cannot find expected parameter Unit conversion scalar"}; EXPECT_EQ(validation, expected); } { auto conv = Conversion::create( PropertyMap(), PropertyMap().set(IdentifiedObject::NAME_KEY, EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT), {OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "unit conversion scalar"))}, {ParameterValue::create(Measure(1.0, UnitOfMeasure::SCALE_UNITY))}); auto validation = conv->validateParameters(); auto expected = std::list<std::string>{ "Parameter name unit conversion scalar is equivalent to official " "Unit conversion scalar but not strictly equal"}; EXPECT_EQ(validation, expected); } { auto conv = Conversion::create( PropertyMap(), PropertyMap().set(IdentifiedObject::NAME_KEY, EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT), {OperationParameter::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "fancy name") .set(Identifier::CODESPACE_KEY, Identifier::EPSG) .set(Identifier::CODE_KEY, EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR))}, {ParameterValue::create(Measure(1.0, UnitOfMeasure::SCALE_UNITY))}); auto validation = conv->validateParameters(); auto expected = std::list<std::string>{ "Parameter name fancy name, matched to Unit conversion scalar, " "through its EPSG code has not an equivalent name"}; EXPECT_EQ(validation, expected); } { auto conv = Conversion::create( PropertyMap(), PropertyMap().set(IdentifiedObject::NAME_KEY, EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT), {OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "extra param"))}, {ParameterValue::create(Measure(1.0, UnitOfMeasure::SCALE_UNITY))}); auto validation = conv->validateParameters(); auto expected = std::list<std::string>{ "Cannot find expected parameter Unit conversion scalar", "Parameter extra param found but not expected for this method"}; EXPECT_EQ(validation, expected); } } // --------------------------------------------------------------------------- TEST(operation, normalizeForVisualization) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); const auto checkThroughWKTRoundtrip = [](const CoordinateOperationNNPtr &opRef) { auto wkt = opRef->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); auto objFromWkt = WKTParser().createFromWKT(wkt); auto opFromWkt = nn_dynamic_pointer_cast<CoordinateOperation>(objFromWkt); ASSERT_TRUE(opFromWkt != nullptr); EXPECT_TRUE(opRef->_isEquivalentTo(opFromWkt.get())); EXPECT_EQ( opFromWkt->exportToPROJString(PROJStringFormatter::create().get()), opRef->exportToPROJString(PROJStringFormatter::create().get())); }; // Source(geographic) must be inverted { auto src = authFactory->createCoordinateReferenceSystem("4326"); auto dst = authFactory->createCoordinateReferenceSystem("32631"); auto op = CoordinateOperationFactory::create()->createOperation(src, dst); ASSERT_TRUE(op != nullptr); auto opNormalized = op->normalizeForVisualization(); EXPECT_FALSE(opNormalized->_isEquivalentTo(op.get())); EXPECT_EQ(opNormalized->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=utm +zone=31 +ellps=WGS84"); checkThroughWKTRoundtrip(opNormalized); } // Target(geographic) must be inverted { auto src = authFactory->createCoordinateReferenceSystem("32631"); auto dst = authFactory->createCoordinateReferenceSystem("4326"); auto op = CoordinateOperationFactory::create()->createOperation(src, dst); ASSERT_TRUE(op != nullptr); auto opNormalized = op->normalizeForVisualization(); EXPECT_FALSE(opNormalized->_isEquivalentTo(op.get())); EXPECT_EQ(opNormalized->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=31 +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); checkThroughWKTRoundtrip(opNormalized); } // Source(geographic) and target(projected) must be inverted { auto src = authFactory->createCoordinateReferenceSystem("4326"); auto dst = authFactory->createCoordinateReferenceSystem("3040"); auto op = CoordinateOperationFactory::create()->createOperation(src, dst); ASSERT_TRUE(op != nullptr); auto opNormalized = op->normalizeForVisualization(); EXPECT_FALSE(opNormalized->_isEquivalentTo(op.get())); EXPECT_EQ(opNormalized->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=utm +zone=28 +ellps=GRS80"); checkThroughWKTRoundtrip(opNormalized); } // No inversion { auto src = authFactory->createCoordinateReferenceSystem("32631"); auto dst = authFactory->createCoordinateReferenceSystem("32632"); auto op = CoordinateOperationFactory::create()->createOperation(src, dst); ASSERT_TRUE(op != nullptr); auto opNormalized = op->normalizeForVisualization(); EXPECT_TRUE(opNormalized->_isEquivalentTo(op.get())); } // Source(compoundCRS) and target(geographic 3D) must be inverted { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setUsePROJAlternativeGridNames(false); auto src = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{ authFactory->createCoordinateReferenceSystem("4326"), // EGM2008 height authFactory->createCoordinateReferenceSystem("3855")}); auto list = CoordinateOperationFactory::create()->createOperations( src, authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 3D ctxt); ASSERT_GE(list.size(), 3U); auto op = list[1]; auto opNormalized = op->normalizeForVisualization(); EXPECT_FALSE(opNormalized->_isEquivalentTo(op.get())); EXPECT_EQ( opNormalized->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm08_25.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // Source(boundCRS) and target(geographic) must be inverted { auto src = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4269, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto dst = authFactory->createCoordinateReferenceSystem("4326"); auto op = CoordinateOperationFactory::create()->createOperation(src, dst); ASSERT_TRUE(op != nullptr); auto opNormalized = op->normalizeForVisualization(); EXPECT_FALSE(opNormalized->_isEquivalentTo(op.get())); EXPECT_EQ(opNormalized->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=push +v_3 " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 " "+convention=position_vector " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } } // --------------------------------------------------------------------------- TEST(operation, export_of_Geographic3D_to_GravityRelatedHeight_gtx_unknown_grid) { auto wkt = "COORDINATEOPERATION[\"bla\",\n" " SOURCECRS[\n" " GEOGCRS[\"ETRS89\",\n" " DATUM[\"European Terrestrial Reference System 1989\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4937]]],\n" " TARGETCRS[\n" " VERTCRS[\"bar\",\n" " VDATUM[\"bar\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]]],\n" " METHOD[\"Geographic3D to GravityRelatedHeight (gtx)\",\n" " ID[\"EPSG\",9665]],\n" " PARAMETERFILE[\"Geoid (height correction) model " "file\",\"foo.gtx\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto transf = nn_dynamic_pointer_cast<Transformation>(obj); ASSERT_TRUE(transf != nullptr); // Test that even if the .gtx file is unknown, we export in the correct // direction EXPECT_EQ(transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift +grids=foo.gtx +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, export_of_boundCRS_with_proj_string_method) { auto wkt = "BOUNDCRS[\n" " SOURCECRS[\n" " GEOGCRS[\"unknown\",\n" " DATUM[\"Unknown based on GRS80 ellipsoid\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7019]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]]],\n" " ABRIDGEDTRANSFORMATION[\"Transformation from unknown to WGS84\",\n" " METHOD[\"PROJ-based operation method: +proj=pipeline +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=axisswap " "+order=2,1 " "+step +proj=cart +ellps=GRS80 +step +proj=helmert " "+convention=coordinate_frame +exact +step +inv +proj=cart " "+ellps=WGS84 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ(boundCRS->transformation()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=axisswap +order=2,1 " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +convention=coordinate_frame +exact " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, PointMotionOperation_with_epochs) { auto wkt = "POINTMOTIONOPERATION[\"Canada velocity grid v7 from epoch 2010 to " "epoch 2002\",\n" " SOURCECRS[\n" " GEOGCRS[\"NAD83(CSRS)v7\",\n" " DATUM[\"North American Datum of 1983 (CSRS) version 7\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",8254]]],\n" " METHOD[\"Point motion by grid (Canada NTv2_Vel)\",\n" " ID[\"EPSG\",1070]],\n" " PARAMETERFILE[\"Point motion velocity grid " "file\",\"ca_nrc_NAD83v70VG.tif\"],\n" " OPERATIONACCURACY[0.01],\n" " ID[\"DERIVED_FROM(EPSG)\",9483],\n" " REMARK[\"File initially published with name cvg70.cvb, later " "renamed to NAD83v70VG.gvb with no change of content.\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto pmo = nn_dynamic_pointer_cast<PointMotionOperation>(obj); ASSERT_TRUE(pmo != nullptr); EXPECT_EQ(pmo->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=set +v_4=2010 +omit_fwd " "+step +proj=deformation +dt=-8 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(pmo->inverse()->nameStr(), "Canada velocity grid v7 from epoch 2002 to epoch 2010"); EXPECT_EQ( pmo->inverse()->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_fwd " "+step +proj=deformation +dt=8 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2010 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); }
cpp
PROJ
data/projects/PROJ/test/unit/test_datum.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "proj/common.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" using namespace osgeo::proj::common; using namespace osgeo::proj::datum; using namespace osgeo::proj::io; using namespace osgeo::proj::metadata; using namespace osgeo::proj::util; namespace { struct UnrelatedObject : public IComparable { UnrelatedObject() = default; bool _isEquivalentTo(const IComparable *, Criterion, const DatabaseContextPtr &) const override { assert(false); return false; } }; static nn<std::shared_ptr<UnrelatedObject>> createUnrelatedObject() { return nn_make_shared<UnrelatedObject>(); } } // namespace // --------------------------------------------------------------------------- TEST(datum, ellipsoid_from_sphere) { auto ellipsoid = Ellipsoid::createSphere(PropertyMap(), Length(6378137)); EXPECT_FALSE(ellipsoid->inverseFlattening().has_value()); EXPECT_FALSE(ellipsoid->semiMinorAxis().has_value()); EXPECT_FALSE(ellipsoid->semiMedianAxis().has_value()); EXPECT_TRUE(ellipsoid->isSphere()); EXPECT_EQ(ellipsoid->semiMajorAxis(), Length(6378137)); EXPECT_EQ(ellipsoid->celestialBody(), "Earth"); EXPECT_EQ(ellipsoid->computeSemiMinorAxis(), Length(6378137)); EXPECT_EQ(ellipsoid->computedInverseFlattening(), 0); EXPECT_EQ( ellipsoid->exportToPROJString(PROJStringFormatter::create().get()), "+R=6378137"); EXPECT_TRUE(ellipsoid->isEquivalentTo(ellipsoid.get())); EXPECT_FALSE(ellipsoid->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(datum, ellipsoid_non_earth) { auto ellipsoid = Ellipsoid::createSphere(PropertyMap(), Length(1), "Unity sphere"); EXPECT_EQ(ellipsoid->celestialBody(), "Unity sphere"); } // --------------------------------------------------------------------------- TEST(datum, ellipsoid_from_inverse_flattening) { auto ellipsoid = Ellipsoid::createFlattenedSphere( PropertyMap(), Length(6378137), Scale(298.257223563)); EXPECT_TRUE(ellipsoid->inverseFlattening().has_value()); EXPECT_FALSE(ellipsoid->semiMinorAxis().has_value()); EXPECT_FALSE(ellipsoid->semiMedianAxis().has_value()); EXPECT_FALSE(ellipsoid->isSphere()); EXPECT_EQ(ellipsoid->semiMajorAxis(), Length(6378137)); EXPECT_EQ(*ellipsoid->inverseFlattening(), Scale(298.257223563)); EXPECT_EQ(ellipsoid->computeSemiMinorAxis().unit(), ellipsoid->semiMajorAxis().unit()); EXPECT_NEAR(ellipsoid->computeSemiMinorAxis().value(), Length(6356752.31424518).value(), 1e-9); EXPECT_EQ(ellipsoid->computedInverseFlattening(), 298.257223563); EXPECT_EQ( ellipsoid->exportToPROJString(PROJStringFormatter::create().get()), "+ellps=WGS84"); EXPECT_TRUE(ellipsoid->isEquivalentTo(ellipsoid.get())); EXPECT_FALSE(ellipsoid->isEquivalentTo( Ellipsoid::createTwoAxis(PropertyMap(), Length(6378137), Length(6356752.31424518)) .get())); EXPECT_TRUE(ellipsoid->isEquivalentTo( Ellipsoid::createTwoAxis(PropertyMap(), Length(6378137), Length(6356752.31424518)) .get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(Ellipsoid::WGS84->isEquivalentTo( Ellipsoid::GRS1980.get(), IComparable::Criterion::EQUIVALENT)); auto sphere = Ellipsoid::createSphere(PropertyMap(), Length(6378137)); EXPECT_FALSE(Ellipsoid::WGS84->isEquivalentTo( sphere.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(sphere->isEquivalentTo(Ellipsoid::WGS84.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(datum, ellipsoid_from_null_inverse_flattening) { auto ellipsoid = Ellipsoid::createFlattenedSphere( PropertyMap(), Length(6378137), Scale(0)); EXPECT_FALSE(ellipsoid->inverseFlattening().has_value()); EXPECT_FALSE(ellipsoid->semiMinorAxis().has_value()); EXPECT_FALSE(ellipsoid->semiMedianAxis().has_value()); EXPECT_TRUE(ellipsoid->isSphere()); } // --------------------------------------------------------------------------- TEST(datum, ellipsoid_from_semi_minor_axis) { auto ellipsoid = Ellipsoid::createTwoAxis(PropertyMap(), Length(6378137), Length(6356752.31424518)); EXPECT_FALSE(ellipsoid->inverseFlattening().has_value()); EXPECT_TRUE(ellipsoid->semiMinorAxis().has_value()); EXPECT_FALSE(ellipsoid->semiMedianAxis().has_value()); EXPECT_FALSE(ellipsoid->isSphere()); EXPECT_EQ(ellipsoid->semiMajorAxis(), Length(6378137)); EXPECT_EQ(*ellipsoid->semiMinorAxis(), Length(6356752.31424518)); EXPECT_EQ(ellipsoid->computeSemiMinorAxis(), Length(6356752.31424518)); EXPECT_NEAR(ellipsoid->computedInverseFlattening(), 298.257223563, 1e-10); EXPECT_EQ( ellipsoid->exportToPROJString(PROJStringFormatter::create().get()), "+ellps=WGS84"); EXPECT_TRUE(ellipsoid->isEquivalentTo(ellipsoid.get())); EXPECT_FALSE(ellipsoid->isEquivalentTo( Ellipsoid::createFlattenedSphere(PropertyMap(), Length(6378137), Scale(298.257223563)) .get())); EXPECT_TRUE(ellipsoid->isEquivalentTo( Ellipsoid::createFlattenedSphere(PropertyMap(), Length(6378137), Scale(298.257223563)) .get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(datum, prime_meridian_to_PROJString) { EXPECT_EQ(PrimeMeridian::GREENWICH->exportToPROJString( PROJStringFormatter::create().get()), "+proj=noop"); EXPECT_EQ(PrimeMeridian::PARIS->exportToPROJString( PROJStringFormatter::create().get()), "+pm=paris"); EXPECT_EQ(PrimeMeridian::create(PropertyMap(), Angle(3.5)) ->exportToPROJString(PROJStringFormatter::create().get()), "+pm=3.5"); EXPECT_EQ( PrimeMeridian::create(PropertyMap(), Angle(100, UnitOfMeasure::GRAD)) ->exportToPROJString(PROJStringFormatter::create().get()), "+pm=90"); EXPECT_EQ( PrimeMeridian::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Origin meridian"), Angle(0)) ->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); EXPECT_TRUE(PrimeMeridian::GREENWICH->isEquivalentTo( PrimeMeridian::GREENWICH.get())); EXPECT_FALSE(PrimeMeridian::GREENWICH->isEquivalentTo( createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(datum, prime_meridian_to_JSON) { EXPECT_EQ(PrimeMeridian::GREENWICH->exportToJSON( &(JSONFormatter::create()->setSchema(""))), "{\n" " \"type\": \"PrimeMeridian\",\n" " \"name\": \"Greenwich\",\n" " \"longitude\": 0,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8901\n" " }\n" "}"); EXPECT_EQ(PrimeMeridian::PARIS->exportToJSON( &(JSONFormatter::create()->setSchema(""))), "{\n" " \"type\": \"PrimeMeridian\",\n" " \"name\": \"Paris\",\n" " \"longitude\": {\n" " \"value\": 2.5969213,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"grad\",\n" " \"conversion_factor\": 0.015707963267949\n" " }\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8903\n" " }\n" "}"); } // --------------------------------------------------------------------------- TEST(datum, datum_with_ANCHOR) { auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS_1984 with anchor"), Ellipsoid::WGS84, optional<std::string>("My anchor"), PrimeMeridian::GREENWICH); ASSERT_TRUE(datum->anchorDefinition()); EXPECT_EQ(*datum->anchorDefinition(), "My anchor"); ASSERT_FALSE(datum->anchorEpoch()); auto expected = "DATUM[\"WGS_1984 with anchor\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ANCHOR[\"My anchor\"]]"; EXPECT_EQ(datum->exportToWKT(WKTFormatter::create().get()), expected); } // --------------------------------------------------------------------------- TEST(datum, datum_with_ANCHOREPOCH) { auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my_datum"), Ellipsoid::WGS84, optional<std::string>(), optional<Measure>(Measure(2002.5, UnitOfMeasure::YEAR)), PrimeMeridian::GREENWICH); ASSERT_FALSE(datum->anchorDefinition()); ASSERT_TRUE(datum->anchorEpoch()); EXPECT_NEAR(datum->anchorEpoch()->convertToUnit(UnitOfMeasure::YEAR), 2002.5, 1e-8); auto expected = "DATUM[\"my_datum\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ANCHOREPOCH[2002.5]]"; EXPECT_EQ( datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(datum, unknown_datum) { auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my_datum"), Ellipsoid::GRS1980, optional<std::string>(), optional<Measure>(), PrimeMeridian::GREENWICH); auto unknown_datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unknown"), Ellipsoid::GRS1980, optional<std::string>(), optional<Measure>(), PrimeMeridian::GREENWICH); EXPECT_FALSE(datum->isEquivalentTo(unknown_datum.get(), IComparable::Criterion::STRICT)); EXPECT_TRUE(datum->isEquivalentTo(unknown_datum.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(unknown_datum->isEquivalentTo(datum.get(), IComparable::Criterion::STRICT)); EXPECT_TRUE(unknown_datum->isEquivalentTo( datum.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(datum, dynamic_geodetic_reference_frame) { auto drf = DynamicGeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), Ellipsoid::WGS84, optional<std::string>("My anchor"), PrimeMeridian::GREENWICH, Measure(2018.5, UnitOfMeasure::YEAR), optional<std::string>("My model")); auto expected = "DATUM[\"test\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ANCHOR[\"My anchor\"]]"; EXPECT_EQ(drf->exportToWKT(WKTFormatter::create().get()), expected); auto expected_wtk2_2019 = "DYNAMIC[\n" " FRAMEEPOCH[2018.5],\n" " MODEL[\"My model\"]],\n" "DATUM[\"test\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ANCHOR[\"My anchor\"]]"; EXPECT_EQ( drf->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected_wtk2_2019); EXPECT_TRUE(drf->isEquivalentTo(drf.get())); EXPECT_TRUE( drf->isEquivalentTo(drf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(drf->isEquivalentTo(createUnrelatedObject().get())); // "Same" datum, except that it is a non-dynamic one auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), Ellipsoid::WGS84, optional<std::string>("My anchor"), PrimeMeridian::GREENWICH); EXPECT_FALSE(datum->isEquivalentTo(drf.get())); EXPECT_FALSE(drf->isEquivalentTo(datum.get())); EXPECT_TRUE( datum->isEquivalentTo(drf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( drf->isEquivalentTo(datum.get(), IComparable::Criterion::EQUIVALENT)); auto unrelated_datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test2"), Ellipsoid::WGS84, optional<std::string>("My anchor"), PrimeMeridian::GREENWICH); EXPECT_FALSE(unrelated_datum->isEquivalentTo(drf.get())); EXPECT_FALSE(drf->isEquivalentTo(unrelated_datum.get())); EXPECT_FALSE(unrelated_datum->isEquivalentTo( drf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(drf->isEquivalentTo(unrelated_datum.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(datum, ellipsoid_to_PROJString) { EXPECT_EQ(Ellipsoid::WGS84->exportToPROJString( PROJStringFormatter::create().get()), "+ellps=WGS84"); EXPECT_EQ(Ellipsoid::GRS1980->exportToPROJString( PROJStringFormatter::create().get()), "+ellps=GRS80"); EXPECT_EQ( Ellipsoid::createFlattenedSphere( PropertyMap(), Length(10, UnitOfMeasure("km", 1000)), Scale(0.5)) ->exportToPROJString(PROJStringFormatter::create().get()), "+a=10000 +rf=0.5"); EXPECT_EQ(Ellipsoid::createTwoAxis(PropertyMap(), Length(10, UnitOfMeasure("km", 1000)), Length(5, UnitOfMeasure("km", 1000))) ->exportToPROJString(PROJStringFormatter::create().get()), "+a=10000 +b=5000"); } // --------------------------------------------------------------------------- TEST(datum, temporal_datum_WKT2) { auto datum = TemporalDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Gregorian calendar"), DateTime::create("0000-01-01"), TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN); auto expected = "TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]]"; EXPECT_EQ(datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); EXPECT_THROW( datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); EXPECT_TRUE(datum->isEquivalentTo(datum.get())); EXPECT_FALSE(datum->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(datum, temporal_datum_time_origin_non_ISO8601) { auto datum = TemporalDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Gregorian calendar"), DateTime::create("0001 January 1st"), TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN); auto expected = "TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[\"0001 January 1st\"]]"; EXPECT_EQ(datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); } // --------------------------------------------------------------------------- TEST(datum, temporal_datum_WKT2_2019) { auto datum = TemporalDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Gregorian calendar"), DateTime::create("0000-01-01"), TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN); auto expected = "TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]"; EXPECT_EQ( datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(datum, dynamic_vertical_reference_frame) { auto drf = DynamicVerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), optional<std::string>("My anchor"), optional<RealizationMethod>(), Measure(2018.5, UnitOfMeasure::YEAR), optional<std::string>("My model")); auto expected = "VDATUM[\"test\",\n" " ANCHOR[\"My anchor\"]]"; EXPECT_EQ(drf->exportToWKT(WKTFormatter::create().get()), expected); auto expected_wtk2_2019 = "DYNAMIC[\n" " FRAMEEPOCH[2018.5],\n" " MODEL[\"My model\"]],\n" "VDATUM[\"test\",\n" " ANCHOR[\"My anchor\"]]"; EXPECT_EQ( drf->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected_wtk2_2019); EXPECT_TRUE(drf->isEquivalentTo(drf.get())); EXPECT_TRUE( drf->isEquivalentTo(drf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(drf->isEquivalentTo(createUnrelatedObject().get())); // "Same" datum, except that it is a non-dynamic one auto datum = VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), optional<std::string>("My anchor"), optional<RealizationMethod>()); EXPECT_FALSE(datum->isEquivalentTo(drf.get())); EXPECT_FALSE(drf->isEquivalentTo(datum.get())); EXPECT_TRUE( datum->isEquivalentTo(drf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( drf->isEquivalentTo(datum.get(), IComparable::Criterion::EQUIVALENT)); auto unrelated_datum = VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test2"), optional<std::string>("My anchor"), optional<RealizationMethod>()); EXPECT_FALSE(unrelated_datum->isEquivalentTo(drf.get())); EXPECT_FALSE(drf->isEquivalentTo(unrelated_datum.get())); EXPECT_FALSE(unrelated_datum->isEquivalentTo( drf.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(drf->isEquivalentTo(unrelated_datum.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(datum, datum_ensemble) { auto otherDatum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "other datum"), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH); auto ensemble = DatumEnsemble::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), std::vector<DatumNNPtr>{GeodeticReferenceFrame::EPSG_6326, otherDatum}, PositionalAccuracy::create("100")); EXPECT_EQ(ensemble->datums().size(), 2U); EXPECT_EQ(ensemble->positionalAccuracy()->value(), "100"); EXPECT_EQ( ensemble->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), "ENSEMBLE[\"test\",\n" " MEMBER[\"World Geodetic System 1984\",\n" " ID[\"EPSG\",6326]],\n" " MEMBER[\"other datum\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ENSEMBLEACCURACY[100]]"); EXPECT_EQ( ensemble->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2015).get()), "DATUM[\"test\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]]]"); } // --------------------------------------------------------------------------- TEST(datum, datum_ensemble_vertical) { auto ensemble = DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{ VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "vdatum1")), VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "vdatum2"))}, PositionalAccuracy::create("100")); EXPECT_EQ( ensemble->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), "ENSEMBLE[\"unnamed\",\n" " MEMBER[\"vdatum1\"],\n" " MEMBER[\"vdatum2\"],\n" " ENSEMBLEACCURACY[100]]"); } // --------------------------------------------------------------------------- TEST(datum, datum_ensemble_exceptions) { // No datum EXPECT_THROW(DatumEnsemble::create(PropertyMap(), std::vector<DatumNNPtr>{}, PositionalAccuracy::create("100")), Exception); // Single datum EXPECT_THROW(DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{GeodeticReferenceFrame::EPSG_6326}, PositionalAccuracy::create("100")), Exception); auto vdatum = VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "vdatum1")); // Different datum type EXPECT_THROW( DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{GeodeticReferenceFrame::EPSG_6326, vdatum}, PositionalAccuracy::create("100")), Exception); // Different datum type EXPECT_THROW( DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{vdatum, GeodeticReferenceFrame::EPSG_6326}, PositionalAccuracy::create("100")), Exception); // Different ellipsoid EXPECT_THROW(DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{GeodeticReferenceFrame::EPSG_6326, GeodeticReferenceFrame::EPSG_6267}, PositionalAccuracy::create("100")), Exception); // Different prime meridian EXPECT_THROW(DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{ GeodeticReferenceFrame::EPSG_6326, GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "other datum"), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::PARIS)}, PositionalAccuracy::create("100")), Exception); } // --------------------------------------------------------------------------- TEST(datum, edatum) { auto datum = EngineeringDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Engineering datum"), optional<std::string>("my anchor")); auto expected = "EDATUM[\"Engineering datum\",\n" " ANCHOR[\"my anchor\"]]"; EXPECT_EQ(datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); } // --------------------------------------------------------------------------- TEST(datum, pdatum) { auto datum = ParametricDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Parametric datum"), optional<std::string>("my anchor")); auto expected = "PDATUM[\"Parametric datum\",\n" " ANCHOR[\"my anchor\"]]"; EXPECT_EQ(datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); }
cpp
PROJ
data/projects/PROJ/test/unit/test_grids.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test grids.hpp * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2020, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "grids.hpp" #include "proj_internal.h" // M_PI namespace { // --------------------------------------------------------------------------- class GridTest : public ::testing::Test { static void DummyLogFunction(void *, int, const char *) {} protected: void SetUp() override { m_ctxt = proj_context_create(); proj_log_func(m_ctxt, nullptr, DummyLogFunction); m_ctxt2 = proj_context_create(); proj_log_func(m_ctxt2, nullptr, DummyLogFunction); } void TearDown() override { proj_context_destroy(m_ctxt); proj_context_destroy(m_ctxt2); } PJ_CONTEXT *m_ctxt = nullptr; PJ_CONTEXT *m_ctxt2 = nullptr; }; // --------------------------------------------------------------------------- TEST_F(GridTest, VerticalShiftGridSet_null) { auto gridSet = NS_PROJ::VerticalShiftGridSet::open(m_ctxt, "null"); ASSERT_NE(gridSet, nullptr); auto grid = gridSet->gridAt(0.0, 0.0); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 3); EXPECT_EQ(grid->height(), 3); EXPECT_EQ(grid->extentAndRes().west, -M_PI); EXPECT_TRUE(grid->isNullGrid()); EXPECT_FALSE(grid->hasChanged()); float out = -1.0f; EXPECT_TRUE(grid->valueAt(0, 0, out)); EXPECT_EQ(out, 0.0f); EXPECT_FALSE(grid->isNodata(0.0f, 0.0)); gridSet->reassign_context(m_ctxt2); gridSet->reopen(m_ctxt2); } // --------------------------------------------------------------------------- TEST_F(GridTest, VerticalShiftGridSet_gtx) { ASSERT_EQ(NS_PROJ::VerticalShiftGridSet::open(m_ctxt, "foobar"), nullptr); auto gridSet = NS_PROJ::VerticalShiftGridSet::open(m_ctxt, "tests/test_nodata.gtx"); ASSERT_NE(gridSet, nullptr); ASSERT_EQ(gridSet->gridAt(-100, -100), nullptr); auto grid = gridSet->gridAt(4.15 / 180 * M_PI, 52.15 / 180 * M_PI); ASSERT_NE(grid, nullptr); EXPECT_TRUE(grid->isNodata(-88.8888f, 1.0)); gridSet->reassign_context(m_ctxt2); gridSet->reopen(m_ctxt2); grid = gridSet->gridAt(4.15 / 180 * M_PI, 52.15 / 180 * M_PI); EXPECT_NE(grid, nullptr); } // --------------------------------------------------------------------------- TEST_F(GridTest, HorizontalShiftGridSet_null) { auto gridSet = NS_PROJ::HorizontalShiftGridSet::open(m_ctxt, "null"); ASSERT_NE(gridSet, nullptr); auto grid = gridSet->gridAt(0.0, 0.0); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 3); EXPECT_EQ(grid->height(), 3); EXPECT_EQ(grid->extentAndRes().west, -M_PI); EXPECT_TRUE(grid->isNullGrid()); EXPECT_FALSE(grid->hasChanged()); float out1 = -1.0f; float out2 = -1.0f; EXPECT_TRUE(grid->valueAt(0, 0, false, out1, out2)); EXPECT_EQ(out1, 0.0f); EXPECT_EQ(out2, 0.0f); gridSet->reassign_context(m_ctxt2); gridSet->reopen(m_ctxt2); } // --------------------------------------------------------------------------- TEST_F(GridTest, GenericShiftGridSet_null) { auto gridSet = NS_PROJ::GenericShiftGridSet::open(m_ctxt, "null"); ASSERT_NE(gridSet, nullptr); auto grid = gridSet->gridAt(0.0, 0.0); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 3); EXPECT_EQ(grid->height(), 3); EXPECT_EQ(grid->extentAndRes().west, -M_PI); EXPECT_TRUE(grid->isNullGrid()); EXPECT_FALSE(grid->hasChanged()); float out = -1.0f; EXPECT_TRUE(grid->valueAt(0, 0, 0, out)); EXPECT_EQ(out, 0.0f); EXPECT_EQ(grid->unit(0), ""); EXPECT_EQ(grid->description(0), ""); EXPECT_EQ(grid->metadataItem("foo"), ""); EXPECT_EQ(grid->samplesPerPixel(), 0); gridSet->reassign_context(m_ctxt2); gridSet->reopen(m_ctxt2); } #ifdef TIFF_ENABLED // --------------------------------------------------------------------------- TEST_F(GridTest, HorizontalShiftGridSet_gtiff) { auto gridSet = NS_PROJ::HorizontalShiftGridSet::open(m_ctxt, "tests/test_hgrid.tif"); ASSERT_NE(gridSet, nullptr); EXPECT_EQ(gridSet->format(), "gtiff"); EXPECT_TRUE(gridSet->name().find("tests/test_hgrid.tif") != std::string::npos) << gridSet->name(); EXPECT_EQ(gridSet->grids().size(), 1U); ASSERT_EQ(gridSet->gridAt(-100, -100), nullptr); auto grid = gridSet->gridAt(5.5 / 180 * M_PI, 53.5 / 180 * M_PI); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 4); EXPECT_EQ(grid->height(), 4); EXPECT_EQ(grid->extentAndRes().west, 4.0 / 180 * M_PI); EXPECT_FALSE(grid->isNullGrid()); EXPECT_FALSE(grid->hasChanged()); float out1 = -1.0f; float out2 = -1.0f; EXPECT_TRUE(grid->valueAt(0, 3, false, out1, out2)); EXPECT_EQ(out1, static_cast<float>(14400.0 / 3600. / 180 * M_PI)); EXPECT_EQ(out2, static_cast<float>(900.0 / 3600. / 180 * M_PI)); gridSet->reassign_context(m_ctxt2); gridSet->reopen(m_ctxt2); grid = gridSet->gridAt(5.5 / 180 * M_PI, 53.5 / 180 * M_PI); EXPECT_NE(grid, nullptr); } // --------------------------------------------------------------------------- TEST_F(GridTest, GenericShiftGridSet_gtiff) { ASSERT_EQ(NS_PROJ::GenericShiftGridSet::open(m_ctxt, "foobar"), nullptr); auto gridSet = NS_PROJ::GenericShiftGridSet::open( m_ctxt, "tests/nkgrf03vel_realigned_extract.tif"); ASSERT_NE(gridSet, nullptr); ASSERT_EQ(gridSet->gridAt(-100, -100), nullptr); auto grid = gridSet->gridAt(21.3333333 / 180 * M_PI, 63.0 / 180 * M_PI); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 5); EXPECT_EQ(grid->height(), 5); EXPECT_EQ(grid->extentAndRes().isGeographic, true); EXPECT_EQ(grid->extentAndRes().west, 21.0 / 180 * M_PI); EXPECT_FALSE(grid->isNullGrid()); EXPECT_FALSE(grid->hasChanged()); float out = -1.0f; EXPECT_FALSE(grid->valueAt(0, 0, grid->samplesPerPixel(), out)); EXPECT_TRUE(grid->valueAt(0, 0, 0, out)); EXPECT_EQ(out, 0.20783890783786773682f); EXPECT_TRUE(grid->valueAt(1, 0, 0, out)); EXPECT_EQ(out, 0.22427035868167877197); EXPECT_TRUE(grid->valueAt(0, 1, 0, out)); EXPECT_EQ(out, 0.19718019664287567139f); int bandZero = 0; bool nodataFound = false; EXPECT_TRUE(grid->valuesAt(0, 0, 1, 1, 1, &bandZero, &out, nodataFound)); EXPECT_EQ(out, 0.20783890783786773682f); constexpr int COUNT_X = 2; constexpr int COUNT_Y = 4; constexpr int COUNT_BANDS = 3; float values[COUNT_Y * COUNT_X * COUNT_BANDS]; const int bands[] = {0, 1, 2}; constexpr int OFFSET_X = 2; constexpr int OFFSET_Y = 1; EXPECT_TRUE(grid->valuesAt(OFFSET_X, OFFSET_Y, COUNT_X, COUNT_Y, COUNT_BANDS, bands, values, nodataFound)); int valuesIdx = 0; for (int y = 0; y < COUNT_Y; ++y) { for (int x = 0; x < COUNT_X; ++x) { for (int band = 0; band < COUNT_BANDS; ++band) { EXPECT_TRUE( grid->valueAt(OFFSET_X + x, OFFSET_Y + y, band, out)); EXPECT_EQ(out, values[valuesIdx]); ++valuesIdx; } } } EXPECT_EQ(grid->metadataItem("area_of_use"), "Nordic and Baltic countries"); EXPECT_EQ(grid->metadataItem("non_existing"), std::string()); EXPECT_EQ(grid->metadataItem("non_existing", 1), std::string()); EXPECT_EQ(grid->metadataItem("non_existing", 10), std::string()); gridSet->reassign_context(m_ctxt2); gridSet->reopen(m_ctxt2); grid = gridSet->gridAt(21.3333333 / 180 * M_PI, 63.0 / 180 * M_PI); EXPECT_NE(grid, nullptr); } // --------------------------------------------------------------------------- TEST_F(GridTest, GenericShiftGridSet_gtiff_valuesAt_tiled_optim) { auto gridSet = NS_PROJ::GenericShiftGridSet::open( m_ctxt, "tests/nkgrf03vel_realigned_extract_tiled_256x256.tif"); ASSERT_NE(gridSet, nullptr); ASSERT_EQ(gridSet->gridAt(-100, -100), nullptr); auto grid = gridSet->gridAt(21.3333333 / 180 * M_PI, 63.0 / 180 * M_PI); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 5); EXPECT_EQ(grid->height(), 5); EXPECT_EQ(grid->extentAndRes().isGeographic, true); EXPECT_EQ(grid->extentAndRes().west, 21.0 / 180 * M_PI); EXPECT_FALSE(grid->isNullGrid()); EXPECT_FALSE(grid->hasChanged()); float out = -1.0f; EXPECT_FALSE(grid->valueAt(0, 0, grid->samplesPerPixel(), out)); EXPECT_TRUE(grid->valueAt(0, 0, 0, out)); EXPECT_EQ(out, 0.20783890783786773682f); EXPECT_TRUE(grid->valueAt(1, 0, 0, out)); EXPECT_EQ(out, 0.22427035868167877197); EXPECT_TRUE(grid->valueAt(0, 1, 0, out)); EXPECT_EQ(out, 0.19718019664287567139f); int bandZero = 0; bool nodataFound = false; EXPECT_TRUE(grid->valuesAt(0, 0, 1, 1, 1, &bandZero, &out, nodataFound)); EXPECT_EQ(out, 0.20783890783786773682f); constexpr int COUNT_X = 2; constexpr int COUNT_Y = 4; constexpr int COUNT_BANDS_THREE = 3; float values[COUNT_Y * COUNT_X * COUNT_BANDS_THREE]; const int bands[] = {0, 1, 2}; constexpr int OFFSET_X = 2; constexpr int OFFSET_Y = 1; EXPECT_TRUE(grid->valuesAt(OFFSET_X, OFFSET_Y, COUNT_X, COUNT_Y, COUNT_BANDS_THREE, bands, values, nodataFound)); for (int y = 0, valuesIdx = 0; y < COUNT_Y; ++y) { for (int x = 0; x < COUNT_X; ++x) { for (int band = 0; band < COUNT_BANDS_THREE; ++band) { EXPECT_TRUE( grid->valueAt(OFFSET_X + x, OFFSET_Y + y, band, out)); EXPECT_EQ(out, values[valuesIdx]); ++valuesIdx; } } } constexpr int COUNT_BANDS_TWO = 2; EXPECT_TRUE(grid->valuesAt(OFFSET_X, OFFSET_Y, COUNT_X, COUNT_Y, COUNT_BANDS_TWO, bands, values, nodataFound)); for (int y = 0, valuesIdx = 0; y < COUNT_Y; ++y) { for (int x = 0; x < COUNT_X; ++x) { for (int band = 0; band < COUNT_BANDS_TWO; ++band) { EXPECT_TRUE( grid->valueAt(OFFSET_X + x, OFFSET_Y + y, band, out)); EXPECT_EQ(out, values[valuesIdx]); ++valuesIdx; } } } } // --------------------------------------------------------------------------- TEST_F(GridTest, GenericShiftGridSet_gtiff_with_subgrid) { auto gridSet = NS_PROJ::GenericShiftGridSet::open( m_ctxt, "tests/test_hgrid_with_subgrid.tif"); ASSERT_NE(gridSet, nullptr); ASSERT_EQ(gridSet->gridAt(-100, -100), nullptr); auto grid = gridSet->gridAt(-115.5416667 / 180 * M_PI, 51.1666667 / 180 * M_PI); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 11); EXPECT_EQ(grid->height(), 21); EXPECT_EQ(grid->metadataItem("grid_name"), "ALbanff"); } // --------------------------------------------------------------------------- TEST_F(GridTest, GenericShiftGridSet_gtiff_with_two_level_of_subgrids_no_grid_name) { auto gridSet = NS_PROJ::GenericShiftGridSet::open( m_ctxt, "tests/test_hgrid_with_two_level_of_subgrids_no_grid_name.tif"); ASSERT_NE(gridSet, nullptr); ASSERT_EQ(gridSet->gridAt(-100, -100), nullptr); auto grid = gridSet->gridAt(-45.5 / 180 * M_PI, 22.5 / 180 * M_PI); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 8); EXPECT_EQ(grid->height(), 8); } // --------------------------------------------------------------------------- TEST_F(GridTest, GenericShiftGridSet_gtiff_projected) { auto gridSet = NS_PROJ::GenericShiftGridSet::open( m_ctxt, "tests/test_3d_grid_projected.tif"); ASSERT_NE(gridSet, nullptr); ASSERT_EQ(gridSet->gridAt(-1000, -1000), nullptr); auto grid = gridSet->gridAt(1500300.0, 5400300.0); ASSERT_NE(grid, nullptr); EXPECT_EQ(grid->width(), 2); EXPECT_EQ(grid->height(), 2); EXPECT_EQ(grid->extentAndRes().isGeographic, false); EXPECT_EQ(grid->extentAndRes().west, 1500000.0); EXPECT_EQ(grid->extentAndRes().east, 1501000.0); EXPECT_EQ(grid->extentAndRes().south, 5400000.0); EXPECT_EQ(grid->extentAndRes().north, 5401000.0); EXPECT_EQ(grid->extentAndRes().resX, 1000); EXPECT_EQ(grid->extentAndRes().resY, 1000); } #endif // TIFF_ENABLED } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_metadata.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" using namespace osgeo::proj::io; using namespace osgeo::proj::metadata; using namespace osgeo::proj::util; // --------------------------------------------------------------------------- TEST(metadata, citation) { Citation c("my citation"); Citation c2(c); ASSERT_TRUE(c2.title().has_value()); ASSERT_EQ(*(c2.title()), "my citation"); } // --------------------------------------------------------------------------- static bool equals(ExtentNNPtr extent1, ExtentNNPtr extent2) { return extent1->contains(extent2) && extent2->contains(extent1); } static bool equals(GeographicExtentNNPtr extent1, GeographicExtentNNPtr extent2) { return extent1->contains(extent2) && extent2->contains(extent1); } static GeographicExtentNNPtr getBBox(ExtentNNPtr extent) { assert(extent->geographicElements().size() == 1); return extent->geographicElements()[0]; } TEST(metadata, extent) { Extent::create( optional<std::string>(), std::vector<GeographicExtentNNPtr>(), std::vector<VerticalExtentNNPtr>(), std::vector<TemporalExtentNNPtr>()); auto world = Extent::createFromBBOX(-180, -90, 180, 90); EXPECT_TRUE(world->isEquivalentTo(world.get())); EXPECT_TRUE(world->contains(world)); auto west_hemisphere = Extent::createFromBBOX(-180, -90, 0, 90); EXPECT_TRUE(!world->isEquivalentTo(west_hemisphere.get())); EXPECT_TRUE(world->contains(west_hemisphere)); EXPECT_TRUE(!west_hemisphere->contains(world)); auto world_inter_world = world->intersection(world); ASSERT_TRUE(world_inter_world != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(world_inter_world), world)); auto france = Extent::createFromBBOX(-5, 40, 12, 51); EXPECT_TRUE(france->contains(france)); EXPECT_TRUE(world->contains(france)); EXPECT_TRUE(!france->contains( world)); // We are only speaking about geography here ;-) EXPECT_TRUE(world->intersects(france)); EXPECT_TRUE(france->intersects(world)); auto france_inter_france = france->intersection(france); ASSERT_TRUE(france_inter_france != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(france_inter_france), france)); auto france_inter_world = france->intersection(world); ASSERT_TRUE(france_inter_world != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(france_inter_world), france)); auto world_inter_france = world->intersection(france); ASSERT_TRUE(world_inter_france != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(world_inter_france), france)); auto france_shifted = Extent::createFromBBOX(-5 + 5, 40 + 5, 12 + 5, 51 + 5); EXPECT_TRUE(france->intersects(france_shifted)); EXPECT_TRUE(france_shifted->intersects(france)); EXPECT_TRUE(!france->contains(france_shifted)); EXPECT_TRUE(!france_shifted->contains(france)); auto europe = Extent::createFromBBOX(-30, 25, 30, 70); EXPECT_TRUE(europe->contains(france)); EXPECT_TRUE(!france->contains(europe)); auto france_inter_europe = france->intersection(europe); ASSERT_TRUE(france_inter_europe != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(france_inter_europe), france)); auto europe_intersects_france = europe->intersection(france); ASSERT_TRUE(europe_intersects_france != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(europe_intersects_france), france)); auto nz = Extent::createFromBBOX(155.0, -60.0, -170.0, -25.0); EXPECT_TRUE(nz->contains(nz)); EXPECT_TRUE(world->contains(nz)); EXPECT_TRUE(nz->intersects(world)); EXPECT_TRUE(world->intersects(nz)); EXPECT_TRUE(!nz->contains(world)); EXPECT_TRUE(!nz->contains(france)); EXPECT_TRUE(!france->contains(nz)); EXPECT_TRUE(!nz->intersects(france)); EXPECT_TRUE(!france->intersects(nz)); { auto nz_inter_world = nz->intersection(world); ASSERT_TRUE(nz_inter_world != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_inter_world), nz)); } { auto nz_inter_world = getBBox(nz)->intersection(getBBox(world)); ASSERT_TRUE(nz_inter_world != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_inter_world), getBBox(nz))); } { auto world_inter_nz = world->intersection(nz); ASSERT_TRUE(world_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(world_inter_nz), nz)); } { auto world_inter_nz = getBBox(world)->intersection(getBBox(nz)); ASSERT_TRUE(world_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(world_inter_nz), getBBox(nz))); } EXPECT_TRUE(nz->intersection(france) == nullptr); EXPECT_TRUE(france->intersection(nz) == nullptr); auto bbox_antimeridian_north = Extent::createFromBBOX(155.0, 10.0, -170.0, 30.0); EXPECT_TRUE(!nz->contains(bbox_antimeridian_north)); EXPECT_TRUE(!bbox_antimeridian_north->contains(nz)); EXPECT_TRUE(!nz->intersects(bbox_antimeridian_north)); EXPECT_TRUE(!bbox_antimeridian_north->intersects(nz)); EXPECT_TRUE(!nz->intersection(bbox_antimeridian_north)); EXPECT_TRUE(!bbox_antimeridian_north->intersection(nz)); auto nz_pos_long = Extent::createFromBBOX(155.0, -60.0, 180.0, -25.0); EXPECT_TRUE(nz->contains(nz_pos_long)); EXPECT_TRUE(!nz_pos_long->contains(nz)); EXPECT_TRUE(nz->intersects(nz_pos_long)); EXPECT_TRUE(nz_pos_long->intersects(nz)); auto nz_inter_nz_pos_long = nz->intersection(nz_pos_long); ASSERT_TRUE(nz_inter_nz_pos_long != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_inter_nz_pos_long), nz_pos_long)); auto nz_pos_long_inter_nz = nz_pos_long->intersection(nz); ASSERT_TRUE(nz_pos_long_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_pos_long_inter_nz), nz_pos_long)); auto nz_neg_long = Extent::createFromBBOX(-180.0, -60.0, -170.0, -25.0); EXPECT_TRUE(nz->contains(nz_neg_long)); EXPECT_TRUE(!nz_neg_long->contains(nz)); EXPECT_TRUE(nz->intersects(nz_neg_long)); EXPECT_TRUE(nz_neg_long->intersects(nz)); auto nz_inter_nz_neg_long = nz->intersection(nz_neg_long); ASSERT_TRUE(nz_inter_nz_neg_long != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_inter_nz_neg_long), nz_neg_long)); auto nz_neg_long_inter_nz = nz_neg_long->intersection(nz); ASSERT_TRUE(nz_neg_long_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_neg_long_inter_nz), nz_neg_long)); auto nz_smaller = Extent::createFromBBOX(160, -55.0, -175.0, -30.0); EXPECT_TRUE(nz->contains(nz_smaller)); EXPECT_TRUE(!nz_smaller->contains(nz)); auto nz_pos_long_shifted_west = Extent::createFromBBOX(150.0, -60.0, 175.0, -25.0); EXPECT_TRUE(!nz->contains(nz_pos_long_shifted_west)); EXPECT_TRUE(!nz_pos_long_shifted_west->contains(nz)); EXPECT_TRUE(nz->intersects(nz_pos_long_shifted_west)); EXPECT_TRUE(nz_pos_long_shifted_west->intersects(nz)); auto nz_smaller_shifted = Extent::createFromBBOX(165, -60.0, -170.0, -25.0); EXPECT_TRUE(!nz_smaller->contains(nz_smaller_shifted)); EXPECT_TRUE(!nz_smaller_shifted->contains(nz_smaller)); EXPECT_TRUE(nz_smaller->intersects(nz_smaller_shifted)); EXPECT_TRUE(nz_smaller_shifted->intersects(nz_smaller)); auto nz_shifted = Extent::createFromBBOX(165.0, -60.0, -160.0, -25.0); auto nz_intersect_nz_shifted = nz->intersection(nz_shifted); ASSERT_TRUE(nz_intersect_nz_shifted != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_intersect_nz_shifted), Extent::createFromBBOX(165, -60.0, -170.0, -25.0))); auto nz_inter_nz_smaller = nz->intersection(nz_smaller); ASSERT_TRUE(nz_inter_nz_smaller != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_inter_nz_smaller), nz_smaller)); auto nz_smaller_inter_nz = nz_smaller->intersection(nz); ASSERT_TRUE(nz_smaller_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_smaller_inter_nz), nz_smaller)); auto world_smaller = Extent::createFromBBOX(-179, -90, 179, 90); EXPECT_TRUE(!world_smaller->contains(nz)); EXPECT_TRUE(!nz->contains(world_smaller)); auto nz_inter_world_smaller = nz->intersection(world_smaller); ASSERT_TRUE(nz_inter_world_smaller != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_inter_world_smaller), Extent::createFromBBOX(155, -60, 179, -25))); auto world_smaller_inter_nz = world_smaller->intersection(nz); ASSERT_TRUE(world_smaller_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(world_smaller_inter_nz), Extent::createFromBBOX(155, -60, 179, -25))); auto world_smaller_east = Extent::createFromBBOX(-179, -90, 150, 90); EXPECT_TRUE(!world_smaller_east->contains(nz)); EXPECT_TRUE(!nz->contains(world_smaller_east)); auto nz_inter_world_smaller_east = nz->intersection(world_smaller_east); ASSERT_TRUE(nz_inter_world_smaller_east != nullptr); EXPECT_EQ(nn_dynamic_pointer_cast<GeographicBoundingBox>( nz_inter_world_smaller_east->geographicElements()[0]) ->westBoundLongitude(), -179); EXPECT_EQ(nn_dynamic_pointer_cast<GeographicBoundingBox>( nz_inter_world_smaller_east->geographicElements()[0]) ->eastBoundLongitude(), -170); EXPECT_TRUE(equals(NN_CHECK_ASSERT(nz_inter_world_smaller_east), Extent::createFromBBOX(-179, -60, -170, -25))); auto world_smaller_east_inter_nz = world_smaller_east->intersection(nz); ASSERT_TRUE(world_smaller_east_inter_nz != nullptr); EXPECT_EQ(nn_dynamic_pointer_cast<GeographicBoundingBox>( world_smaller_east_inter_nz->geographicElements()[0]) ->westBoundLongitude(), -179); EXPECT_EQ(nn_dynamic_pointer_cast<GeographicBoundingBox>( world_smaller_east_inter_nz->geographicElements()[0]) ->eastBoundLongitude(), -170); EXPECT_TRUE(equals(NN_CHECK_ASSERT(world_smaller_east_inter_nz), Extent::createFromBBOX(-179, -60, -170, -25))); auto east_hemisphere = Extent::createFromBBOX(0, -90, 180, 90); auto east_hemisphere_inter_nz = east_hemisphere->intersection(nz); ASSERT_TRUE(east_hemisphere_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(east_hemisphere_inter_nz), Extent::createFromBBOX(155.0, -60.0, 180.0, -25.0))); auto minus_180_to_156 = Extent::createFromBBOX(-180, -90, 156, 90); auto minus_180_to_156_inter_nz = minus_180_to_156->intersection(nz); ASSERT_TRUE(minus_180_to_156_inter_nz != nullptr); EXPECT_TRUE(equals(NN_CHECK_ASSERT(minus_180_to_156_inter_nz), Extent::createFromBBOX(-180.0, -60.0, -170.0, -25.0))); } // --------------------------------------------------------------------------- TEST(metadata, extent_edge_cases) { Extent::create( optional<std::string>(), std::vector<GeographicExtentNNPtr>(), std::vector<VerticalExtentNNPtr>(), std::vector<TemporalExtentNNPtr>()); { auto A = Extent::createFromBBOX(-180, -90, 180, 90); auto B = Extent::createFromBBOX(180, -90, 180, 90); EXPECT_FALSE(A->intersects(B)); EXPECT_FALSE(B->intersects(A)); EXPECT_FALSE(A->contains(B)); EXPECT_TRUE(A->intersection(B) == nullptr); EXPECT_TRUE(B->intersection(A) == nullptr); } EXPECT_THROW(Extent::createFromBBOX( std::numeric_limits<double>::quiet_NaN(), -90, 180, 90), InvalidValueTypeException); EXPECT_THROW(Extent::createFromBBOX( -180, std::numeric_limits<double>::quiet_NaN(), 180, 90), InvalidValueTypeException); EXPECT_THROW(Extent::createFromBBOX( -180, -90, std::numeric_limits<double>::quiet_NaN(), 90), InvalidValueTypeException); EXPECT_THROW(Extent::createFromBBOX( -180, -90, 180, std::numeric_limits<double>::quiet_NaN()), InvalidValueTypeException); // Scenario of https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=57328 // and https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=60084 { auto A = Extent::createFromBBOX(0, 1, 2, 3); auto B = Extent::createFromBBOX(200, -80, -100, 80); EXPECT_FALSE(A->intersects(B)); EXPECT_FALSE(B->intersects(A)); EXPECT_TRUE(A->intersection(B) == nullptr); EXPECT_TRUE(B->intersection(A) == nullptr); } { auto A = Extent::createFromBBOX(0, 1, 2, 3); auto B = Extent::createFromBBOX(100, -80, -200, 80); EXPECT_FALSE(A->intersects(B)); EXPECT_FALSE(B->intersects(A)); EXPECT_TRUE(A->intersection(B) == nullptr); EXPECT_TRUE(B->intersection(A) == nullptr); } } // --------------------------------------------------------------------------- TEST(metadata, identifier_empty) { auto id(Identifier::create()); Identifier id2(*id); ASSERT_TRUE(!id2.authority().has_value()); ASSERT_TRUE(id2.code().empty()); ASSERT_TRUE(!id2.codeSpace().has_value()); ASSERT_TRUE(!id2.version().has_value()); ASSERT_TRUE(!id2.description().has_value()); } // --------------------------------------------------------------------------- TEST(metadata, identifier_properties) { PropertyMap properties; properties.set(Identifier::AUTHORITY_KEY, "authority"); properties.set(Identifier::CODESPACE_KEY, "codespace"); properties.set(Identifier::VERSION_KEY, "version"); properties.set(Identifier::DESCRIPTION_KEY, "description"); auto id(Identifier::create("my code", properties)); Identifier id2(*id); ASSERT_TRUE(id2.authority().has_value()); ASSERT_EQ(*(id2.authority()->title()), "authority"); ASSERT_EQ(id2.code(), "my code"); ASSERT_TRUE(id2.codeSpace().has_value()); ASSERT_EQ(*(id2.codeSpace()), "codespace"); ASSERT_TRUE(id2.version().has_value()); ASSERT_EQ(*(id2.version()), "version"); ASSERT_TRUE(id2.description().has_value()); ASSERT_EQ(*(id2.description()), "description"); } // --------------------------------------------------------------------------- TEST(metadata, identifier_code_integer) { PropertyMap properties; properties.set(Identifier::CODE_KEY, 1234); auto id(Identifier::create(std::string(), properties)); ASSERT_EQ(id->code(), "1234"); } // --------------------------------------------------------------------------- TEST(metadata, identifier_code_string) { PropertyMap properties; properties.set(Identifier::CODE_KEY, "1234"); auto id(Identifier::create(std::string(), properties)); ASSERT_EQ(id->code(), "1234"); } // --------------------------------------------------------------------------- TEST(metadata, identifier_code_invalid_type) { PropertyMap properties; properties.set(Identifier::CODE_KEY, true); ASSERT_THROW(Identifier::create(std::string(), properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(metadata, identifier_authority_citation) { PropertyMap properties; properties.set(Identifier::AUTHORITY_KEY, nn_make_shared<Citation>("authority")); auto id(Identifier::create(std::string(), properties)); ASSERT_TRUE(id->authority().has_value()); ASSERT_EQ(*(id->authority()->title()), "authority"); } // --------------------------------------------------------------------------- TEST(metadata, identifier_authority_invalid_type) { PropertyMap properties; properties.set(Identifier::AUTHORITY_KEY, true); ASSERT_THROW(Identifier::create(std::string(), properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(metadata, id) { auto in_wkt = "ID[\"EPSG\",4946,1.5,\n" " CITATION[\"my citation\"],\n" " URI[\"urn:ogc:def:crs:EPSG::4946\"]]"; auto id = nn_dynamic_pointer_cast<Identifier>(WKTParser().createFromWKT(in_wkt)); ASSERT_TRUE(id != nullptr); EXPECT_TRUE(id->authority().has_value()); EXPECT_EQ(*(id->authority()->title()), "my citation"); EXPECT_EQ(*(id->codeSpace()), "EPSG"); EXPECT_EQ(id->code(), "4946"); EXPECT_TRUE(id->version().has_value()); EXPECT_EQ(*(id->version()), "1.5"); EXPECT_TRUE(id->uri().has_value()); EXPECT_EQ(*(id->uri()), "urn:ogc:def:crs:EPSG::4946"); auto got_wkt = id->exportToWKT(WKTFormatter::create().get()); EXPECT_EQ(got_wkt, in_wkt); } // --------------------------------------------------------------------------- TEST(metadata, Identifier_isEquivalentName) { EXPECT_TRUE(Identifier::isEquivalentName("", "")); EXPECT_TRUE(Identifier::isEquivalentName("x", "x")); EXPECT_TRUE(Identifier::isEquivalentName("x", "X")); EXPECT_TRUE(Identifier::isEquivalentName("X", "x")); EXPECT_FALSE(Identifier::isEquivalentName("x", "")); EXPECT_FALSE(Identifier::isEquivalentName("", "x")); EXPECT_FALSE(Identifier::isEquivalentName("x", "y")); EXPECT_TRUE(Identifier::isEquivalentName("Central_Meridian", "Central_- ()/Meridian")); EXPECT_TRUE(Identifier::isEquivalentName("\xc3\xa1", "a")); EXPECT_FALSE(Identifier::isEquivalentName("\xc3", "a")); EXPECT_TRUE(Identifier::isEquivalentName("a", "\xc3\xa1")); EXPECT_FALSE(Identifier::isEquivalentName("a", "\xc3")); EXPECT_TRUE(Identifier::isEquivalentName("\xc3\xa4", "\xc3\xa1")); EXPECT_TRUE(Identifier::isEquivalentName( "Unknown based on International 1924 (Hayford 1909, 1910) ellipsoid", "Unknown_based_on_International_1924_Hayford_1909_1910_ellipsoid")); EXPECT_TRUE(Identifier::isEquivalentName("foo + ", "foo + ")); EXPECT_TRUE(Identifier::isEquivalentName("foo + bar", "foo + bar")); EXPECT_TRUE(Identifier::isEquivalentName("foo + bar", "foobar")); }
cpp
PROJ
data/projects/PROJ/test/unit/include_proj_h_from_c.c
/****************************************************************************** * * Project: PROJ * Purpose: Dummy test to check that we can include proj.h from a pure C file * Author: Even Rouault * ****************************************************************************** * Copyright (c) 2018, Even Rouault * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "proj.h" #include "proj_experimental.h" int main() { return 0; }
c
PROJ
data/projects/PROJ/test/unit/test_primitives.hpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2018 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef TEST_PRIMITIVES_HPP_INCLUDED #define TEST_PRIMITIVES_HPP_INCLUDED #include "gtest_include.h" #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/internal/internal.hpp" #include <cmath> #include <cstdlib> static ::testing::AssertionResult ComparePROJString(const char *m_expr, const char *n_expr, const std::string &m, const std::string &n) { // if (m == n) return ::testing::AssertionSuccess(); auto mTokens = osgeo::proj::internal::split(m, ' '); auto nTokens = osgeo::proj::internal::split(n, ' '); if (mTokens.size() == nTokens.size()) { bool success = true; for (size_t i = 0; i < mTokens.size(); i++) { auto mSubTokens = osgeo::proj::internal::split(mTokens[i], '='); auto nSubTokens = osgeo::proj::internal::split(nTokens[i], '='); if (mSubTokens.size() != nSubTokens.size()) { success = false; break; } if (mSubTokens.size() == 2 && nSubTokens.size() == 2) { if (mSubTokens[0] != nSubTokens[0]) { success = false; break; } double mValue = 0.0; bool mIsDouble = false; try { mValue = osgeo::proj::internal::c_locale_stod(mSubTokens[1]); mIsDouble = true; } catch (const std::exception &) { } double nValue = 0.0; bool nIsDouble = false; try { nValue = osgeo::proj::internal::c_locale_stod(nSubTokens[1]); nIsDouble = true; } catch (const std::exception &) { } if (mIsDouble != nIsDouble) { success = false; break; } if (mIsDouble) { success = std::abs(mValue - nValue) <= 1e-14 * std::abs(mValue); } else { success = mSubTokens[1] == nSubTokens[1]; } if (!success) { break; } } } if (success) { return ::testing::AssertionSuccess(); } } return ::testing::AssertionFailure() << m_expr << " and " << n_expr << " (" << m << " and " << n << ") are different"; } #endif /* TEST_PRIMITIVES_HPP_INCLUDED */
hpp
PROJ
data/projects/PROJ/test/unit/proj_angular_io_test.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test that in- and output units behave correctly, especially * angular units that need special treatment. * Author: Kristian Evers <[email protected]> * ****************************************************************************** * Copyright (c) 2019, Kristian Evers * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "proj.h" #include "gtest_include.h" namespace { TEST(AngularUnits, Basic) { auto ctx = proj_context_create(); auto P = proj_create(ctx, "proj=latlong"); EXPECT_TRUE(proj_angular_input(P, PJ_FWD)); EXPECT_TRUE(proj_angular_output(P, PJ_FWD)); EXPECT_TRUE(proj_angular_input(P, PJ_INV)); EXPECT_TRUE(proj_angular_output(P, PJ_INV)); proj_destroy(P); proj_context_destroy(ctx); } TEST(AngularUnits, Pipelines) { auto ctx = proj_context_create(); auto P = proj_create(ctx, "proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=latlong +step +proj=axisswap +order=2,1"); EXPECT_TRUE(proj_angular_input(P, PJ_FWD)); EXPECT_TRUE(proj_angular_output(P, PJ_FWD)); EXPECT_TRUE(proj_angular_input(P, PJ_INV)); EXPECT_TRUE(proj_angular_output(P, PJ_INV)); proj_destroy(P); proj_context_destroy(ctx); } TEST(AngularUnits, Pipelines2) { auto ctx = proj_context_create(); auto P = proj_create( ctx, "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=tmerc +lat_0=0 +lon_0=-81 +k=0.9996 +x_0=500000.001016002 " "+y_0=0 +ellps=WGS84 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=m +z_in=m +xy_out=us-ft +z_out=us-ft"); EXPECT_FALSE(proj_angular_input(P, PJ_FWD)); EXPECT_FALSE(proj_angular_output(P, PJ_FWD)); proj_destroy(P); proj_context_destroy(ctx); } TEST(AngularUnits, Pipelines3) { auto ctx = proj_context_create(); auto P = proj_create( ctx, "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=tmerc +lat_0=0 +lon_0=-81 +k=0.9996 +x_0=500000.001016002 " "+y_0=0 +ellps=WGS84 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=m +z_in=m +xy_out=us-ft +z_out=us-ft"); EXPECT_TRUE(proj_angular_input(P, PJ_FWD)); EXPECT_FALSE(proj_angular_output(P, PJ_FWD)); proj_destroy(P); proj_context_destroy(ctx); } TEST(AngularUnits, Degrees) { auto ctx = proj_context_create(); auto P = proj_create(ctx, "+proj=pipeline " "+step +inv +proj=utm +zone=32 +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg "); EXPECT_FALSE(proj_degree_input(P, PJ_FWD)); EXPECT_TRUE(proj_degree_input(P, PJ_INV)); EXPECT_TRUE(proj_degree_output(P, PJ_FWD)); EXPECT_FALSE(proj_degree_output(P, PJ_INV)); proj_destroy(P); proj_context_destroy(ctx); } } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/proj_context_test.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test functions in proj_context namespae * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2019, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <stdlib.h> #ifdef _MSC_VER #include <io.h> #else #include <unistd.h> #endif #include "proj.h" #include "proj_internal.h" #include "gtest_include.h" namespace { static bool createTmpFile(const std::string &filename) { FILE *f = fopen(filename.c_str(), "wt"); if (!f) return false; fprintf( f, "<MY_PIPELINE> +proj=pipeline +step +proj=utm +zone=31 +ellps=GRS80\n"); fclose(f); return true; } // --------------------------------------------------------------------------- static std::string createTempDict(std::string &dirname, const char *filename) { const char *temp_dir = getenv("TEMP"); if (!temp_dir) { temp_dir = getenv("TMP"); } #ifndef WIN32 if (!temp_dir) { temp_dir = "/tmp"; } #endif if (!temp_dir) return std::string(); dirname = temp_dir; std::string tmpFilename; tmpFilename = temp_dir; tmpFilename += DIR_CHAR; tmpFilename += filename; return createTmpFile(tmpFilename) ? tmpFilename : std::string(); } // --------------------------------------------------------------------------- static int MyUnlink(const std::string &filename) { #ifdef _MSC_VER return _unlink(filename.c_str()); #else return unlink(filename.c_str()); #endif } // --------------------------------------------------------------------------- TEST(proj_context, proj_context_set_file_finder) { std::string dirname; auto filename = createTempDict(dirname, "temp_proj_dic1"); if (filename.empty()) return; auto ctx = proj_context_create(); struct FinderData { PJ_CONTEXT *got_ctx = nullptr; std::string dirname{}; std::string tmpFilename{}; }; const auto finder = [](PJ_CONTEXT *got_ctx, const char *file, void *user_data) -> const char * { auto finderData = static_cast<FinderData *>(user_data); finderData->got_ctx = got_ctx; finderData->tmpFilename = finderData->dirname; finderData->tmpFilename += DIR_CHAR; finderData->tmpFilename += file; return finderData->tmpFilename.c_str(); }; FinderData finderData; finderData.dirname = dirname; proj_context_set_file_finder(ctx, finder, &finderData); auto P = proj_create(ctx, "+init=temp_proj_dic1:MY_PIPELINE"); EXPECT_NE(P, nullptr); proj_destroy(P); EXPECT_EQ(finderData.got_ctx, ctx); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(proj_context, proj_context_set_search_paths) { std::string dirname; auto filename = createTempDict(dirname, "temp_proj_dic2"); if (filename.empty()) return; auto ctx = proj_context_create(); const char *path = dirname.c_str(); proj_context_set_search_paths(ctx, 1, &path); auto P = proj_create(ctx, "+init=temp_proj_dic2:MY_PIPELINE"); EXPECT_NE(P, nullptr); proj_destroy(P); proj_context_destroy(ctx); MyUnlink(filename); } // --------------------------------------------------------------------------- TEST(proj_context, read_grid_from_user_writable_directory) { auto ctx = proj_context_create(); auto path = std::string(proj_context_get_user_writable_directory(ctx, true)); EXPECT_TRUE(!path.empty()); auto filename = path + DIR_CHAR + "temp_proj_dic3"; EXPECT_TRUE(createTmpFile(filename)); { // Check that with PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=YES (set by // calling script), we cannot find the file auto P = proj_create(ctx, "+init=temp_proj_dic3:MY_PIPELINE"); EXPECT_EQ(P, nullptr); proj_destroy(P); } { // Cancel the effect of PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY putenv(const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=")); auto P = proj_create(ctx, "+init=temp_proj_dic3:MY_PIPELINE"); EXPECT_NE(P, nullptr); putenv( const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=YES")); proj_destroy(P); } proj_context_destroy(ctx); MyUnlink(filename); } // --------------------------------------------------------------------------- TEST(proj_context, proj_context_set_ca_bundle_path) { std::string dirname("/tmp/dummmy/path/cacert.pem"); auto ctx = proj_context_create(); proj_context_set_ca_bundle_path(ctx, dirname.c_str()); ASSERT_EQ(ctx->ca_bundle_path, dirname); proj_context_destroy(ctx); } } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_fork.c
/****************************************************************************** * * Project: PROJ * Purpose: Test behavior of database access across fork() * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2021, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #if defined(_WIN32) && defined(PROJ_HAS_PTHREADS) #undef PROJ_HAS_PTHREADS #endif #ifdef PROJ_HAS_PTHREADS #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include "proj.h" int main() { PJ_CONTEXT *ctxt = proj_context_create(); PJ_CONTEXT *ctxt2 = proj_context_create(); /* Cause database initialization */ { PJ *P = proj_create(ctxt, "EPSG:4326"); if (P == NULL) { proj_context_destroy(ctxt); return 1; } proj_destroy(P); } { PJ *P = proj_create(ctxt2, "EPSG:4326"); if (P == NULL) { proj_context_destroy(ctxt); proj_context_destroy(ctxt2); return 1; } proj_destroy(P); } for (int iters = 0; iters < 100; ++iters) { pid_t children[4]; for (int i = 0; i < 4; i++) { children[i] = fork(); if (children[i] < 0) { fprintf(stderr, "fork() failed\n"); return 1; } if (children[i] == 0) { { PJ *P = proj_create(ctxt, "EPSG:3067"); if (P == NULL) _exit(1); proj_destroy(P); } { PJ *P = proj_create(ctxt2, "EPSG:32631"); if (P == NULL) _exit(1); proj_destroy(P); } _exit(0); } } for (int i = 0; i < 4; i++) { int status = 0; waitpid(children[i], &status, 0); if (status != 0) { fprintf(stderr, "Error in child\n"); return 1; } } } proj_context_destroy(ctxt); proj_context_destroy(ctxt2); return 0; } #else int main() { return 0; } #endif
c
PROJ
data/projects/PROJ/test/unit/gie_self_tests.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2017, Thomas Knudsen * Copyright (c) 2017, SDFE * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" // PROJ include order is sensitive // clang-format off #include "proj.h" #include "proj_internal.h" // clang-format on #include <cmath> #include <string> namespace { // --------------------------------------------------------------------------- TEST(gie, cart_selftest) { PJ_CONTEXT *ctx; PJ *P; PJ_COORD a, b, obs[2]; PJ_COORD coord[3]; size_t n, sz; double dist, h, t; const char *const args[3] = {"proj=utm", "zone=32", "ellps=GRS80"}; char arg[50] = {"+proj=utm; +zone=32; +ellps=GRS80"}; /* An utm projection on the GRS80 ellipsoid */ P = proj_create(PJ_DEFAULT_CTX, arg); ASSERT_TRUE(P != nullptr); /* Clean up */ proj_destroy(P); /* Same projection, now using argc/argv style initialization */ P = proj_create_argv(PJ_DEFAULT_CTX, 3, const_cast<char **>(args)); ASSERT_TRUE(P != nullptr); /* zero initialize everything, then set (longitude, latitude) to (12, 55) */ a = proj_coord(0, 0, 0, 0); /* a.lp: The coordinate part of a, interpreted as a classic LP pair */ a.lp.lam = proj_torad(12); a.lp.phi = proj_torad(55); /* Forward projection */ b = proj_trans(P, PJ_FWD, a); /* Inverse projection */ a = proj_trans(P, PJ_INV, b); /* Null projection */ a = proj_trans(P, PJ_IDENT, a); /* Forward again, to get two linear items for comparison */ a = proj_trans(P, PJ_FWD, a); dist = proj_xy_dist(a, b); ASSERT_LE(dist, 2e-9); /* Clear any previous error */ proj_errno_reset(P); /* Clean up */ proj_destroy(P); /* Now do some 3D transformations */ P = proj_create(PJ_DEFAULT_CTX, "+proj=cart +ellps=GRS80"); ASSERT_TRUE(P != nullptr); /* zero initialize everything, then set (longitude, latitude, height) to * (12, 55, 100) */ a = b = proj_coord(0, 0, 0, 0); a.lpz.lam = proj_torad(12); a.lpz.phi = proj_torad(55); a.lpz.z = 100; /* Forward projection: 3D-Cartesian-to-Ellipsoidal */ b = proj_trans(P, PJ_FWD, a); /* Check roundtrip precision for 10000 iterations each way */ dist = proj_roundtrip(P, PJ_FWD, 10000, &a); dist += proj_roundtrip(P, PJ_INV, 10000, &b); ASSERT_LE(dist, 4e-9); /* Test at the North Pole */ a = b = proj_coord(0, 0, 0, 0); a.lpz.lam = proj_torad(0); a.lpz.phi = proj_torad(90); a.lpz.z = 100; /* Forward projection: Ellipsoidal-to-3D-Cartesian */ dist = proj_roundtrip(P, PJ_FWD, 1, &a); ASSERT_LE(dist, 1e-9); /* Test at the South Pole */ a = b = proj_coord(0, 0, 0, 0); a.lpz.lam = proj_torad(0); a.lpz.phi = proj_torad(-90); a.lpz.z = 100; b = a; /* Forward projection: Ellipsoidal-to-3D-Cartesian */ dist = proj_roundtrip(P, PJ_FWD, 1, &a); ASSERT_LE(dist, 4e-9); /* Inverse projection: 3D-Cartesian-to-Ellipsoidal */ b = proj_trans(P, PJ_INV, b); /* Move p to another context */ ctx = proj_context_create(); ASSERT_NE(ctx, pj_get_default_ctx()); proj_context_set(P, ctx); ASSERT_EQ(ctx, P->ctx); b = proj_trans(P, PJ_FWD, b); /* Move it back to the default context */ proj_context_set(P, nullptr); ASSERT_EQ(pj_get_default_ctx(), P->ctx); proj_context_destroy(ctx); /* We go on with the work - now back on the default context */ b = proj_trans(P, PJ_INV, b); proj_destroy(P); /* Testing proj_trans_generic () */ /* An utm projection on the GRS80 ellipsoid */ P = proj_create(PJ_DEFAULT_CTX, "+proj=utm +zone=32 +ellps=GRS80"); ASSERT_TRUE(P != nullptr); obs[0] = proj_coord(proj_torad(12), proj_torad(55), 45, 0); obs[1] = proj_coord(proj_torad(12), proj_torad(56), 50, 0); sz = sizeof(PJ_COORD); /* Forward projection */ a = proj_trans(P, PJ_FWD, obs[0]); b = proj_trans(P, PJ_FWD, obs[1]); n = proj_trans_generic(P, PJ_FWD, &(obs[0].lpz.lam), sz, 2, &(obs[0].lpz.phi), sz, 2, &(obs[0].lpz.z), sz, 2, nullptr, sz, 0); ASSERT_EQ(n, 2U); ASSERT_EQ(a.lpz.lam, obs[0].lpz.lam); ASSERT_EQ(a.lpz.phi, obs[0].lpz.phi); ASSERT_EQ(a.lpz.z, obs[0].lpz.z); ASSERT_EQ(b.lpz.lam, obs[1].lpz.lam); ASSERT_EQ(b.lpz.phi, obs[1].lpz.phi); ASSERT_EQ(b.lpz.z, obs[1].lpz.z); /* now test the case of constant z */ obs[0] = proj_coord(proj_torad(12), proj_torad(55), 45, 0); obs[1] = proj_coord(proj_torad(12), proj_torad(56), 50, 0); h = 27; t = 33; n = proj_trans_generic(P, PJ_FWD, &(obs[0].lpz.lam), sz, 2, &(obs[0].lpz.phi), sz, 2, &h, 0, 1, &t, 0, 1); ASSERT_EQ(n, 2U); ASSERT_EQ(a.lpz.lam, obs[0].lpz.lam); ASSERT_EQ(a.lpz.phi, obs[0].lpz.phi); ASSERT_EQ(45, obs[0].lpz.z); ASSERT_EQ(b.lpz.lam, obs[1].lpz.lam); ASSERT_EQ(b.lpz.phi, obs[1].lpz.phi); ASSERT_EQ(50, obs[1].lpz.z); ASSERT_NE(50, h); /* test proj_trans_array () */ coord[0] = proj_coord(proj_torad(12), proj_torad(55), 45, 0); coord[1] = proj_coord(proj_torad(12), proj_torad(56), 50, 0); ASSERT_EQ(proj_trans_array(P, PJ_FWD, 2, coord), 0); ASSERT_EQ(a.lpz.lam, coord[0].lpz.lam); ASSERT_EQ(a.lpz.phi, coord[0].lpz.phi); ASSERT_EQ(a.lpz.z, coord[0].lpz.z); ASSERT_EQ(b.lpz.lam, coord[1].lpz.lam); ASSERT_EQ(b.lpz.phi, coord[1].lpz.phi); ASSERT_EQ(b.lpz.z, coord[1].lpz.z); /* test proj_trans_array () with two failed points for the same reason */ coord[0] = proj_coord(proj_torad(12), proj_torad(95), 45, 0); // invalid latitude coord[1] = proj_coord(proj_torad(12), proj_torad(56), 50, 0); coord[2] = proj_coord(proj_torad(12), proj_torad(95), 45, 0); // invalid latitude ASSERT_EQ(proj_trans_array(P, PJ_FWD, 3, coord), PROJ_ERR_COORD_TRANSFM_INVALID_COORD); ASSERT_EQ(HUGE_VAL, coord[0].lpz.lam); ASSERT_EQ(HUGE_VAL, coord[0].lpz.phi); ASSERT_EQ(HUGE_VAL, coord[0].lpz.z); ASSERT_EQ(b.lpz.lam, coord[1].lpz.lam); ASSERT_EQ(b.lpz.phi, coord[1].lpz.phi); ASSERT_EQ(b.lpz.z, coord[1].lpz.z); ASSERT_EQ(HUGE_VAL, coord[2].lpz.lam); ASSERT_EQ(HUGE_VAL, coord[2].lpz.phi); ASSERT_EQ(HUGE_VAL, coord[2].lpz.z); /* test proj_trans_array () with two failed points for different reasons */ coord[0] = proj_coord(proj_torad(12), proj_torad(95), 45, 0); // invalid latitude coord[1] = proj_coord(proj_torad(105), proj_torad(0), 45, 0); // in the equatorial axis, at 90° of the central meridian ASSERT_EQ(proj_trans_array(P, PJ_FWD, 2, coord), PROJ_ERR_COORD_TRANSFM); /* Clean up after proj_trans_* tests */ proj_destroy(P); } // --------------------------------------------------------------------------- class gieTest : public ::testing::Test { static void DummyLogFunction(void *, int, const char *) {} protected: void SetUp() override { m_ctxt = proj_context_create(); proj_log_func(m_ctxt, nullptr, DummyLogFunction); } void TearDown() override { proj_context_destroy(m_ctxt); } PJ_CONTEXT *m_ctxt = nullptr; }; // --------------------------------------------------------------------------- TEST_F(gieTest, proj_create_crs_to_crs) { /* test proj_create_crs_to_crs() */ auto P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "epsg:25832", "epsg:25833", nullptr); ASSERT_TRUE(P != nullptr); PJ_COORD a, b; a.xyzt.x = 700000.0; a.xyzt.y = 6000000.0; a.xyzt.z = 0; a.xyzt.t = HUGE_VAL; b.xy.x = 307788.8761171057; b.xy.y = 5999669.3036037628; a = proj_trans(P, PJ_FWD, a); EXPECT_NEAR(a.xy.x, b.xy.x, 1e-8); EXPECT_NEAR(a.xy.y, b.xy.y, 1e-8); auto src = proj_get_source_crs(PJ_DEFAULT_CTX, P); ASSERT_TRUE(src != nullptr); EXPECT_EQ(proj_get_name(src), std::string("ETRS89 / UTM zone 32N")); proj_destroy(src); proj_destroy(P); /* we can also allow PROJ strings as a usable PJ */ P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "proj=utm +zone=32 +datum=WGS84", "proj=utm +zone=33 +datum=WGS84", nullptr); ASSERT_TRUE(P != nullptr); proj_destroy(P); EXPECT_TRUE(proj_create_crs_to_crs(m_ctxt, "invalid", "EPSG:25833", NULL) == nullptr); EXPECT_TRUE(proj_create_crs_to_crs(m_ctxt, "EPSG:25832", "invalid", NULL) == nullptr); } // --------------------------------------------------------------------------- TEST_F(gieTest, proj_create_crs_to_crs_EPSG_4326) { auto P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "EPSG:4326", "EPSG:32631", nullptr); ASSERT_TRUE(P != nullptr); PJ_COORD a, b; // Lat, long degrees a.xyzt.x = 0.0; a.xyzt.y = 3.0; a.xyzt.z = 0; a.xyzt.t = HUGE_VAL; b.xy.x = 500000.0; b.xy.y = 0.0; a = proj_trans(P, PJ_FWD, a); EXPECT_NEAR(a.xy.x, b.xy.x, 1e-9); EXPECT_NEAR(a.xy.y, b.xy.y, 1e-9); proj_destroy(P); } // --------------------------------------------------------------------------- TEST_F(gieTest, proj_create_crs_to_crs_proj_longlat) { auto P = proj_create_crs_to_crs( PJ_DEFAULT_CTX, "+proj=longlat +datum=WGS84", "EPSG:32631", nullptr); ASSERT_TRUE(P != nullptr); PJ_COORD a, b; // Long, lat degrees a.xyzt.x = 3.0; a.xyzt.y = 0; a.xyzt.z = 0; a.xyzt.t = HUGE_VAL; b.xy.x = 500000.0; b.xy.y = 0.0; a = proj_trans(P, PJ_FWD, a); EXPECT_NEAR(a.xy.x, b.xy.x, 1e-9); EXPECT_NEAR(a.xy.y, b.xy.y, 1e-9); proj_destroy(P); } // --------------------------------------------------------------------------- TEST(gie, info_functions) { PJ_INFO info; PJ_PROJ_INFO pj_info; PJ_GRID_INFO grid_info; PJ_INIT_INFO init_info; PJ_FACTORS factors; const PJ_OPERATIONS *oper_list; const PJ_ELLPS *ellps_list; const PJ_PRIME_MERIDIANS *pm_list; std::vector<char> buf(40); PJ *P; char arg[50] = {"+proj=utm; +zone=32; +ellps=GRS80"}; PJ_COORD a; /* ********************************************************************** */ /* Test info functions */ /* ********************************************************************** */ /* proj_info() */ /* this one is difficult to test, since the output changes with the setup */ putenv(const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=")); info = proj_info(); putenv(const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=YES")); if (info.version[0] != '\0') { char tmpstr[64]; snprintf(tmpstr, sizeof(tmpstr), "%d.%d.%d", info.major, info.minor, info.patch); ASSERT_EQ(std::string(info.version), std::string(tmpstr)); } ASSERT_NE(std::string(info.release), ""); if (getenv("HOME") || getenv("PROJ_LIB") || getenv("PROJ_DATA")) { ASSERT_NE(std::string(info.searchpath), std::string()); } ASSERT_TRUE(std::string(info.searchpath).find("/proj") != std::string::npos); /* proj_pj_info() */ { P = proj_create(PJ_DEFAULT_CTX, "+proj=august"); /* august has no inverse */ auto has_inverse = proj_pj_info(P).has_inverse; proj_destroy(P); ASSERT_FALSE(has_inverse); } P = proj_create(PJ_DEFAULT_CTX, arg); pj_info = proj_pj_info(P); ASSERT_TRUE(pj_info.has_inverse); pj_shrink(arg); ASSERT_EQ(std::string(pj_info.definition), arg); ASSERT_EQ(std::string(pj_info.id), "utm"); proj_destroy(P); #ifdef TIFF_ENABLED /* proj_grid_info() */ grid_info = proj_grid_info("tests/test_hgrid.tif"); ASSERT_NE(std::string(grid_info.filename), ""); ASSERT_EQ(std::string(grid_info.gridname), "tests/test_hgrid.tif"); ASSERT_EQ(std::string(grid_info.format), "gtiff"); EXPECT_EQ(grid_info.n_lon, 4); EXPECT_EQ(grid_info.n_lat, 4); EXPECT_NEAR(grid_info.cs_lon, 0.017453292519943295, 1e-15); EXPECT_NEAR(grid_info.cs_lat, 0.017453292519943295, 1e-15); EXPECT_NEAR(grid_info.lowerleft.lam, 0.069813170079773182, 1e-15); EXPECT_NEAR(grid_info.lowerleft.phi, 0.90757121103705141, 1e-15); EXPECT_NEAR(grid_info.upperright.lam, 0.12217304763960307, 1e-15); EXPECT_NEAR(grid_info.upperright.phi, 0.95993108859688125, 1e-15); #endif grid_info = proj_grid_info("nonexistinggrid"); ASSERT_EQ(std::string(grid_info.filename), ""); // File exists, but is not a grid grid_info = proj_grid_info("proj.db"); ASSERT_EQ(std::string(grid_info.filename), ""); /* proj_init_info() */ init_info = proj_init_info("unknowninit"); ASSERT_EQ(std::string(init_info.filename), ""); init_info = proj_init_info("epsg"); /* Need to allow for "Unknown" until all commonly distributed EPSG-files * comes with a metadata section */ ASSERT_TRUE(std::string(init_info.origin) == "EPSG" || std::string(init_info.origin) == "Unknown") << std::string(init_info.origin); ASSERT_EQ(std::string(init_info.name), "epsg"); /* test proj_rtodms() and proj_dmstor() */ ASSERT_EQ(std::string("180dN"), proj_rtodms2(&buf[0], buf.size(), M_PI, 'N', 'S')); ASSERT_EQ(proj_dmstor(&buf[0], NULL), M_PI); ASSERT_EQ(std::string("114d35'29.612\"S"), proj_rtodms2(&buf[0], buf.size(), -2.0, 'N', 'S')); // buffer of just one byte ASSERT_EQ(std::string(""), proj_rtodms2(&buf[0], 1, -2.0, 'N', 'S')); // last character truncated ASSERT_EQ(std::string("114d35'29.612\""), proj_rtodms2(&buf[0], 15, -2.0, 'N', 'S')); // just enough bytes to store the string and the terminating nul character ASSERT_EQ(std::string("114d35'29.612\"S"), proj_rtodms2(&buf[0], 16, -2.0, 'N', 'S')); // buffer of just one byte ASSERT_EQ(std::string(""), proj_rtodms2(&buf[0], 1, -2.0, 0, 0)); // last character truncated ASSERT_EQ(std::string("-114d35'29.612"), proj_rtodms2(&buf[0], 15, -2.0, 0, 0)); // just enough bytes to store the string and the terminating nul character ASSERT_EQ(std::string("-114d35'29.612\""), proj_rtodms2(&buf[0], 16, -2.0, 0, 0)); /* we can't expect perfect numerical accuracy so testing with a tolerance */ ASSERT_NEAR(-2.0, proj_dmstor(&buf[0], NULL), 1e-7); /* test UTF-8 degree sign on DMS input */ ASSERT_NEAR(0.34512432, proj_dmstor("19°46'27\"E", NULL), 1e-7); /* test ISO 8859-1, cp1252, et al. degree sign on DMS input */ ASSERT_NEAR(0.34512432, proj_dmstor("19" "\260" "46'27\"E", NULL), 1e-7); /* test proj_derivatives_retrieve() and proj_factors_retrieve() */ P = proj_create(PJ_DEFAULT_CTX, "+proj=merc +ellps=WGS84"); a = proj_coord(0, 0, 0, 0); a.lp.lam = proj_torad(12); a.lp.phi = proj_torad(55); factors = proj_factors(P, a); ASSERT_FALSE(proj_errno(P)); /* factors not created correctly */ /* check a few key characteristics of the Mercator projection */ EXPECT_NEAR(factors.angular_distortion, 0.0, 1e-7) << factors.angular_distortion; /* angular distortion should be 0 */ /* Meridian/parallel angle should be 90 deg */ EXPECT_NEAR(factors.meridian_parallel_angle, M_PI_2, 1e-7) << factors.meridian_parallel_angle; EXPECT_EQ(factors.meridian_convergence, 0.0); /* meridian convergence should be 0 */ proj_destroy(P); // Test with a projected CRS { P = proj_create(PJ_DEFAULT_CTX, "EPSG:3395"); const auto factors2 = proj_factors(P, a); EXPECT_EQ(factors.angular_distortion, factors2.angular_distortion); EXPECT_EQ(factors.meridian_parallel_angle, factors2.meridian_parallel_angle); EXPECT_EQ(factors.meridian_convergence, factors2.meridian_convergence); EXPECT_EQ(factors.tissot_semimajor, factors2.tissot_semimajor); proj_destroy(P); } // Test with a projected CRS with feet unit { PJ_COORD c; c.lp.lam = proj_torad(-110); c.lp.phi = proj_torad(30); P = proj_create(PJ_DEFAULT_CTX, "+proj=tmerc +lat_0=31 +lon_0=-110.166666666667 " "+k=0.9999 +x_0=213360 +y_0=0 +ellps=GRS80 +units=ft"); factors = proj_factors(P, c); EXPECT_NEAR(factors.meridional_scale, 0.99990319, 1e-8) << factors.meridional_scale; EXPECT_NEAR(factors.parallel_scale, 0.99990319, 1e-8) << factors.parallel_scale; EXPECT_NEAR(factors.angular_distortion, 0, 1e-7) << factors.angular_distortion; EXPECT_NEAR(factors.meridian_parallel_angle, M_PI_2, 1e-7) << factors.meridian_parallel_angle; proj_destroy(P); P = proj_create(PJ_DEFAULT_CTX, "EPSG:2222"); const auto factors2 = proj_factors(P, c); EXPECT_NEAR(factors.meridional_scale, factors2.meridional_scale, 1e-10); EXPECT_NEAR(factors.parallel_scale, factors2.parallel_scale, 1e-10); EXPECT_NEAR(factors.angular_distortion, factors2.angular_distortion, 1e-10); EXPECT_NEAR(factors.meridian_parallel_angle, factors2.meridian_parallel_angle, 1e-109); proj_destroy(P); } // Test with a projected CRS with northing, easting axis order { PJ_COORD c; c.lp.lam = proj_torad(9); c.lp.phi = proj_torad(0); P = proj_create(PJ_DEFAULT_CTX, "+proj=utm +zone=32 +ellps=GRS80"); factors = proj_factors(P, c); EXPECT_NEAR(factors.meridional_scale, 0.9996, 1e-8) << factors.meridional_scale; EXPECT_NEAR(factors.parallel_scale, 0.9996, 1e-8) << factors.parallel_scale; EXPECT_NEAR(factors.angular_distortion, 0, 1e-7) << factors.angular_distortion; EXPECT_NEAR(factors.meridian_parallel_angle, M_PI_2, 1e-7) << factors.meridian_parallel_angle; proj_destroy(P); P = proj_create(PJ_DEFAULT_CTX, "EPSG:3044"); const auto factors2 = proj_factors(P, c); EXPECT_NEAR(factors.meridional_scale, factors2.meridional_scale, 1e-10); EXPECT_NEAR(factors.parallel_scale, factors2.parallel_scale, 1e-10); EXPECT_NEAR(factors.angular_distortion, factors2.angular_distortion, 1e-10); EXPECT_NEAR(factors.meridian_parallel_angle, factors2.meridian_parallel_angle, 1e-109); proj_destroy(P); } // Test with a projected CRS whose datum has a non-Greenwich prime meridian { P = proj_create(PJ_DEFAULT_CTX, "EPSG:27571"); PJ_COORD c; c.lp.lam = proj_torad(0.0689738); c.lp.phi = proj_torad(49.508567); const auto factors2 = proj_factors(P, c); EXPECT_NEAR(factors2.meridional_scale, 1 - 12.26478760 * 1e-5, 1e-8); proj_destroy(P); } // Test with a compound CRS of a projected CRS { P = proj_create(PJ_DEFAULT_CTX, "EPSG:5972"); PJ_COORD c; c.lp.lam = proj_torad(10.729030600); c.lp.phi = proj_torad(59.916494500); const auto factors2 = proj_factors(P, c); EXPECT_NEAR(factors2.meridional_scale, 1 - 28.54587730 * 1e-5, 1e-8); proj_destroy(P); } // Test with a geographic CRS --> error { P = proj_create(PJ_DEFAULT_CTX, "EPSG:4326"); const auto factors2 = proj_factors(P, a); EXPECT_NE(proj_errno(P), 0); proj_errno_reset(P); EXPECT_EQ(factors2.meridian_parallel_angle, 0); proj_destroy(P); } /* Check that proj_list_* functions work by looping through them */ size_t n = 0; for (oper_list = proj_list_operations(); oper_list->id; ++oper_list) n++; ASSERT_NE(n, 0U); n = 0; for (ellps_list = proj_list_ellps(); ellps_list->id; ++ellps_list) n++; ASSERT_NE(n, 0U); n = 0; for (pm_list = proj_list_prime_meridians(); pm_list->id; ++pm_list) n++; /* hard-coded prime meridians are not updated; expect a fixed size */ EXPECT_EQ(n, 14U); } // --------------------------------------------------------------------------- TEST(gie, io_predicates) { /* check io-predicates */ /* angular in on fwd, linear out */ auto P = proj_create(PJ_DEFAULT_CTX, "+proj=cart +ellps=GRS80"); ASSERT_TRUE(P != nullptr); ASSERT_TRUE(proj_angular_input(P, PJ_FWD)); ASSERT_FALSE(proj_angular_input(P, PJ_INV)); ASSERT_FALSE(proj_angular_output(P, PJ_FWD)); ASSERT_TRUE(proj_angular_output(P, PJ_INV)); P->inverted = 1; ASSERT_FALSE(proj_angular_input(P, PJ_FWD)); ASSERT_TRUE(proj_angular_input(P, PJ_INV)); ASSERT_TRUE(proj_angular_output(P, PJ_FWD)); ASSERT_FALSE(proj_angular_output(P, PJ_INV)); proj_destroy(P); /* angular in and out */ P = proj_create(PJ_DEFAULT_CTX, "+proj=molodensky +a=6378160 +rf=298.25 " "+da=-23 +df=-8.120449e-8 +dx=-134 +dy=-48 +dz=149 " "+abridged "); ASSERT_TRUE(P != nullptr); ASSERT_TRUE(proj_angular_input(P, PJ_FWD)); ASSERT_TRUE(proj_angular_input(P, PJ_INV)); ASSERT_TRUE(proj_angular_output(P, PJ_FWD)); ASSERT_TRUE(proj_angular_output(P, PJ_INV)); P->inverted = 1; ASSERT_TRUE(proj_angular_input(P, PJ_FWD)); ASSERT_TRUE(proj_angular_input(P, PJ_INV)); ASSERT_TRUE(proj_angular_output(P, PJ_FWD)); ASSERT_TRUE(proj_angular_output(P, PJ_INV)); proj_destroy(P); /* linear in and out */ P = proj_create(PJ_DEFAULT_CTX, " +proj=helmert" " +x=0.0127 +y=0.0065 +z=-0.0209 +s=0.00195" " +rx=-0.00039 +ry=0.00080 +rz=-0.00114" " +dx=-0.0029 +dy=-0.0002 +dz=-0.0006 +ds=0.00001" " +drx=-0.00011 +dry=-0.00019 +drz=0.00007" " +t_epoch=1988.0 +convention=coordinate_frame"); ASSERT_TRUE(P != nullptr); ASSERT_FALSE(proj_angular_input(P, PJ_FWD)); ASSERT_FALSE(proj_angular_input(P, PJ_INV)); ASSERT_FALSE(proj_angular_output(P, PJ_FWD)); ASSERT_FALSE(proj_angular_output(P, PJ_INV)); P->inverted = 1; ASSERT_FALSE(proj_angular_input(P, PJ_FWD)); ASSERT_FALSE(proj_angular_input(P, PJ_INV)); ASSERT_FALSE(proj_angular_output(P, PJ_FWD)); ASSERT_FALSE(proj_angular_output(P, PJ_INV)); /* pj_init_ctx should default to GRS80 */ ASSERT_EQ(P->a, 6378137.0); ASSERT_EQ(P->f, 1.0 / 298.257222101); proj_destroy(P); /* Test that pj_fwd* and pj_inv* returns NaNs when receiving NaN input */ P = proj_create(PJ_DEFAULT_CTX, "+proj=merc +ellps=WGS84"); ASSERT_TRUE(P != nullptr); auto a = proj_coord(NAN, NAN, NAN, NAN); a = proj_trans(P, PJ_FWD, a); ASSERT_TRUE((std::isnan(a.v[0]) && std::isnan(a.v[1]) && std::isnan(a.v[2]) && std::isnan(a.v[3]))); a = proj_coord(NAN, NAN, NAN, NAN); a = proj_trans(P, PJ_INV, a); ASSERT_TRUE((std::isnan(a.v[0]) && std::isnan(a.v[1]) && std::isnan(a.v[2]) && std::isnan(a.v[3]))); proj_destroy(P); } // --------------------------------------------------------------------------- static void test_time(const char *args, double tol, double t_in, double t_exp) { PJ_COORD in, out; PJ *P = proj_create(PJ_DEFAULT_CTX, args); ASSERT_TRUE(P != nullptr); in = proj_coord(0.0, 0.0, 0.0, t_in); out = proj_trans(P, PJ_FWD, in); EXPECT_NEAR(out.xyzt.t, t_exp, tol); out = proj_trans(P, PJ_INV, out); EXPECT_NEAR(out.xyzt.t, t_in, tol); proj_destroy(P); proj_log_level(nullptr, PJ_LOG_NONE); } // --------------------------------------------------------------------------- TEST(gie, unitconvert_selftest) { char args1[] = "+proj=unitconvert +t_in=decimalyear +t_out=decimalyear"; double in1 = 2004.25; char args2[] = "+proj=unitconvert +t_in=gps_week +t_out=gps_week"; double in2 = 1782.0; char args3[] = "+proj=unitconvert +t_in=mjd +t_out=mjd"; double in3 = 57390.0; char args4[] = "+proj=unitconvert +t_in=gps_week +t_out=decimalyear"; double in4 = 1877.71428, exp4 = 2016.0; char args5[] = "+proj=unitconvert +t_in=yyyymmdd +t_out=yyyymmdd"; double in5 = 20170131; test_time(args1, 1e-6, in1, in1); test_time(args2, 1e-6, in2, in2); test_time(args3, 1e-6, in3, in3); test_time(args4, 1e-6, in4, exp4); test_time(args5, 1e-6, in5, in5); } static void test_date(const char *args, double tol, double t_in, double t_exp) { PJ_COORD in, out; PJ *P = proj_create(PJ_DEFAULT_CTX, args); ASSERT_TRUE(P != nullptr); in = proj_coord(0.0, 0.0, 0.0, t_in); out = proj_trans(P, PJ_FWD, in); EXPECT_NEAR(out.xyzt.t, t_exp, tol); proj_destroy(P); proj_log_level(nullptr, PJ_LOG_NONE); } TEST(gie, unitconvert_selftest_date) { char args[] = "+proj=unitconvert +t_in=decimalyear +t_out=yyyymmdd"; test_date(args, 1e-6, 2022.0027, 20220102); test_date(args, 1e-6, 1990.0, 19900101); test_date(args, 1e-6, 2004.1612, 20040229); test_date(args, 1e-6, 1899.999, 19000101); strcpy(&args[18], "+t_in=yyyymmdd +t_out=decimalyear"); test_date(args, 1e-6, 20220102, 2022.0027397); test_date(args, 1e-6, 19900101, 1990.0); test_date(args, 1e-6, 20040229, 2004.1612022); test_date(args, 1e-6, 18991231, 1899.9972603); } static const char tc32_utm32[] = { " +proj=horner" " +ellps=intl" " +range=500000" " +fwd_origin=877605.269066,6125810.306769" " +inv_origin=877605.760036,6125811.281773" " +deg=4" " +fwd_v=6.1258112678e+06,9.9999971567e-01,1.5372750011e-10,5.9300860915e-" "15,2.2609497633e-19,4.3188227445e-05,2.8225130416e-10,7.8740007114e-16,-1." "7453997279e-19,1.6877465415e-10,-1.1234649773e-14,-1.7042333358e-18,-7." "9303467953e-15,-5.2906832535e-19,3.9984284847e-19" " +fwd_u=8.7760574982e+05,9.9999752475e-01,2.8817299305e-10,5.5641310680e-" "15,-1.5544700949e-18,-4.1357045890e-05,4.2106213519e-11,2.8525551629e-14,-" "1.9107771273e-18,3.3615590093e-10,2.4380247154e-14,-2.0241230315e-18,1." "2429019719e-15,5.3886155968e-19,-1.0167505000e-18" " +inv_v=6.1258103208e+06,1.0000002826e+00,-1.5372762184e-10,-5." "9304261011e-15,-2.2612705361e-19,-4.3188331419e-05,-2.8225549995e-10,-7." "8529116371e-16,1.7476576773e-19,-1.6875687989e-10,1.1236475299e-14,1." "7042518057e-18,7.9300735257e-15,5.2881862699e-19,-3.9990736798e-19" " +inv_u=8.7760527928e+05,1.0000024735e+00,-2.8817540032e-10,-5." "5627059451e-15,1.5543637570e-18,4.1357152105e-05,-4.2114813612e-11,-2." "8523713454e-14,1.9109017837e-18,-3.3616407783e-10,-2.4382678126e-14,2." "0245020199e-18,-1.2441377565e-15,-5.3885232238e-19,1.0167203661e-18"}; static const char sb_utm32[] = { " +proj=horner" " +ellps=intl" " +range=500000" " +tolerance=0.0005" " +fwd_origin=4.94690026817276e+05,6.13342113183056e+06" " +inv_origin=6.19480258923588e+05,6.13258568148837e+06" " +deg=3" " +fwd_c=6.13258562111350e+06,6.19480105709997e+05,9.99378966275206e-01,-2." "82153291753490e-02,-2.27089979140026e-10,-1.77019590701470e-09,1." "08522286274070e-14,2.11430298751604e-15" " +inv_c=6.13342118787027e+06,4.94690181709311e+05,9.99824464710368e-01,2." "82279070814774e-02,7.66123542220864e-11,1.78425334628927e-09,-1." "05584823306400e-14,-3.32554258683744e-15"}; // --------------------------------------------------------------------------- TEST(gie, horner_selftest) { PJ *P; PJ_COORD a, b, c; double dist; /* Real polynonia relating the technical coordinate system TC32 to "System * 45 Bornholm" */ P = proj_create(PJ_DEFAULT_CTX, tc32_utm32); ASSERT_TRUE(P != nullptr); a = b = proj_coord(0, 0, 0, 0); a.uv.v = 6125305.4245; a.uv.u = 878354.8539; c = a; /* Check roundtrip precision for 1 iteration each way, starting in forward * direction */ dist = proj_roundtrip(P, PJ_FWD, 1, &c); EXPECT_LE(dist, 0.01); proj_destroy(P); /* The complex polynomial transformation between the "System Storebaelt" and * utm32/ed50 */ P = proj_create(PJ_DEFAULT_CTX, sb_utm32); ASSERT_TRUE(P != nullptr); /* Test value: utm32_ed50(620000, 6130000) = sb_ed50(495136.8544, * 6130821.2945) */ a = b = c = proj_coord(0, 0, 0, 0); a.uv.v = 6130821.2945; a.uv.u = 495136.8544; c.uv.v = 6130000.0000; c.uv.u = 620000.0000; /* Forward projection */ b = proj_trans(P, PJ_FWD, a); dist = proj_xy_dist(b, c); EXPECT_LE(dist, 0.001); /* Inverse projection */ b = proj_trans(P, PJ_INV, c); dist = proj_xy_dist(b, a); EXPECT_LE(dist, 0.001); /* Check roundtrip precision for 1 iteration each way */ dist = proj_roundtrip(P, PJ_FWD, 1, &a); EXPECT_LE(dist, 0.01); proj_destroy(P); } static const char tc32_utm32_fwd_only[] = { " +proj=horner" " +ellps=intl" " +range=10000000" " +fwd_origin=877605.269066,6125810.306769" " +deg=4" " +fwd_v=6.1258112678e+06,9.9999971567e-01,1.5372750011e-10,5.9300860915e-" "15,2.2609497633e-19,4.3188227445e-05,2.8225130416e-10,7.8740007114e-16,-1." "7453997279e-19,1.6877465415e-10,-1.1234649773e-14,-1.7042333358e-18,-7." "9303467953e-15,-5.2906832535e-19,3.9984284847e-19" " +fwd_u=8.7760574982e+05,9.9999752475e-01,2.8817299305e-10,5.5641310680e-" "15,-1.5544700949e-18,-4.1357045890e-05,4.2106213519e-11,2.8525551629e-14,-" "1.9107771273e-18,3.3615590093e-10,2.4380247154e-14,-2.0241230315e-18,1." "2429019719e-15,5.3886155968e-19,-1.0167505000e-18"}; static const char sb_utm32_fwd_only[] = { " +proj=horner" " +ellps=intl" " +range=10000000" " +fwd_origin=4.94690026817276e+05,6.13342113183056e+06" " +deg=3" " +fwd_c=6.13258562111350e+06,6.19480105709997e+05,9.99378966275206e-01,-2." "82153291753490e-02,-2.27089979140026e-10,-1.77019590701470e-09,1." "08522286274070e-14,2.11430298751604e-15"}; static const char hatt_to_ggrs[] = { " +proj=horner" " +ellps=bessel" " +fwd_origin=0.0, 0.0" " +deg=2" " +range=10000000" " +fwd_u=370552.68, 0.9997155, -1.08e-09, 0.0175123, 2.04e-09, 1.63e-09" " +fwd_v=4511927.23, 0.9996979, 5.60e-10, -0.0174755, -1.65e-09, " "-6.50e-10"}; TEST(gie, horner_only_fwd_selftest) { { PJ *P = proj_create(PJ_DEFAULT_CTX, tc32_utm32_fwd_only); ASSERT_TRUE(P != nullptr); PJ_COORD a = proj_coord(0, 0, 0, 0); a.uv.v = 6125305.4245; a.uv.u = 878354.8539; /* Check roundtrip precision for 1 iteration each way, starting in * forward direction */ double dist = proj_roundtrip(P, PJ_FWD, 1, &a); EXPECT_LE(dist, 0.01); proj_destroy(P); } { PJ_COORD a; a = proj_coord(0, 0, 0, 0); a.xy.x = -10157.950; a.xy.y = -21121.093; PJ_COORD c; c = proj_coord(0, 0, 0, 0); c.enu.e = 360028.794; c.enu.n = 4490989.862; PJ *P = proj_create(PJ_DEFAULT_CTX, hatt_to_ggrs); ASSERT_TRUE(P != nullptr); /* Forward projection */ PJ_COORD b = proj_trans(P, PJ_FWD, a); double dist = proj_xy_dist(b, c); EXPECT_LE(dist, 0.001); /* Inverse projection */ b = proj_trans(P, PJ_INV, c); dist = proj_xy_dist(b, a); EXPECT_LE(dist, 0.001); /* Check roundtrip precision for 1 iteration each way, starting in * forward direction */ dist = proj_roundtrip(P, PJ_FWD, 1, &a); EXPECT_LE(dist, 0.01); proj_destroy(P); } { PJ *P = proj_create(PJ_DEFAULT_CTX, sb_utm32_fwd_only); ASSERT_TRUE(P != nullptr); PJ_COORD a = proj_coord(0, 0, 0, 0); PJ_COORD b = proj_coord(0, 0, 0, 0); PJ_COORD c = proj_coord(0, 0, 0, 0); a.uv.v = 6130821.2945; a.uv.u = 495136.8544; c.uv.v = 6130000.0000; c.uv.u = 620000.0000; /* Forward projection */ b = proj_trans(P, PJ_FWD, a); double dist = proj_xy_dist(b, c); EXPECT_LE(dist, 0.001); /* Inverse projection */ b = proj_trans(P, PJ_INV, c); dist = proj_xy_dist(b, a); EXPECT_LE(dist, 0.001); /* Check roundtrip precision for 1 iteration each way */ dist = proj_roundtrip(P, PJ_FWD, 1, &a); EXPECT_LE(dist, 0.01); proj_destroy(P); } } // --------------------------------------------------------------------------- TEST(gie, proj_create_crs_to_crs_PULKOVO42_ETRS89) { auto P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "EPSG:4179", "EPSG:4258", nullptr); ASSERT_TRUE(P != nullptr); PJ_COORD c; EXPECT_EQ(std::string(proj_pj_info(P).definition), "unavailable until proj_trans is called"); EXPECT_EQ(proj_get_name(P), nullptr); EXPECT_EQ(P->fwd, nullptr); EXPECT_EQ(P->fwd3d, nullptr); EXPECT_EQ(P->fwd4d, nullptr); // get source CRS even if the P object is in a dummy state auto src_crs = proj_get_source_crs(PJ_DEFAULT_CTX, P); EXPECT_TRUE(src_crs != nullptr); EXPECT_EQ(proj_get_name(src_crs), std::string("Pulkovo 1942(58)")); proj_destroy(src_crs); // get target CRS even if the P object is in a dummy state auto target_crs = proj_get_target_crs(PJ_DEFAULT_CTX, P); EXPECT_TRUE(target_crs != nullptr); EXPECT_EQ(proj_get_name(target_crs), std::string("ETRS89")); proj_destroy(target_crs); // Romania c.xyzt.x = 45; // Lat c.xyzt.y = 25; // Long c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(P, PJ_FWD, c); EXPECT_NEAR(c.xy.x, 44.999701238, 1e-9); EXPECT_NEAR(c.xy.y, 24.998474948, 1e-9); EXPECT_EQ(std::string(proj_pj_info(P).definition), "proj=pipeline step proj=axisswap order=2,1 " "step proj=unitconvert xy_in=deg xy_out=rad " "step proj=push v_3 " "step proj=cart " "ellps=krass step proj=helmert x=2.3287 y=-147.0425 z=-92.0802 " "rx=0.3092483 ry=-0.32482185 rz=-0.49729934 s=5.68906266 " "convention=coordinate_frame step inv proj=cart ellps=GRS80 " "step proj=pop v_3 " "step proj=unitconvert xy_in=rad xy_out=deg step proj=axisswap " "order=2,1"); c = proj_trans(P, PJ_INV, c); EXPECT_NEAR(c.xy.x, 45, 1e-8); EXPECT_NEAR(c.xy.y, 25, 1e-8); c.xyzt.x = 45; // Lat c.xyzt.y = 25; // Long c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; proj_trans_generic(P, PJ_FWD, &(c.xyz.x), sizeof(double), 1, &(c.xyz.y), sizeof(double), 1, &(c.xyz.z), sizeof(double), 1, nullptr, 0, 0); EXPECT_NEAR(c.xy.x, 44.999701238, 1e-9); EXPECT_NEAR(c.xy.y, 24.998474948, 1e-9); // Poland c.xyz.x = 52; // Lat c.xyz.y = 20; // Long c.xyz.z = 0; c = proj_trans(P, PJ_FWD, c); EXPECT_NEAR(c.xy.x, 51.999714150, 1e-9); EXPECT_NEAR(c.xy.y, 19.998187811, 1e-9); EXPECT_EQ(std::string(proj_pj_info(P).definition), "proj=pipeline step proj=axisswap order=2,1 " "step proj=unitconvert xy_in=deg xy_out=rad " "step proj=push v_3 " "step proj=cart " "ellps=krass step proj=helmert x=33.4 y=-146.6 z=-76.3 rx=-0.359 " "ry=-0.053 rz=0.844 s=-0.84 convention=position_vector step inv " "proj=cart ellps=GRS80 step proj=pop v_3 " "step proj=unitconvert xy_in=rad " "xy_out=deg step proj=axisswap order=2,1"); proj_destroy(P); } // --------------------------------------------------------------------------- TEST(gie, proj_create_crs_to_crs_WGS84_EGM08_to_WGS84) { auto P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "EPSG:4326+3855", "EPSG:4979", nullptr); ASSERT_TRUE(P != nullptr); EXPECT_EQ(std::string(proj_pj_info(P).description), "Transformation from EGM2008 height to WGS 84 (ballpark vertical " "transformation, without ellipsoid height to vertical height " "correction)"); proj_destroy(P); } // --------------------------------------------------------------------------- TEST(gie, proj_create_crs_to_crs_outside_area_of_use) { // See https://github.com/OSGeo/proj.4/issues/1329 auto P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "EPSG:4275", "EPSG:4807", nullptr); ASSERT_TRUE(P != nullptr); PJ_COORD c; EXPECT_EQ(P->fwd, nullptr); // Test point outside area of use of both candidate coordinate operations c.xyzt.x = 58; // Lat in deg c.xyzt.y = 5; // Long in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(P, PJ_FWD, c); EXPECT_NEAR(c.xy.x, 64.44444444444444, 1e-9); // Lat in grad EXPECT_NEAR(c.xy.y, 2.958634259259258, 1e-9); // Long in grad proj_destroy(P); } // --------------------------------------------------------------------------- TEST(gie, proj_create_crs_to_crs_with_area_large) { // Test bugfix for https://github.com/OSGeo/gdal/issues/3695 auto area = proj_area_create(); proj_area_set_bbox(area, -14.1324, 49.5614, 3.76488, 62.1463); auto P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "EPSG:4277", "EPSG:4326", area); proj_area_destroy(area); ASSERT_TRUE(P != nullptr); PJ_COORD c; c.xyzt.x = 50; // Lat in deg c.xyzt.y = -2; // Long in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(P, PJ_FWD, c); EXPECT_NEAR(c.xy.x, 50.00065628, 1e-8); EXPECT_NEAR(c.xy.y, -2.00133989, 1e-8); proj_destroy(P); } // --------------------------------------------------------------------------- TEST(gie, proj_create_crs_to_crs_with_longitude_outside_minus_180_180) { // Test bugfix for https://github.com/OSGeo/PROJ/issues/3594 auto P = proj_create_crs_to_crs(PJ_DEFAULT_CTX, "EPSG:4277", "EPSG:4326", nullptr); ASSERT_TRUE(P != nullptr); PJ_COORD c; c.xyzt.x = 50; // Lat in deg c.xyzt.y = -2 + 360; // Long in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(P, PJ_FWD, c); EXPECT_NEAR(c.xy.x, 50.00065628, 1e-8); EXPECT_NEAR(c.xy.y, -2.00133989, 1e-8); c.xyzt.x = 50; // Lat in deg c.xyzt.y = -2 - 360; // Long in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(P, PJ_FWD, c); EXPECT_NEAR(c.xy.x, 50.00065628, 1e-8); EXPECT_NEAR(c.xy.y, -2.00133989, 1e-8); c.xyzt.x = 50.00065628; // Lat in deg c.xyzt.y = -2.00133989 + 360; // Long in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(P, PJ_INV, c); EXPECT_NEAR(c.xy.x, 50, 1e-8); EXPECT_NEAR(c.xy.y, -2, 1e-8); c.xyzt.x = 50.00065628; // Lat in deg c.xyzt.y = -2.00133989 - 360; // Long in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(P, PJ_INV, c); EXPECT_NEAR(c.xy.x, 50, 1e-8); EXPECT_NEAR(c.xy.y, -2, 1e-8); auto Pnormalized = proj_normalize_for_visualization(PJ_DEFAULT_CTX, P); c.xyzt.x = -2 + 360; // Long in deg c.xyzt.y = 50; // Lat in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(Pnormalized, PJ_FWD, c); EXPECT_NEAR(c.xy.x, -2.00133989, 1e-8); EXPECT_NEAR(c.xy.y, 50.00065628, 1e-8); c.xyzt.x = -2.00133989 + 360; // Long in deg c.xyzt.y = 50.00065628; // Lat in deg c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(Pnormalized, PJ_INV, c); EXPECT_NEAR(c.xy.x, -2, 1e-8); EXPECT_NEAR(c.xy.y, 50, 1e-8); proj_destroy(Pnormalized); proj_destroy(P); } // --------------------------------------------------------------------------- TEST(gie, proj_trans_generic) { // GDA2020 to WGS84 (G1762) auto P = proj_create( PJ_DEFAULT_CTX, "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=0 +y=0 +z=0 +rx=0 +ry=0 +rz=0 +s=0 +dx=0 " "+dy=0 +dz=0 +drx=-0.00150379 +dry=-0.00118346 +drz=-0.00120716 " "+ds=0 +t_epoch=2020 +convention=coordinate_frame " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); double lat = -60; double longitude = 120; proj_trans_generic(P, PJ_FWD, &lat, sizeof(double), 1, &longitude, sizeof(double), 1, nullptr, 0, 0, nullptr, 0, 0); // Should be a no-op when the time is unknown (or equal to 2020) EXPECT_NEAR(lat, -60, 1e-9); EXPECT_NEAR(longitude, 120, 1e-9); proj_destroy(P); } // --------------------------------------------------------------------------- TEST(gie, proj_trans_with_a_crs) { auto P = proj_create(PJ_DEFAULT_CTX, "EPSG:4326"); PJ_COORD input; input.xyzt.x = 0; input.xyzt.y = 0; input.xyzt.z = 0; input.xyzt.t = 0; auto output = proj_trans(P, PJ_FWD, input); EXPECT_EQ(proj_errno(P), PROJ_ERR_INVALID_OP_ILLEGAL_ARG_VALUE); proj_destroy(P); EXPECT_EQ(HUGE_VAL, output.xyzt.x); } // --------------------------------------------------------------------------- TEST(gie, proj_create_crs_to_crs_from_pj_force_over) { PJ_CONTEXT *ctx; ctx = proj_context_create(); ASSERT_TRUE(ctx != nullptr); auto epsg27700 = proj_create(ctx, "EPSG:27700"); ASSERT_TRUE(epsg27700 != nullptr); auto epsg4326 = proj_create(ctx, "EPSG:4326"); ASSERT_TRUE(epsg4326 != nullptr); auto epsg3857 = proj_create(ctx, "EPSG:3857"); ASSERT_TRUE(epsg3857 != nullptr); { const char *const options[] = {"FORCE_OVER=YES", nullptr}; auto P = proj_create_crs_to_crs_from_pj(ctx, epsg4326, epsg3857, nullptr, options); ASSERT_TRUE(P != nullptr); ASSERT_TRUE(P->over); PJ_COORD input; PJ_COORD input_over; // Test a point along the equator. // The same point, but in two different representations. input.xyzt.x = 0; // Lat in deg input.xyzt.y = 140; // Long in deg input.xyzt.z = 0; input.xyzt.t = HUGE_VAL; input_over.xyzt.x = 0; // Lat in deg input_over.xyzt.y = -220; // Long in deg input_over.xyzt.z = 0; input_over.xyzt.t = HUGE_VAL; auto output = proj_trans(P, PJ_FWD, input); auto output_over = proj_trans(P, PJ_FWD, input_over); auto input_inv = proj_trans(P, PJ_INV, output); auto input_over_inv = proj_trans(P, PJ_INV, output_over); // Web Mercator x's between 0 and 180 longitude come out positive. // But when forcing the over flag, the -220 calculation makes it flip. EXPECT_GT(output.xyz.x, 0); EXPECT_LT(output_over.xyz.x, 0); EXPECT_NEAR(output.xyz.x, 15584728.711058298, 1e-8); EXPECT_NEAR(output_over.xyz.x, -24490287.974520184, 1e-8); // The distance from 140 to 180 and -220 to -180 should be pretty much // the same. auto dx_o = fabs(output.xyz.x - 20037508.342789244); auto dx_over = fabs(output_over.xyz.x + 20037508.342789244); auto dx = fabs(dx_o - dx_over); EXPECT_NEAR(dx, 0, 1e-8); // Check the inverse operations get us back close to our original input // values. EXPECT_NEAR(input.xyz.x, input_inv.xyz.x, 1e-8); EXPECT_NEAR(input.xyz.y, input_inv.xyz.y, 1e-8); EXPECT_NEAR(input_over.xyz.x, input_over_inv.xyz.x, 1e-8); EXPECT_NEAR(input_over.xyz.y, input_over_inv.xyz.y, 1e-8); auto Pnormalized = proj_normalize_for_visualization(ctx, P); ASSERT_TRUE(Pnormalized->over); PJ_COORD input_over_normalized; input_over_normalized.xyzt.x = -220; // Long in deg input_over_normalized.xyzt.y = 0; // Lat in deg input_over_normalized.xyzt.z = 0; input_over_normalized.xyzt.t = HUGE_VAL; auto output_over_normalized = proj_trans(Pnormalized, PJ_FWD, input_over_normalized); EXPECT_NEAR(output_over_normalized.xyz.x, -24490287.974520184, 1e-8); proj_destroy(Pnormalized); proj_destroy(P); } { // Try again with force over set to anything but YES to verify it didn't // do anything. const char *const options[] = {"FORCE_OVER=NO", nullptr}; auto P = proj_create_crs_to_crs_from_pj(ctx, epsg4326, epsg3857, nullptr, options); ASSERT_TRUE(P != nullptr); ASSERT_FALSE(P->over); PJ_COORD input; PJ_COORD input_notOver; input.xyzt.x = 0; // Lat in deg input.xyzt.y = 140; // Long in deg input.xyzt.z = 0; input.xyzt.t = HUGE_VAL; input_notOver.xyzt.x = 0; // Lat in deg input_notOver.xyzt.y = -220; // Long in deg input_notOver.xyzt.z = 0; input_notOver.xyzt.t = HUGE_VAL; auto output = proj_trans(P, PJ_FWD, input); auto output_notOver = proj_trans(P, PJ_FWD, input_notOver); EXPECT_GT(output.xyz.x, 0); EXPECT_GT(output_notOver.xyz.x, 0); EXPECT_NEAR(output.xyz.x, 15584728.711058298, 1e-8); EXPECT_NEAR(output_notOver.xyz.x, 15584728.711058298, 1e-8); proj_destroy(P); } { // Try again with no options to verify it didn't do anything. auto P = proj_create_crs_to_crs_from_pj(ctx, epsg4326, epsg3857, nullptr, nullptr); ASSERT_TRUE(P != nullptr); ASSERT_FALSE(P->over); PJ_COORD input; PJ_COORD input_notOver; input.xyzt.x = 0; // Lat in deg input.xyzt.y = 140; // Long in deg input.xyzt.z = 0; input.xyzt.t = HUGE_VAL; input_notOver.xyzt.x = 0; // Lat in deg input_notOver.xyzt.y = -220; // Long in deg input_notOver.xyzt.z = 0; input_notOver.xyzt.t = HUGE_VAL; auto output = proj_trans(P, PJ_FWD, input); auto output_notOver = proj_trans(P, PJ_FWD, input_notOver); EXPECT_GT(output.xyz.x, 0); EXPECT_GT(output_notOver.xyz.x, 0); EXPECT_NEAR(output.xyz.x, 15584728.711058298, 1e-8); EXPECT_NEAR(output_notOver.xyz.x, 15584728.711058298, 1e-8); proj_destroy(P); } { // EPSG:4326 -> EPSG:27700 has more than one coordinate operation // candidate. const char *const options[] = {"FORCE_OVER=YES", nullptr}; auto P = proj_create_crs_to_crs_from_pj(ctx, epsg4326, epsg27700, nullptr, options); ASSERT_TRUE(P != nullptr); ASSERT_TRUE(P->over); PJ_COORD input; PJ_COORD input_over; input.xyzt.x = 0; // Lat in deg input.xyzt.y = 140; // Long in deg input.xyzt.z = 0; input.xyzt.t = HUGE_VAL; input_over.xyzt.x = 0; // Lat in deg input_over.xyzt.y = -220; // Long in deg input_over.xyzt.z = 0; input_over.xyzt.t = HUGE_VAL; auto output = proj_trans(P, PJ_FWD, input); auto output_over = proj_trans(P, PJ_FWD, input_over); // Doesn't actually change the result for this tmerc transformation. EXPECT_NEAR(output.xyz.x, 4980122.749364435, 1e-8); EXPECT_NEAR(output.xyz.y, 14467212.882603768, 1e-8); EXPECT_NEAR(output_over.xyz.x, 4980122.749364435, 1e-8); EXPECT_NEAR(output_over.xyz.y, 14467212.882603768, 1e-8); auto Pnormalized = proj_normalize_for_visualization(ctx, P); ASSERT_TRUE(Pnormalized->over); for (const auto &op : Pnormalized->alternativeCoordinateOperations) { ASSERT_TRUE(op.pj->over); } PJ_COORD input_over_normalized; input_over_normalized.xyzt.x = -220; // Long in deg input_over_normalized.xyzt.y = 0; // Lat in deg input_over_normalized.xyzt.z = 0; input_over_normalized.xyzt.t = HUGE_VAL; auto output_over_normalized = proj_trans(Pnormalized, PJ_FWD, input_over_normalized); EXPECT_NEAR(output_over_normalized.xyz.x, 4980122.749364435, 1e-8); EXPECT_NEAR(output_over_normalized.xyz.y, 14467212.882603768, 1e-8); proj_destroy(Pnormalized); proj_destroy(P); } { // Negative test for 27700. const char *const options[] = {"FORCE_OVER=NO", nullptr}; auto P = proj_create_crs_to_crs_from_pj(ctx, epsg4326, epsg27700, nullptr, options); ASSERT_TRUE(P != nullptr); ASSERT_FALSE(P->over); PJ_COORD input; PJ_COORD input_over; input.xyzt.x = 0; // Lat in deg input.xyzt.y = 140; // Long in deg input.xyzt.z = 0; input.xyzt.t = HUGE_VAL; input_over.xyzt.x = 0; // Lat in deg input_over.xyzt.y = -220; // Long in deg input_over.xyzt.z = 0; input_over.xyzt.t = HUGE_VAL; auto output = proj_trans(P, PJ_FWD, input); auto output_over = proj_trans(P, PJ_FWD, input_over); EXPECT_NEAR(output.xyz.x, 4980122.749364435, 1e-8); EXPECT_NEAR(output.xyz.y, 14467212.882603768, 1e-8); EXPECT_NEAR(output_over.xyz.x, 4980122.749364435, 1e-8); EXPECT_NEAR(output_over.xyz.y, 14467212.882603768, 1e-8); proj_destroy(P); } proj_destroy(epsg27700); proj_destroy(epsg4326); proj_destroy(epsg3857); proj_context_destroy(ctx); } } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/proj_errno_string_test.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Unit test for proj_errno_string() * Author: Kristian Evers <[email protected]> * ****************************************************************************** * Copyright (c) 2018, Kristian Evers. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <cstring> #include "proj.h" #include "proj_config.h" #include "gtest_include.h" namespace { TEST(ProjErrnoStringTest, NoError) { EXPECT_EQ(nullptr, proj_errno_string(0)); } TEST(ProjErrnoStringTest, ProjErrnos) { EXPECT_STREQ("Unknown error (code -1)", proj_errno_string(-1)); EXPECT_STREQ("Invalid PROJ string syntax", proj_errno_string(PROJ_ERR_INVALID_OP_WRONG_SYNTAX)); EXPECT_STREQ( "Unspecified error related to coordinate operation initialization", proj_errno_string(PROJ_ERR_INVALID_OP)); EXPECT_STREQ("Unspecified error related to coordinate transformation", proj_errno_string(PROJ_ERR_COORD_TRANSFM)); } TEST(ProjErrnoStringTest, proj_context_errno_string) { EXPECT_STREQ("Unknown error (code -1)", proj_context_errno_string(nullptr, -1)); PJ_CONTEXT *ctx = proj_context_create(); EXPECT_STREQ("Unknown error (code -999)", proj_context_errno_string(ctx, -999)); proj_context_destroy(ctx); } } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/gtest_include.h
/****************************************************************************** * * Project: PROJ * Purpose: Wrapper for gtest/gtest.h * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ // Disable all warnings for gtest.h, so as to be able to still use them for // our own code. #if defined(__GNUC__) #pragma GCC system_header #endif #include "gtest/gtest.h"
h
PROJ
data/projects/PROJ/test/unit/test_common.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include <limits> using namespace osgeo::proj::common; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; // --------------------------------------------------------------------------- TEST(common, unit_of_measure) { EXPECT_EQ(UnitOfMeasure::METRE.name(), "metre"); EXPECT_EQ(UnitOfMeasure::METRE.conversionToSI(), 1.0); EXPECT_EQ(UnitOfMeasure::METRE.type(), UnitOfMeasure::Type::LINEAR); EXPECT_EQ(UnitOfMeasure::DEGREE.name(), "degree"); EXPECT_EQ(UnitOfMeasure::DEGREE.conversionToSI(), 0.017453292519943295); EXPECT_EQ(UnitOfMeasure::DEGREE.type(), UnitOfMeasure::Type::ANGULAR); EXPECT_EQ(UnitOfMeasure::RADIAN.name(), "radian"); EXPECT_EQ(UnitOfMeasure::RADIAN.conversionToSI(), 1.0); EXPECT_EQ(UnitOfMeasure::RADIAN.type(), UnitOfMeasure::Type::ANGULAR); EXPECT_EQ(Length(2.0, UnitOfMeasure("km", 1000.0)) .convertToUnit(UnitOfMeasure::METRE), 2000.0); EXPECT_EQ( Angle(2.0, UnitOfMeasure::DEGREE).convertToUnit(UnitOfMeasure::RADIAN), 2 * 0.017453292519943295); EXPECT_EQ(Angle(2.5969213, UnitOfMeasure::GRAD) .convertToUnit(UnitOfMeasure::DEGREE), 2.5969213 / 100.0 * 90.0); } // --------------------------------------------------------------------------- TEST(common, measure) { EXPECT_TRUE(Measure(0.0) == Measure(0.0)); EXPECT_TRUE(Measure(1.0) == Measure(1.0)); EXPECT_FALSE(Measure(1.0) == Measure(2.0)); EXPECT_FALSE(Measure(1.0) == Measure(0.0)); EXPECT_FALSE(Measure(0.0) == Measure(1.0)); EXPECT_TRUE(Measure(std::numeric_limits<double>::infinity()) == Measure(std::numeric_limits<double>::infinity())); EXPECT_TRUE(Measure(-std::numeric_limits<double>::infinity()) == Measure(-std::numeric_limits<double>::infinity())); EXPECT_FALSE(Measure(std::numeric_limits<double>::infinity()) == Measure(-std::numeric_limits<double>::infinity())); EXPECT_FALSE(Measure(std::numeric_limits<double>::infinity()) == Measure(1.0)); EXPECT_FALSE(Measure(1.0) == Measure(std::numeric_limits<double>::infinity())); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_empty) { PropertyMap properties; auto obj = OperationParameter::create(properties); EXPECT_TRUE(obj->name()->code().empty()); EXPECT_TRUE(obj->identifiers().empty()); EXPECT_TRUE(obj->aliases().empty()); EXPECT_TRUE(obj->remarks().empty()); EXPECT_TRUE(!obj->isDeprecated()); EXPECT_TRUE(obj->alias().empty()); } // --------------------------------------------------------------------------- TEST(common, identifiedobject) { PropertyMap properties; properties.set(IdentifiedObject::NAME_KEY, "name"); properties.set(IdentifiedObject::IDENTIFIERS_KEY, Identifier::create("identifier_code")); properties.set(IdentifiedObject::ALIAS_KEY, "alias"); properties.set(IdentifiedObject::REMARKS_KEY, "remarks"); properties.set(IdentifiedObject::DEPRECATED_KEY, true); auto obj = OperationParameter::create(properties); EXPECT_EQ(*(obj->name()->description()), "name"); ASSERT_EQ(obj->identifiers().size(), 1U); EXPECT_EQ(obj->identifiers()[0]->code(), "identifier_code"); ASSERT_EQ(obj->aliases().size(), 1U); EXPECT_EQ(obj->aliases()[0]->toString(), "alias"); EXPECT_EQ(obj->remarks(), "remarks"); EXPECT_TRUE(obj->isDeprecated()); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_name_invalid_type_integer) { PropertyMap properties; properties.set(IdentifiedObject::NAME_KEY, 123); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_name_invalid_type_citation) { PropertyMap properties; properties.set(IdentifiedObject::NAME_KEY, nn_make_shared<Citation>("invalid")); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_identifier_invalid_type) { PropertyMap properties; properties.set(IdentifiedObject::IDENTIFIERS_KEY, "string not allowed"); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_identifier_array_of_identifier) { PropertyMap properties; auto array = ArrayOfBaseObject::create(); array->add(Identifier::create("identifier_code1")); array->add(Identifier::create("identifier_code2")); properties.set(IdentifiedObject::IDENTIFIERS_KEY, array); auto obj = OperationParameter::create(properties); ASSERT_EQ(obj->identifiers().size(), 2U); EXPECT_EQ(obj->identifiers()[0]->code(), "identifier_code1"); EXPECT_EQ(obj->identifiers()[1]->code(), "identifier_code2"); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_identifier_array_of_invalid_type) { PropertyMap properties; auto array = ArrayOfBaseObject::create(); array->add(nn_make_shared<Citation>("unexpected type")); properties.set(IdentifiedObject::IDENTIFIERS_KEY, array); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_alias_array_of_string) { PropertyMap properties; properties.set(IdentifiedObject::ALIAS_KEY, std::vector<std::string>{"alias1", "alias2"}); auto obj = OperationParameter::create(properties); ASSERT_EQ(obj->aliases().size(), 2U); EXPECT_EQ(obj->aliases()[0]->toString(), "alias1"); EXPECT_EQ(obj->aliases()[1]->toString(), "alias2"); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_alias_invalid_type) { PropertyMap properties; properties.set(IdentifiedObject::ALIAS_KEY, nn_make_shared<Citation>("unexpected type")); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, identifiedobject_alias_array_of_invalid_type) { PropertyMap properties; auto array = ArrayOfBaseObject::create(); array->add(nn_make_shared<Citation>("unexpected type")); properties.set(IdentifiedObject::ALIAS_KEY, array); ASSERT_THROW(OperationParameter::create(properties), InvalidValueTypeException); } // --------------------------------------------------------------------------- TEST(common, DataEpoch) { DataEpoch epochSrc(Measure(2010.5, UnitOfMeasure::YEAR)); DataEpoch epoch(epochSrc); EXPECT_EQ(epoch.coordinateEpoch().value(), 2010.5); EXPECT_EQ(epoch.coordinateEpoch().unit(), UnitOfMeasure::YEAR); }
cpp
PROJ
data/projects/PROJ/test/unit/test_misc.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2021, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "proj.h" namespace { TEST(misc, version) { EXPECT_EQ(PROJ_COMPUTE_VERSION(2200, 98, 76), 22009876); EXPECT_EQ(PROJ_VERSION_NUMBER, PROJ_VERSION_MAJOR * 10000 + PROJ_VERSION_MINOR * 100 + PROJ_VERSION_PATCH); EXPECT_TRUE(PROJ_AT_LEAST_VERSION(PROJ_VERSION_MAJOR, PROJ_VERSION_MINOR, PROJ_VERSION_PATCH)); EXPECT_TRUE(PROJ_AT_LEAST_VERSION(PROJ_VERSION_MAJOR - 1, PROJ_VERSION_MINOR, PROJ_VERSION_PATCH)); EXPECT_FALSE(PROJ_AT_LEAST_VERSION(PROJ_VERSION_MAJOR, PROJ_VERSION_MINOR, PROJ_VERSION_PATCH + 1)); } } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_crs.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" // to be able to use internal::replaceAll #define FROM_PROJ_CPP #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj/internal/io_internal.hpp" using namespace osgeo::proj::common; using namespace osgeo::proj::crs; using namespace osgeo::proj::cs; using namespace osgeo::proj::datum; using namespace osgeo::proj::io; using namespace osgeo::proj::internal; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; namespace { struct UnrelatedObject : public IComparable { UnrelatedObject() = default; bool _isEquivalentTo(const IComparable *, Criterion, const DatabaseContextPtr &) const override { assert(false); return false; } }; static nn<std::shared_ptr<UnrelatedObject>> createUnrelatedObject() { return nn_make_shared<UnrelatedObject>(); } } // namespace // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_get_components) { auto crs = GeographicCRS::EPSG_4326; ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "4326"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(crs->nameStr(), "WGS 84"); auto datum = crs->datum(); ASSERT_EQ(datum->identifiers().size(), 1U); EXPECT_EQ(datum->identifiers()[0]->code(), "6326"); EXPECT_EQ(*(datum->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(datum->nameStr(), "World Geodetic System 1984"); auto ellipsoid = datum->ellipsoid(); EXPECT_EQ(ellipsoid->semiMajorAxis().value(), 6378137.0); EXPECT_EQ(ellipsoid->semiMajorAxis().unit(), UnitOfMeasure::METRE); EXPECT_EQ(ellipsoid->inverseFlattening()->value(), 298.257223563); ASSERT_EQ(ellipsoid->identifiers().size(), 1U); EXPECT_EQ(ellipsoid->identifiers()[0]->code(), "7030"); EXPECT_EQ(*(ellipsoid->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(ellipsoid->nameStr(), "WGS 84"); } // --------------------------------------------------------------------------- TEST(crs, GeographicCRS_isEquivalentTo) { auto crs = GeographicCRS::EPSG_4326; EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE( crs->isEquivalentTo(crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(crs->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS)); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_FALSE(crs->isEquivalentTo(GeographicCRS::EPSG_4979.get())); EXPECT_FALSE(crs->isEquivalentTo(GeographicCRS::EPSG_4979.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(crs->isEquivalentTo(GeographicCRS::OGC_CRS84.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(crs->isEquivalentTo( GeographicCRS::OGC_CRS84.get(), IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS)); EXPECT_TRUE(GeographicCRS::OGC_CRS84->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS)); EXPECT_FALSE( GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->isEquivalentTo(crs.get())); EXPECT_FALSE( GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->isEquivalentTo( GeographicCRS::create(PropertyMap(), GeodeticReferenceFrame::create( PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude( UnitOfMeasure::DEGREE)) .get())); } // --------------------------------------------------------------------------- TEST(crs, GeographicCRS_datum_ensemble) { auto ensemble_vdatum = DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{GeodeticReferenceFrame::EPSG_6326, GeodeticReferenceFrame::EPSG_6326}, PositionalAccuracy::create("100")); { auto crs = GeographicCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "unnamed") .set(Identifier::CODESPACE_KEY, "MY_CODESPACE") .set(Identifier::CODE_KEY, "MY_ID"), nullptr, ensemble_vdatum, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); crs->exportToWKT(f.get()); auto expected = "GEOGCRS[\"unnamed\",\n" " ENSEMBLE[\"unnamed\",\n" " MEMBER[\"World Geodetic System 1984\"],\n" " MEMBER[\"World Geodetic System 1984\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[100]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"MY_CODESPACE\",\"MY_ID\"]]"; EXPECT_EQ(f->toString(), expected); } { auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), nullptr, ensemble_vdatum, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); crs->exportToWKT(f.get()); auto expected = "GEOGCRS[\"unnamed\",\n" " ENSEMBLE[\"unnamed\",\n" " MEMBER[\"World Geodetic System 1984\",\n" " ID[\"EPSG\",6326]],\n" " MEMBER[\"World Geodetic System 1984\",\n" " ID[\"EPSG\",6326]],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ENSEMBLEACCURACY[100]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; EXPECT_EQ(f->toString(), expected); } } // --------------------------------------------------------------------------- TEST(crs, GeographicCRS_ensemble_exception_in_create) { EXPECT_THROW(GeographicCRS::create(PropertyMap(), nullptr, nullptr, EllipsoidalCS::createLatitudeLongitude( UnitOfMeasure::DEGREE)), Exception); auto ensemble_vdatum = DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{ VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "vdatum1")), VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "vdatum2"))}, PositionalAccuracy::create("100")); EXPECT_THROW(GeographicCRS::create(PropertyMap(), nullptr, ensemble_vdatum, EllipsoidalCS::createLatitudeLongitude( UnitOfMeasure::DEGREE)), Exception); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT2) { auto crs = GeographicCRS::EPSG_4326; WKTFormatterNNPtr f(WKTFormatter::create()); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT2_2019) { auto crs = GeographicCRS::EPSG_4326; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT2_SIMPLIFIED) { auto crs = GeographicCRS::EPSG_4326; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_SIMPLIFIED)); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north],\n" " AXIS[\"longitude\",east],\n" " UNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",4326]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT2_SIMPLIFIED_single_line) { auto crs = GeographicCRS::EPSG_4326; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_SIMPLIFIED)); f->setMultiLine(false); crs->exportToWKT(f.get()); EXPECT_EQ( f->toString(), "GEODCRS[\"WGS 84\",DATUM[\"World Geodetic System " "1984\",ELLIPSOID[\"WGS " "84\",6378137,298.257223563]]," "CS[ellipsoidal,2],AXIS[\"latitude\",north],AXIS[\"longitude\",east]," "UNIT[\"degree\",0.0174532925199433],ID[\"EPSG\",4326]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT2_2019_SIMPLIFIED) { auto crs = GeographicCRS::EPSG_4326; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019_SIMPLIFIED)); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north],\n" " AXIS[\"longitude\",east],\n" " UNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",4326]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT1_GDAL) { auto crs = GeographicCRS::EPSG_4326; auto wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_EQ(wkt, "GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT1_GDAL_with_axis) { auto crs = GeographicCRS::EPSG_4326; auto wkt = crs->exportToWKT( &(WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL) ->setOutputAxis(WKTFormatter::OutputAxisRule::YES))); EXPECT_EQ(wkt, "GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"Latitude\",NORTH],\n" " AXIS[\"Longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4326\"]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_from_db_as_WKT1_GDAL_with_axis) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createCoordinateReferenceSystem("4326"); auto wkt = crs->exportToWKT( &(WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL) ->setOutputAxis(WKTFormatter::OutputAxisRule::YES))); EXPECT_EQ(wkt, "GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"Latitude\",NORTH],\n" " AXIS[\"Longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4326\"]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT1_ESRI_with_database) { auto crs = GeographicCRS::EPSG_4326; WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_" "1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4901_as_WKT1_ESRI_with_PRIMEM_unit_name_morphing) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createCoordinateReferenceSystem("4901"); WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"GCS_ATF_Paris\",DATUM[\"D_ATF\"," "SPHEROID[\"Plessis_1817\",6376523.0,308.64]]," "PRIMEM[\"Paris_RGS\",2.33720833333333]," "UNIT[\"Grad\",0.0157079632679489]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_WKT1_ESRI_without_database) { auto crs = GeographicCRS::EPSG_4326; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI)); EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_" "1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4326_as_PROJ_string) { auto crs = GeographicCRS::EPSG_4326; EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +datum=WGS84 +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4979_as_WKT2_SIMPLIFIED) { auto crs = GeographicCRS::EPSG_4979; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_SIMPLIFIED)); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " UNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4979_as_WKT2_2019_SIMPLIFIED) { auto crs = GeographicCRS::EPSG_4979; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019_SIMPLIFIED)); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " UNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4979_as_WKT1_GDAL_with_axis_not_strict_mode) { auto crs = GeographicCRS::EPSG_4979; auto wkt = crs->exportToWKT( &(WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL) ->setStrict(false) .setOutputAxis(WKTFormatter::OutputAxisRule::YES))); // WKT1 only supports 2 axis for GEOGCS. So this is an extension of // WKT1 as it // and GDAL doesn't really export such as beast, although it can import it // so allow it only in non-strict more EXPECT_EQ(wkt, "GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"Latitude\",NORTH],\n" " AXIS[\"Longitude\",EAST],\n" " AXIS[\"Ellipsoidal height\",UP],\n" " AUTHORITY[\"EPSG\",\"4979\"]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4979_as_WKT1_GDAL) { auto crs = GeographicCRS::EPSG_4979; EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4979_as_WKT1_GDAL_with_ellipsoidal_height_as_vertical_crs) { auto crs = GeographicCRS::EPSG_4979; auto wkt = crs->exportToWKT( &(WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, DatabaseContext::create()) ->setAllowEllipsoidalHeightAsVerticalCRS(true))); // For LAS 1.4 WKT1... EXPECT_EQ(wkt, "COMPD_CS[\"WGS 84 + Ellipsoid (metre)\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " VERT_CS[\"Ellipsoid (metre)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Ellipsoidal height\",UP]]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4979_as_WKT1_ESRI) { auto crs = GeographicCRS::EPSG_4979; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI)); const auto wkt = "GEOGCS[\"WGS_1984_3D\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]," "LINUNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT(f.get()), wkt); } // --------------------------------------------------------------------------- TEST(crs, geographic3D_crs_as_WKT1_ESRI_database) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("7087"); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext)); const auto wkt = "GEOGCS[\"RGTAAF07_(lon-lat)_3D\"," "DATUM[\"D_Reseau_Geodesique_des_Terres_Australes_et_" "Antarctiques_Francaises_2007\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]," "LINUNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT(f.get()), wkt); } // --------------------------------------------------------------------------- TEST(crs, geographic3D_NAD83_as_WKT1_ESRI_database) { auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "GEOGCS[\"GCS_North_American_1983\",DATUM[\"D_North_American_1983\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "VERTCS[\"NAD_1983\",DATUM[\"D_North_American_1983\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext)); const auto wkt = "GEOGCS[\"GCS_NAD83\",DATUM[\"D_North_American_1983\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]," "LINUNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT(f.get()), wkt); } // --------------------------------------------------------------------------- TEST(crs, GeographicCRS_is2DPartOf3D) { EXPECT_TRUE(GeographicCRS::EPSG_4326->is2DPartOf3D( NN_NO_CHECK(GeographicCRS::EPSG_4979.get()))); EXPECT_FALSE(GeographicCRS::EPSG_4326->is2DPartOf3D( NN_NO_CHECK(GeographicCRS::EPSG_4326.get()))); EXPECT_FALSE(GeographicCRS::EPSG_4979->is2DPartOf3D( NN_NO_CHECK(GeographicCRS::EPSG_4326.get()))); EXPECT_FALSE(GeographicCRS::EPSG_4979->is2DPartOf3D( NN_NO_CHECK(GeographicCRS::EPSG_4979.get()))); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4807_as_WKT2) { auto crs = GeographicCRS::EPSG_4807; WKTFormatterNNPtr f(WKTFormatter::create(WKTFormatter::Convention::WKT2)); crs->exportToWKT(f.get()); EXPECT_EQ( f->toString(), "GEODCRS[\"NTF (Paris)\",\n" " DATUM[\"Nouvelle Triangulation Francaise (Paris)\",\n" " ELLIPSOID[\"Clarke 1880 (IGN)\",6378249.2,293.466021293627,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Paris\",2.5969213,\n" " ANGLEUNIT[\"grad\",0.015707963267949]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"grad\",0.015707963267949]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"grad\",0.015707963267949]],\n" " ID[\"EPSG\",4807]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4807_as_WKT2_SIMPLIFIED) { auto crs = GeographicCRS::EPSG_4807; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_SIMPLIFIED)); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEODCRS[\"NTF (Paris)\",\n" " DATUM[\"Nouvelle Triangulation Francaise (Paris)\",\n" " ELLIPSOID[\"Clarke 1880 " "(IGN)\",6378249.2,293.466021293627]],\n" " PRIMEM[\"Paris\",2.5969213],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north],\n" " AXIS[\"longitude\",east],\n" " UNIT[\"grad\",0.015707963267949],\n" " ID[\"EPSG\",4807]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4807_as_WKT1_GDAL) { auto crs = GeographicCRS::EPSG_4807; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL)); crs->exportToWKT(f.get()); EXPECT_EQ( f->toString(), "GEOGCS[\"NTF (Paris)\",\n" " DATUM[\"Nouvelle_Triangulation_Francaise_Paris\",\n" " SPHEROID[\"Clarke 1880 (IGN)\",6378249.2,293.466021293627,\n" " AUTHORITY[\"EPSG\",\"7011\"]],\n" " AUTHORITY[\"EPSG\",\"6807\"]],\n" " PRIMEM[\"Paris\",2.33722917,\n" /* WKT1_GDAL weirdness: PRIMEM is converted to degree */ " AUTHORITY[\"EPSG\",\"8903\"]],\n" " UNIT[\"grad\",0.015707963267949,\n" " AUTHORITY[\"EPSG\",\"9105\"]],\n" " AUTHORITY[\"EPSG\",\"4807\"]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4807_as_WKT1_ESRI_with_database) { auto crs = GeographicCRS::EPSG_4807; WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"GCS_NTF_Paris\"," "DATUM[\"Nouvelle_Triangulation_Francaise_(Paris)\"," "SPHEROID[\"Clarke_1880_IGN\",6378249.2,293.466021293627]]," "PRIMEM[\"Paris\",2.33722917],UNIT[\"Grad\",0.015707963267949]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4807_as_WKT1_ESRI_without_database) { auto crs = GeographicCRS::EPSG_4807; WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI)); EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"GCS_NTF_Paris\",DATUM[\"D_Nouvelle_Triangulation_" "Francaise_Paris\",SPHEROID[\"Clarke_1880_IGN\",6378249.2,293." "466021293627]],PRIMEM[\"Paris\",2.33722917],UNIT[\"Grad\",0." "015707963267949]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4807_as_PROJ_string) { auto crs = GeographicCRS::EPSG_4807; EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +ellps=clrk80ign +pm=paris +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4267) { auto crs = GeographicCRS::EPSG_4267; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), "GEODCRS[\"NAD27\",\n" " DATUM[\"North American Datum 1927\",\n" " ELLIPSOID[\"Clarke 1866\",6378206.4,294.978698213898,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4267]]"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +datum=NAD27 +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4267_as_WKT1_ESRI_with_database) { auto crs = GeographicCRS::EPSG_4267; WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"GCS_North_American_1927\"," "DATUM[\"D_North_American_1927\",SPHEROID[\"Clarke_1866\"," "6378206.4,294.978698213898]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4269) { auto crs = GeographicCRS::EPSG_4269; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), "GEODCRS[\"NAD83\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4269]]"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +datum=NAD83 +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4268_geogcrs_deprecated_as_WKT1_GDAL) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("4268"); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL)); auto wkt = crs->exportToWKT(f.get()); EXPECT_TRUE(wkt.find("GEOGCS[\"NAD27 Michigan (deprecated)\"") == 0) << wkt; } // --------------------------------------------------------------------------- TEST(crs, ESRI_104971_as_WKT1_ESRI_with_database) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "ESRI"); auto crs = factory->createCoordinateReferenceSystem("104971"); WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); // Check that the _(Sphere) suffix is preserved EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"Mars_2000_(Sphere)\",DATUM[\"Mars_2000_(Sphere)\"," "SPHEROID[\"Mars_2000_(Sphere)\",3396190.0,0.0]]," "PRIMEM[\"Reference_Meridian\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"); } // --------------------------------------------------------------------------- TEST(crs, implicit_compound_ESRI_104024_plus_115844_as_WKT1_ESRI_with_database) { auto dbContext = DatabaseContext::create(); auto obj = createFromUserInput("ESRI:104024+115844", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); f->setAllowLINUNITNode(false); // Situation where there is no EPSG official name EXPECT_EQ(crs->exportToWKT(f.get()), "GEOGCS[\"California_SRS_Epoch_2017.50_(NAD83)\"," "DATUM[\"California_SRS_Epoch_2017.50_(NAD83)\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "VERTCS[\"California_SRS_Epoch_2017.50_(NAD83)\"," "DATUM[\"California_SRS_Epoch_2017.50_(NAD83)\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]]"); } // --------------------------------------------------------------------------- TEST(crs, implicit_compound_ESRI_104971_to_3D_as_WKT1_ESRI_with_database) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "ESRI"); auto crs = factory->createGeographicCRS("104971")->promoteTo3D( std::string(), dbContext); WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); f->setAllowLINUNITNode(false); // Situation where there is no ESRI vertical CRS, but the GEOGCS does exist // This will be only partly recognized by ESRI software. // See https://github.com/OSGeo/PROJ/issues/2757 const char *wkt = "GEOGCS[\"Mars_2000_(Sphere)\"," "DATUM[\"Mars_2000_(Sphere)\"," "SPHEROID[\"Mars_2000_(Sphere)\",3396190.0,0.0]]," "PRIMEM[\"Reference_Meridian\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "VERTCS[\"Mars_2000_(Sphere)\"," "DATUM[\"Mars_2000_(Sphere)\"," "SPHEROID[\"Mars_2000_(Sphere)\",3396190.0,0.0]]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT(f.get()), wkt); auto obj2 = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs2 = nn_dynamic_pointer_cast<GeographicCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); EXPECT_EQ(crs2->coordinateSystem()->axisList().size(), 3U); } // --------------------------------------------------------------------------- TEST(crs, IAU_1000_as_WKT2) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "IAU_2015"); auto crs = factory->createCoordinateReferenceSystem("1000"); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019, dbContext)); auto wkt = crs->exportToWKT(f.get()); // Check that IAU_2015 is split into a authority name and version EXPECT_TRUE(wkt.find("ID[\"IAU\",1000,2015]") != std::string::npos) << wkt; auto obj = createFromUserInput(wkt, dbContext); auto crs2 = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(crs2 != nullptr); auto wkt2 = crs2->exportToWKT(f.get()); // Check that IAU_2015 is split into a authority name and version EXPECT_TRUE(wkt2.find("ID[\"IAU\",1000,2015]") != std::string::npos) << wkt2; } // --------------------------------------------------------------------------- TEST(crs, IAU_1000_as_PROJJSON) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "IAU_2015"); auto crs = factory->createCoordinateReferenceSystem("1000"); auto projjson = crs->exportToJSON(JSONFormatter::create(dbContext).get()); // Check that IAU_2015 is split into a authority name and version EXPECT_TRUE(projjson.find("\"authority\": \"IAU\",") != std::string::npos) << projjson; EXPECT_TRUE(projjson.find("\"code\": 1000,") != std::string::npos) << projjson; EXPECT_TRUE(projjson.find("\"version\": 2015") != std::string::npos) << projjson; auto obj = createFromUserInput(projjson, dbContext); auto crs2 = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(crs2 != nullptr); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019, dbContext)); auto wkt2 = crs2->exportToWKT(f.get()); // Check that IAU_2015 is split into a authority name and version EXPECT_TRUE(wkt2.find("ID[\"IAU\",1000,2015]") != std::string::npos) << wkt2; } // --------------------------------------------------------------------------- TEST(crs, EPSG_2008_projcrs_deprecated_as_WKT1_GDAL) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("2008"); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL)); auto wkt = crs->exportToWKT(f.get()); EXPECT_TRUE( wkt.find("PROJCS[\"NAD27(CGQ77) / SCoPQ zone 2 (deprecated)\"") == 0) << wkt; } // --------------------------------------------------------------------------- TEST(crs, EPSG_27561_projected_with_geodetic_in_grad_as_PROJ_string_and_WKT1) { auto obj = WKTParser().createFromWKT( "PROJCRS[\"NTF (Paris) / Lambert Nord France\",\n" " BASEGEODCRS[\"NTF (Paris)\",\n" " DATUM[\"Nouvelle Triangulation Francaise (Paris)\",\n" " ELLIPSOID[\"Clarke 1880 " "(IGN)\",6378249.2,293.4660213,LENGTHUNIT[\"metre\",1.0]]],\n" " PRIMEM[\"Paris\",2.5969213,ANGLEUNIT[\"grad\",0.015707963268]]],\n" " CONVERSION[\"Lambert Nord France\",\n" " METHOD[\"Lambert Conic Conformal (1SP)\",ID[\"EPSG\",9801]],\n" " PARAMETER[\"Latitude of natural " "origin\",55,ANGLEUNIT[\"grad\",0.015707963268]],\n" " PARAMETER[\"Longitude of natural " "origin\",0,ANGLEUNIT[\"grad\",0.015707963268]],\n" " PARAMETER[\"Scale factor at natural " "origin\",0.999877341,SCALEUNIT[\"unity\",1.0]],\n" " PARAMETER[\"False easting\",600000,LENGTHUNIT[\"metre\",1.0]],\n" " PARAMETER[\"False northing\",200000,LENGTHUNIT[\"metre\",1.0]]],\n" " CS[cartesian,2],\n" " AXIS[\"easting (X)\",east,ORDER[1]],\n" " AXIS[\"northing (Y)\",north,ORDER[2]],\n" " LENGTHUNIT[\"metre\",1.0],\n" " ID[\"EPSG\",27561]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=lcc +lat_1=49.5 +lat_0=49.5 +lon_0=0 +k_0=0.999877341 " "+x_0=600000 +y_0=200000 +ellps=clrk80ign +pm=paris +units=m " "+no_defs +type=crs"); auto nn_crs = NN_CHECK_ASSERT(crs); EXPECT_TRUE(nn_crs->isEquivalentTo(nn_crs.get())); EXPECT_FALSE(nn_crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_FALSE( nn_crs->DerivedCRS::isEquivalentTo(createUnrelatedObject().get())); auto wkt1 = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, DatabaseContext::create()) .get()); EXPECT_EQ( wkt1, "PROJCS[\"NTF (Paris) / Lambert Nord France\",\n" " GEOGCS[\"NTF (Paris)\",\n" " DATUM[\"Nouvelle_Triangulation_Francaise_Paris\",\n" " SPHEROID[\"Clarke 1880 (IGN)\",6378249.2,293.4660213]],\n" " PRIMEM[\"Paris\",2.33722917000759],\n" " UNIT[\"grad\",0.015707963268]],\n" " PROJECTION[\"Lambert_Conformal_Conic_1SP\"],\n" " PARAMETER[\"latitude_of_origin\",55],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"scale_factor\",0.999877341],\n" " PARAMETER[\"false_easting\",600000],\n" " PARAMETER[\"false_northing\",200000],\n" " UNIT[\"metre\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"27561\"]]"); auto wkt1_esri = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()); EXPECT_EQ(wkt1_esri, "PROJCS[\"NTF_Paris_Lambert_Nord_France\"," "GEOGCS[\"GCS_NTF_Paris\"," "DATUM[\"Nouvelle_Triangulation_Francaise_(Paris)\"," "SPHEROID[\"Clarke_1880_IGN\",6378249.2,293.4660213]]," "PRIMEM[\"Paris\",2.33722917000759]," "UNIT[\"Grad\",0.015707963268]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",600000.0]," "PARAMETER[\"False_Northing\",200000.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",55.0]," "PARAMETER[\"Scale_Factor\",0.999877341]," "PARAMETER[\"Latitude_Of_Origin\",55.0]," "UNIT[\"Meter\",1.0]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_3040_projected_northing_easting_as_PROJ_string) { auto obj = WKTParser().createFromWKT( "PROJCRS[\"ETRS89 / UTM zone 28N (N-E)\",\n" " BASEGEODCRS[\"ETRS89\",\n" " DATUM[\"European Terrestrial Reference System 1989\",\n" " ELLIPSOID[\"GRS " "1980\",6378137,298.257222101,LENGTHUNIT[\"metre\",1.0]]]],\n" " CONVERSION[\"UTM zone 28N\",\n" " METHOD[\"Transverse Mercator\",ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural " "origin\",0,ANGLEUNIT[\"degree\",0.01745329252]],\n" " PARAMETER[\"Longitude of natural " "origin\",-15,ANGLEUNIT[\"degree\",0.01745329252]],\n" " PARAMETER[\"Scale factor at natural " "origin\",0.9996,SCALEUNIT[\"unity\",1.0]],\n" " PARAMETER[\"False easting\",500000,LENGTHUNIT[\"metre\",1.0]],\n" " PARAMETER[\"False northing\",0,LENGTHUNIT[\"metre\",1.0]]],\n" " CS[cartesian,2],\n" " AXIS[\"northing (N)\",north,ORDER[1]],\n" " AXIS[\"easting (E)\",east,ORDER[2]],\n" " LENGTHUNIT[\"metre\",1.0],\n" " ID[\"EPSG\",3040]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=28 +ellps=GRS80 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_2222_projected_unit_foot_as_PROJ_string_and_WKT1) { auto obj = WKTParser().createFromWKT( "PROJCRS[\"NAD83 / Arizona East (ft)\",\n" " BASEGEODCRS[\"NAD83\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS " "1980\",6378137,298.257222101,LENGTHUNIT[\"metre\",1.0]]]],\n" " CONVERSION[\"SPCS83 Arizona East zone (International feet)\",\n" " METHOD[\"Transverse Mercator\",ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural " "origin\",31,ANGLEUNIT[\"degree\",0.01745329252]],\n" " PARAMETER[\"Longitude of natural " "origin\",-110.166666666667,ANGLEUNIT[\"degree\",0.01745329252]],\n" " PARAMETER[\"Scale factor at natural " "origin\",0.9999,SCALEUNIT[\"unity\",1.0]],\n" " PARAMETER[\"False easting\",700000,LENGTHUNIT[\"foot\",0.3048]],\n" " PARAMETER[\"False northing\",0,LENGTHUNIT[\"foot\",0.3048]]],\n" " CS[cartesian,2],\n" " AXIS[\"easting (X)\",east,ORDER[1]],\n" " AXIS[\"northing (Y)\",north,ORDER[2]],\n" " LENGTHUNIT[\"foot\",0.3048],\n" " ID[\"EPSG\",2222]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=tmerc +lat_0=31 +lon_0=-110.166666666667 +k=0.9999 " "+x_0=213360 +y_0=0 +datum=NAD83 +units=ft +no_defs +type=crs"); auto wkt1 = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, DatabaseContext::create()) .get()); EXPECT_EQ(wkt1, "PROJCS[\"NAD83 / Arizona East (ft)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",31],\n" " PARAMETER[\"central_meridian\",-110.166666666667],\n" " PARAMETER[\"scale_factor\",0.9999],\n" " PARAMETER[\"false_easting\",700000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"foot\",0.3048],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"2222\"]]"); } // --------------------------------------------------------------------------- TEST(crs, projected_with_parameter_unit_different_than_cs_unit_as_WKT1) { auto obj = WKTParser().createFromWKT( "PROJCRS[\"unknown\"," " BASEGEODCRS[\"unknown\"," " DATUM[\"Unknown based on GRS80 ellipsoid\"," " ELLIPSOID[\"GRS 1980\",6378137,298.257222101," " LENGTHUNIT[\"metre\",1]]]," " PRIMEM[\"Greenwich\",0]]," " CONVERSION[\"UTM zone 32N\"," " METHOD[\"Transverse Mercator\"]," " PARAMETER[\"Latitude of natural origin\",0]," " PARAMETER[\"Longitude of natural origin\",9]," " PARAMETER[\"Scale factor at natural origin\",0.9996]," " PARAMETER[\"False easting\",500000,LENGTHUNIT[\"metre\",1]]," " PARAMETER[\"False northing\",0,LENGTHUNIT[\"metre\",1]]]," " CS[Cartesian,2]," " AXIS[\"(E)\",east]," " AXIS[\"(N)\",north]," " LENGTHUNIT[\"US survey foot\",0.304800609601219]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto wkt1 = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, DatabaseContext::create()) .get()); EXPECT_EQ(wkt1, "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"Unknown based on GRS80 ellipsoid\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",9],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",1640416.66666667],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"US survey foot\",0.304800609601219],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_32661_projected_north_pole_north_east) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("32661"); auto proj_crs = nn_dynamic_pointer_cast<ProjectedCRS>(crs); ASSERT_TRUE(proj_crs != nullptr); auto proj_string = "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=stere " "+lat_0=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84 +step +proj=axisswap +order=2,1"; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(proj_crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), proj_string); auto opNormalized = op->normalizeForVisualization(); auto proj_string_normalized = "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step " "+proj=stere +lat_0=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84"; EXPECT_EQ( opNormalized->exportToPROJString(PROJStringFormatter::create().get()), proj_string_normalized); EXPECT_EQ(opNormalized->sourceCRS()->domains().size(), 1U); EXPECT_EQ(opNormalized->sourceCRS()->remarks(), "Axis order reversed compared to EPSG:4326"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_5041_projected_north_pole_east_north) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("5041"); auto proj_crs = nn_dynamic_pointer_cast<ProjectedCRS>(crs); ASSERT_TRUE(proj_crs != nullptr); auto proj_string = "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=stere " "+lat_0=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84"; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(proj_crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), proj_string); auto opNormalized = op->normalizeForVisualization(); auto proj_string_normalized = "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step " "+proj=stere +lat_0=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84"; EXPECT_EQ( opNormalized->exportToPROJString(PROJStringFormatter::create().get()), proj_string_normalized); } // --------------------------------------------------------------------------- TEST(crs, EPSG_32761_projected_south_pole_north_east) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("32761"); auto proj_crs = nn_dynamic_pointer_cast<ProjectedCRS>(crs); ASSERT_TRUE(proj_crs != nullptr); auto proj_string = "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=stere " "+lat_0=-90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84 +step +proj=axisswap +order=2,1"; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(proj_crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), proj_string); auto opNormalized = op->normalizeForVisualization(); auto proj_string_normalized = "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step " "+proj=stere +lat_0=-90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84"; EXPECT_EQ( opNormalized->exportToPROJString(PROJStringFormatter::create().get()), proj_string_normalized); } // --------------------------------------------------------------------------- TEST(crs, EPSG_5042_projected_south_pole_east_north) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("5042"); auto proj_crs = nn_dynamic_pointer_cast<ProjectedCRS>(crs); ASSERT_TRUE(proj_crs != nullptr); auto proj_string = "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=stere " "+lat_0=-90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84"; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(proj_crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), proj_string); auto opNormalized = op->normalizeForVisualization(); auto proj_string_normalized = "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step " "+proj=stere +lat_0=-90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 " "+ellps=WGS84"; EXPECT_EQ( opNormalized->exportToPROJString(PROJStringFormatter::create().get()), proj_string_normalized); } // --------------------------------------------------------------------------- TEST(crs, EPSG_5482_projected_south_pole_south_west) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factory->createCoordinateReferenceSystem("5482"); auto proj_crs = nn_dynamic_pointer_cast<ProjectedCRS>(crs); ASSERT_TRUE(proj_crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( factory->createCoordinateReferenceSystem("4764"), NN_NO_CHECK(proj_crs)); ASSERT_TRUE(op != nullptr); auto proj_string = "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=stere +lat_0=-90 +lon_0=180 +k=0.994 " "+x_0=5000000 +y_0=1000000 +ellps=GRS80 " "+step +proj=axisswap +order=2,1"; EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), proj_string); auto opNormalized = op->normalizeForVisualization(); auto proj_string_normalized = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=stere +lat_0=-90 +lon_0=180 +k=0.994 " "+x_0=5000000 +y_0=1000000 +ellps=GRS80"; EXPECT_EQ( opNormalized->exportToPROJString(PROJStringFormatter::create().get()), proj_string_normalized); } // --------------------------------------------------------------------------- TEST(crs, geodetic_crs_both_datum_datum_ensemble_null) { EXPECT_THROW(GeodeticCRS::create( PropertyMap(), nullptr, nullptr, CartesianCS::createGeocentric(UnitOfMeasure::METRE)), Exception); } // --------------------------------------------------------------------------- TEST(crs, geodetic_crs_both_datum_datum_ensemble_non_null) { auto ensemble = DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{GeodeticReferenceFrame::EPSG_6326, GeodeticReferenceFrame::EPSG_6326}, PositionalAccuracy::create("100")); EXPECT_THROW(GeodeticCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, ensemble, CartesianCS::createGeocentric(UnitOfMeasure::METRE)), Exception); } // --------------------------------------------------------------------------- static GeodeticCRSNNPtr createGeocentric() { PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 4328) .set(IdentifiedObject::NAME_KEY, "WGS 84"); return GeodeticCRS::create( propertiesCRS, GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(crs, geocentricCRS_as_WKT2) { auto crs = createGeocentric(); auto expected = "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4328]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), expected); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(crs, geocentricCRS_as_WKT2_simplified) { auto crs = createGeocentric(); auto expected = "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX],\n" " AXIS[\"(Y)\",geocentricY],\n" " AXIS[\"(Z)\",geocentricZ],\n" " UNIT[\"metre\",1],\n" " ID[\"EPSG\",4328]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create( WKTFormatter::Convention::WKT2_SIMPLIFIED) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, geocentricCRS_as_WKT1_GDAL) { auto crs = createGeocentric(); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL)); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEOCCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Geocentric X\",OTHER],\n" " AXIS[\"Geocentric Y\",OTHER],\n" " AXIS[\"Geocentric Z\",NORTH],\n" " AUTHORITY[\"EPSG\",\"4328\"]]"); } // --------------------------------------------------------------------------- TEST(crs, EPSG_4978_as_WKT1_GDAL_with_database) { auto crs = GeodeticCRS::EPSG_4978; auto wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, DatabaseContext::create()) .get()); EXPECT_EQ(wkt, "GEOCCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Geocentric X\",OTHER],\n" " AXIS[\"Geocentric Y\",OTHER],\n" " AXIS[\"Geocentric Z\",NORTH],\n" " AUTHORITY[\"EPSG\",\"4978\"]]"); } // --------------------------------------------------------------------------- TEST(crs, geocentricCRS_as_PROJ_string) { auto crs = createGeocentric(); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=geocent +datum=WGS84 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, geocentricCRS_non_meter_unit_as_PROJ_string) { auto crs = GeodeticCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric( UnitOfMeasure("kilometre", 1000.0, UnitOfMeasure::Type::LINEAR))); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, crs); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=cart " "+ellps=WGS84 +step +proj=unitconvert +xy_in=m +z_in=m " "+xy_out=km +z_out=km"); EXPECT_THROW(crs->exportToPROJString(PROJStringFormatter::create().get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, geocentricCRS_unsupported_unit_as_PROJ_string) { auto crs = GeodeticCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric( UnitOfMeasure("my unit", 500.0, UnitOfMeasure::Type::LINEAR))); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, crs); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=cart " "+ellps=WGS84 +step +proj=unitconvert +xy_in=m +z_in=m " "+xy_out=500 +z_out=500"); } // --------------------------------------------------------------------------- TEST(crs, geodeticcrs_identify_no_db) { { auto res = GeodeticCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, nullptr, CartesianCS::createGeocentric(UnitOfMeasure::METRE)) ->identify(nullptr); ASSERT_EQ(res.size(), 0U); } { auto res = GeographicCRS::EPSG_4326->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 100); } { // Using virtual method auto res = static_cast<const CRS *>(GeographicCRS::EPSG_4326.get()) ->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 100); } { auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS 84"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 100); } { auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS84"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 90); } { // Long Lat order auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS 84"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLongitudeLatitude(UnitOfMeasure::DEGREE)) ->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 25); } { // WKT1 identification auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT( "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\"," "6378137,298.257223563]],PRIMEM[\"Greenwich\",0]," "UNIT[\"Degree\",0.0174532925199433]]"); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 100); } } // --------------------------------------------------------------------------- TEST(crs, geodeticcrs_identify_db) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); { // No match auto res = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::create( PropertyMap(), Ellipsoid::createFlattenedSphere( PropertyMap(), Length(6378137), Scale(10)), optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(nullptr); ASSERT_EQ(res.size(), 0U); } { // Identify by datum code auto res = GeodeticCRS::create( PropertyMap(), GeodeticReferenceFrame::EPSG_6326, nullptr, CartesianCS::createGeocentric(UnitOfMeasure::METRE)) ->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4978); EXPECT_EQ(res.front().second, 70); } { // Identify by datum code auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 70); } { // Identify by datum code (as a fallback) auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "foobar"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 70); } { // Perfect match, and ID available. Hardcoded case auto res = GeographicCRS::EPSG_4326->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 100); } { // Perfect match, but no ID available. Hardcoded case auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS 84"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first.get(), GeographicCRS::EPSG_4326.get()); EXPECT_EQ(res.front().second, 100); } { // Perfect match, but no ID available auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "NTF (Paris)"), GeographicCRS::EPSG_4807->datum(), nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::GRAD)) ->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4807); EXPECT_EQ(res.front().second, 100); } { // Perfect match, and ID available auto res = GeographicCRS::EPSG_4807->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4807); EXPECT_EQ(res.front().second, 100); } { // The object has an unexisting ID auto res = GeographicCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "NTF (Paris)") .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 1), GeographicCRS::EPSG_4807->datum(), nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::GRAD)) ->identify(factory); ASSERT_EQ(res.size(), 0U); } { // The object has a unreliable ID auto res = GeographicCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "NTF (Paris)") .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 4326), GeographicCRS::EPSG_4807->datum(), nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::GRAD)) ->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 25); } { // Approximate match by name auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS84"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 90); } { // Long Lat order auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS 84"), GeodeticReferenceFrame::EPSG_6326, nullptr, EllipsoidalCS::createLongitudeLatitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_EQ(res.size(), 3U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 25); } { // Identify by ellipsoid code auto res = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::create(PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_GT(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 60.0); } { // Identify by ellipsoid code (as a fallback) auto res = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), GeodeticReferenceFrame::create(PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_GT(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 60.0); } { // Identify by ellipsoid description auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=6378521.049 +rf=298.257222100883 +axis=neu " "+type=crs"); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); EXPECT_EQ(res.size(), 5U); } { // Identify by name, without any code auto wkt = "GEODCRS[\"GCS_Datum_Lisboa_Bessel\",\n" " DATUM[\"D_Datum_Lisboa_Bessel\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_EQ(res.size(), 1U); ASSERT_TRUE(!res.front().first->identifiers().empty()); EXPECT_EQ(*res.front().first->identifiers()[0]->codeSpace(), "ESRI"); EXPECT_EQ(res.front().first->identifiers()[0]->code(), "104105"); EXPECT_EQ(res.front().second, 100); } { // Identification by non-existing code auto res = GeographicCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "foobar") .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, "i_dont_exist"), GeodeticReferenceFrame::create( PropertyMap(), Ellipsoid::createFlattenedSphere( PropertyMap(), Length(6378137), Scale(10)), optional<std::string>(), PrimeMeridian::GREENWICH), nullptr, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)) ->identify(factory); ASSERT_EQ(res.size(), 0U); } { // Test identification from PROJ string auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); ASSERT_TRUE(!res.front().first->identifiers().empty()); EXPECT_EQ(*res.front().first->identifiers()[0]->codeSpace(), "EPSG"); EXPECT_EQ(res.front().first->identifiers()[0]->code(), "4326"); EXPECT_EQ(res.front().second, 70); } { // Test identification from PROJ string with just the ellipsoid auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); bool foundGDA2020 = false; for (const auto &pair : res) { // one among many others... if (pair.first->getEPSGCode() == 7844) { foundGDA2020 = true; EXPECT_EQ(pair.second, 60); } } EXPECT_TRUE(foundGDA2020); } { // Identify by code, but datum name is an alias of the official one auto wkt = "GEOGCRS[\"GDA2020\",\n" " DATUM[\"GDA2020\",\n" " ELLIPSOID[\"GRS_1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",7844]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_EQ(res.size(), 1U); ASSERT_TRUE(!res.front().first->identifiers().empty()); EXPECT_EQ(*res.front().first->identifiers()[0]->codeSpace(), "EPSG"); EXPECT_EQ(res.front().first->identifiers()[0]->code(), "7844"); EXPECT_EQ(res.front().second, 100); EXPECT_TRUE(crs->_isEquivalentTo(res.front().first.get(), IComparable::Criterion::EQUIVALENT, dbContext)); EXPECT_TRUE(res.front().first->_isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT, dbContext)); } { // Identify by name, but datum name is an alias of the official one auto wkt = "GEOGCRS[\"GDA2020\",\n" " DATUM[\"GDA2020\",\n" " ELLIPSOID[\"GRS_1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_EQ(res.size(), 1U); ASSERT_TRUE(!res.front().first->identifiers().empty()); EXPECT_EQ(*res.front().first->identifiers()[0]->codeSpace(), "EPSG"); EXPECT_EQ(res.front().first->identifiers()[0]->code(), "7844"); EXPECT_EQ(res.front().second, 100); EXPECT_TRUE(crs->_isEquivalentTo(res.front().first.get(), IComparable::Criterion::EQUIVALENT, dbContext)); EXPECT_TRUE(res.front().first->_isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT, dbContext)); } { // Identify "a" ESRI WKT representation of GDA2020. See #1911 auto wkt = "GEOGCS[\"GDA2020\",DATUM[\"D_GDA2020\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.017453292519943295]]"; auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_EQ(res.size(), 1U); ASSERT_TRUE(!res.front().first->identifiers().empty()); EXPECT_EQ(*res.front().first->identifiers()[0]->codeSpace(), "EPSG"); EXPECT_EQ(res.front().first->identifiers()[0]->code(), "7844"); EXPECT_EQ(res.front().second, 100); } { // Identify with DatumEnsemble auto wkt = "GEOGCRS[\"WGS 84\"," " ENSEMBLE[\"World Geodetic System 1984 ensemble\"," " MEMBER[\"World Geodetic System 1984 (Transit)\"," " ID[\"EPSG\",1166]]," " MEMBER[\"World Geodetic System 1984 (G730)\"," " ID[\"EPSG\",1152]]," " MEMBER[\"World Geodetic System 1984 (G873)\"," " ID[\"EPSG\",1153]]," " MEMBER[\"World Geodetic System 1984 (G1150)\"," " ID[\"EPSG\",1154]]," " MEMBER[\"World Geodetic System 1984 (G1674)\"," " ID[\"EPSG\",1155]]," " MEMBER[\"World Geodetic System 1984 (G1762)\"," " ID[\"EPSG\",1156]]," " ELLIPSOID[\"WGS 84\",6378137,298.257223563," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]," " ID[\"EPSG\",7030]]," " ENSEMBLEACCURACY[2]]," " PRIMEM[\"Greenwich\",0," " ANGLEUNIT[\"degree\",0.0174532925199433,ID[\"EPSG\",9102]]," " ID[\"EPSG\",8901]]," " CS[ellipsoidal,2," " ID[\"EPSG\",6422]]," " AXIS[\"Geodetic latitude (Lat)\",north," " ORDER[1]]," " AXIS[\"Geodetic longitude (Lon)\",east," " ORDER[2]]," " ANGLEUNIT[\"degree (supplier to define representation)\"," "0.0174532925199433,ID[\"EPSG\",9122]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 100.0); } { // Identify with DatumEnsemble and unknown CRS name auto wkt = "GEOGCRS[\"unknown\"," " ENSEMBLE[\"World Geodetic System 1984 ensemble\"," " MEMBER[\"World Geodetic System 1984 (Transit)\"," " ID[\"EPSG\",1166]]," " MEMBER[\"World Geodetic System 1984 (G730)\"," " ID[\"EPSG\",1152]]," " MEMBER[\"World Geodetic System 1984 (G873)\"," " ID[\"EPSG\",1153]]," " MEMBER[\"World Geodetic System 1984 (G1150)\"," " ID[\"EPSG\",1154]]," " MEMBER[\"World Geodetic System 1984 (G1674)\"," " ID[\"EPSG\",1155]]," " MEMBER[\"World Geodetic System 1984 (G1762)\"," " ID[\"EPSG\",1156]]," " ELLIPSOID[\"WGS 84\",6378137,298.257223563," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]," " ID[\"EPSG\",7030]]," " ENSEMBLEACCURACY[2]]," " PRIMEM[\"Greenwich\",0," " ANGLEUNIT[\"degree\",0.0174532925199433,ID[\"EPSG\",9102]]," " ID[\"EPSG\",8901]]," " CS[ellipsoidal,2," " ID[\"EPSG\",6422]]," " AXIS[\"Geodetic latitude (Lat)\",north," " ORDER[1]]," " AXIS[\"Geodetic longitude (Lon)\",east," " ORDER[2]]," " ANGLEUNIT[\"degree (supplier to define representation)\"," "0.0174532925199433,ID[\"EPSG\",9122]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 4326); EXPECT_EQ(res.front().second, 70.0); } } // --------------------------------------------------------------------------- static ProjectedCRSNNPtr createProjected() { PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 32631) .set(IdentifiedObject::NAME_KEY, "WGS 84 / UTM zone 31N"); return ProjectedCRS::create( propertiesCRS, GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_derivingConversion) { auto crs = createProjected(); auto conv = crs->derivingConversion(); EXPECT_TRUE(conv->sourceCRS() != nullptr); ASSERT_TRUE(conv->targetCRS() != nullptr); EXPECT_EQ(conv->targetCRS().get(), crs.get()); // derivingConversion() returns a copy of the internal conversion auto targetCRSAsProjCRS = std::dynamic_pointer_cast<ProjectedCRS>(conv->targetCRS()); ASSERT_TRUE(targetCRSAsProjCRS != nullptr); EXPECT_NE(targetCRSAsProjCRS->derivingConversion(), conv); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_shallowClone) { { auto crs = createProjected(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); auto clone = nn_dynamic_pointer_cast<ProjectedCRS>(crs->shallowClone()); EXPECT_TRUE(clone->isEquivalentTo(crs.get())); EXPECT_EQ(clone->derivingConversion()->targetCRS().get(), clone.get()); } { ProjectedCRSPtr clone; { auto crs = ProjectedCRS::create( PropertyMap(), createGeocentric(), Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); clone = nn_dynamic_pointer_cast<ProjectedCRS>(crs->shallowClone()); } EXPECT_EQ(clone->baseCRS()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=geocent +datum=WGS84 +units=m +no_defs +type=crs"); } } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_as_WKT2) { auto crs = createProjected(); auto expected = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",32631]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), expected); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_as_WKT2_2019) { auto crs = createProjected(); auto expected = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",32631]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_as_WKT2_simplified) { auto crs = createProjected(); auto expected = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\"],\n" " PARAMETER[\"Latitude of natural origin\",0],\n" " PARAMETER[\"Longitude of natural origin\",3],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996],\n" " PARAMETER[\"False easting\",500000],\n" " PARAMETER[\"False northing\",0]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1],\n" " ID[\"EPSG\",32631]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create( WKTFormatter::Convention::WKT2_SIMPLIFIED) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_as_WKT2_2019_simplified) { auto crs = createProjected(); auto expected = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\"],\n" " PARAMETER[\"Latitude of natural origin\",0],\n" " PARAMETER[\"Longitude of natural origin\",3],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996],\n" " PARAMETER[\"False easting\",500000],\n" " PARAMETER[\"False northing\",0]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1],\n" " ID[\"EPSG\",32631]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019_SIMPLIFIED) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_as_WKT1_GDAL) { auto crs = createProjected(); auto expected = "PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), expected); EXPECT_EQ(crs->exportToWKT( &(WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL) ->setOutputAxis(WKTFormatter::OutputAxisRule::YES))), expected); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_as_WKT1_ESRI) { auto crs = createProjected(); auto expected = "PROJCS[\"WGS_1984_UTM_Zone_31N\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0," "298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"False_Easting\",500000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",3.0]," "PARAMETER[\"Scale_Factor\",0.9996]," "PARAMETER[\"Latitude_Of_Origin\",0.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_3D_as_WKT1_GDAL_with_ellipsoidal_height_as_vertical_crs) { auto dbContext = DatabaseContext::create(); auto crs = AuthorityFactory::create(dbContext, "EPSG") ->createProjectedCRS("32631") ->promoteTo3D(std::string(), dbContext); auto wkt = crs->exportToWKT( &(WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, dbContext) ->setAllowEllipsoidalHeightAsVerticalCRS(true))); // For LAS 1.4 WKT1... EXPECT_EQ(wkt, "COMPD_CS[\"WGS 84 / UTM zone 31N + Ellipsoid (metre)\",\n" " PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]],\n" " VERT_CS[\"Ellipsoid (metre)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Ellipsoidal height\",UP]]]"); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_with_other_deprecated_crs_of_same_name_as_WKT1_ESRI) { auto dbContext = DatabaseContext::create(); // EPSG:3800 is the non-deprecated version of EPSG:3774 // This used to cause an issue when looking for the ESRI CRS name auto crs = AuthorityFactory::create(dbContext, "EPSG")->createProjectedCRS("3800"); auto esri_wkt = "PROJCS[\"NAD_1927_3TM_120\",GEOGCS[\"GCS_North_American_1927\"," "DATUM[\"D_North_American_1927\"," "SPHEROID[\"Clarke_1866\",6378206.4,294.978698213898]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",-120.0]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), esri_wkt); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(esri_wkt); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs2 != nullptr); EXPECT_EQ(crs2->nameStr(), "NAD27 / Alberta 3TM ref merid 120 W"); EXPECT_EQ( crs2->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), esri_wkt); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_with_ESRI_code_as_WKT1_ESRI) { auto dbContext = DatabaseContext::create(); auto crs = AuthorityFactory::create(dbContext, "ESRI") ->createProjectedCRS("102113"); // Comes literally from the text_definition column of // projected_crs table auto esri_wkt = "PROJCS[\"WGS_1984_Web_Mercator\"," "GEOGCS[\"GCS_WGS_1984_Major_Auxiliary_Sphere\"," "DATUM[\"D_WGS_1984_Major_Auxiliary_Sphere\"," "SPHEROID[\"WGS_1984_Major_Auxiliary_Sphere\",6378137.0,0.0]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Mercator\"],PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",0.0],UNIT[\"Meter\",1.0]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), esri_wkt); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_from_WKT1_ESRI_as_WKT1_ESRI) { auto dbContext = DatabaseContext::create(); // Comes literally from the text_definition column of // projected_crs table auto esri_wkt = "PROJCS[\"WGS_1984_Web_Mercator\"," "GEOGCS[\"GCS_WGS_1984_Major_Auxiliary_Sphere\"," "DATUM[\"D_WGS_1984_Major_Auxiliary_Sphere\"," "SPHEROID[\"WGS_1984_Major_Auxiliary_Sphere\",6378137.0,0.0]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Mercator\"],PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",0.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(esri_wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), esri_wkt); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_from_WKT1_ESRI_as_WKT1_ESRI_s_jtsk03_krovak_east_north) { // EPSG:8353 auto wkt = "PROJCS[\"S-JTSK_[JTSK03]_Krovak_East_North\"," "GEOGCS[\"S-JTSK_[JTSK03]\",DATUM[\"S-JTSK_[JTSK03]\"," "SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Krovak\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Pseudo_Standard_Parallel_1\",78.5]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Azimuth\",30.2881397527778]," "PARAMETER[\"Longitude_Of_Center\",24.8333333333333]," "PARAMETER[\"Latitude_Of_Center\",49.5]," "PARAMETER[\"X_Scale\",-1.0]," "PARAMETER[\"Y_Scale\",1.0]," "PARAMETER[\"XY_Plane_Rotation\",90.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected_wkt2 = "PROJCRS[\"S-JTSK [JTSK03] / Krovak East North\",\n" " BASEGEOGCRS[\"S-JTSK [JTSK03]\",\n" " DATUM[\"System of the Unified Trigonometrical Cadastral " "Network [JTSK03]\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",1201]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Krovak (North Orientated)\",\n" " ID[\"EPSG\",1041]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",24.8333333333333,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard " "parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019, dbContext) .get()), expected_wkt2); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_from_EPSG_as_WKT1_ESRI_s_jtsk03_krovak_east_north) { auto dbContext = DatabaseContext::create(); auto factoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); auto crs = factoryEPSG->createProjectedCRS("8353"); auto wkt = "PROJCS[\"S-JTSK_[JTSK03]_Krovak_East_North\"," "GEOGCS[\"S-JTSK_[JTSK03]\",DATUM[\"S-JTSK_[JTSK03]\"," "SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Krovak\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Pseudo_Standard_Parallel_1\",78.5]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Azimuth\",30.2881397527778]," "PARAMETER[\"Longitude_Of_Center\",24.8333333333333]," "PARAMETER[\"Latitude_Of_Center\",49.5]," "PARAMETER[\"X_Scale\",-1.0]," "PARAMETER[\"Y_Scale\",1.0]," "PARAMETER[\"XY_Plane_Rotation\",90.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_as_PROJ_string) { auto crs = createProjected(); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, crs); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=utm " "+zone=31 +ellps=WGS84"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_3D_is_WKT1_equivalent_to_WKT2) { auto dbContext = DatabaseContext::create(); // "Illegal" WKT1 with a Projected 3D CRS auto wkt1 = "PROJCS[\"WGS 84 / UTM zone 16N [EGM08-1]\"," "GEOGCS[\"WGS 84 / UTM zone 16N [EGM08-1]\"," "DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.257223563," "AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0.0000000000000000," "AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"Degree\",0.01745329251994329547," "AUTHORITY[\"EPSG\",\"9102\"]],AUTHORITY[\"EPSG\",\"32616\"]]," "UNIT[\"Meter\",1.00000000000000000000," "AUTHORITY[\"EPSG\",\"9001\"]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"latitude_of_origin\",0.0000000000000000]," "PARAMETER[\"central_meridian\",-87.0000000002777938]," "PARAMETER[\"scale_factor\",0.9996000000000000]," "PARAMETER[\"false_easting\",500000.000]," "PARAMETER[\"false_northing\",0.000]," "AXIS[\"Easting\",EAST]," "AXIS[\"Northing\",NORTH]," "AXIS[\"Height\",UP]," "AUTHORITY[\"EPSG\",\"32616\"]]"; auto obj = WKTParser() .setStrict(false) .attachDatabaseContext(dbContext) .createFromWKT(wkt1); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); auto wkt2 = crs->exportToWKT(f.get()); auto obj2 = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt2); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); EXPECT_TRUE(crs->isEquivalentTo( crs2.get(), IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS)); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_Krovak_EPSG_5221_as_PROJ_string) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createProjectedCRS("5221"); // 30deg 17' 17.30311'' = 30.28813975277777776 auto op = CoordinateOperationFactory::create()->createOperation( crs->baseCRS(), crs); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=longlat +ellps=bessel +pm=ferro " "+step +proj=krovak +lat_0=49.5 +lon_0=42.5 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 " "+ellps=bessel +pm=ferro"); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_Krovak_with_approximate_alpha_as_PROJ_string) { // 30deg 17' 17.303'' = 30.288139722222223 as used in GDAL WKT1 auto obj = PROJStringParser().createFromPROJString( "+proj=krovak +lat_0=49.5 +lon_0=42.5 +alpha=30.28813972222222 " "+k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +pm=ferro +units=m +no_defs " "+type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); auto op = CoordinateOperationFactory::create()->createOperation( crs->baseCRS(), NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=longlat +ellps=bessel +pm=ferro " "+step +proj=krovak +lat_0=49.5 +lon_0=42.5 " "+alpha=30.2881397222222 +k=0.9999 +x_0=0 +y_0=0 " "+ellps=bessel +pm=ferro"); } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_identify_no_db) { { // Hard-coded case: WGS 84 / UTM. No name auto res = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 1, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)) ->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 32601); EXPECT_EQ(res.front().second, 70); EXPECT_TRUE(res.front().first->isEquivalentTo( AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createProjectedCRS("32601") .get(), IComparable::Criterion::EQUIVALENT)); } { // Hard-coded case: WGS 84 / UTM (south). Exact name. // Using virtual method auto crs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WGS 84 / UTM zone 60S"), GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 60, false), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto res = static_cast<const CRS *>(crs.get())->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 32760); EXPECT_EQ(res.front().second, 100); EXPECT_TRUE(res.front().first->isEquivalentTo( AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createProjectedCRS("32760") .get(), IComparable::Criterion::EQUIVALENT)); } { // Hard-coded case: NAD27 / UTM. Approximate name. auto res = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "NAD27_UTM_zone_11N"), GeographicCRS::EPSG_4267, Conversion::createUTM(PropertyMap(), 11, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)) ->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 26711); EXPECT_EQ(res.front().second, 90); EXPECT_TRUE(res.front().first->isEquivalentTo( AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createProjectedCRS("26711") .get(), IComparable::Criterion::EQUIVALENT)); } { // Hard-coded case: NAD83 / UTM auto res = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4269, Conversion::createUTM(PropertyMap(), 11, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)) ->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 26911); EXPECT_EQ(res.front().second, 70); EXPECT_TRUE(res.front().first->isEquivalentTo( AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createProjectedCRS("26911") .get(), IComparable::Criterion::EQUIVALENT)); } { // Tolerance on axis order auto obj = PROJStringParser().createFromPROJString( "+proj=utm +zone=31 +datum=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(nullptr); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 32631); EXPECT_EQ(res.front().second, 70); EXPECT_TRUE(res.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS)); } } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_identify_db) { auto dbContext = DatabaseContext::create(); auto factoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); auto factoryIGNF = AuthorityFactory::create(dbContext, "IGNF"); auto factoryAnonymous = AuthorityFactory::create(dbContext, std::string()); { // Identify by existing code auto crs = factoryEPSG->createProjectedCRS("2172"); { auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2172); EXPECT_EQ(res.front().second, 100); } { auto res = crs->identify(factoryAnonymous); ASSERT_EQ(res.size(), 1U); } { auto res = crs->identify(factoryIGNF); ASSERT_EQ(res.size(), 0U); } } { // Identify by existing code auto crs = factoryIGNF->createProjectedCRS("ETRS89UTM28"); { auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 25828); EXPECT_EQ(res.front().second, 70); } } { // Non-existing code auto sourceCRS = factoryEPSG->createProjectedCRS("2172"); auto crs = ProjectedCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "Pulkovo 1942(58) / Poland zone II") .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 1), sourceCRS->baseCRS(), sourceCRS->derivingConversion(), sourceCRS->coordinateSystem()); auto res = crs->identify(factoryEPSG); EXPECT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2172); EXPECT_EQ(res.front().second, 70); } { // Existing code, but not matching content auto sourceCRS = factoryEPSG->createProjectedCRS("2172"); auto crs = ProjectedCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "Pulkovo 1942(58) / Poland zone II") .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 32631), sourceCRS->baseCRS(), sourceCRS->derivingConversion(), sourceCRS->coordinateSystem()); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2172); EXPECT_EQ(res.front().second, 70); } { // Identify by exact name auto sourceCRS = factoryEPSG->createProjectedCRS("2172"); auto crs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Pulkovo 1942(58) / Poland zone II"), sourceCRS->baseCRS(), sourceCRS->derivingConversion(), sourceCRS->coordinateSystem()); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2172); EXPECT_EQ(res.front().second, 100); } { // Identify by equivalent name auto sourceCRS = factoryEPSG->createProjectedCRS("2172"); auto crs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Pulkovo_1942_58_Poland_zone_II"), sourceCRS->baseCRS(), sourceCRS->derivingConversion(), sourceCRS->coordinateSystem()); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2172); EXPECT_EQ(res.front().second, 90); } { // Identify by properties auto sourceCRS = factoryEPSG->createProjectedCRS("2172"); auto crs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "i am a faked name"), sourceCRS->baseCRS(), sourceCRS->derivingConversion(), sourceCRS->coordinateSystem()); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2172); EXPECT_EQ(res.front().second, 70); } { // Identify by name, but objects aren't equivalent auto sourceCRS = factoryEPSG->createProjectedCRS("3375"); auto crs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Pulkovo 1942(58) / Poland zone II"), sourceCRS->baseCRS(), sourceCRS->derivingConversion(), sourceCRS->coordinateSystem()); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2172); EXPECT_EQ(res.front().second, 25); } { // Identify from a PROJ string auto obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=omerc " "+no_uoff +lat_0=4 +lonc=102.25 +alpha=323.025796466667 " "+gamma=323.130102361111 +k=0.99984 +x_0=804671 +y_0=0 " "+ellps=GRS80"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 3375); EXPECT_EQ(res.front().second, 70); } { // Identify from a PROJ string (with "wrong" axis order for the geodetic // part) auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +no_uoff +lat_0=4 +lonc=102.25 " "+alpha=323.025796466667 +gamma=323.130102361111 +k=0.99984 " "+x_0=804671 +y_0=0 +ellps=GRS80 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 3375); EXPECT_EQ(res.front().second, 70); } { // Identify from a WKT1 string wit explicit correct axis order auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"ETRS89 / UTM zone 32N (N-E)\",GEOGCS[\"ETRS89\"," "DATUM[\"European_Terrestrial_Reference_System_1989\"," "SPHEROID[\"GRS 1980\",6378137,298.257222101]]," "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"latitude_of_origin\",0]," "PARAMETER[\"central_meridian\",9]," "PARAMETER[\"scale_factor\",0.9996]," "PARAMETER[\"false_easting\",500000]," "PARAMETER[\"false_northing\",0]," "UNIT[\"metre\",1]," "AXIS[\"Northing\",NORTH],AXIS[\"Easting\",EAST]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 3044); EXPECT_EQ(res.front().second, 100); } { // Identify from a WKT1 string wit wrong axis order auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"ETRS89 / UTM zone 32N (N-E)\",GEOGCS[\"ETRS89\"," "DATUM[\"European_Terrestrial_Reference_System_1989\"," "SPHEROID[\"GRS 1980\",6378137,298.257222101]]," "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"latitude_of_origin\",0]," "PARAMETER[\"central_meridian\",9]," "PARAMETER[\"scale_factor\",0.9996]," "PARAMETER[\"false_easting\",500000]," "PARAMETER[\"false_northing\",0]," "UNIT[\"metre\",1]," "AXIS[\"Easting\",EAST], AXIS[\"Northing\",NORTH]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 3044); EXPECT_EQ(res.front().second, 50); } { // Identify from a WKT1 string, without explicit axis auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"ETRS89 / UTM zone 32N (N-E)\",GEOGCS[\"ETRS89\"," "DATUM[\"European_Terrestrial_Reference_System_1989\"," "SPHEROID[\"GRS 1980\",6378137,298.257222101]]," "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"latitude_of_origin\",0]," "PARAMETER[\"central_meridian\",9]," "PARAMETER[\"scale_factor\",0.9996]," "PARAMETER[\"false_easting\",500000]," "PARAMETER[\"false_northing\",0]," "UNIT[\"metre\",1]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 3044); EXPECT_EQ(res.front().second, 100); } { // Identify from a WKT ESRI with bad PROJCS and GEOGCS names. auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"Lambert Conformal Conic\",GEOGCS[\"grs80\"," "DATUM[\"D_North_American_1983\"," "SPHEROID[\"Geodetic_Reference_System_1980\"," "6378137,298.257222101]],PRIMEM[\"Greenwich\",0]," "UNIT[\"Degree\",0.017453292519943295]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"standard_parallel_1\",34.33333333333334]," "PARAMETER[\"standard_parallel_2\",36.16666666666666]," "PARAMETER[\"latitude_of_origin\",33.75]," "PARAMETER[\"central_meridian\",-79]," "PARAMETER[\"false_easting\",609601.22]," "PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 32119); EXPECT_EQ(res.front().second, 70); } { // No equivalent CRS to input one in result set auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +datum=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 0U); } { // ESRI:103729 definition as a PROJ string auto obj = PROJStringParser() .attachDatabaseContext(dbContext) .createFromPROJString( "+proj=lcc +lat_0=43.5 +lon_0=-93.95 " "+lat_1=43.5666666666667 " "+lat_2=43.8 +x_0=152400.30480061 +y_0=30480.0609601219 " "+a=6378521.049 +rf=298.257222100883 +units=us-ft " "+type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); EXPECT_GE(res.size(), 1U); bool found = false; for (const auto &pair : res) { if (pair.first->identifiers()[0]->code() == "103729") { found = true; EXPECT_EQ(pair.second, 70); break; } } EXPECT_TRUE(found); } { // EPSG:2327 as PROJ.4 string (so with easting, northing order whereas // official CRS is northing, easting) auto obj = PROJStringParser() .attachDatabaseContext(dbContext) .createFromPROJString( "+proj=tmerc +lat_0=0 +lon_0=75 +k=1 +x_0=13500000 +y_0=0 " "+a=6378140 +b=6356755.288157528 +units=m +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); EXPECT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2327); EXPECT_EQ(res.front().second, 70); } { // EPSG:6646 as PROJ.4 string, using clrk80 which is pretty generic auto obj = PROJStringParser() .attachDatabaseContext(dbContext) .createFromPROJString( "+proj=tmerc +lat_0=29.02626833333333 +lon_0=46.5 " "+k=0.9994 +x_0=800000 +y_0=0 +ellps=clrk80 " "+units=m +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); EXPECT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 6646); EXPECT_EQ(res.front().second, 70); } { // Identify from a WKT ESRI that has the same name has ESRI:102039 // but uses us-ft instead of metres! auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"USA_Contiguous_Albers_Equal_Area_Conic_USGS_version\"," "GEOGCS[\"GCS_North_American_1983\"," "DATUM[\"D_North_American_1983\",SPHEROID[\"GRS_1980\"," "6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Albers\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",-96.0]," "PARAMETER[\"Standard_Parallel_1\",29.5]," "PARAMETER[\"Standard_Parallel_2\",45.5]," "PARAMETER[\"Latitude_Of_Origin\",23.0]," "UNIT[\"Foot_US\",0.3048006096012192]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); EXPECT_GE(res.size(), 1U); bool found = false; for (const auto &pair : res) { if (pair.first->identifiers()[0]->code() == "102039") { found = true; EXPECT_EQ(pair.second, 50); break; } } EXPECT_TRUE(found); } { // Identify a ESRI WKT where the EPSG system has Northing/Easting order auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"NZGD2000_New_Zealand_Transverse_Mercator_2000\"," " GEOGCS[\"GCS_NZGD2000\"," " DATUM[\"New_Zealand_Geodetic_Datum_2000\"," " SPHEROID[\"GRS 1980\",6378137,298.2572221010042," " AUTHORITY[\"EPSG\",\"7019\"]]," " AUTHORITY[\"EPSG\",\"6167\"]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"degree\",0.0174532925199433]]," " PROJECTION[\"Transverse_Mercator\"]," " PARAMETER[\"latitude_of_origin\",0]," " PARAMETER[\"central_meridian\",173]," " PARAMETER[\"scale_factor\",0.9996]," " PARAMETER[\"false_easting\",1600000]," " PARAMETER[\"false_northing\",10000000]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2193); EXPECT_EQ(res.front().second, 90); } { // Special case for https://github.com/OSGeo/PROJ/issues/2086 // The name of the CRS to identify is // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501 // whereas it should be // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501_Feet auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501\"," "GEOGCS[\"GCS_North_American_1983_HARN\"," "DATUM[\"D_North_American_1983_HARN\",SPHEROID[\"GRS_1980\"," "6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",3000000.000316083]," "PARAMETER[\"False_Northing\",999999.999996]," "PARAMETER[\"Central_Meridian\",-105.5]," "PARAMETER[\"Standard_Parallel_1\",39.71666666666667]," "PARAMETER[\"Standard_Parallel_2\",40.78333333333333]," "PARAMETER[\"Latitude_Of_Origin\",39.33333333333334]," "UNIT[\"Foot_US\",0.3048006096012192]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2876); EXPECT_EQ(res.front().second, 100); } { // Test case of https://github.com/OSGeo/PROJ/issues/2099 // The name of the CRS to identify is // JGD2011_Japan_Zone_2 // whereas the official ESRI alias is // JGD_2011_Japan_Zone_2 auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"JGD2011_Japan_Zone_2\",GEOGCS[\"GCS_JGD_2011\"," "DATUM[\"D_JGD_2011\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",131]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Latitude_Of_Origin\",33],UNIT[\"Meter\",1.0]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 6670); EXPECT_EQ(res.front().second, 90); } { // Test case of https://github.com/OSGeo/PROJ/issues/2116 // The NAD_1983_CSRS_Prince_Edward_Island has entries in the alias // table under the ESRI authority for deprecated EPSG:2292 and // non-deprecated EPSG:2954 auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"NAD_1983_CSRS_Prince_Edward_Island\"," "GEOGCS[\"GCS_North_American_1983_CSRS\"," "DATUM[\"D_North_American_1983_CSRS\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Double_Stereographic\"]," "PARAMETER[\"False_Easting\",400000.0]," "PARAMETER[\"False_Northing\",800000.0]," "PARAMETER[\"Central_Meridian\",-63.0]," "PARAMETER[\"Scale_Factor\",0.999912]," "PARAMETER[\"Latitude_Of_Origin\",47.25],UNIT[\"Meter\",1.0]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2954); EXPECT_EQ(res.front().second, 100); } { // Test identification of LCC_2SP with switched standard parallels. auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"foo\",\n" " GEOGCS[\"RGF93\",\n" " DATUM[\"Reseau_Geodesique_Francais_1993\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Lambert_Conformal_Conic_2SP\"],\n" " PARAMETER[\"latitude_of_origin\",46.5],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"standard_parallel_1\",44],\n" " PARAMETER[\"standard_parallel_2\",49],\n" " PARAMETER[\"false_easting\",700000],\n" " PARAMETER[\"false_northing\",6600000],\n" " UNIT[\"metre\",1]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2154); EXPECT_EQ(res.front().second, 70); } { // Test identification of LKS92_Latvia_TM (#2214) auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"LKS92_Latvia_TM\",GEOGCS[\"GCS_LKS92\"," "DATUM[\"D_Latvia_1992\"," "SPHEROID[\"GRS_1980\",6378137,298.257222101]]," "PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"latitude_of_origin\",0]," "PARAMETER[\"central_meridian\",24]," "PARAMETER[\"scale_factor\",0.9996]," "PARAMETER[\"false_easting\",500000]," "PARAMETER[\"false_northing\",-6000000]," "UNIT[\"Meter\",1]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 3059); EXPECT_EQ(res.front().second, 90); } { // Test identification of CRS where everything but datum names matches auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"WGS_1984_UTM_Zone_31N\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"wrong_datum_name\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"False_Easting\",500000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",3.0]," "PARAMETER[\"Scale_Factor\",0.9996]," "PARAMETER[\"Latitude_Of_Origin\",0.0]," "UNIT[\"Meter\",1.0]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 32631); EXPECT_EQ(res.front().second, 60); } { // Test case of https://github.com/qgis/QGIS/issues/36111 // The name of the CRS to identify is // ETRS89_LAEA_Europe // We identify it through a registered EPSG alias "ETRS89 / LAEA Europe" auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"ETRS89_LAEA_Europe\"," "GEOGCS[\"GCS_ETRS_1989\",DATUM[\"D_ETRS_1989\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Azimuthal_Equal_Area\"]," "PARAMETER[\"false_easting\",4321000.0]," "PARAMETER[\"false_northing\",3210000.0]," "PARAMETER[\"central_meridian\",10.0]," "PARAMETER[\"latitude_of_origin\",52.0]," "UNIT[\"Meter\",1.0]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 3035); EXPECT_EQ(res.front().second, 90); } { // Test case of https://github.com/qgis/QGIS/issues/32255 auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"RGF93_Lambert_93\",GEOGCS[\"GCS_RGF_1993\"," "DATUM[\"D_RGF_1993\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",700000.0]," "PARAMETER[\"False_Northing\",6600000.0]," "PARAMETER[\"Central_Meridian\",3.0]," "PARAMETER[\"Standard_Parallel_1\",44.0]," "PARAMETER[\"Standard_Parallel_2\",49.0]," "PARAMETER[\"Latitude_Of_Origin\",46.5],UNIT[\"Meter\",1.0]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); bool found = false; for (const auto &candidate : res) { if (candidate.first->getEPSGCode() == 2154) { found = true; EXPECT_EQ(candidate.second, 90); } } EXPECT_TRUE(found); } { // Identify with DatumEnsemble auto wkt = "PROJCRS[\"WGS 84 / UTM zone 31N\"," " BASEGEOGCRS[\"WGS 84\"," " ENSEMBLE[\"World Geodetic System 1984 ensemble\"," " MEMBER[\"World Geodetic System 1984 (Transit)\"," " ID[\"EPSG\",1166]]," " MEMBER[\"World Geodetic System 1984 (G730)\"," " ID[\"EPSG\",1152]]," " MEMBER[\"World Geodetic System 1984 (G873)\"," " ID[\"EPSG\",1153]]," " MEMBER[\"World Geodetic System 1984 (G1150)\"," " ID[\"EPSG\",1154]]," " MEMBER[\"World Geodetic System 1984 (G1674)\"," " ID[\"EPSG\",1155]]," " MEMBER[\"World Geodetic System 1984 (G1762)\"," " ID[\"EPSG\",1156]]," " ELLIPSOID[\"WGS 84\",6378137,298.257223563," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]," " ENSEMBLEACCURACY[2]]]," " CONVERSION[\"UTM zone 31N\"," " METHOD[\"Transverse Mercator\"," " ID[\"EPSG\",9807]]," " PARAMETER[\"Latitude of natural origin\",0," " ANGLEUNIT[\"degree\",0.0174532925199433,ID[\"EPSG\",9102]]]," " PARAMETER[\"Longitude of natural origin\",3," " ANGLEUNIT[\"degree\",0.0174532925199433,ID[\"EPSG\",9102]]]," " PARAMETER[\"Scale factor at natural origin\",0.9996," " SCALEUNIT[\"unity\",1,ID[\"EPSG\",9201]]]," " PARAMETER[\"False easting\",500000," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]," " PARAMETER[\"False northing\",0," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]]," " CS[Cartesian,2]," " AXIS[\"Easting (E)\",east," " ORDER[1]]," " AXIS[\"Northing (N)\",north," " ORDER[2]]," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 32631); EXPECT_EQ(res.front().second, 100.0); } { // Identify with DatumEnsemble and unknown CRS name auto wkt = "PROJCRS[\"unknown\"," " BASEGEOGCRS[\"unknown\"," " ENSEMBLE[\"World Geodetic System 1984 ensemble\"," " MEMBER[\"World Geodetic System 1984 (Transit)\"," " ID[\"EPSG\",1166]]," " MEMBER[\"World Geodetic System 1984 (G730)\"," " ID[\"EPSG\",1152]]," " MEMBER[\"World Geodetic System 1984 (G873)\"," " ID[\"EPSG\",1153]]," " MEMBER[\"World Geodetic System 1984 (G1150)\"," " ID[\"EPSG\",1154]]," " MEMBER[\"World Geodetic System 1984 (G1674)\"," " ID[\"EPSG\",1155]]," " MEMBER[\"World Geodetic System 1984 (G1762)\"," " ID[\"EPSG\",1156]]," " ELLIPSOID[\"WGS 84\",6378137,298.257223563," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]," " ENSEMBLEACCURACY[2]]]," " CONVERSION[\"UTM zone 31N\"," " METHOD[\"Transverse Mercator\"," " ID[\"EPSG\",9807]]," " PARAMETER[\"Latitude of natural origin\",0," " ANGLEUNIT[\"degree\",0.0174532925199433,ID[\"EPSG\",9102]]]," " PARAMETER[\"Longitude of natural origin\",3," " ANGLEUNIT[\"degree\",0.0174532925199433,ID[\"EPSG\",9102]]]," " PARAMETER[\"Scale factor at natural origin\",0.9996," " SCALEUNIT[\"unity\",1,ID[\"EPSG\",9201]]]," " PARAMETER[\"False easting\",500000," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]," " PARAMETER[\"False northing\",0," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]]," " CS[Cartesian,2]," " AXIS[\"Easting (E)\",east," " ORDER[1]]," " AXIS[\"Northing (N)\",north," " ORDER[2]]," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 32631); EXPECT_GE(res.front().second, 70.0); } { // Identify a ESRI WKT where the datum name doesn't start with D_ auto wkt = "PROJCS[\"S-JTSK_[JTSK03]_Krovak_East_North\"," "GEOGCS[\"S-JTSK_[JTSK03]\"," " DATUM[\"S-JTSK_[JTSK03]\"," " SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]]," " PRIMEM[\"Greenwich\",0.0]," " UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Krovak\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Pseudo_Standard_Parallel_1\",78.5]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Azimuth\",30.2881397527778]," "PARAMETER[\"Longitude_Of_Center\",24.8333333333333]," "PARAMETER[\"Latitude_Of_Center\",49.5]," "PARAMETER[\"X_Scale\",-1.0]," "PARAMETER[\"Y_Scale\",1.0]," "PARAMETER[\"XY_Plane_Rotation\",90.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(WKTParser().guessDialect(wkt), WKTParser::WKTGuessedDialect::WKT1_ESRI); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 8353); EXPECT_EQ(res.front().second, 100); } { // Identify from a pseudo WKT ESRI with has an AUTHORITY node that // points to another object. // Cf // https://lists.osgeo.org/pipermail/qgis-user/2023-January/052299.html auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"ETRS_1989_UTM_Zone_32N_6Stellen\"," "GEOGCS[\"GCS_ETRS_1989\",DATUM[\"D_ETRS_1989\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"False_Easting\",500000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",9.0]," "PARAMETER[\"Scale_Factor\",0.9996]," "PARAMETER[\"Latitude_Of_Origin\",0.0]," "UNIT[\"Meter\",1.0]," "AUTHORITY[\"ESRI\",\"102328\"]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_GE(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 25832); EXPECT_EQ(res.front().second, 70); } { // Identify a projected CRS whose base CRS is not a geographic CRS but // a geodetic CRS with a spherical -ocentric coordinate system. // Cf https://github.com/OSGeo/PROJ/issues/3828 auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCRS[\"unknown\",\n" " BASEGEODCRS[\"Mercury (2015) / Ocentric\",\n" " DATUM[\"Mercury (2015)\",\n" " ELLIPSOID[\"Mercury " "(2015)\",2440530,1075.12334801762,\n" " LENGTHUNIT[\"metre\",1]],\n" " ANCHOR[\"Hun Kal: 20 W.0\"]],\n" " PRIMEM[\"Reference Meridian\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"IAU\",19902,2015]],\n" " CONVERSION[\"Equirectangular, clon = 0\",\n" " METHOD[\"Equidistant Cylindrical\",\n" " ID[\"EPSG\",1028]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto allFactory = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(allFactory); ASSERT_GE(res.size(), 1U); EXPECT_EQ(res.front().first->identifiers()[0]->code(), "19912"); EXPECT_EQ(*(res.front().first->identifiers()[0]->codeSpace()), "IAU_2015"); EXPECT_EQ(res.front().second, 90); } } // --------------------------------------------------------------------------- TEST(crs, projectedCRS_identify_wrong_auth_name_case) { auto dbContext = DatabaseContext::create(); auto factoryAnonymous = AuthorityFactory::create(dbContext, std::string()); auto obj = WKTParser() .attachDatabaseContext(dbContext) .setStrict(false) .createFromWKT( "PROJCS[\"World_Cylindrical_Equal_Area\"," "GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Cylindrical_Equal_Area\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",0.0],UNIT[\"Meter\",1.0]," "AUTHORITY[\"Esri\",54034]]"); // should be ESRI all caps auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryAnonymous); ASSERT_EQ(res.size(), 1U); const auto &ids = res.front().first->identifiers(); ASSERT_EQ(ids.size(), 1U); EXPECT_EQ(*(ids.front()->codeSpace()), "ESRI"); EXPECT_EQ(ids.front()->code(), "54034"); } // --------------------------------------------------------------------------- TEST(crs, mercator_1SP_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=merc +lon_0=110 +k=0.997 +x_0=3900000 +y_0=900000 " "+ellps=bessel +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_Unknown_based_on_Bessel_1841_ellipsoid\"," "SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Mercator\"]," "PARAMETER[\"False_Easting\",3900000.0]," "PARAMETER[\"False_Northing\",900000.0]," "PARAMETER[\"Central_Meridian\",110.0]," "PARAMETER[\"Standard_Parallel_1\",4.45405154589748]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Plate_Carree_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+title=my Plate carree +proj=eqc +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"my_Plate_carree\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Plate_Carree\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Equidistant_Cylindrical_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString("+proj=eqc +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Equidistant_Cylindrical\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",0.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Hotine_Oblique_Mercator_Azimuth_Natural_Origin_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +no_uoff +gamma=295 +alpha=295 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[" "\"Hotine_Oblique_Mercator_Azimuth_Natural_Origin\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Scale_Factor\",1.0]," // we renormalize angles to [-180,180] "PARAMETER[\"Azimuth\",-65.0]," "PARAMETER[\"Longitude_Of_Center\",0.0]," "PARAMETER[\"Latitude_Of_Center\",0.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Rectified_Skew_Orthomorphic_Natural_Origin_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +no_uoff +gamma=3 +alpha=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[" "\"Rectified_Skew_Orthomorphic_Natural_Origin\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Scale_Factor\",1.0]," "PARAMETER[\"Azimuth\",2.0]," "PARAMETER[\"Longitude_Of_Center\",0.0]," "PARAMETER[\"Latitude_Of_Center\",0.0]," "PARAMETER[\"XY_Plane_Rotation\",3.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Hotine_Oblique_Mercator_Azimuth_Center_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +gamma=2 +alpha=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[" "\"Hotine_Oblique_Mercator_Azimuth_Center\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Scale_Factor\",1.0]," "PARAMETER[\"Azimuth\",2.0]," "PARAMETER[\"Longitude_Of_Center\",0.0]," "PARAMETER[\"Latitude_Of_Center\",0.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Rectified_Skew_Orthomorphic_Center_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +gamma=3 +alpha=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[" "\"Rectified_Skew_Orthomorphic_Center\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Scale_Factor\",1.0]," "PARAMETER[\"Azimuth\",2.0]," "PARAMETER[\"Longitude_Of_Center\",0.0]," "PARAMETER[\"Latitude_Of_Center\",0.0]," "PARAMETER[\"XY_Plane_Rotation\",3.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Gauss_Kruger_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+title=my Gauss Kruger +proj=tmerc +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"my_Gauss_Kruger\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0," "298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Gauss_Kruger\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Scale_Factor\",1.0]," "PARAMETER[\"Latitude_Of_Origin\",0.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Stereographic_North_Pole_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=stere +lat_0=90 +lat_ts=70 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Stereographic_North_Pole\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",70.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Stereographic_South_Pole_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=stere +lat_0=-90 +lat_ts=-70 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Stereographic_South_Pole\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",-70.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Krovak_North_Orientated_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString("+proj=krovak +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_Unknown_based_on_Bessel_1841_ellipsoid\"," "SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Krovak\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Pseudo_Standard_Parallel_1\",78.5]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Azimuth\",30.2881397527778]," "PARAMETER[\"Longitude_Of_Center\",24.8333333333333]," "PARAMETER[\"Latitude_Of_Center\",49.5]," "PARAMETER[\"X_Scale\",-1.0]," "PARAMETER[\"Y_Scale\",1.0]," "PARAMETER[\"XY_Plane_Rotation\",90.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, Krovak_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=krovak +axis=swu +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_Unknown_based_on_Bessel_1841_ellipsoid\"," "SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Krovak\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Pseudo_Standard_Parallel_1\",78.5]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Azimuth\",30.2881397527778]," "PARAMETER[\"Longitude_Of_Center\",24.8333333333333]," "PARAMETER[\"Latitude_Of_Center\",49.5]," "PARAMETER[\"X_Scale\",1.0]," "PARAMETER[\"Y_Scale\",1.0]," "PARAMETER[\"XY_Plane_Rotation\",0.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, LCC_1SP_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=lcc +lat_1=1 +lat_0=1 +k=0.9 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",1.0]," "PARAMETER[\"Scale_Factor\",0.9]," "PARAMETER[\"Latitude_Of_Origin\",1.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, LCC_2SP_as_WKT1_ESRI) { auto obj = PROJStringParser().createFromPROJString( "+proj=lcc +lat_0=1.5 +lat_1=1 +lat_2=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Standard_Parallel_1\",1.0]," "PARAMETER[\"Standard_Parallel_2\",2.0]," "PARAMETER[\"Latitude_Of_Origin\",1.5]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, ESRI_WKT1_to_ESRI_WKT1) { auto in_wkt = "PROJCS[\"NAD_1983_CORS96_StatePlane_North_Carolina_FIPS_3200_Ft_US\"," "GEOGCS[\"GCS_NAD_1983_CORS96\",DATUM[\"D_NAD_1983_CORS96\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",2000000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",-79.0]," "PARAMETER[\"Standard_Parallel_1\",34.33333333333334]," "PARAMETER[\"Standard_Parallel_2\",36.16666666666666]," "PARAMETER[\"Latitude_Of_Origin\",33.75]," "UNIT[\"Foot_US\",0.3048006096012192]]"; auto obj = WKTParser().createFromWKT(in_wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCS[\"NAD_1983_CORS96_StatePlane_North_Carolina_FIPS_3200_Ft_US\"," "GEOGCS[\"GCS_NAD_1983_CORS96\",DATUM[\"D_NAD_1983_CORS96\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",2000000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",-79.0]," "PARAMETER[\"Standard_Parallel_1\",34.3333333333333]," "PARAMETER[\"Standard_Parallel_2\",36.1666666666667]," "PARAMETER[\"Latitude_Of_Origin\",33.75]," "UNIT[\"Foot_US\",0.304800609601219]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(datum, cs_with_MERIDIAN) { std::vector<CoordinateSystemAxisNNPtr> axis{ CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Easting"), "X", AxisDirection::SOUTH, UnitOfMeasure::METRE, Meridian::create(Angle(90))), CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Northing"), "Y", AxisDirection::SOUTH, UnitOfMeasure::METRE, Meridian::create(Angle(180.0)))}; auto cs(CartesianCS::create(PropertyMap(), axis[0], axis[1])); auto expected = "CS[Cartesian,2],\n" " AXIS[\"easting (X)\",south,\n" " MERIDIAN[90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (Y)\",south,\n" " MERIDIAN[180,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]"; auto formatter = WKTFormatter::create(); formatter->setOutputId(false); EXPECT_EQ(cs->exportToWKT(formatter.get()), expected); } // --------------------------------------------------------------------------- TEST(crs, scope_area_bbox_remark) { auto in_wkt = "GEODETICCRS[\"JGD2000\"," "DATUM[\"Japanese Geodetic Datum 2000\"," " ELLIPSOID[\"GRS 1980\",6378137,298.257222101]]," "CS[Cartesian,3]," " AXIS[\"(X)\",geocentricX]," " AXIS[\"(Y)\",geocentricY]," " AXIS[\"(Z)\",geocentricZ]," " LENGTHUNIT[\"metre\",1.0]," "SCOPE[\"Geodesy, topographic mapping and cadastre\"]," "AREA[\"Japan\"]," "BBOX[17.09,122.38,46.05,157.64]," "VERTICALEXTENT[-10000,10000]," "TIMEEXTENT[2002-04-01,2011-10-21]," "ID[\"EPSG\",4946],\n" "REMARK[\"some_remark\"]]"; auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(WKTParser().createFromWKT(in_wkt)); ASSERT_TRUE(crs != nullptr); ASSERT_EQ(crs->domains().size(), 1U); auto domain = crs->domains()[0]; EXPECT_TRUE(domain->scope().has_value()); EXPECT_EQ(*(domain->scope()), "Geodesy, topographic mapping and cadastre"); ASSERT_TRUE(domain->domainOfValidity() != nullptr); EXPECT_TRUE(domain->domainOfValidity()->description().has_value()); EXPECT_EQ(*(domain->domainOfValidity()->description()), "Japan"); ASSERT_EQ(domain->domainOfValidity()->geographicElements().size(), 1U); auto geogElement = domain->domainOfValidity()->geographicElements()[0]; auto bbox = nn_dynamic_pointer_cast<GeographicBoundingBox>(geogElement); ASSERT_TRUE(bbox != nullptr); EXPECT_EQ(bbox->southBoundLatitude(), 17.09); EXPECT_EQ(bbox->westBoundLongitude(), 122.38); EXPECT_EQ(bbox->northBoundLatitude(), 46.05); EXPECT_EQ(bbox->eastBoundLongitude(), 157.64); ASSERT_EQ(domain->domainOfValidity()->verticalElements().size(), 1U); auto verticalElement = domain->domainOfValidity()->verticalElements()[0]; EXPECT_EQ(verticalElement->minimumValue(), -10000); EXPECT_EQ(verticalElement->maximumValue(), 10000); EXPECT_EQ(*(verticalElement->unit()), UnitOfMeasure::METRE); ASSERT_EQ(domain->domainOfValidity()->temporalElements().size(), 1U); auto temporalElement = domain->domainOfValidity()->temporalElements()[0]; EXPECT_EQ(temporalElement->start(), "2002-04-01"); EXPECT_EQ(temporalElement->stop(), "2011-10-21"); auto got_wkt = crs->exportToWKT(WKTFormatter::create().get()); auto expected = "GEODCRS[\"JGD2000\",\n" " DATUM[\"Japanese Geodetic Datum 2000\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " SCOPE[\"Geodesy, topographic mapping and cadastre\"],\n" " AREA[\"Japan\"],\n" " BBOX[17.09,122.38,46.05,157.64],\n" " VERTICALEXTENT[-10000,10000,\n" " LENGTHUNIT[\"metre\",1]],\n" " TIMEEXTENT[2002-04-01,2011-10-21],\n" " ID[\"EPSG\",4946],\n" " REMARK[\"some_remark\"]]"; EXPECT_EQ(got_wkt, expected); } // --------------------------------------------------------------------------- TEST(crs, usage) { auto in_wkt = "GEODETICCRS[\"JGD2000\"," "DATUM[\"Japanese Geodetic Datum 2000\"," " ELLIPSOID[\"GRS 1980\",6378137,298.257222101]]," "CS[Cartesian,3]," " AXIS[\"(X)\",geocentricX]," " AXIS[\"(Y)\",geocentricY]," " AXIS[\"(Z)\",geocentricZ]," " LENGTHUNIT[\"metre\",1.0]," "USAGE[SCOPE[\"scope\"],AREA[\"area.\"]]]"; auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(WKTParser().createFromWKT(in_wkt)); ASSERT_TRUE(crs != nullptr); auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); auto expected = "GEODCRS[\"JGD2000\",\n" " DATUM[\"Japanese Geodetic Datum 2000\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"scope\"],\n" " AREA[\"area.\"]]]"; EXPECT_EQ(got_wkt, expected); } // --------------------------------------------------------------------------- TEST(crs, multiple_ID) { PropertyMap propertiesCRS; propertiesCRS.set(IdentifiedObject::NAME_KEY, "WGS 84"); auto identifiers = ArrayOfBaseObject::create(); identifiers->add(Identifier::create( "codeA", PropertyMap().set(Identifier::CODESPACE_KEY, "authorityA"))); identifiers->add(Identifier::create( "codeB", PropertyMap().set(Identifier::CODESPACE_KEY, "authorityB"))); propertiesCRS.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers); auto crs = GeodeticCRS::create( propertiesCRS, GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric(UnitOfMeasure::METRE)); auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_SIMPLIFIED).get()); auto expected = "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX],\n" " AXIS[\"(Y)\",geocentricY],\n" " AXIS[\"(Z)\",geocentricZ],\n" " UNIT[\"metre\",1],\n" " ID[\"authorityA\",\"codeA\"],\n" " ID[\"authorityB\",\"codeB\"]]"; EXPECT_EQ(got_wkt, expected); } // --------------------------------------------------------------------------- static VerticalCRSNNPtr createVerticalCRS() { PropertyMap propertiesVDatum; propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5101) .set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn"); auto vdatum = VerticalReferenceFrame::create(propertiesVDatum); PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5701) .set(IdentifiedObject::NAME_KEY, "ODN height"); return VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_as_WKT2) { auto crs = createVerticalCRS(); auto expected = "VERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5701]]"; EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), expected); } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_as_WKT1_GDAL) { auto crs = createVerticalCRS(); auto expected = "VERT_CS[\"ODN height\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005,\n" " AUTHORITY[\"EPSG\",\"5101\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5701\"]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_as_WKT1_ESRI) { auto crs = createVerticalCRS(); auto expected = "VERTCS[\"ODN_height\",VDATUM[\"Ordnance_Datum_Newlyn\"]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_as_WKT1_ESRI_context) { auto crs = createVerticalCRS(); auto expected = "VERTCS[\"Newlyn\",VDATUM[\"Ordnance_Datum_Newlyn\"]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0]," "UNIT[\"Meter\",1.0]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create()) .get()), expected); } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_down_as_WKT1_ESRI) { auto wkt = "VERTCS[\"Caspian\",VDATUM[\"Caspian_Sea\"]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",-1.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI).get()), wkt); } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_ESRI_115834_as_WKT1_ESRI_with_database) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "ESRI"); auto crs = factory->createCoordinateReferenceSystem("115834"); WKTFormatterNNPtr f(WKTFormatter::create( WKTFormatter::Convention::WKT1_ESRI, DatabaseContext::create())); // Check that the parentheses in the VERTCS and DATUM names are preserved EXPECT_EQ(crs->exportToWKT(f.get()), "VERTCS[\"NAD83(CSRS)v5\"," "DATUM[\"North_American_Datum_of_1983_(CSRS)_version_5\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]]"); } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_identify_db) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); { // Identify by existing code auto res = factory->createVerticalCRS("7651")->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 7651); EXPECT_EQ(res.front().second, 100); // Test with null EXPECT_TRUE( factory->createVerticalCRS("7651")->identify(nullptr).empty()); } { // Non-existing code auto sourceCRS = factory->createVerticalCRS("7651"); auto crs = VerticalCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, sourceCRS->nameStr()) .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 1), sourceCRS->datum(), sourceCRS->datumEnsemble(), sourceCRS->coordinateSystem()); auto res = crs->identify(factory); EXPECT_EQ(res.size(), 0U); } { // Existing code, but not matching content auto sourceCRS = factory->createVerticalCRS("7651"); auto crs = VerticalCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, sourceCRS->nameStr()) .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 7652), sourceCRS->datum(), sourceCRS->datumEnsemble(), sourceCRS->coordinateSystem()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 7652); EXPECT_EQ(res.front().second, 25); } { // Identify by exact name auto sourceCRS = factory->createVerticalCRS("7651"); auto crs = VerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, sourceCRS->nameStr()), sourceCRS->datum(), sourceCRS->datumEnsemble(), sourceCRS->coordinateSystem()); auto res = static_cast<const CRS *>(crs.get())->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 7651); EXPECT_EQ(res.front().second, 100); } { // Identify by equivalent name auto sourceCRS = factory->createVerticalCRS("7651"); auto crs = VerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Kumul_34_height"), sourceCRS->datum(), sourceCRS->datumEnsemble(), sourceCRS->coordinateSystem()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 7651); EXPECT_EQ(res.front().second, 90); } { // Identify by name, but objects aren't equivalent auto sourceCRS = factory->createVerticalCRS("7652"); auto crs = VerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Kumul_34_height"), sourceCRS->datum(), sourceCRS->datumEnsemble(), sourceCRS->coordinateSystem()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 7651); EXPECT_EQ(res.front().second, 25); } { auto sourceCRS = factory->createVerticalCRS("7651"); auto crs = VerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "no match"), sourceCRS->datum(), sourceCRS->datumEnsemble(), sourceCRS->coordinateSystem()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 0U); } } // --------------------------------------------------------------------------- TEST(crs, verticalCRS_datum_ensemble) { auto ensemble = DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{ VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "vdatum1")), VerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "vdatum2"))}, PositionalAccuracy::create("100")); auto crs = VerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), nullptr, ensemble, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "VERTCRS[\"unnamed\",\n" " ENSEMBLE[\"unnamed\",\n" " MEMBER[\"vdatum1\"],\n" " MEMBER[\"vdatum2\"],\n" " ENSEMBLEACCURACY[100]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(crs, VerticalCRS_ensemble_exception_in_create) { EXPECT_THROW(VerticalCRS::create(PropertyMap(), nullptr, nullptr, VerticalCS::createGravityRelatedHeight( UnitOfMeasure::METRE)), Exception); auto ensemble_hdatum = DatumEnsemble::create( PropertyMap(), std::vector<DatumNNPtr>{GeodeticReferenceFrame::EPSG_6326, GeodeticReferenceFrame::EPSG_6326}, PositionalAccuracy::create("100")); EXPECT_THROW(VerticalCRS::create(PropertyMap(), nullptr, ensemble_hdatum, VerticalCS::createGravityRelatedHeight( UnitOfMeasure::METRE)), Exception); } // --------------------------------------------------------------------------- TEST(datum, vdatum_with_anchor) { PropertyMap propertiesVDatum; propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5101) .set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn"); auto vdatum = VerticalReferenceFrame::create( propertiesVDatum, optional<std::string>("my anchor"), optional<RealizationMethod>(RealizationMethod::LEVELLING)); EXPECT_TRUE(vdatum->realizationMethod().has_value()); EXPECT_EQ(*(vdatum->realizationMethod()), RealizationMethod::LEVELLING); auto expected = "VDATUM[\"Ordnance Datum Newlyn\",\n" " ANCHOR[\"my anchor\"],\n" " ID[\"EPSG\",5101]]"; EXPECT_EQ(vdatum->exportToWKT(WKTFormatter::create().get()), expected); EXPECT_TRUE(vdatum->isEquivalentTo(vdatum.get())); EXPECT_FALSE(vdatum->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- static CompoundCRSNNPtr createCompoundCRS() { PropertyMap properties; properties.set(Identifier::CODESPACE_KEY, "codespace") .set(Identifier::CODE_KEY, "code") .set(IdentifiedObject::NAME_KEY, "horizontal + vertical"); return CompoundCRS::create( properties, std::vector<CRSNNPtr>{createProjected(), createVerticalCRS()}); } // --------------------------------------------------------------------------- static DerivedProjectedCRSNNPtr createDerivedProjectedCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), PropertyMap().set(IdentifiedObject::NAME_KEY, "PROJ unimplemented"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "derived projectedCRS"), createProjected(), derivingConversion, CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } static DerivedProjectedCRSNNPtr createDerivedProjectedCRSNorthingEasting() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), PropertyMap().set(IdentifiedObject::NAME_KEY, "PROJ unimplemented"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "derived projectedCRS"), createProjected(), derivingConversion, CartesianCS::createNorthingEasting(UnitOfMeasure::FOOT)); } // --------------------------------------------------------------------------- static DerivedVerticalCRSNNPtr createDerivedVerticalCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), PropertyMap().set(IdentifiedObject::NAME_KEY, "PROJ unimplemented"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedVerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Derived vertCRS"), createVerticalCRS(), derivingConversion, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_valid) { // geographic 2D + vertical CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{GeographicCRS::EPSG_4326, createVerticalCRS()}); // projected 2D + vertical CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{createProjected(), createVerticalCRS()}); // derived projected 2D + vertical CompoundCRS::create(PropertyMap(), std::vector<CRSNNPtr>{createDerivedProjectedCRS(), createVerticalCRS()}); // derived projected 2D + derived vertical CompoundCRS::create(PropertyMap(), std::vector<CRSNNPtr>{createDerivedProjectedCRS(), createDerivedVerticalCRS()}); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_invalid) { EXPECT_THROW(CompoundCRS::create(PropertyMap(), {}), InvalidCompoundCRSException); // Only one component EXPECT_THROW(CompoundCRS::create(PropertyMap(), std::vector<CRSNNPtr>{createProjected()}), InvalidCompoundCRSException); // Two geographic EXPECT_THROW( CompoundCRS::create(PropertyMap(), std::vector<CRSNNPtr>{GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4326}), InvalidCompoundCRSException); // geographic 3D + vertical EXPECT_THROW( CompoundCRS::create(PropertyMap(), std::vector<CRSNNPtr>{GeographicCRS::EPSG_4979, createVerticalCRS()}), InvalidCompoundCRSException); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_as_WKT2) { auto crs = createCompoundCRS(); auto expected = "COMPOUNDCRS[\"horizontal + vertical\",\n" " PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]],\n" " VERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]],\n" " ID[\"codespace\",\"code\"]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), expected); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_isEquivalentTo) { auto crs = createCompoundCRS(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); auto otherCompoundCRS = CompoundCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, ""), std::vector<CRSNNPtr>{GeographicCRS::EPSG_4326, createVerticalCRS()}); EXPECT_FALSE(crs->isEquivalentTo(otherCompoundCRS.get())); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_as_WKT1_GDAL) { auto crs = createCompoundCRS(); auto expected = "COMPD_CS[\"horizontal + vertical\",\n" " PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]],\n" " VERT_CS[\"ODN height\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005,\n" " AUTHORITY[\"EPSG\",\"5101\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5701\"]],\n" " AUTHORITY[\"codespace\",\"code\"]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_as_PROJ_string) { auto crs = createCompoundCRS(); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=31 +datum=WGS84 +units=m +vunits=m +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_no_name_provided) { auto crs = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{createProjected(), createVerticalCRS()}); EXPECT_EQ(crs->nameStr(), "WGS 84 / UTM zone 31N + ODN height"); } // --------------------------------------------------------------------------- TEST(crs, compoundCRS_identify_db) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); { // Identify by existing code auto res = factory->createCompoundCRS("8769")->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 8769); EXPECT_EQ(res.front().second, 100); // Test with null EXPECT_TRUE( factory->createCompoundCRS("8769")->identify(nullptr).empty()); } { // Non-existing code auto sourceCRS = factory->createCompoundCRS("8769"); auto crs = CompoundCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, sourceCRS->nameStr()) .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 1), sourceCRS->componentReferenceSystems()); auto res = crs->identify(factory); EXPECT_EQ(res.size(), 0U); } { // Existing code, but not matching content auto sourceCRS = factory->createCompoundCRS("8769"); auto crs = CompoundCRS::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, sourceCRS->nameStr()) .set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 8770), sourceCRS->componentReferenceSystems()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 8770); EXPECT_EQ(res.front().second, 25); } { // Identify by exact name auto sourceCRS = factory->createCompoundCRS("8769"); auto crs = CompoundCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, sourceCRS->nameStr()), sourceCRS->componentReferenceSystems()); auto res = static_cast<const CRS *>(crs.get())->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 8769); EXPECT_EQ(res.front().second, 100); } { EXPECT_TRUE(Identifier::isEquivalentName( "NAD83_Ohio_North_ftUS_NAVD88_height_ftUS", "NAD83 / Ohio North (ftUS) + NAVD88 height (ftUS)")); // Identify by equivalent name auto sourceCRS = factory->createCompoundCRS("8769"); auto crs = CompoundCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "NAD83_Ohio_North_ftUS_NAVD88_height_ftUS"), sourceCRS->componentReferenceSystems()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 8769); EXPECT_EQ(res.front().second, 90); } { // Identify by name, but objects aren't equivalent auto sourceCRS = factory->createCompoundCRS("8770"); auto crs = CompoundCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "NAD83_Ohio_North_ftUS_NAVD88_height_ftUS"), sourceCRS->componentReferenceSystems()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 8769); EXPECT_EQ(res.front().second, 25); } { auto sourceCRS = factory->createCompoundCRS("8769"); auto crs = CompoundCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unrelated name"), sourceCRS->componentReferenceSystems()); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 8769); EXPECT_EQ(res.front().second, 70); } { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +lat_0=0 +lon_0=72.05 +k=1 +x_0=3500000 " "+y_0=-5811057.63 +ellps=krass " "+towgs84=23.57,-140.95,-79.8,0,-0.35,-0.79,-0.22 " "+geoidgrids=egm08_25.gtx +units=m +no_defs +type=crs"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); // Just check we don't get an exception crs->identify(factory); } // Identify from ESRI WKT { auto sourceCRS = factory->createCompoundCRS("7405"); auto wkt = sourceCRS->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 7405); EXPECT_EQ(res.front().second, 100); } // Identify a CompoundCRS whose horizontal and vertical parts are known // but not the composition. { auto obj = createFromUserInput("EPSG:4326+5703", dbContext); auto sourceCRS = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(sourceCRS != nullptr); auto wkt = sourceCRS->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()); auto obj2 = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj2); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 0); EXPECT_EQ(res.front().second, 100); const auto &components = res.front().first->componentReferenceSystems(); EXPECT_EQ(components[0]->getEPSGCode(), 4326); EXPECT_EQ(components[1]->getEPSGCode(), 5703); } } // --------------------------------------------------------------------------- TEST(crs, boundCRS_to_WKT2) { auto projcrs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my PROJCRS"), GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my GEOGCRS"), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)), Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto crs = BoundCRS::createFromTOWGS84( projcrs, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); EXPECT_EQ(crs->baseCRS()->nameStr(), projcrs->nameStr()); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); ASSERT_TRUE(crs->transformation()->sourceCRS() != nullptr); EXPECT_EQ(crs->transformation()->sourceCRS()->nameStr(), projcrs->baseCRS()->nameStr()); ASSERT_TRUE(crs->transformation()->targetCRS() != nullptr); EXPECT_EQ(crs->transformation()->targetCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); auto values = crs->transformation()->parameterValues(); ASSERT_EQ(values.size(), 7U); { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[0]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8605); EXPECT_EQ(paramName, "X-axis translation"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::METRE); EXPECT_EQ(measure.value(), 1.0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[1]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8606); EXPECT_EQ(paramName, "Y-axis translation"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::METRE); EXPECT_EQ(measure.value(), 2.0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[2]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8607); EXPECT_EQ(paramName, "Z-axis translation"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::METRE); EXPECT_EQ(measure.value(), 3.0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[3]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8608); EXPECT_EQ(paramName, "X-axis rotation"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::ARC_SECOND); EXPECT_EQ(measure.value(), 4.0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[4]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8609); EXPECT_EQ(paramName, "Y-axis rotation"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::ARC_SECOND); EXPECT_EQ(measure.value(), 5.0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[5]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8610); EXPECT_EQ(paramName, "Z-axis rotation"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::ARC_SECOND); EXPECT_EQ(measure.value(), 6.0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[6]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8611); EXPECT_EQ(paramName, "Scale difference"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::PARTS_PER_MILLION); EXPECT_EQ(measure.value(), 7.0); } auto expected = "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" + "TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) + "],\n" " ABRIDGEDTRANSFORMATION[\"Transformation from myGEOGCRS to " "WGS84\",\n" " METHOD[\"Position Vector transformation (geog2D " "domain)\",\n" " ID[\"EPSG\",9606]],\n" " PARAMETER[\"X-axis translation\",1,\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",2,\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",3,\n" " ID[\"EPSG\",8607]],\n" " PARAMETER[\"X-axis rotation\",4,\n" " ID[\"EPSG\",8608]],\n" " PARAMETER[\"Y-axis rotation\",5,\n" " ID[\"EPSG\",8609]],\n" " PARAMETER[\"Z-axis rotation\",6,\n" " ID[\"EPSG\",8610]],\n" " PARAMETER[\"Scale difference\",1.000007,\n" " ID[\"EPSG\",8611]]]]"; EXPECT_EQ( replaceAll( replaceAll(crs->exportToWKT(WKTFormatter::create().get()), " ", ""), "\n", ""), replaceAll(replaceAll(expected, " ", ""), "\n", "")); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(crs, boundCRS_with_usage) { auto wkt = "BOUNDCRS[\n" " SOURCECRS[\n" " PROJCRS[\"Monte Mario / Italy zone 2\",\n" " BASEGEOGCRS[\"Monte Mario\",\n" " DATUM[\"Monte Mario\",\n" " ELLIPSOID[\"International 1924\",6378388,297,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4265]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",15,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",2520000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"x\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"y\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",3004]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]]],\n" " ABRIDGEDTRANSFORMATION[\"Transformation from Monte Mario to " "WGS84\",\n" " METHOD[\"Position Vector transformation (geog2D domain)\",\n" " ID[\"EPSG\",9606]],\n" " PARAMETER[\"X-axis translation\",-50.2,\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",-50.4,\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",84.8,\n" " ID[\"EPSG\",8607]],\n" " PARAMETER[\"X-axis rotation\",-0.69,\n" " ID[\"EPSG\",8608]],\n" " PARAMETER[\"Y-axis rotation\",-2.012,\n" " ID[\"EPSG\",8609]],\n" " PARAMETER[\"Z-axis rotation\",0.459,\n" " ID[\"EPSG\",8610]],\n" " PARAMETER[\"Scale difference\",0.99997192,\n" " ID[\"EPSG\",8611]]],\n" " USAGE[\n" " SCOPE[\"unknown\"],\n" " AREA[\"Italy - Sicily onshore\"],\n" " BBOX[36.59,12.36,38.35,15.71]]]"; auto crs = nn_dynamic_pointer_cast<BoundCRS>(WKTParser().createFromWKT(wkt)); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Monte Mario / Italy zone 2"); auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_EQ(got_wkt, wkt); } // --------------------------------------------------------------------------- TEST(crs, boundCRS_crs_link) { { std::weak_ptr<CRS> oriBaseCRS; { auto baseCRSIn = GeographicCRS::EPSG_4267->shallowClone(); oriBaseCRS = baseCRSIn.as_nullable(); EXPECT_EQ(oriBaseCRS.use_count(), 1); { auto boundCRS = BoundCRS::createFromTOWGS84( baseCRSIn, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); EXPECT_EQ(oriBaseCRS.use_count(), 3); } EXPECT_EQ(oriBaseCRS.use_count(), 1); } EXPECT_TRUE(oriBaseCRS.expired()); } { CRSPtr baseCRS; { auto baseCRSIn = GeographicCRS::EPSG_4267->shallowClone(); CRS *baseCRSPtr = baseCRSIn.get(); auto boundCRS = BoundCRS::createFromTOWGS84( baseCRSIn, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); baseCRS = boundCRS->baseCRS().as_nullable(); EXPECT_TRUE(baseCRS.get() == baseCRSPtr); } EXPECT_TRUE(baseCRS->isEquivalentTo(GeographicCRS::EPSG_4267.get())); EXPECT_TRUE(baseCRS->canonicalBoundCRS() == nullptr); } { CRSPtr baseCRS; { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4267->shallowClone(), std::vector<double>{1, 2, 3, 4, 5, 6, 7}); baseCRS = boundCRS->baseCRSWithCanonicalBoundCRS().as_nullable(); } EXPECT_TRUE(baseCRS->isEquivalentTo(GeographicCRS::EPSG_4267.get())); EXPECT_TRUE(baseCRS->canonicalBoundCRS() != nullptr); EXPECT_TRUE( baseCRS ->createBoundCRSToWGS84IfPossible( nullptr, CoordinateOperationContext::IntermediateCRSUse::NEVER) ->isEquivalentTo(baseCRS->canonicalBoundCRS().get())); } { std::weak_ptr<CRS> oriBaseCRS; { BoundCRSPtr boundCRSExterior; { auto baseCRS = GeographicCRS::EPSG_4267->shallowClone(); oriBaseCRS = baseCRS.as_nullable(); EXPECT_EQ(oriBaseCRS.use_count(), 1); auto boundCRS = BoundCRS::createFromTOWGS84( baseCRS, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); EXPECT_EQ(oriBaseCRS.use_count(), 3); boundCRSExterior = boundCRS->baseCRSWithCanonicalBoundCRS() ->canonicalBoundCRS(); EXPECT_EQ(oriBaseCRS.use_count(), 4); } EXPECT_EQ(oriBaseCRS.use_count(), 2); EXPECT_TRUE(!oriBaseCRS.expired()); EXPECT_TRUE(boundCRSExterior->baseCRS()->isEquivalentTo( GeographicCRS::EPSG_4267.get())); } EXPECT_EQ(oriBaseCRS.use_count(), 0); EXPECT_TRUE(oriBaseCRS.expired()); } { std::weak_ptr<CRS> oriBaseCRS; { BoundCRSPtr boundCRSExterior; { auto baseCRS = createProjected(); oriBaseCRS = baseCRS.as_nullable(); EXPECT_EQ(oriBaseCRS.use_count(), 1); auto boundCRS = BoundCRS::createFromTOWGS84( baseCRS, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); EXPECT_EQ(oriBaseCRS.use_count(), 2); boundCRSExterior = boundCRS->baseCRSWithCanonicalBoundCRS() ->canonicalBoundCRS(); EXPECT_EQ(oriBaseCRS.use_count(), 3); } EXPECT_EQ(oriBaseCRS.use_count(), 1); EXPECT_TRUE(!oriBaseCRS.expired()); EXPECT_TRUE(boundCRSExterior->baseCRS()->isEquivalentTo( createProjected().get())); } EXPECT_EQ(oriBaseCRS.use_count(), 0); EXPECT_TRUE(oriBaseCRS.expired()); } } // --------------------------------------------------------------------------- TEST(crs, boundCRS_to_WKT1) { auto projcrs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my PROJCRS"), GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my GEOGCRS"), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)), Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto crs = BoundCRS::createFromTOWGS84( projcrs, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto expected = "PROJCS[\"my PROJCRS\",\n" " GEOGCS[\"my GEOGCRS\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " TOWGS84[1,2,3,4,5,6,7],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, boundCRS_geographicCRS_to_PROJ_string) { auto basecrs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my GEOGCRS"), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto crs = BoundCRS::createFromTOWGS84( basecrs, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +ellps=WGS84 +towgs84=1,2,3,4,5,6,7 +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, boundCRS_projectedCRS_to_PROJ_string) { auto projcrs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my PROJCRS"), GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my GEOGCRS"), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)), Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto crs = BoundCRS::createFromTOWGS84( projcrs, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=31 +ellps=WGS84 +towgs84=1,2,3,4,5,6,7 +units=m " "+no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, boundCRS_identify_db) { auto dbContext = DatabaseContext::create(); auto factoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); { auto obj = PROJStringParser() .attachDatabaseContext(dbContext) .createFromPROJString( "+proj=tmerc +lat_0=-37.76111111111111 " "+lon_0=176.4661111111111 +k=1 " "+x_0=400000 +y_0=800000 +ellps=GRS80 " "+towgs84=0,0,0,0,0,0,0 +units=m +type=crs"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); auto boundCRS = dynamic_cast<const BoundCRS *>(res.front().first.get()); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ(boundCRS->baseCRS()->getEPSGCode(), 2106); EXPECT_EQ(boundCRS->transformation()->nameStr(), "NZGD2000 to WGS 84 (1)"); EXPECT_EQ(res.front().second, 70); } { // WKT has EPSG code but the definition doesn't match with the official // one (namely linear units are different) // https://github.com/OSGeo/gdal/issues/990 // Also test that we can handle the synthetic Null geographic offset // between NAD83 and WGS84 auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "PROJCS[\"NAD83 / Ohio North\",GEOGCS[\"NAD83\"," "DATUM[\"North_American_Datum_1983\",SPHEROID[\"GRS 1980\"," "6378137,298.257222101,AUTHORITY[\"EPSG\",\"7019\"]]," "TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6269\"]]," "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"degree\",0.0174532925199433, AUTHORITY[\"EPSG\",\"9122\"]]," "AUTHORITY[\"EPSG\",\"4269\"]]," "PROJECTION[\"Lambert_Conformal_Conic_2SP\"]," "PARAMETER[\"standard_parallel_1\",41.7]," "PARAMETER[\"standard_parallel_2\",40.43333333333333]," "PARAMETER[\"latitude_of_origin\",39.66666666666666]," "PARAMETER[\"central_meridian\",-82.5]," "PARAMETER[\"false_easting\",1968503.937007874]," "PARAMETER[\"false_northing\",0]," "UNIT[\"International Foot\",0.3048,AUTHORITY[\"EPSG\",\"9002\"]]," "AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],AUTHORITY[\"EPSG\",\"32122\"]" "]"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().second, 25); auto boundCRS = dynamic_cast<const BoundCRS *>(res.front().first.get()); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ(boundCRS->baseCRS()->getEPSGCode(), 32122); EXPECT_EQ(boundCRS->transformation()->method()->getEPSGCode(), 9603); } { // Identify from a PROJ string with +towgs84 auto obj = PROJStringParser().createFromPROJString( "+proj=utm +zone=48 +a=6377276.345 +b=6356075.41314024 " "+towgs84=198,881,317,0,0,0,0 +units=m +no_defs +type=crs"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); auto boundCRS = dynamic_cast<const BoundCRS *>(res.front().first.get()); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ(boundCRS->baseCRS()->getEPSGCode(), 3148); EXPECT_EQ(res.front().second, 70); } { // Identify a WKT with datum WGS84 and TOWGS84 auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "GEOGCS[\"WGS84 Coordinate System\",DATUM[\"WGS 1984\"," "SPHEROID[\"WGS 1984\",6378137,298.257223563]," "TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]," "AUTHORITY[\"EPSG\",\"4326\"]]"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factoryEPSG); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().second, 100); auto boundCRS = dynamic_cast<const BoundCRS *>(res.front().first.get()); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ(boundCRS->baseCRS()->getEPSGCode(), 4326); EXPECT_EQ(boundCRS->transformation()->method()->getEPSGCode(), 9606); } } // --------------------------------------------------------------------------- TEST(crs, incompatible_boundCRS_hubCRS_to_WKT1) { auto crs = BoundCRS::create( GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4807, Transformation::createGeocentricTranslations( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4807, 1.0, 2.0, 3.0, std::vector<PositionalAccuracyNNPtr>())); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, incompatible_boundCRS_transformation_to_WKT1) { auto crs = BoundCRS::create( GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326, Transformation::create(PropertyMap(), GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326, nullptr, PropertyMap(), std::vector<OperationParameterNNPtr>(), std::vector<ParameterValueNNPtr>(), std::vector<PositionalAccuracyNNPtr>())); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, WKT1_DATUM_EXTENSION_to_WKT1_and_PROJ_string) { auto wkt = "PROJCS[\"unnamed\",\n" " GEOGCS[\"International 1909 (Hayford)\",\n" " DATUM[\"unknown\",\n" " SPHEROID[\"intl\",6378388,297],\n" " EXTENSION[\"PROJ4_GRIDS\",\"nzgd2kgrid0005.gsb\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"New_Zealand_Map_Grid\"],\n" " PARAMETER[\"latitude_of_origin\",-41],\n" " PARAMETER[\"central_meridian\",173],\n" " PARAMETER[\"false_easting\",2510000],\n" " PARAMETER[\"false_northing\",6023150],\n" " UNIT[\"Meter\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), wkt); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=nzmg +lat_0=-41 +lon_0=173 +x_0=2510000 +y_0=6023150 " "+ellps=intl +nadgrids=nzgd2kgrid0005.gsb +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, WKT1_VERT_DATUM_EXTENSION_to_WKT1) { auto wkt = "VERT_CS[\"EGM2008 geoid height\",\n" " VERT_DATUM[\"EGM2008 geoid\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"egm08_25.gtx\"],\n" " AUTHORITY[\"EPSG\",\"1027\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"3855\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), wkt); } // --------------------------------------------------------------------------- TEST(crs, WKT1_VERT_DATUM_EXTENSION_to_WKT2) { auto wkt = "VERT_CS[\"EGM2008 geoid height\",\n" " VERT_DATUM[\"EGM2008 geoid\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"egm08_25.gtx\"],\n" " AUTHORITY[\"EPSG\",\"1027\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Up\",UP],\n" " AUTHORITY[\"EPSG\",\"3855\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto wkt2 = "BOUNDCRS[\n" " SOURCECRS[\n" " VERTCRS[\"EGM2008 geoid height\",\n" " VDATUM[\"EGM2008 geoid\"],\n" " CS[vertical,1],\n" " AXIS[\"up\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",3855]]],\n" " TARGETCRS[\n" " GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[\"EGM2008 geoid height to WGS 84 " "ellipsoidal height\",\n" " METHOD[\"GravityRelatedHeight to Geographic3D\"],\n" " PARAMETERFILE[\"Geoid (height correction) model " "file\",\"egm08_25.gtx\",\n" " ID[\"EPSG\",8666]]]]"; EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), wkt2); } // --------------------------------------------------------------------------- TEST(crs, WKT1_VERT_DATUM_EXTENSION_to_PROJ_string) { auto wkt = "VERT_CS[\"EGM2008 geoid height\",\n" " VERT_DATUM[\"EGM2008 geoid\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"egm08_25.gtx\"],\n" " AUTHORITY[\"EPSG\",\"1027\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Up\",UP],\n" " AUTHORITY[\"EPSG\",\"3855\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+geoidgrids=egm08_25.gtx +geoid_crs=WGS84 +vunits=m +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(crs, extractGeographicCRS) { EXPECT_EQ(GeographicCRS::EPSG_4326->extractGeographicCRS(), GeographicCRS::EPSG_4326); EXPECT_EQ(createProjected()->extractGeographicCRS(), GeographicCRS::EPSG_4326); EXPECT_EQ(CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{GeographicCRS::EPSG_4326, createVerticalCRS()}) ->extractGeographicCRS(), GeographicCRS::EPSG_4326); } // --------------------------------------------------------------------------- TEST(crs, extractVerticalCRS) { EXPECT_EQ(GeographicCRS::EPSG_4326->extractVerticalCRS(), nullptr); { auto vertcrs = createCompoundCRS()->extractVerticalCRS(); ASSERT_TRUE(vertcrs != nullptr); EXPECT_TRUE(vertcrs->isEquivalentTo(createVerticalCRS().get())); } } // --------------------------------------------------------------------------- static DerivedGeographicCRSNNPtr createDerivedGeographicCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Atlantic pole"), PropertyMap().set(IdentifiedObject::NAME_KEY, "Pole rotation"), std::vector<OperationParameterNNPtr>{ OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "Latitude of rotated pole")), OperationParameter::create(PropertyMap().set( IdentifiedObject::NAME_KEY, "Longitude of rotated pole")), OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Axis rotation")), }, std::vector<ParameterValueNNPtr>{ ParameterValue::create(Angle(52.0)), ParameterValue::create(Angle(-30.0)), ParameterValue::create(Angle(-25)), }); return DerivedGeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "WMO Atlantic Pole"), GeographicCRS::EPSG_4326, derivingConversion, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); } // --------------------------------------------------------------------------- TEST(crs, derivedGeographicCRS_basic) { auto derivedCRS = createDerivedGeographicCRS(); EXPECT_TRUE(derivedCRS->isEquivalentTo(derivedCRS.get())); EXPECT_FALSE(derivedCRS->isEquivalentTo( derivedCRS->baseCRS().get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(derivedCRS->baseCRS()->isEquivalentTo( derivedCRS.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(crs, derivedGeographicCRS_WKT2) { auto expected = "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Atlantic pole\",\n" " METHOD[\"Pole rotation\"],\n" " PARAMETER[\"Latitude of rotated pole\",52,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Longitude of rotated pole\",-30,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Axis rotation\",-25,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; auto crs = createDerivedGeographicCRS(); EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(crs, derivedGeographicCRS_WKT2_2019) { auto expected = "GEOGCRS[\"WMO Atlantic Pole\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Atlantic pole\",\n" " METHOD[\"Pole rotation\"],\n" " PARAMETER[\"Latitude of rotated pole\",52,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Longitude of rotated pole\",-30,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Axis rotation\",-25,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; EXPECT_EQ( createDerivedGeographicCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, derivedGeographicCRS_WKT1) { EXPECT_THROW( createDerivedGeographicCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, derivedGeographicCRS_to_PROJ) { auto wkt = "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ ob_tran o_proj=longlat\"],\n" " PARAMETER[\"o_lat_p\",52,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"o_lon_p\",-30,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"lon_0\",-25,\n" " UNIT[\"degree\",0.0174532925199433]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=ob_tran +o_proj=longlat +o_lat_p=52 +o_lon_p=-30 +lon_0=-25 " "+datum=WGS84 +no_defs +type=crs"); auto op = CoordinateOperationFactory::create()->createOperation( crs->baseCRS(), NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=ob_tran " "+o_proj=longlat +o_lat_p=52 +o_lon_p=-30 +lon_0=-25 +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg +step " "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(crs, derivedGeographicCRS_with_affine_transform_to_PROJ) { auto wkt = "GEODCRS[\"WGS 84 Translated\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0]],\n" " DERIVINGCONVERSION[\"Translation\",\n" " METHOD[\"Affine parametric transformation\",\n" " ID[\"EPSG\",9624]],\n" " PARAMETER[\"A0\",0.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8623]],\n" " PARAMETER[\"A1\",1,\n" " SCALEUNIT[\"coefficient\",1],\n" " ID[\"EPSG\",8624]],\n" " PARAMETER[\"A2\",0,\n" " SCALEUNIT[\"coefficient\",1],\n" " ID[\"EPSG\",8625]],\n" " PARAMETER[\"B0\",2.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8639]],\n" " PARAMETER[\"B1\",0,\n" " SCALEUNIT[\"coefficient\",1],\n" " ID[\"EPSG\",8640]],\n" " PARAMETER[\"B2\",1,\n" " SCALEUNIT[\"coefficient\",1],\n" " ID[\"EPSG\",8641]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north],\n" " AXIS[\"longitude\",east],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->derivingConversion()->validateParameters().empty()); auto op = CoordinateOperationFactory::create()->createOperation( crs->baseCRS(), NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=affine +xoff=0.5 +s11=1 +s12=0 +yoff=2.5 +s21=0 +s22=1"); } // --------------------------------------------------------------------------- static DerivedGeodeticCRSNNPtr createDerivedGeodeticCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Some conversion"), PropertyMap().set(IdentifiedObject::NAME_KEY, "Some method"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedGeodeticCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Derived geodetic CRS"), GeographicCRS::EPSG_4326, derivingConversion, CartesianCS::createGeocentric(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(crs, derivedGeodeticCRS_basic) { auto derivedCRS = createDerivedGeodeticCRS(); EXPECT_TRUE(derivedCRS->isEquivalentTo(derivedCRS.get())); EXPECT_FALSE(derivedCRS->isEquivalentTo( derivedCRS->baseCRS().get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(derivedCRS->baseCRS()->isEquivalentTo( derivedCRS.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(crs, derivedGeodeticCRS_WKT2) { auto expected = "GEODCRS[\"Derived geodetic CRS\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Some conversion\",\n" " METHOD[\"Some method\"]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto crs = createDerivedGeodeticCRS(); EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(crs, derivedGeodeticCRS_WKT2_2019) { auto expected = "GEODCRS[\"Derived geodetic CRS\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Some conversion\",\n" " METHOD[\"Some method\"]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; EXPECT_EQ( createDerivedGeodeticCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, derivedGeodeticCRS_WKT1) { EXPECT_THROW( createDerivedGeodeticCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, derivedProjectedCRS_WKT2_2019) { auto expected = "DERIVEDPROJCRS[\"derived projectedCRS\",\n" " BASEPROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto crs = createDerivedProjectedCRS(); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_FALSE(crs->isEquivalentTo(createUnrelatedObject().get())); auto geodCRS = crs->extractGeodeticCRS(); EXPECT_TRUE(geodCRS != nullptr); } // --------------------------------------------------------------------------- TEST(crs, derivedProjectedCRS_WKT2_2015) { auto crs = createDerivedProjectedCRS(); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2015).get()), FormattingException); } // --------------------------------------------------------------------------- static DateTimeTemporalCSNNPtr createDateTimeTemporalCS() { return DateTimeTemporalCS::create( PropertyMap(), CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Time"), "T", AxisDirection::FUTURE, UnitOfMeasure::NONE)); } // --------------------------------------------------------------------------- static TemporalCRSNNPtr createDateTimeTemporalCRS() { auto datum = TemporalDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Gregorian calendar"), DateTime::create("0000-01-01"), TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN); return TemporalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Temporal CRS"), datum, createDateTimeTemporalCS()); } // --------------------------------------------------------------------------- TEST(crs, dateTimeTemporalCRS_WKT2) { auto expected = "TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]"; auto crs = createDateTimeTemporalCRS(); EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); } // --------------------------------------------------------------------------- TEST(crs, dateTimeTemporalCRS_WKT2_2019) { auto expected = "TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]"; EXPECT_EQ( createDateTimeTemporalCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- static TemporalCRSNNPtr createTemporalCountCRSWithConvFactor() { auto datum = TemporalDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "GPS time origin"), DateTime::create("1980-01-01T00:00:00.0Z"), TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN); auto cs = TemporalCountCS::create( PropertyMap(), CoordinateSystemAxis::create(PropertyMap(), "T", AxisDirection::FUTURE, UnitOfMeasure("milliseconds (ms)", 0.001, UnitOfMeasure::Type::TIME))); return TemporalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "GPS milliseconds"), datum, cs); } // --------------------------------------------------------------------------- TEST(crs, temporalCountCRSWithConvFactor_WKT2_2019) { auto expected = "TIMECRS[\"GPS milliseconds\",\n" " TDATUM[\"GPS time origin\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[1980-01-01T00:00:00.0Z]],\n" " CS[TemporalCount,1],\n" " AXIS[\"(T)\",future,\n" " TIMEUNIT[\"milliseconds (ms)\",0.001]]]"; EXPECT_EQ( createTemporalCountCRSWithConvFactor()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- static TemporalCRSNNPtr createTemporalCountCRSWithoutConvFactor() { auto datum = TemporalDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "29 December 1979"), DateTime::create("1979-12-29T00"), TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN); auto cs = TemporalCountCS::create( PropertyMap(), CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Time"), "", AxisDirection::FUTURE, UnitOfMeasure("hour", 0, UnitOfMeasure::Type::TIME))); return TemporalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Calendar hours from 1979-12-29"), datum, cs); } // --------------------------------------------------------------------------- TEST(crs, temporalCountCRSWithoutConvFactor_WKT2_2019) { auto expected = "TIMECRS[\"Calendar hours from 1979-12-29\",\n" " TDATUM[\"29 December 1979\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[1979-12-29T00]],\n" " CS[TemporalCount,1],\n" " AXIS[\"time\",future,\n" " TIMEUNIT[\"hour\"]]]"; EXPECT_EQ( createTemporalCountCRSWithoutConvFactor()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- static TemporalCRSNNPtr createTemporalMeasureCRSWithoutConvFactor() { auto datum = TemporalDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Common Era"), DateTime::create("0000"), TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN); auto cs = TemporalMeasureCS::create( PropertyMap(), CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Decimal years"), "a", AxisDirection::FUTURE, UnitOfMeasure("year", 0, UnitOfMeasure::Type::TIME))); return TemporalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Decimal Years CE"), datum, cs); } // --------------------------------------------------------------------------- TEST(crs, temporalMeasureCRSWithoutConvFactor_WKT2_2019) { auto expected = "TIMECRS[\"Decimal Years CE\",\n" " TDATUM[\"Common Era\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000]],\n" " CS[TemporalMeasure,1],\n" " AXIS[\"decimal years (a)\",future,\n" " TIMEUNIT[\"year\"]]]"; EXPECT_EQ( createTemporalMeasureCRSWithoutConvFactor()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- static EngineeringCRSNNPtr createEngineeringCRS() { auto datum = EngineeringDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Engineering datum")); return EngineeringCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Engineering CRS"), datum, CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(crs, engineeringCRS_WKT2) { auto expected = "ENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto crs = createEngineeringCRS(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, engineeringCRS_WKT1) { auto expected = "LOCAL_CS[\"Engineering CRS\",\n" " LOCAL_DATUM[\"Engineering datum\",32767],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; EXPECT_EQ( createEngineeringCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, engineeringCRS_unknown_equivalence) { // Test equivalent of CRS definition got from GPKG (wkt2) and its equivalent // from GeoTIFF (wkt1) // Cf https://github.com/r-spatial/sf/issues/2049#issuecomment-1486600723 auto wkt1 = "ENGCRS[\"Undefined Cartesian SRS with unknown unit\",\n" " EDATUM[\"\"],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto wkt2 = "ENGCRS[\"Undefined Cartesian SRS with unknown unit\",\n" " EDATUM[\"Unknown engineering datum\"],\n" " CS[Cartesian,2],\n" " AXIS[\"x\",unspecified,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"y\",unspecified,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj1 = WKTParser().createFromWKT(wkt1); auto crs1 = nn_dynamic_pointer_cast<CRS>(obj1); ASSERT_TRUE(crs1 != nullptr); auto obj2 = WKTParser().createFromWKT(wkt2); auto crs2 = nn_dynamic_pointer_cast<CRS>(obj2); ASSERT_TRUE(crs2 != nullptr); EXPECT_TRUE( crs1->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs2->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- static ParametricCSNNPtr createParametricCS() { return ParametricCS::create( PropertyMap(), CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "pressure"), "hPa", AxisDirection::UP, UnitOfMeasure("HectoPascal", 100, UnitOfMeasure::Type::PARAMETRIC))); } // --------------------------------------------------------------------------- static ParametricCRSNNPtr createParametricCRS() { auto datum = ParametricDatum::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Parametric datum")); return ParametricCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Parametric CRS"), datum, createParametricCS()); } // --------------------------------------------------------------------------- TEST(crs, default_identify_method) { EXPECT_TRUE(createParametricCRS()->identify(nullptr).empty()); } // --------------------------------------------------------------------------- TEST(crs, parametricCRS_WKT2) { auto expected = "PARAMETRICCRS[\"Parametric CRS\",\n" " PDATUM[\"Parametric datum\"],\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]"; auto crs = createParametricCRS(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, parametricCRS_WKT1) { EXPECT_THROW( createParametricCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, derivedVerticalCRS_basic) { auto crs = createDerivedVerticalCRS(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_FALSE(crs->isEquivalentTo(crs->baseCRS().get())); EXPECT_FALSE(crs->baseCRS()->isEquivalentTo(crs.get())); } // --------------------------------------------------------------------------- TEST(crs, DerivedVerticalCRS_WKT2) { auto expected = "VERTCRS[\"Derived vertCRS\",\n" " BASEVERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\",\n" " ID[\"EPSG\",5101]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto crs = createDerivedVerticalCRS(); EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, DerivedVerticalCRS_WKT1) { EXPECT_THROW( createDerivedVerticalCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, DerivedVerticalCRS_WKT1_when_simple_derivation) { auto derivingConversion = Conversion::createChangeVerticalUnit(PropertyMap().set( IdentifiedObject::NAME_KEY, "Vertical Axis Unit Conversion")); auto crs = DerivedVerticalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Derived vertCRS"), createVerticalCRS(), derivingConversion, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::FOOT)); auto expected = "VERT_CS[\"Derived vertCRS\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005,\n" " AUTHORITY[\"EPSG\",\"5101\"]],\n" " UNIT[\"foot\",0.3048,\n" " AUTHORITY[\"EPSG\",\"9002\"]],\n" " AXIS[\"Gravity-related height\",UP]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), expected); } // --------------------------------------------------------------------------- static DerivedEngineeringCRSNNPtr createDerivedEngineeringCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), PropertyMap().set(IdentifiedObject::NAME_KEY, "PROJ unimplemented"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedEngineeringCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Derived EngineeringCRS"), createEngineeringCRS(), derivingConversion, CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(crs, DerivedEngineeringCRS_WKT2) { auto expected = "ENGCRS[\"Derived EngineeringCRS\",\n" " BASEENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto crs = createDerivedEngineeringCRS(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_TRUE(crs->coordinateSystem()->isEquivalentTo( CartesianCS::createEastingNorthing(UnitOfMeasure::METRE).get())); EXPECT_TRUE( crs->datum()->isEquivalentTo(createEngineeringCRS()->datum().get())); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); EXPECT_THROW( createDerivedEngineeringCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2015).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, DerivedEngineeringCRS_WKT1) { EXPECT_THROW( createDerivedEngineeringCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- static DerivedParametricCRSNNPtr createDerivedParametricCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), PropertyMap().set(IdentifiedObject::NAME_KEY, "PROJ unimplemented"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedParametricCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Derived ParametricCRS"), createParametricCRS(), derivingConversion, createParametricCS()); } // --------------------------------------------------------------------------- TEST(crs, DerivedParametricCRS_WKT2) { auto expected = "PARAMETRICCRS[\"Derived ParametricCRS\",\n" " BASEPARAMCRS[\"Parametric CRS\",\n" " PDATUM[\"Parametric datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"]],\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]"; auto crs = createDerivedParametricCRS(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_TRUE( crs->coordinateSystem()->isEquivalentTo(createParametricCS().get())); EXPECT_TRUE( crs->datum()->isEquivalentTo(createParametricCRS()->datum().get())); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, DerivedParametricCRS_WKT1) { EXPECT_THROW( createDerivedParametricCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- static DerivedTemporalCRSNNPtr createDerivedTemporalCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), PropertyMap().set(IdentifiedObject::NAME_KEY, "PROJ unimplemented"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedTemporalCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Derived TemporalCRS"), createDateTimeTemporalCRS(), derivingConversion, createDateTimeTemporalCS()); } // --------------------------------------------------------------------------- TEST(crs, DeriveTemporalCRS_WKT2) { auto expected = "TIMECRS[\"Derived TemporalCRS\",\n" " BASETIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]"; auto crs = createDerivedTemporalCRS(); EXPECT_TRUE(crs->isEquivalentTo(crs.get())); EXPECT_TRUE(crs->shallowClone()->isEquivalentTo(crs.get())); EXPECT_TRUE(!crs->isEquivalentTo(createUnrelatedObject().get())); EXPECT_TRUE(crs->coordinateSystem()->isEquivalentTo( createDateTimeTemporalCS().get())); EXPECT_TRUE(crs->datum()->isEquivalentTo( createDateTimeTemporalCRS()->datum().get())); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(crs, DeriveTemporalCRS_WKT1) { EXPECT_THROW( createDerivedTemporalCRS()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(crs, crs_createBoundCRSToWGS84IfPossible) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); { auto crs_4326 = factory->createCoordinateReferenceSystem("4326"); EXPECT_EQ(crs_4326->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_4326); } { auto crs_32631 = factory->createCoordinateReferenceSystem("32631"); EXPECT_EQ(crs_32631->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_32631); } { // Pulkovo 42 East Germany auto crs_5670 = factory->createCoordinateReferenceSystem("5670"); EXPECT_EQ(crs_5670->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_5670); } { // Pulkovo 42 Romania auto crs_3844 = factory->createCoordinateReferenceSystem("3844"); EXPECT_EQ(crs_3844->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_3844); } { // Pulkovo 42 Poland auto crs_2171 = factory->createCoordinateReferenceSystem("2171"); EXPECT_EQ(crs_2171->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_2171); } { // NTF (Paris) auto crs_4807 = factory->createCoordinateReferenceSystem("4807"); auto bound = crs_4807->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER); EXPECT_NE(bound, crs_4807); EXPECT_EQ(bound->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), bound); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(bound); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ( boundCRS->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +ellps=clrk80ign +pm=paris " "+towgs84=-168,-60,320,0,0,0,0 +no_defs +type=crs"); } { // WGS 84 + EGM2008 height auto obj = createFromUserInput("EPSG:4326+3855", dbContext); auto crs = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER); EXPECT_NE(res, crs); EXPECT_EQ(res->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), res); auto compoundCRS = nn_dynamic_pointer_cast<CompoundCRS>(res); ASSERT_TRUE(compoundCRS != nullptr); EXPECT_EQ(compoundCRS->exportToPROJString( PROJStringFormatter::create().get()), "+proj=longlat +datum=WGS84 +geoidgrids=us_nga_egm08_25.tif " "+geoid_crs=WGS84 +vunits=m +no_defs +type=crs"); } #ifdef disabled_since_epsg_10_035 // There are now too many transformations from NGF-IGN69 height to WGS 84 // for createBoundCRSToWGS84IfPossible() to be able to select a // vertical geoidgrid { // NTF (Paris) / Lambert zone II + NGF-IGN69 height auto crs_7421 = factory->createCoordinateReferenceSystem("7421"); auto res = crs_7421->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER); EXPECT_NE(res, crs_7421); EXPECT_EQ(res->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), res); auto compoundCRS = nn_dynamic_pointer_cast<CompoundCRS>(res); ASSERT_TRUE(compoundCRS != nullptr); EXPECT_EQ(compoundCRS->exportToPROJString( PROJStringFormatter::create().get()), "+proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=0 +k_0=0.99987742 " "+x_0=600000 +y_0=2200000 +ellps=clrk80ign +pm=paris " "+towgs84=-168,-60,320,0,0,0,0 +units=m " "+geoidgrids=fr_ign_RAF18.tif +vunits=m +no_defs +type=crs"); } #endif { auto crs = createVerticalCRS(); EXPECT_EQ(crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs); } { auto crs = createCompoundCRS(); EXPECT_EQ(crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs); } { auto factoryIGNF = AuthorityFactory::create(DatabaseContext::create(), "IGNF"); auto crs = factoryIGNF->createCoordinateReferenceSystem("TERA50STEREO"); auto bound = crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER); EXPECT_NE(bound, crs); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(bound); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ( boundCRS->exportToPROJString(PROJStringFormatter::create().get()), "+proj=stere +lat_0=-90 +lon_0=140 +k=0.960272946 " "+x_0=300000 +y_0=-2299363.482 +ellps=intl " "+towgs84=324.8,153.6,172.1,0,0,0,0 +units=m +no_defs +type=crs"); } { auto factoryIGNF = AuthorityFactory::create(DatabaseContext::create(), "IGNF"); auto crs = factoryIGNF->createCoordinateReferenceSystem("PGP50"); auto bound = crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER); EXPECT_NE(bound, crs); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(bound); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ( boundCRS->exportToPROJString(PROJStringFormatter::create().get()), "+proj=geocent +ellps=intl " "+towgs84=324.8,153.6,172.1,0,0,0,0 +units=m +no_defs +type=crs"); } { auto crs = factory->createCoordinateReferenceSystem("4269"); // NAD83 auto bound = crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER); EXPECT_EQ(bound, crs); } { // GDA2020 geocentric auto crs = factory->createCoordinateReferenceSystem("7842"); const auto time_before = ::testing::UnitTest::GetInstance()->elapsed_time(); crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse:: IF_NO_DIRECT_TRANSFORMATION); const auto time_after = ::testing::UnitTest::GetInstance()->elapsed_time(); EXPECT_LE(time_after - time_before, 500); } { // POSGAR 2007: it has 2 helmert shifts to WGS84 (#2356). Don't take // an arbitrary one auto crs_5340 = factory->createCoordinateReferenceSystem("5340"); EXPECT_EQ(crs_5340->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_5340); } { // "MGI 1901 / Balkans zone 7": it has 2 area of validity, one // for Bosnia and Herzegovina/Kosovo/Montenegro/Serbia and another // one for North macedonie auto crs_6316 = factory->createCoordinateReferenceSystem("6316"); EXPECT_EQ(crs_6316->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_6316); } // Check that we get the same result from an EPSG code and a CRS created // from its WKT1 representation. { // Pulkovo 1942 / CS63 zone A2 auto crs = factory->createCoordinateReferenceSystem("2936"); // Two candidate transformations found, so not picking up any EXPECT_EQ(crs->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs); auto wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs_from_wkt = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(crs_from_wkt != nullptr); EXPECT_EQ(crs_from_wkt->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER), crs_from_wkt); } } // --------------------------------------------------------------------------- TEST(crs, crs_stripVerticalComponent) { { auto crs = GeographicCRS::EPSG_4979->stripVerticalComponent(); auto geogCRS = nn_dynamic_pointer_cast<GeographicCRS>(crs); ASSERT_TRUE(geogCRS != nullptr); EXPECT_EQ(geogCRS->coordinateSystem()->axisList().size(), 2U); } { auto crs = GeographicCRS::EPSG_4326->stripVerticalComponent(); EXPECT_TRUE(crs->isEquivalentTo(GeographicCRS::EPSG_4326.get())); } { std::vector<CoordinateSystemAxisNNPtr> axis{ CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Easting"), "E", AxisDirection::EAST, UnitOfMeasure::METRE), CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Northing"), "N", AxisDirection::NORTH, UnitOfMeasure::METRE), CoordinateSystemAxis::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "Height"), "z", AxisDirection::UP, UnitOfMeasure::METRE)}; auto cs(CartesianCS::create(PropertyMap(), axis[0], axis[1], axis[2])); auto projected3DCrs = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 31, true), cs); auto projCRS = nn_dynamic_pointer_cast<ProjectedCRS>( projected3DCrs->stripVerticalComponent()); ASSERT_TRUE(projCRS != nullptr); EXPECT_EQ(projCRS->coordinateSystem()->axisList().size(), 2U); } { auto crs3D = createDerivedProjectedCRS()->promoteTo3D(std::string(), nullptr); auto derivedProj3D = nn_dynamic_pointer_cast<DerivedProjectedCRS>(crs3D); ASSERT_TRUE(derivedProj3D != nullptr); EXPECT_EQ(derivedProj3D->coordinateSystem()->axisList().size(), 3U); auto derivedProj2D = nn_dynamic_pointer_cast<DerivedProjectedCRS>( derivedProj3D->stripVerticalComponent()); ASSERT_TRUE(derivedProj2D != nullptr); EXPECT_EQ(derivedProj2D->coordinateSystem()->axisList().size(), 2U); } } // --------------------------------------------------------------------------- TEST(crs, crs_alterGeodeticCRS) { { auto crs = GeographicCRS::EPSG_4326->alterGeodeticCRS( GeographicCRS::EPSG_4979); EXPECT_TRUE(crs->isEquivalentTo(GeographicCRS::EPSG_4979.get())); } { auto crs = createProjected()->alterGeodeticCRS(GeographicCRS::EPSG_4979); auto projCRS = dynamic_cast<ProjectedCRS *>(crs.get()); ASSERT_TRUE(projCRS != nullptr); EXPECT_TRUE( projCRS->baseCRS()->isEquivalentTo(GeographicCRS::EPSG_4979.get())); } { auto crs = createCompoundCRS()->alterGeodeticCRS(GeographicCRS::EPSG_4979); auto compoundCRS = dynamic_cast<CompoundCRS *>(crs.get()); ASSERT_TRUE(compoundCRS != nullptr); EXPECT_TRUE(compoundCRS->componentReferenceSystems()[0] ->extractGeographicCRS() ->isEquivalentTo(GeographicCRS::EPSG_4979.get())); } { auto crs = createVerticalCRS()->alterGeodeticCRS(GeographicCRS::EPSG_4979); EXPECT_TRUE(crs->isEquivalentTo(createVerticalCRS().get())); } { auto crs = createDerivedProjectedCRS()->alterGeodeticCRS( GeographicCRS::EPSG_4979); auto derivedProjCRS = dynamic_cast<DerivedProjectedCRS *>(crs.get()); ASSERT_TRUE(derivedProjCRS != nullptr); EXPECT_TRUE(derivedProjCRS->baseCRS()->baseCRS()->isEquivalentTo( GeographicCRS::EPSG_4979.get())); } } // --------------------------------------------------------------------------- TEST(crs, crs_alterCSLinearUnit) { { auto crs = createProjected()->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); auto projCRS = dynamic_cast<ProjectedCRS *>(crs.get()); ASSERT_TRUE(projCRS != nullptr); auto cs = projCRS->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_EQ(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[0]->unit().conversionToSI(), 2); EXPECT_EQ(cs->axisList()[1]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[1]->unit().conversionToSI(), 2); } { auto crs = createDerivedProjectedCRS()->alterCSLinearUnit( UnitOfMeasure("my unit", 2)); auto derivedProjCRS = dynamic_cast<DerivedProjectedCRS *>(crs.get()); ASSERT_TRUE(derivedProjCRS != nullptr); auto cs = derivedProjCRS->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_EQ(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[0]->unit().conversionToSI(), 2); EXPECT_EQ(cs->axisList()[1]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[1]->unit().conversionToSI(), 2); } { auto crs = createDerivedProjectedCRSNorthingEasting(); auto alteredCRS = crs->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); auto leftHandedDerivedCRS = dynamic_cast<DerivedProjectedCRS *>(alteredCRS.get()); ASSERT_TRUE(leftHandedDerivedCRS != nullptr); auto cs = dynamic_cast<CartesianCS *>( leftHandedDerivedCRS->coordinateSystem().get()); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_EQ(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(cs->axisList()[0]->unit().conversionToSI(), 2); EXPECT_EQ(cs->axisList()[1]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[1]->direction(), AxisDirection::EAST); EXPECT_EQ(cs->axisList()[1]->unit().conversionToSI(), 2); } { auto crs = GeodeticCRS::EPSG_4978->alterCSLinearUnit( UnitOfMeasure("my unit", 2)); auto geodCRS = dynamic_cast<GeodeticCRS *>(crs.get()); ASSERT_TRUE(geodCRS != nullptr); auto cs = dynamic_cast<CartesianCS *>(geodCRS->coordinateSystem().get()); ASSERT_EQ(cs->axisList().size(), 3U); EXPECT_EQ(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[0]->unit().conversionToSI(), 2); EXPECT_EQ(cs->axisList()[1]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[1]->unit().conversionToSI(), 2); EXPECT_EQ(cs->axisList()[2]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[2]->unit().conversionToSI(), 2); } { auto crs = GeographicCRS::EPSG_4979->alterCSLinearUnit( UnitOfMeasure("my unit", 2)); auto geogCRS = dynamic_cast<GeographicCRS *>(crs.get()); ASSERT_TRUE(geogCRS != nullptr); auto cs = geogCRS->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 3U); EXPECT_NE(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_NE(cs->axisList()[0]->unit().conversionToSI(), 2); EXPECT_NE(cs->axisList()[1]->unit().name(), "my unit"); EXPECT_NE(cs->axisList()[1]->unit().conversionToSI(), 2); EXPECT_EQ(cs->axisList()[2]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[2]->unit().conversionToSI(), 2); } { auto crs = createVerticalCRS()->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); auto vertCRS = dynamic_cast<VerticalCRS *>(crs.get()); ASSERT_TRUE(vertCRS != nullptr); auto cs = vertCRS->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[0]->unit().conversionToSI(), 2); } { auto obj = WKTParser().createFromWKT("LOCAL_CS[\"foo\"]"); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); auto alteredCRS = crs->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); auto wkt = alteredCRS->exportToWKT( &(WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL) ->setMultiLine(false))); EXPECT_EQ(wkt, "LOCAL_CS[\"foo\",UNIT[\"my unit\",2]," "AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH]]"); } { auto crs = createCompoundCRS()->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); auto compoundCRS = dynamic_cast<CompoundCRS *>(crs.get()); ASSERT_TRUE(compoundCRS != nullptr); EXPECT_EQ(compoundCRS->componentReferenceSystems().size(), 2U); for (const auto &subCrs : compoundCRS->componentReferenceSystems()) { auto singleCrs = dynamic_cast<SingleCRS *>(subCrs.get()); ASSERT_TRUE(singleCrs != nullptr); auto cs = singleCrs->coordinateSystem(); ASSERT_GE(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[0]->unit().conversionToSI(), 2); } } { auto crs = BoundCRS::createFromTOWGS84( createProjected(), std::vector<double>{1, 2, 3, 4, 5, 6, 7}) ->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); auto boundCRS = dynamic_cast<BoundCRS *>(crs.get()); ASSERT_TRUE(boundCRS != nullptr); auto baseCRS = boundCRS->baseCRS(); auto projCRS = dynamic_cast<ProjectedCRS *>(baseCRS.get()); ASSERT_TRUE(projCRS != nullptr); auto cs = projCRS->coordinateSystem(); EXPECT_EQ(cs->axisList()[0]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[0]->unit().conversionToSI(), 2); EXPECT_EQ(cs->axisList()[1]->unit().name(), "my unit"); EXPECT_EQ(cs->axisList()[1]->unit().conversionToSI(), 2); } // Not implemented on parametricCRS auto crs = createParametricCRS()->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); EXPECT_TRUE(createParametricCRS()->isEquivalentTo(crs.get())); } // --------------------------------------------------------------------------- TEST(crs, alterParametersLinearUnit) { { auto crs = createProjected()->alterParametersLinearUnit( UnitOfMeasure("my unit", 2), false); auto wkt = crs->exportToWKT(&WKTFormatter::create()->setMultiLine(false)); EXPECT_TRUE(wkt.find("PARAMETER[\"Longitude of natural origin\",3") != std::string::npos) << wkt; EXPECT_TRUE( wkt.find( "PARAMETER[\"False easting\",500000,UNIT[\"my unit\",2]") != std::string::npos) << wkt; } { auto crs = createProjected()->alterParametersLinearUnit( UnitOfMeasure("my unit", 2), true); auto wkt = crs->exportToWKT(&WKTFormatter::create()->setMultiLine(false)); EXPECT_TRUE( wkt.find( "PARAMETER[\"False easting\",250000,UNIT[\"my unit\",2]") != std::string::npos) << wkt; } } // --------------------------------------------------------------------------- TEST(crs, getNonDeprecated) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); { // No id auto crs = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto list = crs->getNonDeprecated(dbContext); ASSERT_EQ(list.size(), 0U); } { // Non-deprecated auto crs = factory->createGeodeticCRS("4326"); auto list = crs->getNonDeprecated(dbContext); ASSERT_EQ(list.size(), 0U); } { // Non supported CRS type auto crs = BoundCRS::createFromTOWGS84( createProjected(), std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto list = crs->getNonDeprecated(dbContext); ASSERT_EQ(list.size(), 0U); } { auto crs = factory->createGeodeticCRS("4226"); auto list = crs->getNonDeprecated(dbContext); ASSERT_EQ(list.size(), 2U); } { auto crs = factory->createProjectedCRS("26591"); auto list = crs->getNonDeprecated(dbContext); ASSERT_EQ(list.size(), 1U); } { auto crs = factory->createVerticalCRS("5704"); auto list = crs->getNonDeprecated(dbContext); ASSERT_EQ(list.size(), 1U); } { auto crs = factory->createCompoundCRS("7401"); auto list = crs->getNonDeprecated(dbContext); ASSERT_EQ(list.size(), 1U); } } // --------------------------------------------------------------------------- TEST(crs, promoteTo3D_and_demoteTo2D) { auto dbContext = DatabaseContext::create(); { auto crs = GeographicCRS::EPSG_4326; auto crs3D = crs->promoteTo3D(std::string(), nullptr); auto crs3DAsGeog = nn_dynamic_pointer_cast<GeographicCRS>(crs3D); ASSERT_TRUE(crs3DAsGeog != nullptr); EXPECT_EQ(crs3DAsGeog->coordinateSystem()->axisList().size(), 3U); EXPECT_TRUE(crs3D->promoteTo3D(std::string(), nullptr) ->isEquivalentTo(crs3D.get())); } { auto crs = GeographicCRS::EPSG_4326; auto crs3D = crs->promoteTo3D(std::string(), dbContext); auto crs3DAsGeog = nn_dynamic_pointer_cast<GeographicCRS>(crs3D); ASSERT_TRUE(crs3DAsGeog != nullptr); EXPECT_EQ(crs3DAsGeog->coordinateSystem()->axisList().size(), 3U); EXPECT_TRUE(!crs3DAsGeog->identifiers().empty()); auto demoted = crs3DAsGeog->demoteTo2D(std::string(), dbContext); EXPECT_EQ(demoted->coordinateSystem()->axisList().size(), 2U); EXPECT_TRUE(!demoted->identifiers().empty()); } { auto crs = createProjected(); auto crs3D = crs->promoteTo3D(std::string(), nullptr); auto crs3DAsProjected = nn_dynamic_pointer_cast<ProjectedCRS>(crs3D); ASSERT_TRUE(crs3DAsProjected != nullptr); EXPECT_EQ(crs3DAsProjected->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ( crs3DAsProjected->baseCRS()->coordinateSystem()->axisList().size(), 3U); // Check that importing an exported Projected 3D CRS as WKT keeps // the 3D aspect of the baseCRS (see #2122) { WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); crs3DAsProjected->exportToWKT(f.get()); auto obj = WKTParser().createFromWKT(f->toString()); auto crsFromWkt = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crsFromWkt != nullptr); EXPECT_EQ(crsFromWkt->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ( crsFromWkt->baseCRS()->coordinateSystem()->axisList().size(), 3U); } EXPECT_TRUE(crs3D->promoteTo3D(std::string(), nullptr) ->isEquivalentTo(crs3D.get())); auto demoted = crs3DAsProjected->demoteTo2D(std::string(), nullptr); EXPECT_EQ(demoted->coordinateSystem()->axisList().size(), 2U); EXPECT_EQ(demoted->baseCRS()->coordinateSystem()->axisList().size(), 2U); } { auto crs = createProjected(); auto crs3D = crs->promoteTo3D(std::string(), dbContext); auto crs3DAsProjected = nn_dynamic_pointer_cast<ProjectedCRS>(crs3D); ASSERT_TRUE(crs3DAsProjected != nullptr); EXPECT_EQ(crs3DAsProjected->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ( crs3DAsProjected->baseCRS()->coordinateSystem()->axisList().size(), 3U); EXPECT_TRUE(!crs3DAsProjected->baseCRS()->identifiers().empty()); auto demoted = crs3DAsProjected->demoteTo2D(std::string(), dbContext); EXPECT_EQ(demoted->coordinateSystem()->axisList().size(), 2U); EXPECT_EQ(demoted->baseCRS()->coordinateSystem()->axisList().size(), 2U); EXPECT_TRUE(!demoted->baseCRS()->identifiers().empty()); } { auto crs = BoundCRS::createFromTOWGS84( createProjected(), std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto crs3D = crs->promoteTo3D(std::string(), dbContext); auto crs3DAsBound = nn_dynamic_pointer_cast<BoundCRS>(crs3D); ASSERT_TRUE(crs3DAsBound != nullptr); { auto baseCRS = nn_dynamic_pointer_cast<ProjectedCRS>(crs3DAsBound->baseCRS()); ASSERT_TRUE(baseCRS != nullptr); EXPECT_EQ(baseCRS->coordinateSystem()->axisList().size(), 3U); auto hubCRS = nn_dynamic_pointer_cast<GeographicCRS>(crs3DAsBound->hubCRS()); ASSERT_TRUE(hubCRS != nullptr); EXPECT_EQ(hubCRS->coordinateSystem()->axisList().size(), 3U); auto transfSrcCRS = nn_dynamic_pointer_cast<GeographicCRS>( crs3DAsBound->transformation()->sourceCRS()); ASSERT_TRUE(transfSrcCRS != nullptr); EXPECT_EQ(transfSrcCRS->coordinateSystem()->axisList().size(), 3U); auto transfDstCRS = nn_dynamic_pointer_cast<GeographicCRS>( crs3DAsBound->transformation()->targetCRS()); ASSERT_TRUE(transfDstCRS != nullptr); EXPECT_EQ(transfDstCRS->coordinateSystem()->axisList().size(), 3U); } auto demoted = crs3DAsBound->demoteTo2D(std::string(), nullptr); auto crs2DAsBound = nn_dynamic_pointer_cast<BoundCRS>(demoted); ASSERT_TRUE(crs2DAsBound != nullptr); { auto baseCRS = nn_dynamic_pointer_cast<ProjectedCRS>(crs2DAsBound->baseCRS()); ASSERT_TRUE(baseCRS != nullptr); EXPECT_EQ(baseCRS->coordinateSystem()->axisList().size(), 2U); auto hubCRS = nn_dynamic_pointer_cast<GeographicCRS>(crs2DAsBound->hubCRS()); ASSERT_TRUE(hubCRS != nullptr); EXPECT_EQ(hubCRS->coordinateSystem()->axisList().size(), 2U); auto transfSrcCRS = nn_dynamic_pointer_cast<GeographicCRS>( crs2DAsBound->transformation()->sourceCRS()); ASSERT_TRUE(transfSrcCRS != nullptr); EXPECT_EQ(transfSrcCRS->coordinateSystem()->axisList().size(), 2U); auto transfDstCRS = nn_dynamic_pointer_cast<GeographicCRS>( crs2DAsBound->transformation()->targetCRS()); ASSERT_TRUE(transfDstCRS != nullptr); EXPECT_EQ(transfDstCRS->coordinateSystem()->axisList().size(), 2U); } } { auto compoundCRS = createCompoundCRS(); auto demoted = compoundCRS->demoteTo2D(std::string(), nullptr); EXPECT_TRUE(dynamic_cast<const ProjectedCRS *>(demoted.get()) != nullptr); } { auto crs = createDerivedGeographicCRS(); auto crs3D = crs->promoteTo3D(std::string(), dbContext); auto crs3DAsDerivedGeog = nn_dynamic_pointer_cast<DerivedGeographicCRS>(crs3D); ASSERT_TRUE(crs3DAsDerivedGeog != nullptr); EXPECT_EQ(crs3DAsDerivedGeog->baseCRS() ->coordinateSystem() ->axisList() .size(), 3U); EXPECT_EQ(crs3DAsDerivedGeog->coordinateSystem()->axisList().size(), 3U); EXPECT_TRUE(crs3DAsDerivedGeog->promoteTo3D(std::string(), nullptr) ->isEquivalentTo(crs3DAsDerivedGeog.get())); auto demoted = crs3DAsDerivedGeog->demoteTo2D(std::string(), dbContext); EXPECT_EQ(demoted->baseCRS()->coordinateSystem()->axisList().size(), 2U); EXPECT_EQ(demoted->coordinateSystem()->axisList().size(), 2U); EXPECT_TRUE(demoted->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(demoted->demoteTo2D(std::string(), nullptr) ->isEquivalentTo(demoted.get())); } { auto crs = createDerivedProjectedCRS(); auto crs3D = crs->promoteTo3D(std::string(), dbContext); auto crs3DAsDerivedProj = nn_dynamic_pointer_cast<DerivedProjectedCRS>(crs3D); ASSERT_TRUE(crs3DAsDerivedProj != nullptr); EXPECT_EQ(crs3DAsDerivedProj->baseCRS() ->coordinateSystem() ->axisList() .size(), 3U); EXPECT_EQ(crs3DAsDerivedProj->coordinateSystem()->axisList().size(), 3U); EXPECT_TRUE(crs3DAsDerivedProj->promoteTo3D(std::string(), nullptr) ->isEquivalentTo(crs3DAsDerivedProj.get())); // Check that importing an exported DerivedProjected 3D CRS as WKT keeps // the 3D aspect of the baseCRS (see #3340) { WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019)); crs3DAsDerivedProj->exportToWKT(f.get()); auto obj = WKTParser().createFromWKT(f->toString()); auto crsFromWkt = nn_dynamic_pointer_cast<DerivedProjectedCRS>(obj); ASSERT_TRUE(crsFromWkt != nullptr); EXPECT_EQ(crsFromWkt->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ( crsFromWkt->baseCRS()->coordinateSystem()->axisList().size(), 3U); } auto demoted = crs3DAsDerivedProj->demoteTo2D(std::string(), dbContext); EXPECT_EQ(demoted->baseCRS()->coordinateSystem()->axisList().size(), 2U); EXPECT_EQ(demoted->coordinateSystem()->axisList().size(), 2U); EXPECT_TRUE(demoted->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(demoted->demoteTo2D(std::string(), nullptr) ->isEquivalentTo(demoted.get())); } } // --------------------------------------------------------------------------- TEST(crs, normalizeForVisualization_derivedprojected_operation) { auto crs = createDerivedProjectedCRSNorthingEasting(); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, crs); auto proj_string = "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=utm +zone=31 " "+ellps=WGS84 +step +proj=unimplemented +step +proj=unitconvert " "+xy_in=m +xy_out=ft +step +proj=axisswap +order=2,1"; ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), proj_string); auto opNormalized = op->normalizeForVisualization(); auto proj_string_normalized = "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad +step " "+proj=utm +zone=31 +ellps=WGS84 +step +proj=unimplemented +step " "+proj=unitconvert +xy_in=m +xy_out=ft"; EXPECT_EQ( opNormalized->exportToPROJString(PROJStringFormatter::create().get()), proj_string_normalized); } // --------------------------------------------------------------------------- TEST(crs, normalizeForVisualization_bound) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); // NTF (Paris) const auto crs_4807 = factory->createCoordinateReferenceSystem("4807"); const auto bound = crs_4807->createBoundCRSToWGS84IfPossible( dbContext, CoordinateOperationContext::IntermediateCRSUse::NEVER); EXPECT_NE(crs_4807, bound); std::string normalized_proj_string = "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 +step " "+proj=cart +ellps=WGS84 +step +proj=helmert +x=168 +y=60 +z=-320 " "+step +inv +proj=cart +ellps=clrk80ign +step +proj=pop +v_3 +step " "+proj=longlat +ellps=clrk80ign +pm=paris +step +proj=unitconvert " "+xy_in=rad +xy_out=grad"; auto orig_proj_string = normalized_proj_string + " +step +proj=axisswap +order=2,1"; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, bound); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), orig_proj_string); const auto normalizedCrs = bound->normalizeForVisualization(); auto normalizedCrsAsBound = nn_dynamic_pointer_cast<BoundCRS>(normalizedCrs); ASSERT_TRUE(normalizedCrsAsBound != nullptr); auto singleCrs = nn_dynamic_pointer_cast<SingleCRS>(normalizedCrsAsBound->baseCRS()); ASSERT_TRUE(singleCrs != nullptr); const auto &normalizedAxisList = singleCrs->coordinateSystem()->axisList(); ASSERT_EQ(normalizedAxisList.size(), 2U); EXPECT_EQ(normalizedAxisList[0]->direction(), osgeo::proj::cs::AxisDirection::EAST); EXPECT_EQ(normalizedAxisList[1]->direction(), osgeo::proj::cs::AxisDirection::NORTH); auto opNormalized = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, normalizedCrs); ASSERT_TRUE(opNormalized != nullptr); EXPECT_EQ( opNormalized->exportToPROJString(PROJStringFormatter::create().get()), normalized_proj_string); } // --------------------------------------------------------------------------- TEST(crs, normalizeForVisualization_derivedprojected) { auto crs = createDerivedProjectedCRSNorthingEasting(); { const auto &axisList = crs->coordinateSystem()->axisList(); ASSERT_EQ(axisList.size(), 2U); EXPECT_EQ(axisList[0]->direction(), osgeo::proj::cs::AxisDirection::NORTH); EXPECT_EQ(axisList[1]->direction(), osgeo::proj::cs::AxisDirection::EAST); } { auto normalized = nn_dynamic_pointer_cast<SingleCRS>( crs->normalizeForVisualization()); const auto &normalizedAxisList = normalized->coordinateSystem()->axisList(); ASSERT_EQ(normalizedAxisList.size(), 2U); EXPECT_EQ(normalizedAxisList[0]->direction(), osgeo::proj::cs::AxisDirection::EAST); EXPECT_EQ(normalizedAxisList[1]->direction(), osgeo::proj::cs::AxisDirection::NORTH); } { auto normalized3D = nn_dynamic_pointer_cast<SingleCRS>( crs->promoteTo3D(std::string(), nullptr) ->normalizeForVisualization()); const auto &normalized3DAxisList = normalized3D->coordinateSystem()->axisList(); ASSERT_EQ(normalized3DAxisList.size(), 3U); EXPECT_EQ(normalized3DAxisList[0]->direction(), osgeo::proj::cs::AxisDirection::EAST); EXPECT_EQ(normalized3DAxisList[1]->direction(), osgeo::proj::cs::AxisDirection::NORTH); EXPECT_EQ(normalized3DAxisList[2]->direction(), osgeo::proj::cs::AxisDirection::UP); } } // --------------------------------------------------------------------------- TEST(crs, projected_normalizeForVisualization_do_not_mess_deriving_conversion) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // Something with non standard order auto projCRS = authFactory->createProjectedCRS("3035"); { auto src = GeographicCRS::EPSG_4326; auto op = CoordinateOperationFactory::create()->createOperation(src, projCRS); ASSERT_TRUE(op != nullptr); // Make sure to run that in a scope, so that the object get destroyed op->normalizeForVisualization(); } EXPECT_EQ(projCRS->derivingConversion()->targetCRS().get(), projCRS.get()); } // --------------------------------------------------------------------------- TEST(crs, projected_promoteTo3D_do_not_mess_deriving_conversion) { auto projCRS = createProjected(); { // Make sure to run that in a scope, so that the object get destroyed projCRS->promoteTo3D(std::string(), nullptr); } EXPECT_EQ(projCRS->derivingConversion()->targetCRS().get(), projCRS.get()); } // --------------------------------------------------------------------------- TEST(crs, projected_demoteTo2D_do_not_mess_deriving_conversion) { auto projCRS = nn_dynamic_pointer_cast<ProjectedCRS>( createProjected()->promoteTo3D(std::string(), nullptr)); { // Make sure to run that in a scope, so that the object get destroyed projCRS->demoteTo2D(std::string(), nullptr); } EXPECT_EQ(projCRS->derivingConversion()->targetCRS().get(), projCRS.get()); } // --------------------------------------------------------------------------- TEST(crs, projected_alterGeodeticCRS_do_not_mess_deriving_conversion) { auto projCRS = createProjected(); { // Make sure to run that in a scope, so that the object get destroyed projCRS->alterGeodeticCRS(NN_NO_CHECK(projCRS->extractGeographicCRS())); } EXPECT_EQ(projCRS->derivingConversion()->targetCRS().get(), projCRS.get()); } // --------------------------------------------------------------------------- TEST(crs, projected_alterCSLinearUnit_do_not_mess_deriving_conversion) { auto projCRS = createProjected(); { // Make sure to run that in a scope, so that the object get destroyed projCRS->alterCSLinearUnit(UnitOfMeasure("my unit", 2)); } EXPECT_EQ(projCRS->derivingConversion()->targetCRS().get(), projCRS.get()); } // --------------------------------------------------------------------------- TEST(crs, projected_alterParametersLinearUnit_do_not_mess_deriving_conversion) { auto projCRS = createProjected(); { // Make sure to run that in a scope, so that the object get destroyed projCRS->alterParametersLinearUnit(UnitOfMeasure::METRE, false); } EXPECT_EQ(projCRS->derivingConversion()->targetCRS().get(), projCRS.get()); } // --------------------------------------------------------------------------- TEST(crs, projected_is_equivalent_to_with_proj4_extension) { const auto obj1 = PROJStringParser().createFromPROJString( "+proj=omerc +lat_0=50 +alpha=50.0 +no_rot +a=6378144.0 +b=6356759.0 " "+lon_0=8.0 +type=crs"); const auto crs1 = nn_dynamic_pointer_cast<ProjectedCRS>(obj1); ASSERT_TRUE(crs1 != nullptr); const auto wkt = crs1->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); const auto obj_from_wkt = WKTParser().createFromWKT(wkt); const auto crs_from_wkt = nn_dynamic_pointer_cast<ProjectedCRS>(obj_from_wkt); // Check equivalence of the CRS from PROJ.4 and WKT EXPECT_TRUE(crs1->isEquivalentTo(crs_from_wkt.get(), IComparable::Criterion::EQUIVALENT)); ASSERT_TRUE(crs_from_wkt != nullptr); // Same as above but with different option order const auto obj2 = PROJStringParser().createFromPROJString( "+proj=omerc +lat_0=50 +no_rot +alpha=50.0 +a=6378144.0 +b=6356759.0 " "+lon_0=8.0 +type=crs"); const auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); // Check equivalence of the 2 PROJ.4 based CRS EXPECT_TRUE( crs1->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); // Without +no_rot --> no PROJ.4 extension const auto objNoRot = PROJStringParser().createFromPROJString( "+proj=omerc +lat_0=50 +alpha=50.0 +a=6378144.0 +b=6356759.0 " "+lon_0=8.0 +type=crs"); const auto crsNoRot = nn_dynamic_pointer_cast<ProjectedCRS>(objNoRot); ASSERT_TRUE(crsNoRot != nullptr); EXPECT_FALSE(crs1->isEquivalentTo(crsNoRot.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_FALSE(crsNoRot->isEquivalentTo(crs1.get(), IComparable::Criterion::EQUIVALENT)); // Change alpha value const auto objDifferent = PROJStringParser().createFromPROJString( "+proj=omerc +lat_0=50 +alpha=49.0 +no_rot +a=6378144.0 +b=6356759.0 " "+lon_0=8.0 +type=crs"); const auto crsDifferent = nn_dynamic_pointer_cast<ProjectedCRS>(objDifferent); ASSERT_TRUE(crsDifferent != nullptr); EXPECT_FALSE(crs1->isEquivalentTo(crsDifferent.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(crs, is_dynamic) { EXPECT_FALSE(GeographicCRS::EPSG_4326->isDynamic()); EXPECT_TRUE( GeographicCRS::EPSG_4326->isDynamic(/*considerWGS84AsDynamic=*/true)); { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createCoordinateReferenceSystem("4326"); EXPECT_FALSE(crs->isDynamic()); EXPECT_TRUE(crs->isDynamic(/*considerWGS84AsDynamic=*/true)); } { auto drf = DynamicGeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), Ellipsoid::WGS84, optional<std::string>("My anchor"), PrimeMeridian::GREENWICH, Measure(2018.5, UnitOfMeasure::YEAR), optional<std::string>("My model")); auto crs = GeographicCRS::create( PropertyMap(), drf, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); EXPECT_TRUE(crs->isDynamic()); } EXPECT_FALSE(createVerticalCRS()->isDynamic()); { auto drf = DynamicVerticalReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "test"), optional<std::string>("My anchor"), optional<RealizationMethod>(), Measure(2018.5, UnitOfMeasure::YEAR), optional<std::string>("My model")); auto crs = VerticalCRS::create( PropertyMap(), drf, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); EXPECT_TRUE(crs->isDynamic()); } EXPECT_FALSE(createCompoundCRS()->isDynamic()); }
cpp
PROJ
data/projects/PROJ/test/unit/test_defmodel.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test deformation model * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2020, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" // to be able to use internal::toString #define FROM_PROJ_CPP #include "proj/internal/internal.hpp" #include "proj.h" #include "proj_internal.h" // Silence C4702 (unreachable code) due to some dummy implementation of the // interfaces of defmodel.hpp #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4702) #endif #define PROJ_COMPILATION #define DEFORMATON_MODEL_NAMESPACE TestDeformationModel #include "transformations/defmodel.hpp" using namespace DEFORMATON_MODEL_NAMESPACE; namespace { constexpr double modelMinX = 158; constexpr double modelMinY = -58; constexpr double modelMaxX = 194; constexpr double modelMaxY = -25; static json getMinValidContent() { json j; j["file_type"] = "GeoTIFF"; j["format_version"] = "1.0"; j["source_crs"] = "EPSG:4959"; j["target_crs"] = "EPSG:7907"; j["definition_crs"] = "EPSG:4959"; j["extent"]["type"] = "bbox"; j["extent"]["parameters"] = { {"bbox", {modelMinX, modelMinY, modelMaxX, modelMaxY}}}; j["time_extent"]["first"] = "1900-01-01T00:00:00Z"; j["time_extent"]["last"] = "2050-01-01T00:00:00Z"; j["components"] = json::array(); return j; } // --------------------------------------------------------------------------- constexpr int IDX_CONSTANT = 0; constexpr int IDX_VELOCITY = 1; constexpr int IDX_STEP = 2; constexpr int IDX_REVERSE_STEP = 3; constexpr int IDX_PIECEWISE = 4; constexpr int IDX_EXPONENTIAL = 5; static json getFullValidContent() { json j(getMinValidContent()); j["name"] = "name"; j["version"] = "version"; j["publication_date"] = "2018-07-01T00:00:00Z"; j["license"] = "license"; j["description"] = "description"; j["authority"]["name"] = "authority_name"; j["authority"]["url"] = "authority_url"; j["authority"]["address"] = "authority_address"; j["authority"]["email"] = "authority_email"; j["links"] = {{{"href", "href"}, {"rel", "rel"}, {"type", "type"}, {"title", "title"}}}; j["reference_epoch"] = "2000-01-01T00:00:00Z"; j["uncertainty_reference_epoch"] = "2018-12-15T00:00:00Z"; j["horizontal_offset_method"] = "addition"; j["horizontal_offset_unit"] = "metre"; j["vertical_offset_unit"] = "metre"; j["horizontal_uncertainty_type"] = "circular 95% confidence limit"; j["horizontal_uncertainty_unit"] = "metre"; j["vertical_uncertainty_type"] = "95% confidence limit"; j["vertical_uncertainty_unit"] = "metre"; j["components"] = {{ {"description", "description"}, {"displacement_type", "horizontal"}, {"uncertainty_type", "none"}, {"horizontal_uncertainty", 0.01}, {"vertical_uncertainty", 0.02}, {"extent", {{"type", "bbox"}, {"parameters", {{"bbox", {modelMinX, modelMinY, modelMaxX, modelMaxY}}}}}}, {"spatial_model", { {"type", "GeoTIFF"}, {"interpolation_method", "bilinear"}, {"filename", "nzgd2000-ndm-grid02.tif"}, {"md5_checksum", "49fce8ab267be2c8d00d43683060a032"}, }}, {"time_function", { {"type", "constant"}, {"parameters", json::object()}, }}, }}; j["components"].push_back(j["components"][0]); j["components"][IDX_VELOCITY]["time_function"] = { {"type", "velocity"}, {"parameters", {{"reference_epoch", "2000-01-01T00:00:00Z"}}}, }; j["components"].push_back(j["components"][0]); j["components"][IDX_STEP]["time_function"] = { {"type", "step"}, {"parameters", {{"step_epoch", "2000-01-01T00:00:00Z"}}}, }; j["components"].push_back(j["components"][0]); j["components"][IDX_REVERSE_STEP]["time_function"] = { {"type", "reverse_step"}, {"parameters", {{"step_epoch", "2000-01-01T00:00:00Z"}}}, }; j["components"].push_back(j["components"][0]); j["components"][IDX_PIECEWISE]["time_function"] = { {"type", "piecewise"}, {"parameters", {{"before_first", "zero"}, {"after_last", "constant"}, {"model", {{{"epoch", "2016-01-01T00:00:00Z"}, {"scale_factor", 0.5}}, {{"epoch", "2017-01-01T00:00:00Z"}, {"scale_factor", 1.0}}, {{"epoch", "2017-01-01T00:00:00Z"}, {"scale_factor", 2.0}}, {{"epoch", "2018-01-01T00:00:00Z"}, {"scale_factor", 1.0}}}}}}}; j["components"].push_back(j["components"][0]); j["components"][IDX_EXPONENTIAL]["time_function"] = { {"type", "exponential"}, {"parameters", { {"reference_epoch", "2000-01-01T00:00:00Z"}, {"end_epoch", "2001-01-01T00:00:00Z"}, {"relaxation_constant", 2.0}, {"before_scale_factor", 0.0}, {"initial_scale_factor", 1.0}, {"final_scale_factor", 3.0}, }}, }; return j; } // --------------------------------------------------------------------------- TEST(defmodel, basic) { EXPECT_THROW(MasterFile::parse("foo"), ParsingException); EXPECT_THROW(MasterFile::parse("null"), ParsingException); EXPECT_THROW(MasterFile::parse("{}"), ParsingException); const auto jMinValid(getMinValidContent()); { auto mf = MasterFile::parse(jMinValid.dump()); EXPECT_EQ(mf->fileType(), "GeoTIFF"); EXPECT_EQ(mf->formatVersion(), "1.0"); EXPECT_EQ(mf->sourceCRS(), "EPSG:4959"); EXPECT_EQ(mf->targetCRS(), "EPSG:7907"); EXPECT_EQ(mf->definitionCRS(), "EPSG:4959"); EXPECT_EQ(mf->extent().minx(), modelMinX); EXPECT_EQ(mf->extent().miny(), modelMinY); EXPECT_EQ(mf->extent().maxx(), modelMaxX); EXPECT_EQ(mf->extent().maxy(), modelMaxY); EXPECT_EQ(mf->timeExtent().first.toString(), "1900-01-01T00:00:00Z"); EXPECT_EQ(mf->timeExtent().last.toString(), "2050-01-01T00:00:00Z"); } // Check that removing one of each required key causes an exception for (const auto &kv : jMinValid.items()) { json jcopy(jMinValid); jcopy.erase(kv.key()); EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["definition_crs"] = "EPSG:4326"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["file_type"] = 1; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["extent"].erase("type"); EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["extent"].erase("parameters"); EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["extent"]["parameters"].clear(); EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["extent"]["parameters"].erase("bbox"); EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["extent"]["parameters"]["bbox"] = "foo"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["extent"]["parameters"]["bbox"] = {0, 1, 2}; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["extent"]["parameters"]["bbox"] = {0, 1, 2, "foo"}; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["time_extent"] = "foo"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["time_extent"].erase("first"); EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jMinValid); jcopy["time_extent"].erase("last"); EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } } // --------------------------------------------------------------------------- TEST(defmodel, full) { const auto jFullValid(getFullValidContent()); auto mf = MasterFile::parse(jFullValid.dump()); EXPECT_EQ(mf->name(), "name"); EXPECT_EQ(mf->version(), "version"); EXPECT_EQ(mf->publicationDate(), "2018-07-01T00:00:00Z"); EXPECT_EQ(mf->license(), "license"); EXPECT_EQ(mf->description(), "description"); EXPECT_EQ(mf->authority().name, "authority_name"); EXPECT_EQ(mf->authority().url, "authority_url"); EXPECT_EQ(mf->authority().address, "authority_address"); EXPECT_EQ(mf->authority().email, "authority_email"); EXPECT_EQ(mf->links().size(), 1U); EXPECT_EQ(mf->links()[0].href, "href"); EXPECT_EQ(mf->links()[0].rel, "rel"); EXPECT_EQ(mf->links()[0].type, "type"); EXPECT_EQ(mf->links()[0].title, "title"); EXPECT_EQ(mf->referenceEpoch(), "2000-01-01T00:00:00Z"); EXPECT_EQ(mf->uncertaintyReferenceEpoch(), "2018-12-15T00:00:00Z"); EXPECT_EQ(mf->horizontalOffsetUnit(), "metre"); EXPECT_EQ(mf->verticalOffsetUnit(), "metre"); EXPECT_EQ(mf->horizontalUncertaintyType(), "circular 95% confidence limit"); EXPECT_EQ(mf->horizontalUncertaintyUnit(), "metre"); EXPECT_EQ(mf->verticalUncertaintyType(), "95% confidence limit"); EXPECT_EQ(mf->verticalUncertaintyUnit(), "metre"); EXPECT_EQ(mf->horizontalOffsetMethod(), "addition"); ASSERT_EQ(mf->components().size(), 6U); { const auto &comp = mf->components()[IDX_CONSTANT]; EXPECT_EQ(comp.description(), "description"); EXPECT_EQ(comp.displacementType(), "horizontal"); EXPECT_EQ(comp.uncertaintyType(), "none"); EXPECT_EQ(comp.horizontalUncertainty(), 0.01); EXPECT_EQ(comp.verticalUncertainty(), 0.02); EXPECT_EQ(comp.extent().minx(), modelMinX); EXPECT_EQ(comp.extent().miny(), modelMinY); EXPECT_EQ(comp.extent().maxx(), modelMaxX); EXPECT_EQ(comp.extent().maxy(), modelMaxY); EXPECT_EQ(comp.spatialModel().type, "GeoTIFF"); EXPECT_EQ(comp.spatialModel().interpolationMethod, "bilinear"); EXPECT_EQ(comp.spatialModel().filename, "nzgd2000-ndm-grid02.tif"); EXPECT_EQ(comp.spatialModel().md5Checksum, "49fce8ab267be2c8d00d43683060a032"); ASSERT_NE(comp.timeFunction(), nullptr); ASSERT_EQ(comp.timeFunction()->type, "constant"); } { const auto &comp = mf->components()[IDX_VELOCITY]; ASSERT_NE(comp.timeFunction(), nullptr); ASSERT_EQ(comp.timeFunction()->type, "velocity"); const auto velocity = static_cast<const Component::VelocityTimeFunction *>( comp.timeFunction()); EXPECT_EQ(velocity->referenceEpoch.toString(), "2000-01-01T00:00:00Z"); } { const auto &comp = mf->components()[IDX_STEP]; ASSERT_NE(comp.timeFunction(), nullptr); ASSERT_EQ(comp.timeFunction()->type, "step"); const auto step = static_cast<const Component::StepTimeFunction *>( comp.timeFunction()); EXPECT_EQ(step->stepEpoch.toString(), "2000-01-01T00:00:00Z"); } { const auto &comp = mf->components()[IDX_REVERSE_STEP]; ASSERT_NE(comp.timeFunction(), nullptr); ASSERT_EQ(comp.timeFunction()->type, "reverse_step"); const auto step = static_cast<const Component::ReverseStepTimeFunction *>( comp.timeFunction()); EXPECT_EQ(step->stepEpoch.toString(), "2000-01-01T00:00:00Z"); } { const auto &comp = mf->components()[IDX_PIECEWISE]; ASSERT_NE(comp.timeFunction(), nullptr); ASSERT_EQ(comp.timeFunction()->type, "piecewise"); const auto piecewise = static_cast<const Component::PiecewiseTimeFunction *>( comp.timeFunction()); EXPECT_EQ(piecewise->beforeFirst, "zero"); EXPECT_EQ(piecewise->afterLast, "constant"); EXPECT_EQ(piecewise->model.size(), 4U); EXPECT_EQ(piecewise->model[0].epoch.toString(), "2016-01-01T00:00:00Z"); EXPECT_EQ(piecewise->model[0].scaleFactor, 0.5); } { const auto &comp = mf->components()[IDX_EXPONENTIAL]; ASSERT_NE(comp.timeFunction(), nullptr); ASSERT_EQ(comp.timeFunction()->type, "exponential"); const auto exponential = static_cast<const Component::ExponentialTimeFunction *>( comp.timeFunction()); EXPECT_EQ(exponential->referenceEpoch.toString(), "2000-01-01T00:00:00Z"); EXPECT_EQ(exponential->endEpoch.toString(), "2001-01-01T00:00:00Z"); EXPECT_EQ(exponential->relaxationConstant, 2.0); EXPECT_EQ(exponential->beforeScaleFactor, 0.0); EXPECT_EQ(exponential->initialScaleFactor, 1.0); EXPECT_EQ(exponential->finalScaleFactor, 3.0); } } // --------------------------------------------------------------------------- TEST(defmodel, error_cases) { const auto jFullValid(getFullValidContent()); { json jcopy(jFullValid); jcopy["horizontal_offset_method"] = "unsupported"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["horizontal_offset_unit"] = "unsupported"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["vertical_offset_unit"] = "unsupported"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["components"][IDX_CONSTANT]["spatial_model"] ["interpolation_method"] = "unsupported"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["components"][IDX_CONSTANT]["displacement_type"] = "unsupported"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["model"] = "foo"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["before_first"] = "illegal"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["after_last"] = "illegal"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } { json jcopy(jFullValid); jcopy["components"][0]["time_function"]["type"] = "unknown"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } // Unsupported combination { json jcopy(jFullValid); jcopy["horizontal_offset_method"] = "geocentric"; EXPECT_NO_THROW(MasterFile::parse(jcopy.dump())); } { json jcopy(jFullValid); jcopy["horizontal_offset_unit"] = "degree"; EXPECT_NO_THROW(MasterFile::parse(jcopy.dump())); } { json jcopy(jFullValid); jcopy["horizontal_offset_method"] = "geocentric"; jcopy["horizontal_offset_unit"] = "degree"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } // Unsupported combination { json jcopy(jFullValid); jcopy["components"][IDX_VELOCITY]["spatial_model"] ["interpolation_method"] = "geocentric_bilinear"; EXPECT_NO_THROW(MasterFile::parse(jcopy.dump())); } { json jcopy(jFullValid); jcopy["horizontal_offset_unit"] = "degree"; EXPECT_NO_THROW(MasterFile::parse(jcopy.dump())); } { json jcopy(jFullValid); jcopy["components"][IDX_VELOCITY]["spatial_model"] ["interpolation_method"] = "geocentric_bilinear"; jcopy["horizontal_offset_unit"] = "degree"; EXPECT_THROW(MasterFile::parse(jcopy.dump()), ParsingException); } } // --------------------------------------------------------------------------- TEST(defmodel, ISO8601ToDecimalYear) { EXPECT_EQ(ISO8601ToDecimalYear("2000-01-01T00:00:00Z"), 2000.0); EXPECT_EQ(ISO8601ToDecimalYear("2000-02-29T12:00:00Z"), 2000.0 + ((31 + 28) * 86400. + 12 * 3600) / (366 * 86400)); EXPECT_EQ(ISO8601ToDecimalYear("2000-12-31T23:59:59Z"), 2000.0 + (366 * 86400 - 1.) / (366 * 86400)); EXPECT_EQ(ISO8601ToDecimalYear("2001-01-01T00:00:00Z"), 2001.0); EXPECT_EQ(ISO8601ToDecimalYear("2001-12-31T23:59:59Z"), 2001.0 + (365 * 86400 - 1.) / (365 * 86400)); EXPECT_THROW(ISO8601ToDecimalYear(""), ParsingException); EXPECT_THROW(ISO8601ToDecimalYear("0000-01-01T00:00:00Z"), ParsingException); EXPECT_THROW(ISO8601ToDecimalYear("2001-02-29T00:00:00Z"), ParsingException); EXPECT_THROW(ISO8601ToDecimalYear("2000-13-01T00:00:00Z"), ParsingException); EXPECT_THROW(ISO8601ToDecimalYear("2000-01-32T00:00:00Z"), ParsingException); EXPECT_THROW(ISO8601ToDecimalYear("2000-01-01T24:00:00Z"), ParsingException); EXPECT_THROW(ISO8601ToDecimalYear("2000-01-01T00:60:00Z"), ParsingException); EXPECT_THROW(ISO8601ToDecimalYear("2000-01-01T00:00:61Z"), ParsingException); } // --------------------------------------------------------------------------- TEST(defmodel, evaluate_constant) { const auto jFullValid(getFullValidContent()); const auto mf = MasterFile::parse(jFullValid.dump()); const auto &comp = mf->components()[IDX_CONSTANT]; EXPECT_EQ(comp.timeFunction()->evaluateAt(1999.0), 1.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.0), 1.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2001.0), 1.0); } // --------------------------------------------------------------------------- TEST(defmodel, evaluate_velocity) { const auto jFullValid(getFullValidContent()); const auto mf = MasterFile::parse(jFullValid.dump()); const auto &comp = mf->components()[IDX_VELOCITY]; EXPECT_EQ(comp.timeFunction()->evaluateAt(1999.0), -1.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.0), 0.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2001.0), 1.0); } // --------------------------------------------------------------------------- TEST(defmodel, evaluate_step) { const auto jFullValid(getFullValidContent()); const auto mf = MasterFile::parse(jFullValid.dump()); const auto &comp = mf->components()[IDX_STEP]; EXPECT_EQ(comp.timeFunction()->evaluateAt(1999.99), 0.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.00), 1.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.01), 1.0); } // --------------------------------------------------------------------------- TEST(defmodel, evaluate_reverse_step) { const auto jFullValid(getFullValidContent()); const auto mf = MasterFile::parse(jFullValid.dump()); const auto &comp = mf->components()[IDX_REVERSE_STEP]; EXPECT_EQ(comp.timeFunction()->evaluateAt(1999.99), -1.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.00), 0.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.01), 0.0); } // --------------------------------------------------------------------------- TEST(defmodel, evaluate_piecewise) { const auto jFullValid(getFullValidContent()); { const auto mf = MasterFile::parse(jFullValid.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2015.99), 0.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2016.00), 0.5); EXPECT_EQ(comp.timeFunction()->evaluateAt(2016.5), 0.75); EXPECT_NEAR(comp.timeFunction()->evaluateAt(2017 - 1e-9), 1.0, 1e-9); EXPECT_EQ(comp.timeFunction()->evaluateAt(2017.0), 2.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2017.5), 1.5); EXPECT_EQ(comp.timeFunction()->evaluateAt(2018.0), 1.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2019.0), 1.0); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["before_first"] = "zero"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2015.5), 0.0); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["before_first"] = "constant"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2015.5), 0.5); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["before_first"] = "linear"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2015.5), 0.25); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["after_last"] = "zero"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2018.5), 0.0); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["after_last"] = "constant"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2018.5), 1.0); } { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["after_last"] = "linear"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2018.5), 0.5); } // No epoch { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["model"] .clear(); const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2015.5), 0.0); } // Just one epoch { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["model"] = { {{"epoch", "2016-01-01T00:00:00Z"}, {"scale_factor", 0.5}}}; jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["before_first"] = "linear"; jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["after_last"] = "linear"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2015.5), 0.5); EXPECT_EQ(comp.timeFunction()->evaluateAt(2016.5), 0.5); } // Two identical epochs { json jcopy(jFullValid); jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["model"] = { {{"epoch", "2016-01-01T00:00:00Z"}, {"scale_factor", 0.5}}, {{"epoch", "2016-01-01T00:00:00Z"}, {"scale_factor", 1.0}}}; jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["before_first"] = "linear"; jcopy["components"][IDX_PIECEWISE]["time_function"]["parameters"] ["after_last"] = "linear"; const auto mf = MasterFile::parse(jcopy.dump()); const auto &comp = mf->components()[IDX_PIECEWISE]; EXPECT_EQ(comp.timeFunction()->evaluateAt(2015.5), 0.5); EXPECT_EQ(comp.timeFunction()->evaluateAt(2016.5), 1.0); } } // --------------------------------------------------------------------------- TEST(defmodel, evaluate_exponential) { const auto jFullValid(getFullValidContent()); const auto mf = MasterFile::parse(jFullValid.dump()); const auto &comp = mf->components()[IDX_EXPONENTIAL]; EXPECT_EQ(comp.timeFunction()->evaluateAt(1999.99), 0.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.00), 1.0); EXPECT_EQ(comp.timeFunction()->evaluateAt(2000.50), 1.0 + (3.0 - 1.0) * (1.0 - std::exp(-(2000.50 - 2000.00) / 2.0))); EXPECT_EQ(comp.timeFunction()->evaluateAt(2001.00), 1.0 + (3.0 - 1.0) * (1.0 - std::exp(-(2001.00 - 2000.00) / 2.0))); EXPECT_EQ(comp.timeFunction()->evaluateAt(2002.00), 1.0 + (3.0 - 1.0) * (1.0 - std::exp(-(2001.00 - 2000.00) / 2.0))); } // --------------------------------------------------------------------------- inline double RadToDeg(double d) { return d / DEG_TO_RAD_CONSTANT; } // --------------------------------------------------------------------------- TEST(defmodel, evaluator_horizontal_unit_degree) { json j(getMinValidContent()); j["horizontal_offset_method"] = "addition"; j["horizontal_offset_unit"] = "degree"; constexpr double tFactor = 0.5; constexpr double gridMinX = 160; constexpr double gridMinY = -50; constexpr double gridMaxX = 190; constexpr double gridMaxY = -30; j["components"] = { {{"displacement_type", "horizontal"}, {"uncertainty_type", "none"}, {"extent", {{"type", "bbox"}, {"parameters", {{"bbox", {gridMinX, gridMinY, gridMaxX, gridMaxY}}}}}}, {"spatial_model", { {"type", "GeoTIFF"}, {"interpolation_method", "bilinear"}, {"filename", "bla.tif"}, }}, {"time_function", {{"type", "piecewise"}, {"parameters", {{"before_first", "zero"}, {"after_last", "zero"}, {"model", {{{"epoch", "2010-01-01T00:00:00Z"}, {"scale_factor", tFactor}}, {{"epoch", "2020-01-01T00:00:00Z"}, {"scale_factor", tFactor}}}}}}}}}}; constexpr int iQueriedX = 1; constexpr int iQueriedY = 3; constexpr double longOffsetQueriedX = 0.01; constexpr double longOffsetQueriedXp1 = 0.02; constexpr double latOffsetQueriedY = 0.03; constexpr double latOffsetQueriedYp1 = 0.04; constexpr double zOffsetQueriedXY = 10.; constexpr double zOffsetQueriedXp1Y = 11.; constexpr double zOffsetQueriedXYp1 = 11.; constexpr double zOffsetQueriedXp1Yp1 = 12.; constexpr double gridResX = 2; constexpr double gridResY = 0.5; struct Grid : public GridPrototype { bool getLongLatOffset(int ix, int iy, double &longOffsetRadian, double &latOffsetRadian) const { if (ix == iQueriedX) { longOffsetRadian = DegToRad(longOffsetQueriedX); } else if (ix == iQueriedX + 1) { longOffsetRadian = DegToRad(longOffsetQueriedXp1); } else { return false; } if (iy == iQueriedY) { latOffsetRadian = DegToRad(latOffsetQueriedY); } else if (iy == iQueriedY + 1) { latOffsetRadian = DegToRad(latOffsetQueriedYp1); } else { return false; } return true; } bool getZOffset(int ix, int iy, double &zOffset) const { if (ix == iQueriedX && iy == iQueriedY) { zOffset = zOffsetQueriedXY; } else if (ix == iQueriedX + 1 && iy == iQueriedY) { zOffset = zOffsetQueriedXp1Y; } else if (ix == iQueriedX && iy == iQueriedY + 1) { zOffset = zOffsetQueriedXYp1; } else if (ix == iQueriedX + 1 && iy == iQueriedY + 1) { zOffset = zOffsetQueriedXp1Yp1; } else { return false; } return true; } bool getLongLatZOffset(int ix, int iy, double &longOffsetRadian, double &latOffsetRadian, double &zOffset) const { return getLongLatOffset(ix, iy, longOffsetRadian, latOffsetRadian) && getZOffset(ix, iy, zOffset); } #ifdef DEBUG_DEFMODEL std::string name() const { return std::string(); } #endif }; struct GridSet : public GridSetPrototype<Grid> { Grid grid{}; GridSet() { grid.minx = DegToRad(gridMinX); grid.miny = DegToRad(gridMinY); grid.resx = DegToRad(gridResX); grid.resy = DegToRad(gridResY); grid.width = 1 + static_cast<int>(0.5 + (gridMaxX - gridMinX) / gridResX); grid.height = 1 + static_cast<int>(0.5 + (gridMaxY - gridMinY) / gridResY); } const Grid *gridAt(double /*x */, double /* y */) { return &grid; } }; struct EvaluatorIface : public EvaluatorIfacePrototype<Grid, GridSet> { std::unique_ptr<GridSet> open(const std::string &filename) { if (filename != "bla.tif") return nullptr; return std::unique_ptr<GridSet>(new GridSet()); } bool isGeographicCRS(const std::string & /* crsDef */) { return true; } #ifdef DEBUG_DEFMODEL void log(const std::string & /* msg */) {} #endif }; EvaluatorIface iface; Evaluator<Grid, GridSet, EvaluatorIface> eval(MasterFile::parse(j.dump()), iface, 1, 1); double newLong; double newLat; double newZ; constexpr double tValid = 2018; constexpr double EPS = 1e-9; constexpr double zVal = 100; // Query on exact grid intersection { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude + tFactor * longOffsetQueriedX, EPS); EXPECT_NEAR(RadToDeg(newLat), lat + tFactor * latOffsetQueriedY, EPS); EXPECT_EQ(newZ, zVal); } // Query between grid points { constexpr double alphaX = 0.25; constexpr double alphaY = 0.125; const double longitude = gridMinX + iQueriedX * gridResX + alphaX * gridResX; const double lat = gridMinY + iQueriedY * gridResY + alphaY * gridResY; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude + tFactor * (longOffsetQueriedX + alphaX * (longOffsetQueriedXp1 - longOffsetQueriedX)), EPS); EXPECT_NEAR( RadToDeg(newLat), lat + tFactor * (latOffsetQueriedY + alphaY * (latOffsetQueriedYp1 - latOffsetQueriedY)), EPS); EXPECT_EQ(newZ, zVal); } // Longitude < model min { const double longitude = modelMinX - 1e-1; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_FALSE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); } // Longitude > model max { const double longitude = modelMaxX + 1e-1; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_FALSE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); } // Latitude < model min { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = modelMinY - 1e-1; EXPECT_FALSE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); } // Latitude > model max { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = modelMaxY + 1e-1; EXPECT_FALSE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); } // Before timeExtent.first { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_FALSE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, 1000, newLong, newLat, newZ)); } // After timeExtent.last { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_FALSE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, 3000, newLong, newLat, newZ)); } // Longitude < grid min { const double longitude = gridMinX - 1e-1; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude, EPS); EXPECT_NEAR(RadToDeg(newLat), lat, EPS); EXPECT_EQ(newZ, zVal); } // Longitude > grid max { const double longitude = gridMaxX + 1e-1; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude, EPS); EXPECT_NEAR(RadToDeg(newLat), lat, EPS); EXPECT_EQ(newZ, zVal); } // Latitude < grid min { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = gridMinY - 1e-1; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude, EPS); EXPECT_NEAR(RadToDeg(newLat), lat, EPS); EXPECT_EQ(newZ, zVal); } // Latitude > grid max { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = gridMaxY + 1e-1; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude, EPS); EXPECT_NEAR(RadToDeg(newLat), lat, EPS); EXPECT_EQ(newZ, zVal); } // Time function values to zero { const double longitude = gridMinX + iQueriedX * gridResX; const double lat = gridMinY + iQueriedY * gridResY; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, 2000, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude, EPS); EXPECT_NEAR(RadToDeg(newLat), lat, EPS); EXPECT_EQ(newZ, zVal); } // Test vertical j["components"][0]["displacement_type"] = "vertical"; j["vertical_offset_unit"] = "metre"; Evaluator<Grid, GridSet, EvaluatorIface> evalVertical( MasterFile::parse(j.dump()), iface, 1, 1); { constexpr double alphaX = 0.25; constexpr double alphaY = 0.125; const double longitude = gridMinX + iQueriedX * gridResX + alphaX * gridResX; const double lat = gridMinY + iQueriedY * gridResY + alphaY * gridResY; EXPECT_TRUE(evalVertical.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude, EPS); EXPECT_NEAR(RadToDeg(newLat), lat, EPS); const double zBottom = zOffsetQueriedXY + alphaX * (zOffsetQueriedXp1Y - zOffsetQueriedXY); const double zTop = zOffsetQueriedXYp1 + alphaX * (zOffsetQueriedXp1Yp1 - zOffsetQueriedXYp1); EXPECT_NEAR( newZ, zVal + tFactor * (zBottom + alphaY * (zTop - zBottom)), EPS); } // Test 3d j["components"][0]["displacement_type"] = "3d"; j["vertical_offset_unit"] = "metre"; Evaluator<Grid, GridSet, EvaluatorIface> eval3d(MasterFile::parse(j.dump()), iface, 1, 1); { constexpr double alphaX = 0.25; constexpr double alphaY = 0.125; const double longitude = gridMinX + iQueriedX * gridResX + alphaX * gridResX; const double lat = gridMinY + iQueriedY * gridResY + alphaY * gridResY; EXPECT_TRUE(eval3d.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); EXPECT_NEAR(RadToDeg(newLong), longitude + tFactor * (longOffsetQueriedX + alphaX * (longOffsetQueriedXp1 - longOffsetQueriedX)), EPS); EXPECT_NEAR( RadToDeg(newLat), lat + tFactor * (latOffsetQueriedY + alphaY * (latOffsetQueriedYp1 - latOffsetQueriedY)), EPS); const double zBottom = zOffsetQueriedXY + alphaX * (zOffsetQueriedXp1Y - zOffsetQueriedXY); const double zTop = zOffsetQueriedXYp1 + alphaX * (zOffsetQueriedXp1Yp1 - zOffsetQueriedXYp1); EXPECT_NEAR( newZ, zVal + tFactor * (zBottom + alphaY * (zTop - zBottom)), EPS); } } // --------------------------------------------------------------------------- inline void DeltaLongLatToEastingNorthing(double phi, double dlam, double dphi, double a, double b, double &de, double &dn) { const double sinphi = sin(phi); const double cosphi = cos(phi); const double a2 = a * a; const double b2 = b * b; const double X = a2 * (cosphi * cosphi) + b2 * (sinphi * sinphi); const double sqrtX = sqrt(X); de = dlam * (a2 * cosphi) / sqrtX; dn = dphi * a2 * b2 / (sqrtX * X); } // --------------------------------------------------------------------------- TEST(defmodel, evaluator_horizontal_unit_metre) { json j(getMinValidContent()); j["horizontal_offset_method"] = "addition"; j["horizontal_offset_unit"] = "metre"; j["vertical_offset_unit"] = "metre"; constexpr double tFactor = 0.5; constexpr double gridMinX = 165.8; constexpr double gridMinY = -37.5; constexpr double gridMaxX = 166.2; constexpr double gridMaxY = -37.2; constexpr double gridResX = gridMaxX - gridMinX; constexpr double gridResY = gridMaxY - gridMinY; constexpr int extraPointX = 1; constexpr int extraPointY = 1; j["components"] = { {{"displacement_type", "horizontal"}, {"uncertainty_type", "none"}, {"extent", {{"type", "bbox"}, {"parameters", {{"bbox", {gridMinX - extraPointX * gridResX, gridMinY - extraPointY * gridResY, gridMaxX, gridMaxY}}}}}}, {"spatial_model", { {"type", "GeoTIFF"}, {"interpolation_method", "XXXXXXX"}, {"filename", "bla.tif"}, }}, {"time_function", {{"type", "piecewise"}, {"parameters", {{"before_first", "zero"}, {"after_last", "zero"}, {"model", {{{"epoch", "2010-01-01T00:00:00Z"}, {"scale_factor", tFactor}}, {{"epoch", "2020-01-01T00:00:00Z"}, {"scale_factor", tFactor}}}}}}}}}}; struct Grid : public GridPrototype { bool getEastingNorthingOffset(int ix, int iy, double &eastingOffset, double &northingOffset) const { ix -= extraPointX; iy -= extraPointY; if (ix == -1) ix = 0; if (iy == -1) iy = 0; if (ix == 0 && iy == 0) { eastingOffset = 0.4f; northingOffset = -0.2f; } else if (ix == 1 && iy == 0) { eastingOffset = 0.5f; northingOffset = -0.25f; } else if (ix == 0 && iy == 1) { eastingOffset = 0.8f; northingOffset = -0.4f; } else if (ix == 1 && iy == 1) { eastingOffset = 1.f; northingOffset = -0.3f; } else { return false; } return true; } bool getZOffset(int ix, int iy, double &zOffset) const { ix -= extraPointX; iy -= extraPointY; if (ix == -1) ix = 0; if (iy == -1) iy = 0; if (ix == 0 && iy == 0) { zOffset = 0.84f; } else if (ix == 1 && iy == 0) { zOffset = 0.75f; } else if (ix == 0 && iy == 1) { zOffset = 0.36f; } else if (ix == 1 && iy == 1) { zOffset = 0.f; } else { return false; } return true; } bool getEastingNorthingZOffset(int ix, int iy, double &eastingOffset, double &northingOffset, double &zOffset) const { return getEastingNorthingOffset(ix, iy, eastingOffset, northingOffset) && getZOffset(ix, iy, zOffset); } #ifdef DEBUG_DEFMODEL std::string name() const { return std::string(); } #endif }; struct GridSet : public GridSetPrototype<Grid> { Grid grid{}; GridSet() { grid.minx = DegToRad(gridMinX - extraPointX * gridResX); grid.miny = DegToRad(gridMinY - extraPointY * gridResY); grid.resx = DegToRad(gridResX); grid.resy = DegToRad(gridResY); grid.width = 2 + extraPointX; grid.height = 2 + extraPointY; } const Grid *gridAt(double /*x */, double /* y */) { return &grid; } }; struct EvaluatorIface : public EvaluatorIfacePrototype<Grid, GridSet> { std::unique_ptr<GridSet> open(const std::string &filename) { if (filename != "bla.tif") return nullptr; return std::unique_ptr<GridSet>(new GridSet()); } bool isGeographicCRS(const std::string & /* crsDef */) { return true; } #ifdef DEBUG_DEFMODEL void log(const std::string & /* msg */) {} #endif void geographicToGeocentric(double lam, double phi, double height, double a, double /*b*/, double es, double &X, double &Y, double &Z) { PJ_CONTEXT *ctx = proj_context_create(); PJ *cart = proj_create( ctx, ("+proj=cart +a=" + osgeo::proj::internal::toString(a, 18) + " +es=" + osgeo::proj::internal::toString(es, 18)) .c_str()); PJ_LPZ lpz; lpz.lam = lam; lpz.phi = phi; lpz.z = height; PJ_XYZ xyz = cart->fwd3d(lpz, cart); X = xyz.x; Y = xyz.y; Z = xyz.z; proj_destroy(cart); proj_context_destroy(ctx); } void geocentricToGeographic(double X, double Y, double Z, double a, double /*b*/, double es, double &lam, double &phi, double &height) { PJ_CONTEXT *ctx = proj_context_create(); PJ *cart = proj_create( ctx, ("+proj=cart +a=" + osgeo::proj::internal::toString(a, 18) + " +es=" + osgeo::proj::internal::toString(es, 18)) .c_str()); PJ_XYZ xyz; xyz.x = X; xyz.y = Y; xyz.z = Z; PJ_LPZ lpz = cart->inv3d(xyz, cart); lam = lpz.lam; phi = lpz.phi; height = lpz.z; proj_destroy(cart); proj_context_destroy(ctx); } }; EvaluatorIface iface; constexpr double a = 6378137; constexpr double b = 6356752.314140; constexpr double tValid = 2018; constexpr double zVal = 100; const struct { double longitude; double lat; double expected_de; double expected_dn; double expected_dz; const char *displacement_type; const char *interpolation_method; } testPoints[] = { {gridMinX - extraPointX * gridResX - 1e-11, gridMinY - extraPointY * gridResY - 1e-11, 0.4, -0.2, 0, "horizontal", "bilinear"}, {gridMinX, gridMinY, 0.4, -0.2, 0, "horizontal", "bilinear"}, {gridMaxX, gridMinY, 0.5, -0.25, 0, "horizontal", "bilinear"}, {gridMinX, gridMaxY, 0.8, -0.4, 0, "horizontal", "bilinear"}, {gridMaxX, gridMaxY, 1, -0.3, 0, "horizontal", "bilinear"}, {gridMaxX + 1e-11, gridMaxY + 1e-11, 1, -0.3, 0, "horizontal", "bilinear"}, {165.9, -37.3, 0.70833334, -0.32083334, 0, "horizontal", "bilinear"}, {165.9, -37.3, 0.70833334, -0.32083334, 0.4525, "3d", "bilinear"}, {gridMinX, gridMinY, 0.4, -0.2, 0, "horizontal", "geocentric_bilinear"}, {gridMaxX, gridMinY, 0.5, -0.25, 0, "horizontal", "geocentric_bilinear"}, {gridMinX, gridMaxY, 0.8, -0.4, 0, "horizontal", "geocentric_bilinear"}, {gridMaxX, gridMaxY, 1, -0.3, 0, "horizontal", "geocentric_bilinear"}, {165.9, -37.3, 0.7083692044608846, -0.3209642339711405, 0, "horizontal", "geocentric_bilinear"}, {165.9, -37.3, 0.7083692044608846, -0.3209642339711405, 0.4525, "3d", "geocentric_bilinear"}, }; for (const auto &testPoint : testPoints) { j["components"][0]["displacement_type"] = testPoint.displacement_type; j["components"][0]["spatial_model"]["interpolation_method"] = testPoint.interpolation_method; Evaluator<Grid, GridSet, EvaluatorIface> eval( MasterFile::parse(j.dump()), iface, a, b); const double longitude = testPoint.longitude; const double lat = testPoint.lat; double newLong; double newLat; double newZ; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)) << longitude << " " << lat << " " << testPoint.displacement_type << testPoint.interpolation_method; EXPECT_NEAR(newZ - zVal, tFactor * testPoint.expected_dz, 1e-8) << longitude << " " << lat << " " << testPoint.displacement_type << testPoint.interpolation_method; double de; double dn; DeltaLongLatToEastingNorthing(DegToRad(lat), newLong - DegToRad(longitude), newLat - DegToRad(lat), a, b, de, dn); EXPECT_NEAR(de, tFactor * testPoint.expected_de, 1e-8) << longitude << " " << lat << " " << testPoint.displacement_type << testPoint.interpolation_method; EXPECT_NEAR(dn, tFactor * testPoint.expected_dn, 1e-8) << longitude << " " << lat << " " << testPoint.displacement_type << testPoint.interpolation_method; if (longitude == gridMinX && lat == gridMinY) { // Redo the exact same test, to test caching double newLong2; double newLat2; double newZ2; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong2, newLat2, newZ2)); EXPECT_EQ(newLong2, newLong); EXPECT_EQ(newLat2, newLat); EXPECT_EQ(newZ2, newZ); // Shift in longitude EXPECT_TRUE(eval.forward(iface, DegToRad(longitude - gridResX / 2), DegToRad(lat), zVal, tValid, newLong2, newLat2, newZ2)); // Redo test at original position EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong2, newLat2, newZ2)); EXPECT_EQ(newLong2, newLong); EXPECT_EQ(newLat2, newLat); EXPECT_EQ(newZ2, newZ); // Shift in latitude EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat - gridResY / 2), zVal, tValid, newLong2, newLat2, newZ2)); // Redo test at original position EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong2, newLat2, newZ2)); EXPECT_EQ(newLong2, newLong); EXPECT_EQ(newLat2, newLat); EXPECT_EQ(newZ2, newZ); } } // Test inverse() { j["horizontal_offset_method"] = "addition"; j["components"][0]["displacement_type"] = "3d"; j["components"][0]["spatial_model"]["interpolation_method"] = "bilinear"; Evaluator<Grid, GridSet, EvaluatorIface> eval( MasterFile::parse(j.dump()), iface, a, b); const double longitude = 165.9; const double lat = -37.3; double newLong; double newLat; double newZ; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); double invLongitude; double invLat; double invZ; EXPECT_TRUE(eval.inverse(iface, newLong, newLat, newZ, tValid, invLongitude, invLat, invZ)); EXPECT_NEAR(RadToDeg(invLongitude), longitude, 1e-10); EXPECT_NEAR(RadToDeg(invLat), lat, 1e-10); EXPECT_NEAR(invZ, zVal, 1e-4); } // Test horizontal_offset_method = geocentric { j["horizontal_offset_method"] = "geocentric"; j["components"][0]["displacement_type"] = "3d"; j["components"][0]["spatial_model"]["interpolation_method"] = "bilinear"; Evaluator<Grid, GridSet, EvaluatorIface> eval( MasterFile::parse(j.dump()), iface, a, b); const double longitude = gridMinX; const double lat = gridMinY; double newLong; double newLat; double newZ; EXPECT_TRUE(eval.forward(iface, DegToRad(longitude), DegToRad(lat), zVal, tValid, newLong, newLat, newZ)); double de; double dn; constexpr double expected_de = 0.40000000948081327; constexpr double expected_dn = -0.19999999810542682; DeltaLongLatToEastingNorthing(DegToRad(lat), newLong - DegToRad(longitude), newLat - DegToRad(lat), a, b, de, dn); EXPECT_NEAR(de, tFactor * expected_de, 1e-10); EXPECT_NEAR(dn, tFactor * expected_dn, 1e-9); EXPECT_NEAR(newZ - zVal, tFactor * 0.84, 1e-4); } } // --------------------------------------------------------------------------- TEST(defmodel, evaluator_projected_crs) { json j(getMinValidContent()); j["horizontal_offset_method"] = "addition"; j["horizontal_offset_unit"] = "metre"; j["vertical_offset_unit"] = "metre"; constexpr double gridMinX = 10000; constexpr double gridMinY = 20000; constexpr double gridMaxX = 30000; constexpr double gridMaxY = 40000; constexpr double gridResX = gridMaxX - gridMinX; constexpr double gridResY = gridMaxY - gridMinY; j["extent"]["parameters"] = { {"bbox", {gridMinX, gridMinY, gridMaxX, gridMaxY}}}; j["components"] = { {{"displacement_type", "horizontal"}, {"uncertainty_type", "none"}, {"extent", {{"type", "bbox"}, {"parameters", {{"bbox", {gridMinX, gridMinY, gridMaxX, gridMaxY}}}}}}, {"spatial_model", { {"type", "GeoTIFF"}, {"interpolation_method", "bilinear"}, {"filename", "bla.tif"}, }}, {"time_function", {{"type", "constant"}}}}}; struct Grid : public GridPrototype { bool getEastingNorthingOffset(int ix, int iy, double &eastingOffset, double &northingOffset) const { if (ix == 0 && iy == 0) { eastingOffset = 0.4; northingOffset = -0.2; } else if (ix == 1 && iy == 0) { eastingOffset = 0.5; northingOffset = -0.25; } else if (ix == 0 && iy == 1) { eastingOffset = 0.8; northingOffset = -0.4; } else if (ix == 1 && iy == 1) { eastingOffset = 1.; northingOffset = -0.3; } else { return false; } return true; } #ifdef DEBUG_DEFMODEL std::string name() const { return std::string(); } #endif }; struct GridSet : public GridSetPrototype<Grid> { Grid grid{}; GridSet() { grid.minx = gridMinX; grid.miny = gridMinY; grid.resx = gridResX; grid.resy = gridResY; grid.width = 2; grid.height = 2; } const Grid *gridAt(double /*x */, double /* y */) { return &grid; } }; struct EvaluatorIface : public EvaluatorIfacePrototype<Grid, GridSet> { std::unique_ptr<GridSet> open(const std::string &filename) { if (filename != "bla.tif") return nullptr; return std::unique_ptr<GridSet>(new GridSet()); } bool isGeographicCRS(const std::string & /* crsDef */) { return false; } #ifdef DEBUG_DEFMODEL void log(const std::string & /* msg */) {} #endif }; EvaluatorIface iface; constexpr double a = 6378137; constexpr double b = 6356752.314140; constexpr double tValid = 2018; constexpr double zVal = 100; Evaluator<Grid, GridSet, EvaluatorIface> eval(MasterFile::parse(j.dump()), iface, a, b); double newX; double newY; double newZ; EXPECT_TRUE(eval.forward(iface, gridMinX, gridMinY, zVal, tValid, newX, newY, newZ)); EXPECT_NEAR(newX - gridMinX, 0.4, 1e-8); EXPECT_NEAR(newY - gridMinY, -0.2, 1e-8); EXPECT_NEAR(newZ - zVal, 0, 1e-8); { json jcopy(j); jcopy["horizontal_offset_unit"] = "degree"; EXPECT_THROW((Evaluator<Grid, GridSet, EvaluatorIface>( MasterFile::parse(jcopy.dump()), iface, a, b)), EvaluatorException); } { json jcopy(j); jcopy["horizontal_offset_method"] = "geocentric"; EXPECT_THROW((Evaluator<Grid, GridSet, EvaluatorIface>( MasterFile::parse(jcopy.dump()), iface, a, b)), EvaluatorException); } { json jcopy(j); jcopy["components"][0]["spatial_model"]["interpolation_method"] = "geocentric_bilinear"; EXPECT_THROW((Evaluator<Grid, GridSet, EvaluatorIface>( MasterFile::parse(jcopy.dump()), iface, a, b)), EvaluatorException); } } } // namespace #ifdef _MSC_VER #pragma warning(pop) #endif
cpp
PROJ
data/projects/PROJ/test/unit/test_factory.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "test_primitives.hpp" #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinates.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include <algorithm> #include <sqlite3.h> #ifdef _MSC_VER #include <stdio.h> #else #include <unistd.h> #endif using namespace osgeo::proj::common; using namespace osgeo::proj::coordinates; using namespace osgeo::proj::crs; using namespace osgeo::proj::cs; using namespace osgeo::proj::datum; using namespace osgeo::proj::io; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; namespace { // --------------------------------------------------------------------------- TEST(factory, databasecontext_create) { DatabaseContext::create(); #ifndef _WIN32 // For some reason, no exception is thrown on AppVeyor Windows EXPECT_THROW(DatabaseContext::create("/i/do_not/exist"), FactoryException); #endif } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createObject) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createObject("-1"), NoSuchAuthorityCodeException); EXPECT_THROW(factory->createObject("4326"), FactoryException); // area and crs } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createUnitOfMeasure_linear) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createUnitOfMeasure("-1"), NoSuchAuthorityCodeException); auto uom = factory->createUnitOfMeasure("9001"); EXPECT_EQ(uom->name(), "metre"); EXPECT_EQ(uom->type(), UnitOfMeasure::Type::LINEAR); EXPECT_EQ(uom->conversionToSI(), 1.0); EXPECT_EQ(uom->codeSpace(), "EPSG"); EXPECT_EQ(uom->code(), "9001"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createUnitOfMeasure_linear_us_survey_foot) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto uom = factory->createUnitOfMeasure("9003"); EXPECT_EQ(uom->conversionToSI(), 12. / 39.37); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createUnitOfMeasure_angular) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto uom = factory->createUnitOfMeasure("9102"); EXPECT_EQ(uom->name(), "degree"); EXPECT_EQ(uom->type(), UnitOfMeasure::Type::ANGULAR); EXPECT_EQ(uom->conversionToSI(), UnitOfMeasure::DEGREE.conversionToSI()); EXPECT_EQ(uom->codeSpace(), "EPSG"); EXPECT_EQ(uom->code(), "9102"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createUnitOfMeasure_angular_9107) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto uom = factory->createUnitOfMeasure("9107"); EXPECT_EQ(uom->name(), "degree minute second"); EXPECT_EQ(uom->type(), UnitOfMeasure::Type::ANGULAR); EXPECT_EQ(uom->conversionToSI(), UnitOfMeasure::DEGREE.conversionToSI()); EXPECT_EQ(uom->codeSpace(), "EPSG"); EXPECT_EQ(uom->code(), "9107"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createUnitOfMeasure_scale) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto uom = factory->createUnitOfMeasure("1028"); EXPECT_EQ(uom->name(), "parts per billion"); EXPECT_EQ(uom->type(), UnitOfMeasure::Type::SCALE); EXPECT_EQ(uom->conversionToSI(), 1e-9); EXPECT_EQ(uom->codeSpace(), "EPSG"); EXPECT_EQ(uom->code(), "1028"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createUnitOfMeasure_time) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto uom = factory->createUnitOfMeasure("1029"); EXPECT_EQ(uom->name(), "year"); EXPECT_EQ(uom->type(), UnitOfMeasure::Type::TIME); EXPECT_EQ(uom->conversionToSI(), 31556925.445); EXPECT_EQ(uom->codeSpace(), "EPSG"); EXPECT_EQ(uom->code(), "1029"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createPrimeMeridian) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createPrimeMeridian("-1"), NoSuchAuthorityCodeException); EXPECT_TRUE(nn_dynamic_pointer_cast<PrimeMeridian>( AuthorityFactory::create(DatabaseContext::create(), "ESRI") ->createObject("108900")) != nullptr); auto pm = factory->createPrimeMeridian("8903"); ASSERT_EQ(pm->identifiers().size(), 1U); EXPECT_EQ(pm->identifiers()[0]->code(), "8903"); EXPECT_EQ(*(pm->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(pm->name()->description()), "Paris"); EXPECT_EQ(pm->longitude(), Angle(2.5969213, UnitOfMeasure::GRAD)); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_identifyBodyFromSemiMajorAxis) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_EQ(factory->identifyBodyFromSemiMajorAxis(6378137, 1e-5), "Earth"); EXPECT_THROW(factory->identifyBodyFromSemiMajorAxis(1, 1e-5), FactoryException); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createEllipsoid) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createEllipsoid("-1"), NoSuchAuthorityCodeException); EXPECT_TRUE(nn_dynamic_pointer_cast<Ellipsoid>( factory->createObject("7030")) != nullptr); auto ellipsoid = factory->createEllipsoid("7030"); ASSERT_EQ(ellipsoid->identifiers().size(), 1U); EXPECT_EQ(ellipsoid->identifiers()[0]->code(), "7030"); EXPECT_EQ(*(ellipsoid->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(ellipsoid->name()->description()), "WGS 84"); EXPECT_TRUE(ellipsoid->inverseFlattening().has_value()); EXPECT_EQ(ellipsoid->semiMajorAxis(), Length(6378137)); EXPECT_EQ(*ellipsoid->inverseFlattening(), Scale(298.257223563)); EXPECT_EQ(ellipsoid->celestialBody(), "Earth"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createEllipsoid_sphere) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ellipsoid = factory->createEllipsoid("7035"); EXPECT_TRUE(ellipsoid->isSphere()); EXPECT_EQ(ellipsoid->semiMajorAxis(), Length(6371000)); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createEllipsoid_with_semi_minor_axis) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ellipsoid = factory->createEllipsoid("7011"); EXPECT_TRUE(ellipsoid->semiMinorAxis().has_value()); EXPECT_EQ(ellipsoid->semiMajorAxis(), Length(6378249.2)); EXPECT_EQ(*ellipsoid->semiMinorAxis(), Length(6356515.0)); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createExtent) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createExtent("-1"), NoSuchAuthorityCodeException); auto extent = factory->createExtent("1262"); EXPECT_EQ(*(extent->description()), "World."); const auto &geogElts = extent->geographicElements(); ASSERT_EQ(geogElts.size(), 1U); auto bbox = nn_dynamic_pointer_cast<GeographicBoundingBox>(geogElts[0]); ASSERT_TRUE(bbox != nullptr); EXPECT_EQ(bbox->westBoundLongitude(), -180); EXPECT_EQ(bbox->eastBoundLongitude(), 180); EXPECT_EQ(bbox->northBoundLatitude(), 90); EXPECT_EQ(bbox->southBoundLatitude(), -90); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createExtent_no_bbox) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto extent = factory->createExtent("1361"); // Sudan - south. Deprecated EXPECT_EQ(*(extent->description()), "Sudan - south."); const auto &geogElts = extent->geographicElements(); EXPECT_TRUE(geogElts.empty()); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createGeodeticDatum) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createGeodeticDatum("-1"), NoSuchAuthorityCodeException); auto grf = factory->createGeodeticDatum("6326"); EXPECT_TRUE(nn_dynamic_pointer_cast<DynamicGeodeticReferenceFrame>(grf) == nullptr); ASSERT_EQ(grf->identifiers().size(), 1U); EXPECT_EQ(grf->identifiers()[0]->code(), "6326"); EXPECT_EQ(*(grf->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(grf->name()->description()), "World Geodetic System 1984"); EXPECT_TRUE(grf->ellipsoid()->isEquivalentTo( factory->createEllipsoid("7030").get())); EXPECT_TRUE(grf->primeMeridian()->isEquivalentTo( factory->createPrimeMeridian("8901").get())); ASSERT_EQ(grf->domains().size(), 1U); auto domain = grf->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("1262").get())); EXPECT_FALSE(grf->publicationDate().has_value()); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createGeodeticDatum_with_publication_date) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // North American Datum 1983 auto grf = factory->createGeodeticDatum("6269"); EXPECT_TRUE(nn_dynamic_pointer_cast<DynamicGeodeticReferenceFrame>(grf) == nullptr); EXPECT_TRUE(grf->publicationDate().has_value()); EXPECT_EQ(grf->publicationDate()->toString(), "1986-01-01"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createDynamicGeodeticDatum) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto grf = factory->createGeodeticDatum("1165"); // ITRF 2014 auto dgrf = nn_dynamic_pointer_cast<DynamicGeodeticReferenceFrame>(grf); ASSERT_TRUE(dgrf != nullptr); EXPECT_EQ(dgrf->frameReferenceEpoch().value(), 2010.0); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createVerticalDatum) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createVerticalDatum("-1"), NoSuchAuthorityCodeException); auto vrf = factory->createVerticalDatum("1027"); ASSERT_EQ(vrf->identifiers().size(), 1U); EXPECT_EQ(vrf->identifiers()[0]->code(), "1027"); EXPECT_EQ(*(vrf->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(vrf->name()->description()), "EGM2008 geoid"); auto domain = vrf->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("1262").get())); EXPECT_TRUE(vrf->publicationDate().has_value()); EXPECT_EQ(vrf->publicationDate()->toString(), "2008-01-01"); EXPECT_TRUE(!vrf->anchorEpoch().has_value()); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createVerticalDatum_with_anchor_epoch) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // "Canadian Geodetic Vertical Datum of 2013 (CGG2013a) epoch 2010" auto vrf = factory->createVerticalDatum("1256"); EXPECT_TRUE(vrf->anchorEpoch().has_value()); EXPECT_NEAR(vrf->anchorEpoch()->convertToUnit(UnitOfMeasure::YEAR), 2010.0, 1e-6); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createDynamicVerticalDatum) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto grf = factory->createVerticalDatum("1096"); // Norway Normal Null 2000 auto dvrf = nn_dynamic_pointer_cast<DynamicVerticalReferenceFrame>(grf); ASSERT_TRUE(dvrf != nullptr); EXPECT_EQ(dvrf->frameReferenceEpoch().value(), 2000.0); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createDatum) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createDatum("-1"), NoSuchAuthorityCodeException); EXPECT_TRUE(factory->createDatum("6326")->isEquivalentTo( factory->createGeodeticDatum("6326").get())); EXPECT_TRUE(factory->createDatum("1027")->isEquivalentTo( factory->createVerticalDatum("1027").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createDatumEnsembleGeodetic) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createDatumEnsemble("-1"), NoSuchAuthorityCodeException); EXPECT_THROW(factory->createDatumEnsemble("6326", "vertical_datum"), NoSuchAuthorityCodeException); auto ensemble = factory->createDatumEnsemble("6326"); EXPECT_EQ(ensemble->nameStr(), "World Geodetic System 1984 ensemble"); ASSERT_EQ(ensemble->identifiers().size(), 1U); EXPECT_EQ(ensemble->identifiers()[0]->code(), "6326"); EXPECT_EQ(*(ensemble->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(ensemble->datums().size(), 7U); EXPECT_EQ(ensemble->positionalAccuracy()->value(), "2.0"); ASSERT_TRUE(!ensemble->domains().empty()); auto domain = ensemble->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("1262").get())); { // Without using db auto datum = ensemble->asDatum(nullptr); EXPECT_EQ(datum->nameStr(), "World Geodetic System 1984"); auto grf = dynamic_cast<GeodeticReferenceFrame *>(datum.get()); ASSERT_TRUE(grf != nullptr); EXPECT_TRUE(grf->isEquivalentTo(factory->createDatum("6326").get())); } { // Using db auto datum = ensemble->asDatum(DatabaseContext::create()); EXPECT_EQ(datum->nameStr(), "World Geodetic System 1984"); auto grf = dynamic_cast<GeodeticReferenceFrame *>(datum.get()); ASSERT_TRUE(grf != nullptr); EXPECT_TRUE(grf->isEquivalentTo(factory->createDatum("6326").get())); } } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createDatumEnsembleVertical) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createDatumEnsemble("1288", "geodetic_datum"), NoSuchAuthorityCodeException); auto ensemble = factory->createDatumEnsemble("1288"); EXPECT_EQ(ensemble->nameStr(), "British Isles height ensemble"); ASSERT_EQ(ensemble->identifiers().size(), 1U); EXPECT_EQ(ensemble->identifiers()[0]->code(), "1288"); EXPECT_EQ(*(ensemble->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(ensemble->datums().size(), 9U); EXPECT_EQ(ensemble->positionalAccuracy()->value(), "0.4"); ASSERT_TRUE(!ensemble->domains().empty()); auto domain = ensemble->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("4606").get())); { // Without using db auto datum = ensemble->asDatum(nullptr); auto vrf = dynamic_cast<VerticalReferenceFrame *>(datum.get()); ASSERT_TRUE(vrf != nullptr); EXPECT_TRUE(vrf->isEquivalentTo(factory->createDatum("1288").get())); } { // Using db auto datum = ensemble->asDatum(DatabaseContext::create()); auto vrf = dynamic_cast<VerticalReferenceFrame *>(datum.get()); ASSERT_TRUE(vrf != nullptr); EXPECT_TRUE(vrf->isEquivalentTo(factory->createDatum("1288").get())); } } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateSystem_ellipsoidal_2_axis) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createCoordinateSystem("-1"), NoSuchAuthorityCodeException); auto cs = factory->createCoordinateSystem("6422"); auto ellipsoidal_cs = nn_dynamic_pointer_cast<EllipsoidalCS>(cs); ASSERT_TRUE(ellipsoidal_cs != nullptr); ASSERT_EQ(ellipsoidal_cs->identifiers().size(), 1U); EXPECT_EQ(ellipsoidal_cs->identifiers()[0]->code(), "6422"); EXPECT_EQ(*(ellipsoidal_cs->identifiers()[0]->codeSpace()), "EPSG"); const auto &axisList = ellipsoidal_cs->axisList(); EXPECT_EQ(axisList.size(), 2U); EXPECT_EQ(*(axisList[0]->name()->description()), "Geodetic latitude"); EXPECT_EQ(axisList[0]->abbreviation(), "Lat"); EXPECT_EQ(axisList[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(axisList[0]->unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(*(axisList[1]->name()->description()), "Geodetic longitude"); EXPECT_EQ(axisList[1]->abbreviation(), "Lon"); EXPECT_EQ(axisList[1]->direction(), AxisDirection::EAST); EXPECT_EQ(axisList[1]->unit(), UnitOfMeasure::DEGREE); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateSystem_ellipsoidal_3_axis) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto cs = factory->createCoordinateSystem("6423"); auto ellipsoidal_cs = nn_dynamic_pointer_cast<EllipsoidalCS>(cs); ASSERT_TRUE(ellipsoidal_cs != nullptr); ASSERT_EQ(ellipsoidal_cs->identifiers().size(), 1U); EXPECT_EQ(ellipsoidal_cs->identifiers()[0]->code(), "6423"); EXPECT_EQ(*(ellipsoidal_cs->identifiers()[0]->codeSpace()), "EPSG"); const auto &axisList = ellipsoidal_cs->axisList(); EXPECT_EQ(axisList.size(), 3U); EXPECT_EQ(*(axisList[0]->name()->description()), "Geodetic latitude"); EXPECT_EQ(axisList[0]->abbreviation(), "Lat"); EXPECT_EQ(axisList[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(axisList[0]->unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(*(axisList[1]->name()->description()), "Geodetic longitude"); EXPECT_EQ(axisList[1]->abbreviation(), "Lon"); EXPECT_EQ(axisList[1]->direction(), AxisDirection::EAST); EXPECT_EQ(axisList[1]->unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(*(axisList[2]->name()->description()), "Ellipsoidal height"); EXPECT_EQ(axisList[2]->abbreviation(), "h"); EXPECT_EQ(axisList[2]->direction(), AxisDirection::UP); EXPECT_EQ(axisList[2]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateSystem_geocentric) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto cs = factory->createCoordinateSystem("6500"); auto cartesian_cs = nn_dynamic_pointer_cast<CartesianCS>(cs); ASSERT_TRUE(cartesian_cs != nullptr); ASSERT_EQ(cartesian_cs->identifiers().size(), 1U); EXPECT_EQ(cartesian_cs->identifiers()[0]->code(), "6500"); EXPECT_EQ(*(cartesian_cs->identifiers()[0]->codeSpace()), "EPSG"); const auto &axisList = cartesian_cs->axisList(); EXPECT_EQ(axisList.size(), 3U); EXPECT_EQ(*(axisList[0]->name()->description()), "Geocentric X"); EXPECT_EQ(axisList[0]->abbreviation(), "X"); EXPECT_EQ(axisList[0]->direction(), AxisDirection::GEOCENTRIC_X); EXPECT_EQ(axisList[0]->unit(), UnitOfMeasure::METRE); EXPECT_EQ(*(axisList[1]->name()->description()), "Geocentric Y"); EXPECT_EQ(axisList[1]->abbreviation(), "Y"); EXPECT_EQ(axisList[1]->direction(), AxisDirection::GEOCENTRIC_Y); EXPECT_EQ(axisList[1]->unit(), UnitOfMeasure::METRE); EXPECT_EQ(*(axisList[2]->name()->description()), "Geocentric Z"); EXPECT_EQ(axisList[2]->abbreviation(), "Z"); EXPECT_EQ(axisList[2]->direction(), AxisDirection::GEOCENTRIC_Z); EXPECT_EQ(axisList[2]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateSystem_vertical) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createCoordinateSystem("-1"), NoSuchAuthorityCodeException); auto cs = factory->createCoordinateSystem("6499"); auto vertical_cs = nn_dynamic_pointer_cast<VerticalCS>(cs); ASSERT_TRUE(vertical_cs != nullptr); ASSERT_EQ(vertical_cs->identifiers().size(), 1U); EXPECT_EQ(vertical_cs->identifiers()[0]->code(), "6499"); EXPECT_EQ(*(vertical_cs->identifiers()[0]->codeSpace()), "EPSG"); const auto &axisList = vertical_cs->axisList(); EXPECT_EQ(axisList.size(), 1U); EXPECT_EQ(*(axisList[0]->name()->description()), "Gravity-related height"); EXPECT_EQ(axisList[0]->abbreviation(), "H"); EXPECT_EQ(axisList[0]->direction(), AxisDirection::UP); EXPECT_EQ(axisList[0]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createGeodeticCRS_geographic2D) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createGeodeticCRS("-1"), NoSuchAuthorityCodeException); auto crs = factory->createGeodeticCRS("4326"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); ASSERT_TRUE(gcrs != nullptr); ASSERT_EQ(gcrs->identifiers().size(), 1U); EXPECT_EQ(gcrs->identifiers()[0]->code(), "4326"); EXPECT_EQ(*(gcrs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(gcrs->name()->description()), "WGS 84"); ASSERT_TRUE(gcrs->datum() == nullptr); ASSERT_TRUE(gcrs->datumEnsemble() != nullptr); EXPECT_TRUE(gcrs->datumEnsemble()->isEquivalentTo( factory->createDatumEnsemble("6326").get())); EXPECT_TRUE(gcrs->coordinateSystem()->isEquivalentTo( factory->createCoordinateSystem("6422").get())); auto domain = crs->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("1262").get())); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +datum=WGS84 +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createGeodeticCRS_geographic2D_area_no_bbox) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createGeodeticCRS("4296"); // Sudan - deprecated auto domain = crs->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("1361").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createGeodeticCRS_geographic3D) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createGeodeticCRS("4979"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); ASSERT_TRUE(gcrs != nullptr); ASSERT_EQ(gcrs->identifiers().size(), 1U); EXPECT_EQ(gcrs->identifiers()[0]->code(), "4979"); EXPECT_EQ(*(gcrs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(gcrs->name()->description()), "WGS 84"); ASSERT_TRUE(gcrs->datum() == nullptr); ASSERT_TRUE(gcrs->datumEnsemble() != nullptr); EXPECT_TRUE(gcrs->datumEnsemble()->isEquivalentTo( factory->createDatumEnsemble("6326").get())); EXPECT_TRUE(gcrs->coordinateSystem()->isEquivalentTo( factory->createCoordinateSystem("6423").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createGeodeticCRS_geocentric) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createGeodeticCRS("4978"); ASSERT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs) == nullptr); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "4978"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(crs->name()->description()), "WGS 84"); ASSERT_TRUE(crs->datum() == nullptr); ASSERT_TRUE(crs->datumEnsemble() != nullptr); EXPECT_TRUE(crs->datumEnsemble()->isEquivalentTo( factory->createDatumEnsemble("6326").get())); EXPECT_TRUE(crs->coordinateSystem()->isEquivalentTo( factory->createCoordinateSystem("6500").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createGeographicCRS) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createGeographicCRS("4979"); ASSERT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs) != nullptr); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "4979"); EXPECT_THROW(factory->createGeographicCRS("4978"), FactoryException); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createVerticalCRS) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createVerticalCRS("-1"), NoSuchAuthorityCodeException); auto crs = factory->createVerticalCRS("3855"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "3855"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(crs->name()->description()), "EGM2008 height"); EXPECT_TRUE( crs->datum()->isEquivalentTo(factory->createDatum("1027").get())); EXPECT_TRUE(crs->coordinateSystem()->isEquivalentTo( factory->createCoordinateSystem("6499").get())); auto domain = crs->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("1262").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createVerticalCRS_with_datum_ensemble) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createVerticalCRS("-1"), NoSuchAuthorityCodeException); auto crs = factory->createVerticalCRS("9451"); // BI height ASSERT_TRUE(crs->datum() == nullptr); ASSERT_TRUE(crs->datumEnsemble() != nullptr); EXPECT_TRUE(crs->datumEnsemble()->isEquivalentTo( factory->createDatumEnsemble("1288").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createConversion) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createConversion("-1"), NoSuchAuthorityCodeException); auto conv = factory->createConversion("16031"); ASSERT_EQ(conv->identifiers().size(), 1U); EXPECT_EQ(conv->identifiers()[0]->code(), "16031"); EXPECT_EQ(*(conv->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(conv->name()->description()), "UTM zone 31N"); auto method = conv->method(); ASSERT_EQ(method->identifiers().size(), 1U); EXPECT_EQ(method->identifiers()[0]->code(), "9807"); EXPECT_EQ(*(method->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(method->name()->description()), "Transverse Mercator"); const auto &values = conv->parameterValues(); ASSERT_EQ(values.size(), 5U); { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[0]); ASSERT_TRUE(opParamvalue); const auto &paramName = *(opParamvalue->parameter()->name()->description()); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8801); EXPECT_EQ(paramName, "Latitude of natural origin"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(measure.value(), 0.0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[1]); ASSERT_TRUE(opParamvalue); const auto &paramName = *(opParamvalue->parameter()->name()->description()); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8802); EXPECT_EQ(paramName, "Longitude of natural origin"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(measure.value(), 3.0); } } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createConversion_from_other_transformation) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("7984", false); auto conversion = nn_dynamic_pointer_cast<Conversion>(op); ASSERT_TRUE(conversion != nullptr); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createProjectedCRS) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createProjectedCRS("-1"), NoSuchAuthorityCodeException); auto crs = factory->createProjectedCRS("32631"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "32631"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(crs->name()->description()), "WGS 84 / UTM zone 31N"); EXPECT_TRUE(crs->baseCRS()->isEquivalentTo( factory->createGeodeticCRS("4326").get())); EXPECT_TRUE(crs->coordinateSystem()->isEquivalentTo( factory->createCoordinateSystem("4400").get())); EXPECT_TRUE(crs->derivingConversion()->isEquivalentTo( factory->createConversion("16031").get())); auto domain = crs->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("2060").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createProjectedCRS_south_pole) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createProjectedCRS("-1"), NoSuchAuthorityCodeException); auto crs = factory->createProjectedCRS("32761"); auto csList = crs->coordinateSystem()->axisList(); ASSERT_EQ(csList.size(), 2U); EXPECT_TRUE(csList[0]->meridian() != nullptr); EXPECT_EQ(csList[0]->direction(), AxisDirection::NORTH); EXPECT_EQ( csList[0]->meridian()->longitude().convertToUnit(UnitOfMeasure::DEGREE), 0); EXPECT_EQ(csList[1]->direction(), AxisDirection::NORTH); EXPECT_EQ( csList[1]->meridian()->longitude().convertToUnit(UnitOfMeasure::DEGREE), 90); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createProjectedCRS_north_pole) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = factory->createProjectedCRS("32661"); auto csList = crs->coordinateSystem()->axisList(); ASSERT_EQ(csList.size(), 2U); EXPECT_TRUE(csList[0]->meridian() != nullptr); EXPECT_EQ(csList[0]->direction(), AxisDirection::SOUTH); EXPECT_EQ( csList[0]->meridian()->longitude().convertToUnit(UnitOfMeasure::DEGREE), 180); EXPECT_EQ(csList[1]->direction(), AxisDirection::SOUTH); EXPECT_EQ( csList[1]->meridian()->longitude().convertToUnit(UnitOfMeasure::DEGREE), 90); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCompoundCRS) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createCompoundCRS("-1"), NoSuchAuthorityCodeException); auto crs = factory->createCompoundCRS("6871"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "6871"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(*(crs->name()->description()), "WGS 84 / Pseudo-Mercator + EGM2008 geoid height"); auto components = crs->componentReferenceSystems(); ASSERT_EQ(components.size(), 2U); EXPECT_TRUE(components[0]->isEquivalentTo( factory->createProjectedCRS("3857").get())); EXPECT_TRUE(components[1]->isEquivalentTo( factory->createVerticalCRS("3855").get())); auto domain = crs->domains()[0]; auto extent = domain->domainOfValidity(); ASSERT_TRUE(extent != nullptr); EXPECT_TRUE(extent->isEquivalentTo(factory->createExtent("1262").get())); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateReferenceSystem) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createCoordinateReferenceSystem("-1"), NoSuchAuthorityCodeException); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>( factory->createCoordinateReferenceSystem("4326"))); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>( factory->createCoordinateReferenceSystem("4979"))); EXPECT_TRUE(nn_dynamic_pointer_cast<GeodeticCRS>( factory->createCoordinateReferenceSystem("4978"))); EXPECT_TRUE(nn_dynamic_pointer_cast<ProjectedCRS>( factory->createCoordinateReferenceSystem("32631"))); EXPECT_TRUE(nn_dynamic_pointer_cast<VerticalCRS>( factory->createCoordinateReferenceSystem("3855"))); EXPECT_TRUE(nn_dynamic_pointer_cast<CompoundCRS>( factory->createCoordinateReferenceSystem("6871"))); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_helmert_3) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->createCoordinateOperation("-1", false), NoSuchAuthorityCodeException); auto op = factory->createCoordinateOperation("1113", false); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +inv " "+proj=longlat +a=6378249.145 +rf=293.4663077 +step +proj=push " "+v_3 +step +proj=cart +a=6378249.145 +rf=293.4663077 +step " "+proj=helmert +x=-143 +y=-90 +z=-294 +step +inv +proj=cart " "+ellps=WGS84 +step +proj=pop +v_3 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_helmert_7_CF) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("7676", false); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=bessel +step +proj=helmert +x=577.88891 " "+y=165.22205 +z=391.18289 +rx=-4.9145 +ry=0.94729 +rz=13.05098 " "+s=7.78664 +convention=coordinate_frame +step +inv +proj=cart " "+ellps=WGS84 +step +proj=pop +v_3 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_helmert_7_PV) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("1074", false); auto wkt = op->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_TRUE(wkt.find("+proj=helmert +x=-275.7224 +y=94.7824 +z=340.8944 " "+rx=-8.001 +ry=-4.42 +rz=-11.821 +s=1 " "+convention=position_vector") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_helmert_8_CF) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("7702", false); auto expected = " PARAMETER[\"Transformation reference epoch\",2002,\n" " TIMEUNIT[\"year\",31556925.445],\n" " ID[\"EPSG\",1049]],\n"; auto wkt = op->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_TRUE(wkt.find(expected) != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_helmert_15_CF) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("6276", false); auto expected = "COORDINATEOPERATION[\"ITRF2008 to GDA94 (1)\",\n" " VERSION[\"GA-Aus 2010\"],\n" " SOURCECRS[\n" " GEODCRS[\"ITRF2008\",\n" " DYNAMIC[\n" " FRAMEEPOCH[2005]],\n" " DATUM[\"International Terrestrial Reference Frame " "2008\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5332]]],\n" " TARGETCRS[\n" " GEODCRS[\"GDA94\",\n" " DATUM[\"Geocentric Datum of Australia 1994\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4938]]],\n" " METHOD[\"Time-dependent Coordinate Frame rotation (geocen)\",\n" " ID[\"EPSG\",1056]],\n" " PARAMETER[\"X-axis translation\",-84.68,\n" " LENGTHUNIT[\"millimetre\",0.001],\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",-19.42,\n" " LENGTHUNIT[\"millimetre\",0.001],\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",32.01,\n" " LENGTHUNIT[\"millimetre\",0.001],\n" " ID[\"EPSG\",8607]],\n" " PARAMETER[\"X-axis rotation\",-0.4254,\n" " ANGLEUNIT[\"milliarc-second\",4.84813681109536E-09],\n" " ID[\"EPSG\",8608]],\n" " PARAMETER[\"Y-axis rotation\",2.2578,\n" " ANGLEUNIT[\"milliarc-second\",4.84813681109536E-09],\n" " ID[\"EPSG\",8609]],\n" " PARAMETER[\"Z-axis rotation\",2.4015,\n" " ANGLEUNIT[\"milliarc-second\",4.84813681109536E-09],\n" " ID[\"EPSG\",8610]],\n" " PARAMETER[\"Scale difference\",9.71,\n" " SCALEUNIT[\"parts per billion\",1E-09],\n" " ID[\"EPSG\",8611]],\n" " PARAMETER[\"Rate of change of X-axis translation\",1.42,\n" " LENGTHUNIT[\"millimetres per year\",3.16887651727315E-11],\n" " ID[\"EPSG\",1040]],\n" " PARAMETER[\"Rate of change of Y-axis translation\",1.34,\n" " LENGTHUNIT[\"millimetres per year\",3.16887651727315E-11],\n" " ID[\"EPSG\",1041]],\n" " PARAMETER[\"Rate of change of Z-axis translation\",0.9,\n" " LENGTHUNIT[\"millimetres per year\",3.16887651727315E-11],\n" " ID[\"EPSG\",1042]],\n" " PARAMETER[\"Rate of change of X-axis rotation\",1.5461,\n" " ANGLEUNIT[\"milliarc-seconds per " "year\",1.53631468932076E-16],\n" " ID[\"EPSG\",1043]],\n" " PARAMETER[\"Rate of change of Y-axis rotation\",1.182,\n" " ANGLEUNIT[\"milliarc-seconds per " "year\",1.53631468932076E-16],\n" " ID[\"EPSG\",1044]],\n" " PARAMETER[\"Rate of change of Z-axis rotation\",1.1551,\n" " ANGLEUNIT[\"milliarc-seconds per " "year\",1.53631468932076E-16],\n" " ID[\"EPSG\",1045]],\n" " PARAMETER[\"Rate of change of Scale difference\",0.109,\n" " SCALEUNIT[\"parts per billion per " "year\",3.16887651727315E-17],\n" " ID[\"EPSG\",1046]],\n" " PARAMETER[\"Parameter reference epoch\",1994,\n" " TIMEUNIT[\"year\",31556925.445],\n" " ID[\"EPSG\",1047]],\n" " OPERATIONACCURACY[0.03],\n" " USAGE[\n" " SCOPE[\"Geodesy.\"],\n" " AREA[\"Australia - onshore and offshore to 200 nautical mile " "EEZ boundary. Includes Lord Howe Island, Ashmore and Cartier " "Islands.\"],\n" " BBOX[-47.2,109.23,-8.88,163.2]],\n" " ID[\"EPSG\",6276],\n" " REMARK[\"RMS residuals 5mm north, 8mm east and 28mm vertical, " "maximum residuals 10mm north, 13mm east and 51mm vertical. Scale " "difference in ppb and scale difference rate in ppb/yr where " "1/billion = 1E-9 or nm/m.\"]]"; EXPECT_EQ( op->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_helmert_15_PV) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("8069", false); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=helmert +x=-0.0254 +y=0.0005 +z=0.1548 +rx=-0.0001 +ry=0 " "+rz=-0.00026 +s=-0.01129 +dx=-0.0001 +dy=0.0005 +dz=0.0033 " "+drx=0 +dry=0 +drz=-2e-05 +ds=-0.00012 +t_epoch=2010 " "+convention=position_vector"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_helmert_15_PV_rounding_of_drz) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("7932", false); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=helmert +x=0 +y=0 +z=0 +rx=0 +ry=0 +rz=0 +s=0 +dx=0 +dy=0 " "+dz=0 +drx=0.00011 +dry=0.00057 +drz=-0.00071 +ds=0 " "+t_epoch=1989 +convention=position_vector"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_molodensky_badekas_PV) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("1066", false); auto so = nn_dynamic_pointer_cast<SingleOperation>(op); ASSERT_TRUE(so != nullptr); EXPECT_TRUE(so->validateParameters().empty()); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=bessel +step +proj=molobadekas " "+x=593.032 +y=26 +z=478.741 +rx=0.409394387439237 " "+ry=-0.359705195614311 +rz=1.86849100035057 +s=4.0772 " "+px=3903453.148 +py=368135.313 +pz=5012970.306 " "+convention=coordinate_frame +step +inv +proj=cart +ellps=GRS80 " "+step +proj=pop +v_3 +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_grid_transformation_one_parameter) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("1295", false); auto expected = "COORDINATEOPERATION[\"RGNC91-93 to NEA74 Noumea (4)\",\n" " VERSION[\"ESRI-Ncl 0.05m\"],\n" " SOURCECRS[\n" " GEOGCRS[\"RGNC91-93\",\n" " DATUM[\"Reseau Geodesique de Nouvelle Caledonie 91-93\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4749]]],\n" " TARGETCRS[\n" " GEOGCRS[\"NEA74 Noumea\",\n" " DATUM[\"NEA74 Noumea\",\n" " ELLIPSOID[\"International 1924\",6378388,297,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4644]]],\n" " METHOD[\"NTv2\",\n" " ID[\"EPSG\",9615]],\n" " PARAMETERFILE[\"Latitude and longitude difference " "file\",\"RGNC1991_NEA74Noumea.gsb\"],\n" " OPERATIONACCURACY[0.05],\n" " USAGE[\n" " SCOPE[\"Geodesy.\"],\n" " AREA[\"New Caledonia - Grande Terre - Noumea district.\"],\n" " BBOX[-22.37,166.35,-22.19,166.54]],\n" " ID[\"EPSG\",1295],\n" " REMARK[\"Emulation using NTv2 method of tfm NEA74 Noumea to " "RGNC91-93 (3) (code 15943). Note reversal of sign of parameter values " "in grid file.\"]]"; EXPECT_EQ( op->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_grid_transformation_two_parameter) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("15864", false); auto expected = " PARAMETERFILE[\"Latitude difference file\",\"alaska.las\"],\n" " PARAMETERFILE[\"Longitude difference file\",\"alaska.los\"],\n"; auto wkt = op->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_TRUE(wkt.find(expected) != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_other_transformation) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("1884", false); auto expected = "COORDINATEOPERATION[\"S-JTSK (Ferro) to S-JTSK (1)\",\n" " VERSION[\"EPSG-Cze\"],\n" " SOURCECRS[\n" " GEOGCRS[\"S-JTSK (Ferro)\",\n" " DATUM[\"System of the Unified Trigonometrical Cadastral " "Network (Ferro)\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Ferro\",-17.6666666666667,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4818]]],\n" " TARGETCRS[\n" " GEOGCRS[\"S-JTSK\",\n" " DATUM[\"System of the Unified Trigonometrical Cadastral " "Network\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4156]]],\n" " METHOD[\"Longitude rotation\",\n" " ID[\"EPSG\",9601]],\n" " PARAMETER[\"Longitude offset\",-17.6666666666667,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8602]],\n" " OPERATIONACCURACY[0.0],\n" " USAGE[\n" " SCOPE[\"Change of prime meridian.\"],\n" " AREA[\"Czechia; Slovakia.\"],\n" " BBOX[47.73,12.09,51.06,22.56]],\n" " ID[\"EPSG\",1884]]"; EXPECT_EQ( op->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_test_uom_9110) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // This tests conversion from unit of measure EPSG:9110 DDD.MMSSsss auto crs = factory->createProjectedCRS("2172"); EXPECT_PRED_FORMAT2( ComparePROJString, crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=sterea +lat_0=53.0019444444444 +lon_0=21.5027777777778 " "+k=0.9998 +x_0=4603000 +y_0=5806000 +ellps=krass +units=m " "+no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_affine_parametric_transform) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("10087", false); // Do not do axis unit change EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=affine +xoff=82357.457 +s11=0.304794369 " "+s12=1.5417425e-05 +yoff=28091.324 +s21=-1.5417425e-05 " "+s22=0.304794369"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_concatenated_operation) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("3896", false); auto concatenated = nn_dynamic_pointer_cast<ConcatenatedOperation>(op); ASSERT_TRUE(concatenated != nullptr); auto operations = concatenated->operations(); ASSERT_EQ(operations.size(), 2U); EXPECT_TRUE(operations[0]->isEquivalentTo( factory->createCoordinateOperation("3895", false).get())); EXPECT_TRUE(operations[1]->isEquivalentTo( factory->createCoordinateOperation("1618", false).get())); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_concatenated_operation_three_steps) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("8647", false); auto concatenated = nn_dynamic_pointer_cast<ConcatenatedOperation>(op); ASSERT_TRUE(concatenated != nullptr); auto operations = concatenated->operations(); ASSERT_EQ(operations.size(), 3U); EXPECT_TRUE(operations[0]->isEquivalentTo( factory->createCoordinateOperation("1313", false).get())); EXPECT_TRUE(operations[1]->isEquivalentTo( factory->createCoordinateOperation("1950", false).get())); EXPECT_TRUE(operations[2]->isEquivalentTo( factory->createCoordinateOperation("1946", false).get())); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_concatenated_operation_inverse_step1) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("8443", false); auto concatenated = nn_dynamic_pointer_cast<ConcatenatedOperation>(op); ASSERT_TRUE(concatenated != nullptr); auto operations = concatenated->operations(); ASSERT_EQ(operations.size(), 2U); EXPECT_TRUE(operations[0]->isEquivalentTo( factory->createCoordinateOperation("8364", false)->inverse().get())); EXPECT_TRUE(operations[1]->isEquivalentTo( factory->createCoordinateOperation("8367", false).get())); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_concatenated_operation_inverse_step2) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("7811", false); auto concatenated = nn_dynamic_pointer_cast<ConcatenatedOperation>(op); ASSERT_TRUE(concatenated != nullptr); auto operations = concatenated->operations(); ASSERT_EQ(operations.size(), 2U); EXPECT_TRUE(operations[0]->isEquivalentTo( factory->createCoordinateOperation("1763", false).get())); EXPECT_TRUE(operations[1]->isEquivalentTo( factory->createCoordinateOperation("15958", false)->inverse().get())); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_concatenated_operation_step1_is_conversion) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("7973", false); auto concatenated = nn_dynamic_pointer_cast<ConcatenatedOperation>(op); ASSERT_TRUE(concatenated != nullptr); auto operations = concatenated->operations(); ASSERT_EQ(operations.size(), 2U); EXPECT_TRUE(operations[0]->isEquivalentTo( factory->createCoordinateOperation("7813", false).get())); EXPECT_TRUE(operations[1]->isEquivalentTo( factory->createCoordinateOperation("7969", false).get())); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_concatenated_operation_step_2_and_3_are_conversion) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("7987", false); auto concatenated = nn_dynamic_pointer_cast<ConcatenatedOperation>(op); ASSERT_TRUE(concatenated != nullptr); auto operations = concatenated->operations(); ASSERT_EQ(operations.size(), 3U); EXPECT_TRUE(operations[0]->isEquivalentTo( factory->createCoordinateOperation("7980", false).get())); EXPECT_TRUE(operations[1]->isEquivalentTo( factory->createCoordinateOperation("7812", false).get())); EXPECT_TRUE(operations[2]->isEquivalentTo( factory->createCoordinateOperation("7813", false).get())); EXPECT_EQ(operations[1]->targetCRS()->nameStr(), "KOC WD depth"); EXPECT_EQ(operations[2]->sourceCRS()->nameStr(), operations[1]->targetCRS()->nameStr()); EXPECT_EQ( concatenated->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=geogoffset +dh=-4.74 " "+step +proj=axisswap +order=1,2,-3 " "+step +proj=unitconvert +z_in=m +z_out=ft"); EXPECT_EQ(concatenated->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +z_in=ft +z_out=m " "+step +proj=axisswap +order=1,2,-3 " "+step +proj=geogoffset +dh=4.74"); } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createCoordinateOperation_concatenated_operation_epsg_9103) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("9103", false); auto concatenated = nn_dynamic_pointer_cast<ConcatenatedOperation>(op); ASSERT_TRUE(concatenated != nullptr); auto operations = concatenated->operations(); ASSERT_EQ(operations.size(), 5U); // we've added an explicit geographic -> geocentric step EXPECT_EQ(operations[0]->nameStr(), "NAD27 to NAD83 (1)"); EXPECT_EQ(operations[1]->nameStr(), "NAD83 to NAD83(2011) (1)"); EXPECT_EQ( operations[2]->nameStr(), "Conversion from NAD83(2011) (geog2D) to NAD83(2011) (geocentric)"); EXPECT_EQ(operations[3]->nameStr(), "Inverse of ITRF2008 to NAD83(2011) (1)"); EXPECT_EQ(operations[4]->nameStr(), "ITRF2008 to ITRF2014 (1)"); } // --------------------------------------------------------------------------- static bool in(const std::string &str, const std::vector<std::string> &list) { for (const auto &listItem : list) { if (str == listItem) { return true; } } return false; } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_build_all_concatenated) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto setConcatenated = factory->getAuthorityCodes( AuthorityFactory::ObjectType::CONCATENATED_OPERATION); auto setConcatenatedNoDeprecated = factory->getAuthorityCodes( AuthorityFactory::ObjectType::CONCATENATED_OPERATION, false); EXPECT_LT(setConcatenatedNoDeprecated.size(), setConcatenated.size()); for (const auto &code : setConcatenated) { if (in(code, {"8422", "8481", "8482", "8565", "8566", "8572"})) { EXPECT_THROW(factory->createCoordinateOperation(code, false), FactoryException) << code; } else { factory->createCoordinateOperation(code, false); } } } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_conversion) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("16031", false); auto conversion = nn_dynamic_pointer_cast<Conversion>(op); ASSERT_TRUE(conversion != nullptr); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createCoordinateOperation_point_motion_operation) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = factory->createCoordinateOperation("9483", false); auto pmo = nn_dynamic_pointer_cast<PointMotionOperation>(op); ASSERT_TRUE(pmo != nullptr); auto expected = "POINTMOTIONOPERATION[\"Canada velocity grid v7\",\n" " VERSION[\"NRC-Can cvg7.0\"],\n" " SOURCECRS[\n" " GEOGCRS[\"NAD83(CSRS)v7\",\n" " DATUM[\"North American Datum of 1983 (CSRS) version 7\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",8254]]],\n" " METHOD[\"Point motion by grid (Canada NTv2_Vel)\",\n" " ID[\"EPSG\",1070]],\n" " PARAMETERFILE[\"Point motion velocity grid " "file\",\"NAD83v70VG.gvb\"],\n" " OPERATIONACCURACY[0.01],\n" " USAGE[\n" " SCOPE[\"Change of coordinate epoch for points referenced to " "NAD83(CSRS)v7.\"],\n" " AREA[\"Canada - onshore and offshore - Alberta; British " "Columbia; Manitoba; New Brunswick; Newfoundland and Labrador; " "Northwest Territories; Nova Scotia; Nunavut; Ontario; Prince Edward " "Island; Quebec; Saskatchewan; Yukon.\"],\n" " BBOX[38.21,-141.01,86.46,-40.73]],\n" " ID[\"EPSG\",9483],\n" " REMARK[\"File initially published with name cvg70.cvb, later " "renamed to NAD83v70VG.gvb with no change of content.\"]]"; EXPECT_EQ( pmo->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_getAuthorityCodes) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto set = factory->getAuthorityCodes( AuthorityFactory::ObjectType::PRIME_MERIDIAN); ASSERT_TRUE(!set.empty()); factory->createPrimeMeridian(*(set.begin())); } { auto set = factory->getAuthorityCodes(AuthorityFactory::ObjectType::ELLIPSOID); ASSERT_TRUE(!set.empty()); factory->createEllipsoid(*(set.begin())); } { auto setDatum = factory->getAuthorityCodes(AuthorityFactory::ObjectType::DATUM); ASSERT_TRUE(!setDatum.empty()); factory->createDatum(*(setDatum.begin())); auto setGeodeticDatum = factory->getAuthorityCodes( AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME); ASSERT_TRUE(!setGeodeticDatum.empty()); factory->createGeodeticDatum(*(setGeodeticDatum.begin())); auto setDynamicGeodeticDatum = factory->getAuthorityCodes( AuthorityFactory::ObjectType::DYNAMIC_GEODETIC_REFERENCE_FRAME); ASSERT_TRUE(!setDynamicGeodeticDatum.empty()); auto dgrf = factory->createGeodeticDatum(*(setDynamicGeodeticDatum.begin())); EXPECT_TRUE(dynamic_cast<DynamicGeodeticReferenceFrame *>(dgrf.get()) != nullptr); EXPECT_LT(setDynamicGeodeticDatum.size(), setGeodeticDatum.size()); auto setVerticalDatum = factory->getAuthorityCodes( AuthorityFactory::ObjectType::VERTICAL_REFERENCE_FRAME); ASSERT_TRUE(!setVerticalDatum.empty()); factory->createVerticalDatum(*(setVerticalDatum.begin())); auto setDynamicVerticalDatum = factory->getAuthorityCodes( AuthorityFactory::ObjectType::DYNAMIC_VERTICAL_REFERENCE_FRAME); ASSERT_TRUE(!setDynamicVerticalDatum.empty()); auto dvrf = factory->createVerticalDatum(*(setDynamicVerticalDatum.begin())); EXPECT_TRUE(dynamic_cast<DynamicVerticalReferenceFrame *>(dvrf.get()) != nullptr); EXPECT_LT(setDynamicVerticalDatum.size(), setVerticalDatum.size()); std::set<std::string> setMerged; for (const auto &v : setGeodeticDatum) { setMerged.insert(v); } for (const auto &v : setVerticalDatum) { setMerged.insert(v); } EXPECT_EQ(setDatum, setMerged); } { auto setCRS = factory->getAuthorityCodes(AuthorityFactory::ObjectType::CRS); ASSERT_TRUE(!setCRS.empty()); factory->createCoordinateReferenceSystem(*(setCRS.begin())); auto setGeodeticCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::GEODETIC_CRS); ASSERT_TRUE(!setGeodeticCRS.empty()); factory->createGeodeticCRS(*(setGeodeticCRS.begin())); auto setGeocentricCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::GEOCENTRIC_CRS); ASSERT_TRUE(!setGeocentricCRS.empty()); factory->createGeodeticCRS(*(setGeocentricCRS.begin())); EXPECT_LT(setGeocentricCRS.size(), setGeodeticCRS.size()); auto setGeographicCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::GEOGRAPHIC_CRS); ASSERT_TRUE(!setGeographicCRS.empty()); factory->createGeographicCRS(*(setGeographicCRS.begin())); EXPECT_LT(setGeographicCRS.size(), setGeodeticCRS.size()); for (const auto &v : setGeographicCRS) { EXPECT_TRUE(setGeodeticCRS.find(v) != setGeodeticCRS.end()); } auto setGeographic2DCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS); ASSERT_TRUE(!setGeographic2DCRS.empty()); factory->createGeographicCRS(*(setGeographic2DCRS.begin())); auto setGeographic3DCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS); ASSERT_TRUE(!setGeographic3DCRS.empty()); factory->createGeographicCRS(*(setGeographic3DCRS.begin())); EXPECT_EQ(setGeographic2DCRS.size() + setGeographic3DCRS.size(), setGeographicCRS.size()); EXPECT_EQ(setGeocentricCRS.size() + setGeographicCRS.size(), setGeodeticCRS.size()); auto setVerticalCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::VERTICAL_CRS); ASSERT_TRUE(!setVerticalCRS.empty()); factory->createVerticalCRS(*(setVerticalCRS.begin())); auto setProjectedCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::PROJECTED_CRS); ASSERT_TRUE(!setProjectedCRS.empty()); factory->createProjectedCRS(*(setProjectedCRS.begin())); auto setCompoundCRS = factory->getAuthorityCodes( AuthorityFactory::ObjectType::COMPOUND_CRS); ASSERT_TRUE(!setCompoundCRS.empty()); factory->createCompoundCRS(*(setCompoundCRS.begin())); std::set<std::string> setMerged; for (const auto &v : setGeodeticCRS) { setMerged.insert(v); } for (const auto &v : setVerticalCRS) { setMerged.insert(v); } for (const auto &v : setProjectedCRS) { setMerged.insert(v); } for (const auto &v : setCompoundCRS) { setMerged.insert(v); } EXPECT_EQ(setCRS, setMerged); } { auto setCO = factory->getAuthorityCodes( AuthorityFactory::ObjectType::COORDINATE_OPERATION); ASSERT_TRUE(!setCO.empty()); factory->createCoordinateOperation(*(setCO.begin()), false); auto setConversion = factory->getAuthorityCodes( AuthorityFactory::ObjectType::CONVERSION); ASSERT_TRUE(!setConversion.empty()); factory->createConversion(*(setConversion.begin())); auto setTransformation = factory->getAuthorityCodes( AuthorityFactory::ObjectType::TRANSFORMATION); ASSERT_TRUE(!setTransformation.empty()); ASSERT_TRUE(nn_dynamic_pointer_cast<Transformation>( factory->createCoordinateOperation( *(setTransformation.begin()), false)) != nullptr); auto setConcatenated = factory->getAuthorityCodes( AuthorityFactory::ObjectType::CONCATENATED_OPERATION); ASSERT_TRUE(!setConcatenated.empty()); ASSERT_TRUE(nn_dynamic_pointer_cast<ConcatenatedOperation>( factory->createCoordinateOperation( *(setConcatenated.begin()), false)) != nullptr); std::set<std::string> setMerged; for (const auto &v : setConversion) { setMerged.insert(v); } for (const auto &v : setTransformation) { setMerged.insert(v); } for (const auto &v : setConcatenated) { setMerged.insert(v); } EXPECT_EQ(setCO.size(), setMerged.size()); std::set<std::string> setMissing; for (const auto &v : setCO) { if (setMerged.find(v) == setMerged.end()) { setMissing.insert(v); } } EXPECT_EQ(setMissing, std::set<std::string>()); EXPECT_EQ(setCO, setMerged); } } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_getDescriptionText) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_THROW(factory->getDescriptionText("-1"), NoSuchAuthorityCodeException); EXPECT_EQ(factory->getDescriptionText("10000"), "RGF93 v1 to NGF-IGN69 height (1)"); // Several objects have 4326 code, including an area of use, but return // the CRS one. EXPECT_EQ(factory->getDescriptionText("4326"), "WGS 84"); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_IAU_2015) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "IAU_2015"); { auto crs = factory->createGeographicCRS("19900"); EXPECT_EQ(crs->nameStr(), "Mercury (2015) - Sphere / Ocentric"); const auto ellps = crs->ellipsoid(); EXPECT_TRUE(ellps->isSphere()); EXPECT_NEAR(ellps->semiMajorAxis().value(), 2440530.0, 1e-6); const auto &axisList = crs->coordinateSystem()->axisList(); EXPECT_EQ(axisList.size(), 2U); EXPECT_EQ(*(axisList[0]->name()->description()), "Geodetic latitude"); EXPECT_EQ(axisList[0]->abbreviation(), "Lat"); EXPECT_EQ(axisList[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(axisList[0]->unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(*(axisList[1]->name()->description()), "Geodetic longitude"); EXPECT_EQ(axisList[1]->abbreviation(), "Lon"); EXPECT_EQ(axisList[1]->direction(), AxisDirection::EAST); EXPECT_EQ(axisList[1]->unit(), UnitOfMeasure::DEGREE); } { auto crs = factory->createGeographicCRS("19901"); EXPECT_EQ(crs->nameStr(), "Mercury (2015) / Ographic"); const auto ellps = crs->ellipsoid(); EXPECT_TRUE(!ellps->isSphere()); EXPECT_NEAR(ellps->semiMajorAxis().value(), 2440530.0, 1e-6); EXPECT_NEAR(ellps->computeSemiMinorAxis().value(), 2438260.0, 1e-6); const auto &axisList = crs->coordinateSystem()->axisList(); EXPECT_EQ(axisList.size(), 2U); EXPECT_EQ(*(axisList[0]->name()->description()), "Geodetic latitude"); EXPECT_EQ(axisList[0]->abbreviation(), "Lat"); EXPECT_EQ(axisList[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(axisList[0]->unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(*(axisList[1]->name()->description()), "Geodetic longitude"); EXPECT_EQ(axisList[1]->abbreviation(), "Lon"); EXPECT_EQ(axisList[1]->direction(), AxisDirection::WEST); // WEST ! EXPECT_EQ(axisList[1]->unit(), UnitOfMeasure::DEGREE); } { auto crs = factory->createGeodeticCRS("19902"); EXPECT_EQ(crs->nameStr(), "Mercury (2015) / Ocentric"); EXPECT_TRUE(dynamic_cast<GeographicCRS *>(crs.get()) == nullptr); const auto ellps = crs->ellipsoid(); EXPECT_TRUE(!ellps->isSphere()); EXPECT_NEAR(ellps->semiMajorAxis().value(), 2440530.0, 1e-6); EXPECT_NEAR(ellps->computeSemiMinorAxis().value(), 2438260.0, 1e-6); const auto &cs = crs->coordinateSystem(); EXPECT_TRUE(dynamic_cast<SphericalCS *>(cs.get()) != nullptr); const auto &axisList = cs->axisList(); EXPECT_EQ(axisList.size(), 2U); EXPECT_EQ(*(axisList[0]->name()->description()), "Planetocentric latitude"); EXPECT_EQ(axisList[0]->abbreviation(), "U"); EXPECT_EQ(axisList[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(axisList[0]->unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(*(axisList[1]->name()->description()), "Planetocentric longitude"); EXPECT_EQ(axisList[1]->abbreviation(), "V"); EXPECT_EQ(axisList[1]->direction(), AxisDirection::EAST); EXPECT_EQ(axisList[1]->unit(), UnitOfMeasure::DEGREE); } } // --------------------------------------------------------------------------- class FactoryWithTmpDatabase : public ::testing::Test { protected: void SetUp() override { sqlite3_open(":memory:", &m_ctxt); } void TearDown() override { sqlite3_free_table(m_papszResult); sqlite3_close(m_ctxt); } void createStructure() { auto referenceDb = DatabaseContext::create(); const auto dbStructure = referenceDb->getDatabaseStructure(); for (const auto &sql : dbStructure) { ASSERT_TRUE(execute(sql)) << last_error(); } ASSERT_TRUE(execute("PRAGMA foreign_keys = 1;")) << last_error(); } void populateWithFakeEPSG() { ASSERT_TRUE(execute("INSERT INTO unit_of_measure " "VALUES('EPSG','9001','metre','length',1.0,NULL," "0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO unit_of_measure " "VALUES('EPSG','9102','degree','angle',1." "74532925199432781271e-02,NULL,0);")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO unit_of_measure VALUES('EPSG','9122','degree " "(supplier to " "define representation)','angle',1.74532925199432781271e-02,NULL," "0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO extent " "VALUES('EPSG','1262','World','World.',-90.0,90.0,-180." "0,180.0,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO scope VALUES('EPSG','1024','Not known.',0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO prime_meridian " "VALUES('EPSG','8901','Greenwich',0.0,'EPSG','9102',0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO celestial_body VALUES('PROJ','EARTH','Earth'," "6378137.0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO ellipsoid VALUES('EPSG','7030','WGS 84',''," "'PROJ','EARTH',6378137.0,'EPSG','9001',298.257223563," "NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO geodetic_datum " "VALUES('EPSG','6326','World Geodetic System 1984',''," "'EPSG','7030','EPSG','8901',NULL,NULL,NULL," "'my anchor',NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'geodetic_datum_6326_usage','geodetic_datum'," "'EPSG','6326','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE( execute("INSERT INTO vertical_datum VALUES('EPSG','1027','EGM2008 " "geoid',NULL,NULL,NULL,NULL,'my anchor',NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'vertical_datum_1027_usage','vertical_datum'," "'EPSG','1027','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO coordinate_system " "VALUES('EPSG','6422','ellipsoidal',2);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO axis VALUES('EPSG','106','Geodetic " "latitude','Lat','north','EPSG','6422',1,'EPSG','9122');")) << last_error(); ASSERT_TRUE( execute("INSERT INTO axis VALUES('EPSG','107','Geodetic " "longitude','Lon','east','EPSG','6422',2,'EPSG','9122');")) << last_error(); ASSERT_TRUE( execute("INSERT INTO geodetic_crs VALUES('EPSG','4326','WGS " "84',NULL,'geographic " "2D','EPSG','6422','EPSG','6326',NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'geodetic_crs4326_usage','geodetic_crs'," "'EPSG','4326','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO coordinate_system " "VALUES('EPSG','6499','vertical',1);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO axis VALUES('EPSG','114','Gravity-related " "height','H','up','EPSG','6499',1,'EPSG','9001');")) << last_error(); ASSERT_TRUE( execute("INSERT INTO vertical_crs VALUES('EPSG','3855','EGM2008 " "height',NULL,'EPSG','6499','EPSG','1027',0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'vertical_crs3855_usage','vertical_crs'," "'EPSG','3855','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO unit_of_measure " "VALUES('EPSG','9201','unity','scale',1.0," "NULL,0);")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO extent VALUES('EPSG','1933','World - N hemisphere - " "0°E to 6°E','',0.0,84.0,0.0,6.0,0);")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO conversion VALUES('EPSG','16031','UTM zone " "31N',NULL,'EPSG','9807','Transverse " "Mercator','EPSG','8801','Latitude " "of " "natural origin',0.0,'EPSG','9102','EPSG','8802','Longitude of " "natural " "origin',3.0,'EPSG','9102','EPSG','8805','Scale factor at natural " "origin',0.9996,'EPSG','9201','EPSG','8806','False " "easting',500000.0,'EPSG','9001','EPSG','8807','False " "northing',0.0,'EPSG','9001',NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL," "NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'conversion16031_usage','conversion'," "'EPSG','16031','EPSG','1933','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO extent VALUES('EPSG','2060','World - N hemisphere - " "0°E to 6°E - by country','',0.0,84.0,0.0,6.0,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO coordinate_system " "VALUES('EPSG','4400','Cartesian',2);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO axis " "VALUES('EPSG','1','Easting','E','east','EPSG','4400'," "1,'EPSG','9001');")) << last_error(); ASSERT_TRUE( execute("INSERT INTO axis " "VALUES('EPSG','2','Northing','N','north','EPSG','4400'" ",2,'EPSG','9001');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO projected_crs " "VALUES('EPSG','32631','WGS 84 / UTM zone " "31N',NULL,'EPSG','4400','EPSG','4326'," "'EPSG','16031',NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'projected_crs32631_usage','projected_crs'," "'EPSG','32631','EPSG','2060','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO compound_crs VALUES('EPSG','MY_COMPOUND','WGS 84 + " "EGM2008 geoid height',NULL,'EPSG','4326','EPSG','3855',0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('EPSG'," "'compound_crsMY_COMPOUND_usage','compound_crs'," "'EPSG','MY_COMPOUND','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO helmert_transformation " "VALUES('EPSG','DUMMY_HELMERT','name',NULL,'EPSG','9603','" "Geocentric translations (geog2D domain)','EPSG','4326'," "'EPSG','4326',44.0,-143." "0,-90.0,-294.0,'EPSG','9001',NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('EPSG'," "'helmert_transformation_DUMMY_HELMERT_usage'," "'helmert_transformation'," "'EPSG','DUMMY_HELMERT','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO grid_transformation " "VALUES('EPSG','DUMMY_GRID_TRANSFORMATION','name',NULL," "'EPSG','9615'" ",'NTv2','EPSG','4326','EPSG','4326',1.0,'EPSG','" "8656','Latitude and longitude difference " "file','nzgd2kgrid0005.gsb',NULL,NULL,NULL,NULL,NULL,NULL,NULL," "0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('EPSG'," "'grid_transformation_DUMMY_GRID_TRANSFORMATION_usage'," "'grid_transformation'," "'EPSG','DUMMY_GRID_TRANSFORMATION'," "'EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO unit_of_measure VALUES('EPSG','9110','sexagesimal " "DMS','angle',NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO other_transformation " "VALUES('EPSG','DUMMY_OTHER_TRANSFORMATION','name',NULL," "'EPSG','9601','Longitude rotation'," "'EPSG','4326','EPSG','4326',0.0,'EPSG'" ",'8602','Longitude " "offset',-17.4,'EPSG','9110',NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('EPSG'," "'other_transformation_DUMMY_OTHER_TRANSFORMATION_usage'," "'other_transformation'," "'EPSG','DUMMY_OTHER_TRANSFORMATION'," "'EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO concatenated_operation " "VALUES('EPSG','DUMMY_CONCATENATED','name',NULL," "'EPSG','4326','EPSG'" ",'4326',NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'concatenated_operation_DUMMY_CONCATENATED_usage'," "'concatenated_operation'," "'EPSG','DUMMY_CONCATENATED'," "'EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','DUMMY_CONCATENATED',1," "'EPSG','DUMMY_OTHER_TRANSFORMATION');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','DUMMY_CONCATENATED',2," "'EPSG','DUMMY_OTHER_TRANSFORMATION');")) << last_error(); } void createSourceTargetPivotCRS() { const auto vals = std::vector<std::string>{"SOURCE", "TARGET", "PIVOT"}; for (const auto &val : vals) { ASSERT_TRUE(execute("INSERT INTO geodetic_datum " "VALUES('FOO','" + val + "','" + val + "',''," "'EPSG','7030','EPSG','8901'," "NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('FOO'," "'geodetic_datum_" + val + "_usage'," "'geodetic_datum'," "'FOO','" + val + "'," "'EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO geodetic_crs " "VALUES('NS_" + val + "','" + val + "','" + val + "',NULL,'geographic 2D','EPSG','6422'," "'FOO','" + val + "',NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('FOO'," "'geodetic_crs_" + val + "_usage'," "'geodetic_crs'," "'NS_" + val + "','" + val + "','EPSG','1262','EPSG','1024');")) << last_error(); } } void createTransformationForPivotTesting(const std::string &src, const std::string &dst) { ASSERT_TRUE(execute( "INSERT INTO helmert_transformation " "VALUES('OTHER','" + src + "_" + dst + "','Transformation from " + src + " to " + dst + "',NULL,'EPSG','9603','" "Geocentric translations (geog2D domain)','NS_" + src + "','" + src + "','NS_" + dst + "','" + dst + "',1.0,0,0,0,'EPSG','9001',NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER'," "'helmert_transformation" + src + '_' + dst + "_usage'," "'helmert_transformation'," "'OTHER','" + src + "_" + dst + "'," "'EPSG','1262','EPSG','1024');")) << last_error(); } void checkSourceToOther() { { auto factoryOTHER = AuthorityFactory::create( DatabaseContext::create(m_ctxt), "OTHER"); auto res = factoryOTHER->createFromCRSCodesWithIntermediates( "NS_SOURCE", "SOURCE", "NS_TARGET", "TARGET", false, false, false, false, {}); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE(res.empty() || nn_dynamic_pointer_cast<ConcatenatedOperation>(res[0])); res = factoryOTHER->createFromCRSCodesWithIntermediates( "NS_SOURCE", "SOURCE", "NS_TARGET", "TARGET", false, false, false, false, {std::make_pair(std::string("NS_PIVOT"), std::string("PIVOT"))}); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE(res.empty() || nn_dynamic_pointer_cast<ConcatenatedOperation>(res[0])); res = factoryOTHER->createFromCRSCodesWithIntermediates( "NS_SOURCE", "SOURCE", "NS_TARGET", "TARGET", false, false, false, false, {std::make_pair(std::string("NS_PIVOT"), std::string("NOT_EXISTING"))}); EXPECT_EQ(res.size(), 0U); res = factoryOTHER->createFromCRSCodesWithIntermediates( "NS_SOURCE", "SOURCE", "NS_TARGET", "TARGET", false, false, false, false, {std::make_pair(std::string("BAD_NS"), std::string("PIVOT"))}); EXPECT_EQ(res.size(), 0U); res = factoryOTHER->createFromCRSCodesWithIntermediates( "NS_TARGET", "TARGET", "NS_SOURCE", "SOURCE", false, false, false, false, {}); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE(res.empty() || nn_dynamic_pointer_cast<ConcatenatedOperation>(res[0])); } { auto factory = AuthorityFactory::create( DatabaseContext::create(m_ctxt), std::string()); auto res = factory->createFromCRSCodesWithIntermediates( "NS_SOURCE", "SOURCE", "NS_TARGET", "TARGET", false, false, false, false, {}); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE(res.empty() || nn_dynamic_pointer_cast<ConcatenatedOperation>(res[0])); auto srcCRS = AuthorityFactory::create( DatabaseContext::create(m_ctxt), "NS_SOURCE") ->createCoordinateReferenceSystem("SOURCE"); auto targetCRS = AuthorityFactory::create( DatabaseContext::create(m_ctxt), "NS_TARGET") ->createCoordinateReferenceSystem("TARGET"); { auto ctxt = CoordinateOperationContext::create(factory, nullptr, 0); res = CoordinateOperationFactory::create()->createOperations( srcCRS, targetCRS, ctxt); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE( res.empty() || nn_dynamic_pointer_cast<ConcatenatedOperation>(res[0])); } { auto ctxt = CoordinateOperationContext::create(factory, nullptr, 0); ctxt->setIntermediateCRS({std::make_pair( std::string("NS_PIVOT"), std::string("PIVOT"))}); res = CoordinateOperationFactory::create()->createOperations( srcCRS, targetCRS, ctxt); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE( res.empty() || nn_dynamic_pointer_cast<ConcatenatedOperation>(res[0])); } { auto ctxt = CoordinateOperationContext::create(factory, nullptr, 0); ctxt->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::NEVER); res = CoordinateOperationFactory::create()->createOperations( srcCRS, targetCRS, ctxt); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE(res.empty() || nn_dynamic_pointer_cast<Transformation>(res[0])); } { auto ctxt = CoordinateOperationContext::create(factory, nullptr, 0); ctxt->setIntermediateCRS({std::make_pair( std::string("NS_PIVOT"), std::string("NOT_EXISTING"))}); res = CoordinateOperationFactory::create()->createOperations( srcCRS, targetCRS, ctxt); EXPECT_EQ(res.size(), 1U); EXPECT_TRUE(res.empty() || nn_dynamic_pointer_cast<Transformation>(res[0])); } } } bool get_table(const char *sql, sqlite3 *db = nullptr) { sqlite3_free_table(m_papszResult); m_papszResult = nullptr; m_nRows = 0; m_nCols = 0; return sqlite3_get_table(db ? db : m_ctxt, sql, &m_papszResult, &m_nRows, &m_nCols, nullptr) == SQLITE_OK; } bool execute(const std::string &sql) { return sqlite3_exec(m_ctxt, sql.c_str(), nullptr, nullptr, nullptr) == SQLITE_OK; } std::string last_error() { const char *msg = sqlite3_errmsg(m_ctxt); return msg ? msg : std::string(); } int m_nRows = 0; int m_nCols = 0; char **m_papszResult = nullptr; sqlite3 *m_ctxt = nullptr; }; // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_test_with_fake_EPSG_database) { createStructure(); populateWithFakeEPSG(); auto factory = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "EPSG"); EXPECT_TRUE(nn_dynamic_pointer_cast<UnitOfMeasure>( factory->createObject("9001")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<Extent>( factory->createObject("1262")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<PrimeMeridian>( factory->createObject("8901")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<Ellipsoid>( factory->createObject("7030")) != nullptr); auto grf = nn_dynamic_pointer_cast<GeodeticReferenceFrame>( factory->createObject("6326")); ASSERT_TRUE(grf != nullptr); EXPECT_EQ(*grf->anchorDefinition(), "my anchor"); auto vrf = nn_dynamic_pointer_cast<VerticalReferenceFrame>( factory->createObject("1027")); ASSERT_TRUE(vrf != nullptr); EXPECT_EQ(*vrf->anchorDefinition(), "my anchor"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>( factory->createObject("4326")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<VerticalCRS>( factory->createObject("3855")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<Conversion>( factory->createObject("16031")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<ProjectedCRS>( factory->createObject("32631")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<CompoundCRS>( factory->createObject("MY_COMPOUND")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<Transformation>( factory->createObject("DUMMY_HELMERT")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<Transformation>(factory->createObject( "DUMMY_GRID_TRANSFORMATION")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<Transformation>(factory->createObject( "DUMMY_OTHER_TRANSFORMATION")) != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<ConcatenatedOperation>( factory->createObject("DUMMY_CONCATENATED")) != nullptr); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_createFromCoordinateReferenceSystemCodes) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); EXPECT_TRUE( factory->createFromCoordinateReferenceSystemCodes("-1", "-1").empty()); { auto res = factory->createFromCoordinateReferenceSystemCodes("4326", "32631"); ASSERT_EQ(res.size(), 1U); EXPECT_TRUE(res[0]->sourceCRS() != nullptr); EXPECT_TRUE(res[0]->targetCRS() != nullptr); EXPECT_TRUE( res[0]->isEquivalentTo(factory->createConversion("16031").get())); } { auto res = factory->createFromCoordinateReferenceSystemCodes("4209", "4326"); EXPECT_TRUE(!res.empty()); for (const auto &conv : res) { EXPECT_TRUE(conv->sourceCRS()->getEPSGCode() == 4209); EXPECT_TRUE(conv->targetCRS()->getEPSGCode() == 4326); EXPECT_FALSE(conv->isDeprecated()); } } { auto list = factory->createFromCoordinateReferenceSystemCodes("4179", "4258"); ASSERT_EQ(list.size(), 3U); // Romania has a larger area than Poland (given our approx formula) EXPECT_EQ(list[0]->getEPSGCode(), 15994); // Romania - 3m EXPECT_EQ(list[1]->getEPSGCode(), 15993); // Romania - 10m EXPECT_EQ(list[2]->getEPSGCode(), 1644); // Poland - 1m } { // Test removal of superseded transform auto list = factory->createFromCoordinateReferenceSystemCodes( "EPSG", "4179", "EPSG", "4258", false, false, false, true); ASSERT_EQ(list.size(), 2U); // Romania has a larger area than Poland (given our approx formula) EXPECT_EQ(list[0]->getEPSGCode(), 15994); // Romania - 3m EXPECT_EQ(list[1]->getEPSGCode(), 1644); // Poland - 1m } } // --------------------------------------------------------------------------- TEST( factory, AuthorityFactory_createFromCoordinateReferenceSystemCodes_anonymous_authority) { auto factory = AuthorityFactory::create(DatabaseContext::create(), std::string()); { auto res = factory->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "EPSG", "32631", false, false, false, false); ASSERT_EQ(res.size(), 1U); } { auto res = factory->createFromCoordinateReferenceSystemCodes( "EPSG", "4209", "EPSG", "4326", false, false, false, false); EXPECT_TRUE(!res.empty()); for (const auto &conv : res) { EXPECT_TRUE(conv->sourceCRS()->getEPSGCode() == 4209); EXPECT_TRUE(conv->targetCRS()->getEPSGCode() == 4326); EXPECT_FALSE(conv->isDeprecated()); } } } TEST(factory, AuthorityFactory_getAvailableGeoidmodels) { const std::string OSGM15{"OSGM15"}; const std::string GEOID12B{"GEOID12B"}; const std::string GEOID18{"GEOID18"}; auto checkNavd88 = [&](const std::list<std::string> &res) { EXPECT_TRUE(res.end() != std::find(res.begin(), res.end(), GEOID12B)); EXPECT_TRUE(res.end() != std::find(res.begin(), res.end(), GEOID18)); EXPECT_FALSE(res.end() != std::find(res.begin(), res.end(), OSGM15)); }; auto checkOdn = [&](const std::list<std::string> &res) { EXPECT_FALSE(res.end() != std::find(res.begin(), res.end(), GEOID12B)); EXPECT_FALSE(res.end() != std::find(res.begin(), res.end(), GEOID18)); EXPECT_TRUE(res.end() != std::find(res.begin(), res.end(), OSGM15)); }; auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto res = factory->getGeoidModels("4326"); ASSERT_TRUE(res.empty()); } { auto res = factory->getGeoidModels("5703"); // "NAVD88 height" checkNavd88(res); } { auto res = factory->getGeoidModels("6360"); // "NAVD88 height (ftUS)" checkNavd88(res); } { auto res = factory->getGeoidModels("8228"); // "NAVD88 height (ft)" checkNavd88(res); } { auto res = factory->getGeoidModels("6357"); // "NAVD88 depth" checkNavd88(res); } { auto res = factory->getGeoidModels("6358"); // "NAVD88 depth (ftUS)" checkNavd88(res); } { auto res = factory->getGeoidModels("5701"); // "ODN height" checkOdn(res); } { auto res = factory->getGeoidModels("5732"); // "Belfast height" checkOdn(res); } } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_test_inversion_first_and_last_steps_of_concat_op) { createStructure(); populateWithFakeEPSG(); // Completely dummy, to test proper inversion of first and last // steps in ConcatenatedOperation, when it is needed ASSERT_TRUE(execute("INSERT INTO geodetic_datum " "VALUES('EPSG','OTHER_DATUM','Other datum',''," "'EPSG','7030','EPSG','8901',NULL,NULL,NULL," "'my anchor',NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO geodetic_crs VALUES('EPSG','OTHER_GEOG_CRS'," "'OTHER_GEOG_CRS',NULL,'geographic 2D','EPSG','6422'," "'EPSG','OTHER_DATUM',NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO other_transformation " "VALUES('EPSG','4326_TO_OTHER_GEOG_CRS','name',NULL," "'EPSG','9601','Longitude rotation'," "'EPSG','4326','EPSG','OTHER_GEOG_CRS',0.0,'EPSG'" ",'8602','Longitude " "offset',-17.4,'EPSG','9110',NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO other_transformation " "VALUES('EPSG','OTHER_GEOG_CRS_TO_4326','name',NULL," "'EPSG','9601','Longitude rotation'," "'EPSG','OTHER_GEOG_CRS','EPSG','4326',0.0,'EPSG'" ",'8602','Longitude " "offset',17.4,'EPSG','9110',NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO concatenated_operation " "VALUES('EPSG','DUMMY_CONCATENATED_2','name',NULL," "'EPSG','4326','EPSG'" ",'4326',NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','DUMMY_CONCATENATED_2',1," "'EPSG','OTHER_GEOG_CRS_TO_4326');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','DUMMY_CONCATENATED_2',2," "'EPSG','4326_TO_OTHER_GEOG_CRS');")) << last_error(); auto factoryEPSG = AuthorityFactory::create(DatabaseContext::create(m_ctxt), std::string("EPSG")); EXPECT_TRUE(nn_dynamic_pointer_cast<ConcatenatedOperation>( factoryEPSG->createObject("DUMMY_CONCATENATED_2")) != nullptr); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_test_with_fake_EPSG_and_OTHER_database) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE( execute("INSERT INTO geodetic_crs VALUES('OTHER','OTHER_4326','WGS " "84',NULL,'geographic " "2D','EPSG','6422','EPSG','6326',NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER'," "'geodetic_crs_OTHER_4326_usage','geodetic_crs'," "'OTHER','OTHER_4326','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO projected_crs " "VALUES('OTHER','OTHER_32631','WGS 84 / UTM zone " "31N',NULL,'EPSG','4400','OTHER','OTHER_4326'," "'EPSG','16031',NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER'," "'projected_crs_OTHER_32631_usage','projected_crs'," "'OTHER','OTHER_32631','EPSG','2060','EPSG','1024');")) << last_error(); auto factoryGeneral = AuthorityFactory::create( DatabaseContext::create(m_ctxt), std::string()); { auto res = factoryGeneral->createFromCoordinateReferenceSystemCodes( "OTHER", "OTHER_4326", "OTHER", "OTHER_32631", false, false, false, false); ASSERT_EQ(res.size(), 1U); } auto factoryEPSG = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "EPSG"); { auto res = factoryEPSG->createFromCoordinateReferenceSystemCodes( "OTHER", "OTHER_4326", "OTHER", "OTHER_32631", false, false, false, false); ASSERT_EQ(res.size(), 1U); } auto factoryOTHER = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "OTHER"); { auto res = factoryOTHER->createFromCoordinateReferenceSystemCodes( "OTHER_4326", "OTHER_32631"); ASSERT_EQ(res.size(), 0U); // the conversion is in the EPSG space } ASSERT_TRUE(execute( "INSERT INTO grid_transformation " "VALUES('OTHER','OTHER_GRID_TRANSFORMATION','name',NULL," "'EPSG','9615'" ",'NTv2','EPSG','4326','OTHER','OTHER_4326',1.0,'EPSG','" "8656','Latitude and longitude difference " "file','nzgd2kgrid0005.gsb',NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO usage VALUES('OTHER'," "'grid_transformation_OTHER_GRID_TRANSFORMATION_usage'," "'grid_transformation'," "'OTHER','OTHER_GRID_TRANSFORMATION','EPSG','1262','EPSG','1024');")) << last_error(); { auto res = factoryGeneral->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "OTHER", "OTHER_4326", false, false, false, false); ASSERT_EQ(res.size(), 1U); } { auto res = factoryEPSG->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "OTHER", "OTHER_4326", false, false, false, false); ASSERT_EQ(res.size(), 0U); } { auto res = factoryOTHER->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "OTHER", "OTHER_4326", false, false, false, false); ASSERT_EQ(res.size(), 1U); } } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_test_sorting_of_coordinate_operations) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE(execute( "INSERT INTO grid_transformation " "VALUES('OTHER','TRANSFORMATION_10M','TRANSFORMATION_10M',NULL," "'EPSG','9615'" ",'NTv2','EPSG','4326','EPSG','4326',10.0,'EPSG','" "8656','Latitude and longitude difference " "file','nzgd2kgrid0005.gsb',NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('OTHER'," "'grid_transformation_TTRANSFORMATION_10M_usage'," "'grid_transformation'," "'OTHER','TRANSFORMATION_10M','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE( execute("INSERT INTO grid_transformation " "VALUES('OTHER','TRANSFORMATION_1M_SMALL_EXTENT','" "TRANSFORMATION_1M_SMALL_EXTENT',NULL,'EPSG','9615'" ",'NTv2','EPSG','4326','EPSG','4326',1.0,'EPSG','" "8656','Latitude and longitude difference " "file','nzgd2kgrid0005.gsb',NULL,NULL,NULL,NULL,NULL,NULL," "NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('OTHER'," "'grid_transformation_TRANSFORMATION_1M_SMALL_EXTENT_usage'," "'grid_transformation'," "'OTHER','TRANSFORMATION_1M_SMALL_EXTENT'," "'EPSG','2060','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO grid_transformation " "VALUES('OTHER','TRANSFORMATION_1M','TRANSFORMATION_1M',NULL," "'EPSG','9615'" ",'NTv2','EPSG','4326','EPSG','4326',1.0,'EPSG','" "8656','Latitude and longitude difference " "file','nzgd2kgrid0005.gsb',NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('OTHER'," "'grid_transformation_TRANSFORMATION_1M_usage'," "'grid_transformation'," "'OTHER','TRANSFORMATION_1M','EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE( execute("INSERT INTO grid_transformation " "VALUES('OTHER','TRANSFORMATION_0.5M_DEPRECATED','" "TRANSFORMATION_0.5M_DEPRECATED',NULL,'EPSG','9615'" ",'NTv2','EPSG','4326','EPSG','4326',1.0,'EPSG','" "8656','Latitude and longitude difference " "file','nzgd2kgrid0005.gsb',NULL,NULL,NULL,NULL,NULL,NULL," "NULL,1);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('OTHER'," "'grid_transformation_TRANSFORMATION_0.5M_DEPRECATED_usage'," "'grid_transformation'," "'OTHER','TRANSFORMATION_0.5M_DEPRECATED'," "'EPSG','1262','EPSG','1024');")) << last_error(); auto factoryOTHER = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "OTHER"); auto res = factoryOTHER->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "EPSG", "4326", false, false, false, false); ASSERT_EQ(res.size(), 3U); EXPECT_EQ(*(res[0]->name()->description()), "TRANSFORMATION_1M"); EXPECT_EQ(*(res[1]->name()->description()), "TRANSFORMATION_10M"); EXPECT_EQ(*(res[2]->name()->description()), "TRANSFORMATION_1M_SMALL_EXTENT"); } // --------------------------------------------------------------------------- TEST_F( FactoryWithTmpDatabase, AuthorityFactory_createFromCRSCodesWithIntermediates_source_equals_target) { createStructure(); populateWithFakeEPSG(); auto factory = AuthorityFactory::create(DatabaseContext::create(m_ctxt), std::string()); auto res = factory->createFromCRSCodesWithIntermediates( "EPSG", "4326", "EPSG", "4326", false, false, false, false, {}); EXPECT_EQ(res.size(), 0U); } // --------------------------------------------------------------------------- TEST_F( FactoryWithTmpDatabase, AuthorityFactory_createFromCRSCodesWithIntermediates_case_source_pivot_target_pivot) { createStructure(); populateWithFakeEPSG(); createSourceTargetPivotCRS(); createTransformationForPivotTesting("SOURCE", "PIVOT"); createTransformationForPivotTesting("TARGET", "PIVOT"); checkSourceToOther(); } // --------------------------------------------------------------------------- TEST_F( FactoryWithTmpDatabase, AuthorityFactory_createFromCRSCodesWithIntermediates_case_source_pivot_pivot_target) { createStructure(); populateWithFakeEPSG(); createSourceTargetPivotCRS(); createTransformationForPivotTesting("SOURCE", "PIVOT"); createTransformationForPivotTesting("PIVOT", "TARGET"); checkSourceToOther(); } // --------------------------------------------------------------------------- TEST_F( FactoryWithTmpDatabase, AuthorityFactory_createFromCRSCodesWithIntermediates_case_pivot_source_pivot_target) { createStructure(); populateWithFakeEPSG(); createSourceTargetPivotCRS(); createTransformationForPivotTesting("PIVOT", "SOURCE"); createTransformationForPivotTesting("PIVOT", "TARGET"); checkSourceToOther(); } // --------------------------------------------------------------------------- TEST_F( FactoryWithTmpDatabase, AuthorityFactory_createFromCRSCodesWithIntermediates_case_pivot_source_target_pivot) { createStructure(); populateWithFakeEPSG(); createSourceTargetPivotCRS(); createTransformationForPivotTesting("PIVOT", "SOURCE"); createTransformationForPivotTesting("TARGET", "PIVOT"); checkSourceToOther(); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_proj_based_transformation) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE(execute( "INSERT INTO other_transformation " "VALUES('OTHER','FOO','My PROJ string based op',NULL,'PROJ'," "'PROJString','+proj=pipeline +ellps=WGS84 +step +proj=longlat'," "'EPSG','4326','EPSG','4326',0.0,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER'," "'other_transformation_FOO_usage'," "'other_transformation'," "'OTHER','FOO'," "'EPSG','1262','EPSG','1024');")) << last_error(); auto factoryOTHER = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "OTHER"); auto res = factoryOTHER->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "EPSG", "4326", false, false, false, false); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res[0]->nameStr(), "My PROJ string based op"); EXPECT_EQ(res[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +ellps=WGS84 +step +proj=longlat"); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_wkt_based_transformation) { createStructure(); populateWithFakeEPSG(); auto wkt = "COORDINATEOPERATION[\"My WKT string based op\",\n" " SOURCECRS[\n" " GEODCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north],\n" " AXIS[\"geodetic longitude (Lon)\",east],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " TARGETCRS[\n" " GEODCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north],\n" " AXIS[\"geodetic longitude (Lon)\",east],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " METHOD[\"Geocentric translations (geog2D domain)\"],\n" " PARAMETER[\"X-axis translation\",1,UNIT[\"metre\",1]],\n" " PARAMETER[\"Y-axis translation\",2,UNIT[\"metre\",1]],\n" " PARAMETER[\"Z-axis translation\",3,UNIT[\"metre\",1]]]"; ASSERT_TRUE( execute("INSERT INTO other_transformation " "VALUES('OTHER','FOO','My WKT string based op',NULL," "'PROJ','WKT','" + std::string(wkt) + "'," "'EPSG','4326','EPSG','4326',0.0,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER'," "'other_transformation_FOO_usage'," "'other_transformation'," "'OTHER','FOO'," "'EPSG','1262','EPSG','1024');")) << last_error(); auto factoryOTHER = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "OTHER"); auto res = factoryOTHER->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "EPSG", "4326", false, false, false, false); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res[0]->nameStr(), "My WKT string based op"); EXPECT_EQ(res[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=WGS84 +step +proj=helmert +x=1 +y=2 " "+z=3 +step +inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg +step " "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_wkt_based_transformation_not_wkt) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE( execute("INSERT INTO other_transformation " "VALUES('OTHER','FOO','My WKT string based op',NULL," "'PROJ','WKT','" + std::string("invalid_wkt") + "'," "'EPSG','4326','EPSG','4326',0.0,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER'," "'other_transformation_FOO_usage'," "'other_transformation'," "'OTHER','FOO'," "'EPSG','1262','EPSG','1024');")) << last_error(); auto factoryOTHER = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "OTHER"); EXPECT_THROW( factoryOTHER->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "EPSG", "4326", false, false, false, false), FactoryException); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, AuthorityFactory_wkt_based_transformation_not_co_wkt) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE( execute("INSERT INTO other_transformation " "VALUES('OTHER','FOO','My WKT string based op',NULL," "'PROJ','WKT','" + std::string("LOCAL_CS[\"foo\"]") + "'," "'EPSG','4326','EPSG','4326',0.0,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER'," "'other_transformation_FOO_usage'," "'other_transformation'," "'OTHER','FOO'," "'EPSG','1262','EPSG','1024');")) << last_error(); auto factoryOTHER = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "OTHER"); EXPECT_THROW( factoryOTHER->createFromCoordinateReferenceSystemCodes( "EPSG", "4326", "EPSG", "4326", false, false, false, false), FactoryException); } // --------------------------------------------------------------------------- TEST(factory, AuthorityFactory_EPSG_4326_approximate_equivalent_to_builtin) { auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>( factory->createCoordinateReferenceSystem("4326")); EXPECT_TRUE(crs->isEquivalentTo(GeographicCRS::EPSG_4326.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, getAuthorities) { createStructure(); populateWithFakeEPSG(); auto res = DatabaseContext::create(m_ctxt)->getAuthorities(); EXPECT_EQ(res.size(), 2U); EXPECT_TRUE(res.find("EPSG") != res.end()); EXPECT_TRUE(res.find("PROJ") != res.end()); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, lookForGridInfo) { createStructure(); ASSERT_TRUE(execute("INSERT INTO grid_alternatives(original_grid_name," "proj_grid_name, " "old_proj_grid_name, " "proj_grid_format, " "proj_method, " "inverse_direction, " "package_name, " "url, direct_download, open_license, directory) " "VALUES (" "'NOT-YET-IN-GRID-TRANSFORMATION-PROJ_fake_grid', " "'PROJ_fake_grid', " "'old_PROJ_fake_grid', " "'NTv2', " "'hgridshift', " "0, " "NULL, " "'url', 1, 1, NULL);")) << last_error(); std::string fullFilename; std::string packageName; std::string url; bool directDownload = false; bool openLicense = false; bool gridAvailable = false; EXPECT_TRUE(DatabaseContext::create(m_ctxt)->lookForGridInfo( "PROJ_fake_grid", false, fullFilename, packageName, url, directDownload, openLicense, gridAvailable)); EXPECT_TRUE(fullFilename.empty()); EXPECT_TRUE(packageName.empty()); EXPECT_EQ(url, "url"); EXPECT_EQ(directDownload, true); EXPECT_EQ(openLicense, true); EXPECT_EQ(gridAvailable, false); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, lookForGridInfo_from_old_name_with_new_grid_available) { createStructure(); ASSERT_TRUE(execute("INSERT INTO grid_alternatives(original_grid_name," "proj_grid_name, " "old_proj_grid_name, " "proj_grid_format, " "proj_method, " "inverse_direction, " "package_name, " "url, direct_download, open_license, directory) " "VALUES (" "'NOT-YET-IN-GRID-TRANSFORMATION-original_grid_name', " "'tests/egm96_15_uncompressed_truncated.tif', " "'old_name.gtx', " "'NTv2', " "'hgridshift', " "0, " "NULL, " "'url', 1, 1, NULL);")) << last_error(); std::string fullFilename; std::string packageName; std::string url; bool directDownload = false; bool openLicense = false; bool gridAvailable = false; EXPECT_TRUE(DatabaseContext::create(m_ctxt)->lookForGridInfo( "old_name.gtx", false, fullFilename, packageName, url, directDownload, openLicense, gridAvailable)); EXPECT_TRUE( fullFilename.find("tests/egm96_15_uncompressed_truncated.tif") != std::string::npos) << fullFilename; EXPECT_EQ(gridAvailable, true); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, custom_geodetic_crs) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE(execute("INSERT INTO geodetic_crs VALUES('TEST_NS','TEST','my " "name TEST',NULL,'geographic 2D'," "NULL,NULL,NULL,NULL,'+proj=longlat +a=2 " "+rf=300',0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO geodetic_crs VALUES" "('TEST_NS','TEST_BOUND'," "'my name TEST',NULL,'geographic 2D'," "NULL,NULL,NULL,NULL,'+proj=longlat +a=2 " "+rf=300 +towgs84=1,2,3',0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO geodetic_crs VALUES('TEST_NS','TEST_GC'," "'my name',NULL,'geocentric',NULL,NULL," "NULL,NULL,'+proj=geocent +a=2 +rf=300',0);")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO geodetic_crs " "VALUES('TEST_NS','TEST_REF_ANOTHER','my name TEST_REF_ANOTHER'," "NULL," "'geographic 2D',NULL,NULL,NULL,NULL,'TEST_NS:TEST',0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO geodetic_crs " "VALUES('TEST_NS','TEST_WRONG','my name',NULL," "'geographic 2D',NULL,NULL,NULL,NULL," "'+proj=merc',0);")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO geodetic_crs " "VALUES('TEST_NS','TEST_RECURSIVE','my name',NULL,'geographic 2D'," "NULL,NULL,NULL,NULL,'TEST_NS:TEST_RECURSIVE',0);")) << last_error(); auto factory = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "TEST_NS"); { auto crs = factory->createGeodeticCRS("TEST"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs) != nullptr); EXPECT_EQ(*(crs->name()->description()), "my name TEST"); EXPECT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis(), Length(2)); EXPECT_EQ(*(crs->ellipsoid()->inverseFlattening()), Scale(300)); EXPECT_TRUE(crs->canonicalBoundCRS() == nullptr); } { auto crs = factory->createGeodeticCRS("TEST_BOUND"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs) != nullptr); EXPECT_EQ(*(crs->name()->description()), "my name TEST"); EXPECT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis(), Length(2)); EXPECT_EQ(*(crs->ellipsoid()->inverseFlattening()), Scale(300)); EXPECT_TRUE(crs->canonicalBoundCRS() != nullptr); } { auto crs = factory->createGeodeticCRS("TEST_GC"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs) == nullptr); EXPECT_EQ(*(crs->name()->description()), "my name"); EXPECT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis(), Length(2)); EXPECT_EQ(*(crs->ellipsoid()->inverseFlattening()), Scale(300)); } { auto crs = factory->createGeodeticCRS("TEST_REF_ANOTHER"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs) != nullptr); EXPECT_EQ(*(crs->name()->description()), "my name TEST_REF_ANOTHER"); EXPECT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis(), Length(2)); EXPECT_EQ(*(crs->ellipsoid()->inverseFlattening()), Scale(300)); } EXPECT_THROW(factory->createGeodeticCRS("TEST_WRONG"), FactoryException); EXPECT_THROW(factory->createGeodeticCRS("TEST_RECURSIVE"), FactoryException); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, custom_projected_crs) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE(execute("INSERT INTO projected_crs " "VALUES('TEST_NS','TEST','my name',NULL,NULL," "NULL,NULL,NULL,NULL,NULL," "'+proj=mbt_s +unused_flag',0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO projected_crs " "VALUES('TEST_NS','TEST_BOUND','my name',NULL," "NULL,NULL,NULL,NULL,NULL,NULL," "'+proj=mbt_s +unused_flag +towgs84=1,2,3',0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO projected_crs " "VALUES('TEST_NS','TEST_WRONG','my name',NULL," "NULL,NULL,NULL,NULL,NULL,NULL," "'+proj=longlat',0);")) << last_error(); // Unknown ellipsoid ASSERT_TRUE(execute("INSERT INTO projected_crs " "VALUES('TEST_NS','TEST_MERC','merc',NULL,NULL," "NULL,NULL,NULL,NULL,NULL," "'+proj=merc +x_0=0 +R=1',0);")) << last_error(); // Well-known ellipsoid ASSERT_TRUE(execute("INSERT INTO projected_crs " "VALUES('TEST_NS','TEST_MERC2','merc2',NULL,NULL," "NULL,NULL,NULL,NULL,NULL," "'+proj=merc +x_0=0 +ellps=GRS80',0);")) << last_error(); // WKT1_GDAL ASSERT_TRUE( execute("INSERT INTO projected_crs " "VALUES('TEST_NS','TEST_WKT1_GDAL','WKT1_GDAL',NULL,NULL," "NULL,NULL,NULL,NULL,NULL," "'" "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"Unknown_based_on_WGS84_ellipsoid\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",0],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]" "',0);")) << last_error(); auto factory = AuthorityFactory::create(DatabaseContext::create(m_ctxt), "TEST_NS"); { auto crs = factory->createProjectedCRS("TEST"); EXPECT_EQ(*(crs->name()->description()), "my name"); EXPECT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->derivingConversion()->targetCRS().get(), crs.get()); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=mbt_s +datum=WGS84 +units=m +no_defs +type=crs"); EXPECT_TRUE(crs->canonicalBoundCRS() == nullptr); } { auto crs = factory->createProjectedCRS("TEST_BOUND"); EXPECT_EQ(*(crs->name()->description()), "my name"); EXPECT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->derivingConversion()->targetCRS().get(), crs.get()); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=mbt_s +datum=WGS84 +units=m +no_defs +type=crs"); EXPECT_TRUE(crs->canonicalBoundCRS() != nullptr); } EXPECT_THROW(factory->createProjectedCRS("TEST_WRONG"), FactoryException); { auto obj = PROJStringParser().createFromPROJString( "+proj=merc +a=1 +b=1 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); EXPECT_EQ(res.size(), 1U); if (!res.empty()) { EXPECT_EQ(res.front().first->nameStr(), "merc"); } } { auto obj = PROJStringParser().createFromPROJString( "+proj=merc +ellps=GRS80 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); EXPECT_EQ(res.size(), 1U); if (!res.empty()) { EXPECT_EQ(res.front().first->nameStr(), "merc2"); } } { auto obj = PROJStringParser().createFromPROJString( "+proj=merc +a=6378137 +rf=298.257222101 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); EXPECT_EQ(res.size(), 1U); if (!res.empty()) { EXPECT_EQ(res.front().first->nameStr(), "merc2"); } } { auto obj = PROJStringParser().createFromPROJString( "+proj=merc +ellps=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto res = crs->identify(factory); EXPECT_EQ(res.size(), 1U); if (!res.empty()) { EXPECT_EQ(res.front().first->nameStr(), "WKT1_GDAL"); } } { const auto list = factory->getCRSInfoList(); bool found = false; for (const auto &info : list) { if (info.authName == "TEST_NS" && info.code == "TEST_BOUND") { found = true; break; } } EXPECT_TRUE(found); } } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, CoordinateMetadata) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE(execute("INSERT INTO coordinate_metadata " "VALUES('TEST_NS','TEST','my desc','EPSG',4326," "NULL,2020.1,0);")) << last_error(); const std::string wkt = "GEOGCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " MEMBER[\"World Geodetic System 1984 (G2139)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " USAGE[\n" " SCOPE[\"Horizontal component of 3D system.\"],\n" " AREA[\"World.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",4326]]"; ASSERT_TRUE(execute("INSERT INTO coordinate_metadata " "VALUES('TEST_NS','TEST2','my desc',NULL,NULL," "'" + wkt + "',2021.1,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO coordinate_metadata " "VALUES('TEST_NS','TEST_NO_EPOCH','my desc'," "'EPSG',4326,NULL,NULL,0);")) << last_error(); auto dbContext = DatabaseContext::create(m_ctxt); auto factoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); auto crs_4326 = factoryEPSG->createCoordinateReferenceSystem("4326"); auto factory = AuthorityFactory::create(dbContext, "TEST_NS"); { auto cm = factory->createCoordinateMetadata("TEST"); EXPECT_TRUE(cm->crs()->isEquivalentTo(crs_4326.get())); EXPECT_TRUE(cm->coordinateEpoch().has_value()); EXPECT_NEAR(cm->coordinateEpochAsDecimalYear(), 2020.1, 1e-10); } { auto cm = factory->createCoordinateMetadata("TEST2"); EXPECT_TRUE(cm->crs()->isEquivalentTo( crs_4326.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE(cm->coordinateEpoch().has_value()); EXPECT_NEAR(cm->coordinateEpochAsDecimalYear(), 2021.1, 1e-10); } { auto cm = factory->createCoordinateMetadata("TEST_NO_EPOCH"); EXPECT_TRUE(cm->crs()->isEquivalentTo(crs_4326.get())); EXPECT_FALSE(cm->coordinateEpoch().has_value()); } { auto obj = createFromUserInput( "urn:ogc:def:coordinateMetadata:TEST_NS::TEST", dbContext, true); auto cm = dynamic_cast<CoordinateMetadata *>(obj.get()); ASSERT_TRUE(cm != nullptr); EXPECT_TRUE(cm->crs()->isEquivalentTo(crs_4326.get())); EXPECT_TRUE(cm->coordinateEpoch().has_value()); EXPECT_NEAR(cm->coordinateEpochAsDecimalYear(), 2020.1, 1e-10); } } // --------------------------------------------------------------------------- TEST(factory, attachExtraDatabases_none) { auto ctxt = DatabaseContext::create(std::string(), {}); auto factory = AuthorityFactory::create(ctxt, "EPSG"); auto crs = factory->createGeodeticCRS("4979"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); EXPECT_TRUE(gcrs != nullptr); } // --------------------------------------------------------------------------- TEST(factory, attachExtraDatabases_auxiliary) { const std::string auxDbName( "file:attachExtraDatabases_auxiliary.db?mode=memory&cache=shared"); sqlite3 *dbAux = nullptr; sqlite3_open_v2( auxDbName.c_str(), &dbAux, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, nullptr); ASSERT_TRUE(dbAux != nullptr); ASSERT_TRUE(sqlite3_exec(dbAux, "BEGIN", nullptr, nullptr, nullptr) == SQLITE_OK); std::vector<std::string> tableStructureBefore; { auto ctxt = DatabaseContext::create(); tableStructureBefore = ctxt->getDatabaseStructure(); for (const auto &sql : tableStructureBefore) { if (sql.find("CREATE TRIGGER") == std::string::npos) { ASSERT_TRUE(sqlite3_exec(dbAux, sql.c_str(), nullptr, nullptr, nullptr) == SQLITE_OK); } } } ASSERT_TRUE(sqlite3_exec( dbAux, "INSERT INTO geodetic_crs VALUES('OTHER','OTHER_4326','WGS " "84',NULL,'geographic 2D','EPSG','6422','EPSG','6326'," "NULL,0);", nullptr, nullptr, nullptr) == SQLITE_OK); ASSERT_TRUE(sqlite3_exec(dbAux, "COMMIT", nullptr, nullptr, nullptr) == SQLITE_OK); { auto ctxt = DatabaseContext::create(std::string(), {auxDbName}); // Look for object located in main DB { auto factory = AuthorityFactory::create(ctxt, "EPSG"); auto crs = factory->createGeodeticCRS("4326"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); EXPECT_TRUE(gcrs != nullptr); } // Look for object located in auxiliary DB { auto factory = AuthorityFactory::create(ctxt, "OTHER"); auto crs = factory->createGeodeticCRS("OTHER_4326"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); EXPECT_TRUE(gcrs != nullptr); } const auto dbStructure = ctxt->getDatabaseStructure(); EXPECT_EQ(dbStructure, tableStructureBefore); } { auto ctxt = DatabaseContext::create(std::string(), {auxDbName, ":memory:"}); // Look for object located in main DB { auto factory = AuthorityFactory::create(ctxt, "EPSG"); auto crs = factory->createGeodeticCRS("4326"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); EXPECT_TRUE(gcrs != nullptr); } // Look for object located in auxiliary DB { auto factory = AuthorityFactory::create(ctxt, "OTHER"); auto crs = factory->createGeodeticCRS("OTHER_4326"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); EXPECT_TRUE(gcrs != nullptr); } } { auto ctxt = DatabaseContext::create(std::string(), {":memory:"}); // Look for object located in main DB { auto factory = AuthorityFactory::create(ctxt, "EPSG"); auto crs = factory->createGeodeticCRS("4326"); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(crs); EXPECT_TRUE(gcrs != nullptr); } // Look for object located in auxiliary DB { auto factory = AuthorityFactory::create(ctxt, "OTHER"); EXPECT_THROW(factory->createGeodeticCRS("OTHER_4326"), FactoryException); } } sqlite3_close(dbAux); } // --------------------------------------------------------------------------- TEST(factory, attachExtraDatabases_auxiliary_error) { EXPECT_THROW(DatabaseContext::create(std::string(), {"i_dont_exist_db"}), FactoryException); } // --------------------------------------------------------------------------- TEST(factory, getOfficialNameFromAlias) { auto ctxt = DatabaseContext::create(std::string(), {}); auto factory = AuthorityFactory::create(ctxt, std::string()); std::string outTableName; std::string outAuthName; std::string outCode; { auto officialName = factory->getOfficialNameFromAlias( "GCS_WGS_1984", std::string(), std::string(), false, outTableName, outAuthName, outCode); EXPECT_EQ(officialName, "WGS 84"); EXPECT_EQ(outTableName, "geodetic_crs"); EXPECT_EQ(outAuthName, "EPSG"); EXPECT_EQ(outCode, "4326"); } { auto officialName = factory->getOfficialNameFromAlias( "GCS_WGS_1984", "geodetic_crs", "ESRI", false, outTableName, outAuthName, outCode); EXPECT_EQ(officialName, "WGS 84"); EXPECT_EQ(outTableName, "geodetic_crs"); EXPECT_EQ(outAuthName, "EPSG"); EXPECT_EQ(outCode, "4326"); } { auto officialName = factory->getOfficialNameFromAlias( "no match", std::string(), std::string(), false, outTableName, outAuthName, outCode); EXPECT_EQ(officialName, ""); } { auto officialName = factory->getOfficialNameFromAlias( "System_Jednotne_Trigonometricke_Site_Katastralni_Ferro", "geodetic_datum", std::string(), true, outTableName, outAuthName, outCode); EXPECT_EQ( officialName, "System of the Unified Trigonometrical Cadastral Network (Ferro)"); } } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, createOperations_exact_transform_not_whole_area) { createStructure(); populateWithFakeEPSG(); ASSERT_TRUE( execute("INSERT INTO other_transformation " "VALUES('OTHER','PARTIAL_AREA_PERFECT_ACCURACY'," "'PARTIAL_AREA_PERFECT_ACCURACY',NULL,'PROJ'," "'PROJString','+proj=helmert +x=1'," "'EPSG','4326','EPSG','4326',0.0,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER', " "'1','other_transformation','OTHER','PARTIAL_AREA_" "PERFECT_ACCURACY','EPSG','1933','EPSG','1024')")) << last_error(); ASSERT_TRUE( execute("INSERT INTO other_transformation " "VALUES('OTHER','WHOLE_AREA_APPROX_ACCURACY'," "'WHOLE_AREA_APPROX_ACCURACY',NULL,'PROJ'," "'PROJString','+proj=helmert +x=2'," "'EPSG','4326','EPSG','4326',1.0,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('OTHER', " "'2','other_transformation','OTHER','WHOLE_AREA_APPROX_" "ACCURACY','EPSG','1262','EPSG','1024')")) << last_error(); auto dbContext = DatabaseContext::create(m_ctxt); auto authFactory = AuthorityFactory::create(dbContext, std::string("OTHER")); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( AuthorityFactory::create(dbContext, "EPSG") ->createCoordinateReferenceSystem("4326"), AuthorityFactory::create(dbContext, "EPSG") ->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->nameStr(), "WHOLE_AREA_APPROX_ACCURACY"); EXPECT_EQ(list[1]->nameStr(), "PARTIAL_AREA_PERFECT_ACCURACY"); } // --------------------------------------------------------------------------- TEST_F(FactoryWithTmpDatabase, check_fixup_direction_concatenated_inverse_map_projection) { // This tests https://github.com/OSGeo/PROJ/issues/2817 createStructure(); populateWithFakeEPSG(); ASSERT_TRUE(execute( "INSERT INTO other_transformation " "VALUES('EPSG','NOOP_TRANSFORMATION_32631','name',NULL," "'PROJ','PROJString','+proj=noop'," "'EPSG','32631','EPSG','32631',0.0," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE( execute("INSERT INTO usage VALUES('EPSG'," "'other_transformation_NOOP_TRANSFORMATION_32631_usage'," "'other_transformation'," "'EPSG','NOOP_TRANSFORMATION_32631'," "'EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute( "INSERT INTO other_transformation " "VALUES('EPSG','NOOP_TRANSFORMATION_4326','name',NULL," "'PROJ','PROJString','+proj=noop'," "'EPSG','4326','EPSG','4326',0.0," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'other_transformation_NOOP_TRANSFORMATION_4326_usage'," "'other_transformation'," "'EPSG','NOOP_TRANSFORMATION_4326'," "'EPSG','1262','EPSG','1024');")) << last_error(); ASSERT_TRUE(execute("INSERT INTO concatenated_operation " "VALUES('EPSG','TEST_CONCATENATED','name',NULL," "'EPSG','4326','EPSG'" ",'4326',NULL,NULL,0);")) << last_error(); ASSERT_TRUE(execute("INSERT INTO usage VALUES('EPSG'," "'concatenated_operation_TEST_CONCATENATED_usage'," "'concatenated_operation'," "'EPSG','TEST_CONCATENATED'," "'EPSG','1262','EPSG','1024');")) << last_error(); // Forward map projection ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','TEST_CONCATENATED',1," "'EPSG','16031');")) << last_error(); // Noop projected ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','TEST_CONCATENATED',2," "'EPSG','NOOP_TRANSFORMATION_32631');")) << last_error(); // Inverse map projection ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','TEST_CONCATENATED',3," "'EPSG','16031');")) << last_error(); // Noop geographic ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','TEST_CONCATENATED',4," "'EPSG','NOOP_TRANSFORMATION_4326');")) << last_error(); // Forward map projection ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','TEST_CONCATENATED',5," "'EPSG','16031');")) << last_error(); // Noop projected ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','TEST_CONCATENATED',6," "'EPSG','NOOP_TRANSFORMATION_32631');")) << last_error(); // Inverse map projection ASSERT_TRUE(execute("INSERT INTO concatenated_operation_step " "VALUES('EPSG','TEST_CONCATENATED',7," "'EPSG','16031');")) << last_error(); auto dbContext = DatabaseContext::create(m_ctxt); auto authFactory = AuthorityFactory::create(dbContext, std::string("EPSG")); const auto op = authFactory->createCoordinateOperation("TEST_CONCATENATED", false); auto wkt = op->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_EQ(wkt, "+proj=noop"); } // --------------------------------------------------------------------------- TEST(factory, createObjectsFromName) { auto ctxt = DatabaseContext::create(); auto factory = AuthorityFactory::create(ctxt, std::string()); auto factoryEPSG = AuthorityFactory::create(ctxt, "EPSG"); EXPECT_EQ(factory->createObjectsFromName("").size(), 0U); // ellipsoid + datum + 3 geodeticCRS EXPECT_EQ(factory->createObjectsFromName("WGS 84", {}, false).size(), 5U); EXPECT_EQ(factory->createObjectsFromName("WGS 84", {}, true, 10).size(), 10U); EXPECT_EQ(factory ->createObjectsFromName( "WGS 84", {AuthorityFactory::ObjectType::CRS}, false) .size(), 3U); EXPECT_EQ( factory ->createObjectsFromName( "WGS 84", {AuthorityFactory::ObjectType::GEOCENTRIC_CRS}, false) .size(), 1U); { auto res = factoryEPSG->createObjectsFromName( "WGS84", {AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS}, true); // EPSG:4326 and the 6 WGS84 realizations // and EPSG:7881 'Tritan St. Helena'' whose alias is // 'WGS 84 Tritan St. Helena' EXPECT_EQ(res.size(), 9U); if (!res.empty()) { EXPECT_EQ(res.front()->getEPSGCode(), 4326); } } // Exact name, but just not the official case ==> should match with exact // match EXPECT_EQ(factory->createObjectsFromName("WGS 84 / utm zone 31n", {}, false) .size(), 1U); // Exact name, but with other CRS that have an aliases to it ==> should // match only the CRS with the given name, not those other CRS. EXPECT_EQ(factory->createObjectsFromName("ETRS89 / UTM zone 32N", {}, false) .size(), 1U); // Prime meridian EXPECT_EQ(factoryEPSG->createObjectsFromName("Paris", {}, false, 2).size(), 1U); // Ellipsoid EXPECT_EQ( factoryEPSG->createObjectsFromName("Clarke 1880 (IGN)", {}, false, 2) .size(), 1U); // Geodetic datum EXPECT_EQ( factoryEPSG->createObjectsFromName("Hungarian Datum 1909", {}, false, 2) .size(), 1U); // Vertical datum EXPECT_EQ(factoryEPSG->createObjectsFromName("EGM2008 geoid", {}, false, 2) .size(), 1U); // Geodetic CRS EXPECT_EQ(factoryEPSG ->createObjectsFromName( "Unknown datum based upon the Airy 1830 ellipsoid", {}, false, 2) .size(), 1U); // Projected CRS EXPECT_EQ(factoryEPSG ->createObjectsFromName( "Anguilla 1957 / British West Indies Grid", {}, false, 2) .size(), 1U); // Vertical CRS EXPECT_EQ(factoryEPSG->createObjectsFromName("EGM2008 height", {}, false, 2) .size(), 1U); // Compound CRS EXPECT_EQ(factoryEPSG ->createObjectsFromName( "KKJ / Finland Uniform Coordinate System + N60 height", {}, false, 2) .size(), 1U); // Conversion EXPECT_EQ( factoryEPSG->createObjectsFromName("Belgian Lambert 2008", {}, false, 2) .size(), 1U); // Helmert transform EXPECT_EQ( factoryEPSG->createObjectsFromName("MGI to ETRS89 (4)", {}, false, 2) .size(), 1U); // Grid transform EXPECT_EQ(factoryEPSG ->createObjectsFromName("Guam 1963 to NAD83(HARN) (1)", {}, false, 2) .size(), 1U); // Other transform EXPECT_EQ(factoryEPSG ->createObjectsFromName( "Monte Mario (Rome) to Monte Mario (1)", {}, false, 2) .size(), 1U); // Concatenated operation EXPECT_EQ( factoryEPSG ->createObjectsFromName("MGI (Ferro) to WGS 84 (2)", {}, false, 2) .size(), 1U); // Deprecated object EXPECT_EQ(factoryEPSG ->createObjectsFromName( "NAD27(CGQ77) / SCoPQ zone 2 (deprecated)", {}, false, 2) .size(), 1U); // Deprecated object (but without explicit deprecated) EXPECT_EQ( factoryEPSG ->createObjectsFromName("NAD27(CGQ77) / SCoPQ zone 2", {}, false, 2) .size(), 1U); // Dynamic Geodetic datum EXPECT_EQ(factoryEPSG ->createObjectsFromName( "International Terrestrial Reference Frame 2008", {AuthorityFactory::ObjectType:: DYNAMIC_GEODETIC_REFERENCE_FRAME}, false, 2) .size(), 1U); // Dynamic Vertical datum EXPECT_EQ( factoryEPSG ->createObjectsFromName("Norway Normal Null 2000", {AuthorityFactory::ObjectType:: DYNAMIC_VERTICAL_REFERENCE_FRAME}, false, 2) .size(), 1U); { auto res = factory->createObjectsFromName( "World Geodetic System 1984 ensemble", {AuthorityFactory::ObjectType::DATUM_ENSEMBLE}, false); EXPECT_EQ(res.size(), 1U); if (!res.empty()) { EXPECT_EQ(res.front()->getEPSGCode(), 6326); EXPECT_TRUE(dynamic_cast<DatumEnsemble *>(res.front().get()) != nullptr); } } { auto res = factory->createObjectsFromName( "World Geodetic System 1984 ensemble", {}, false); EXPECT_EQ(res.size(), 1U); if (!res.empty()) { EXPECT_EQ(res.front()->getEPSGCode(), 6326); EXPECT_TRUE(dynamic_cast<DatumEnsemble *>(res.front().get()) != nullptr); } } const auto types = std::vector<AuthorityFactory::ObjectType>{ AuthorityFactory::ObjectType::PRIME_MERIDIAN, AuthorityFactory::ObjectType::ELLIPSOID, AuthorityFactory::ObjectType::DATUM, AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME, AuthorityFactory::ObjectType::DYNAMIC_GEODETIC_REFERENCE_FRAME, AuthorityFactory::ObjectType::VERTICAL_REFERENCE_FRAME, AuthorityFactory::ObjectType::DYNAMIC_VERTICAL_REFERENCE_FRAME, AuthorityFactory::ObjectType::CRS, AuthorityFactory::ObjectType::GEODETIC_CRS, AuthorityFactory::ObjectType::GEOCENTRIC_CRS, AuthorityFactory::ObjectType::GEOGRAPHIC_CRS, AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS, AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS, AuthorityFactory::ObjectType::PROJECTED_CRS, AuthorityFactory::ObjectType::VERTICAL_CRS, AuthorityFactory::ObjectType::COMPOUND_CRS, AuthorityFactory::ObjectType::COORDINATE_OPERATION, AuthorityFactory::ObjectType::CONVERSION, AuthorityFactory::ObjectType::TRANSFORMATION, AuthorityFactory::ObjectType::CONCATENATED_OPERATION, AuthorityFactory::ObjectType::DATUM_ENSEMBLE, }; for (const auto type : types) { factory->createObjectsFromName("i_dont_exist", {type}, false, 1); } factory->createObjectsFromName("i_dont_exist", types, false, 1); { auto res = factoryEPSG->createObjectsFromName( "ETRS89", {AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS}, false, 1); EXPECT_EQ(res.size(), 1U); if (!res.empty()) { EXPECT_EQ(res.front()->getEPSGCode(), 4258); } } } // --------------------------------------------------------------------------- TEST(factory, getMetadata) { auto ctxt = DatabaseContext::create(); EXPECT_EQ(ctxt->getMetadata("i_do_not_exist"), nullptr); const char *IGNF_VERSION = ctxt->getMetadata("IGNF.VERSION"); ASSERT_TRUE(IGNF_VERSION != nullptr); EXPECT_EQ(std::string(IGNF_VERSION), "3.1.0"); } // --------------------------------------------------------------------------- TEST(factory, listAreaOfUseFromName) { auto ctxt = DatabaseContext::create(); auto factory = AuthorityFactory::create(ctxt, std::string()); auto factoryEPSG = AuthorityFactory::create(ctxt, "EPSG"); { auto res = factory->listAreaOfUseFromName("Denmark - onshore", false); ASSERT_EQ(res.size(), 1U); EXPECT_EQ(res.front().first, "EPSG"); EXPECT_EQ(res.front().second, "3237"); } { auto res = factory->listAreaOfUseFromName("Denmark", true); EXPECT_GT(res.size(), 1U); } { auto res = factory->listAreaOfUseFromName("no where land", false); ASSERT_EQ(res.size(), 0U); } } // --------------------------------------------------------------------------- TEST(factory, getCRSInfoList) { auto ctxt = DatabaseContext::create(); { auto factory = AuthorityFactory::create(ctxt, std::string()); auto list = factory->getCRSInfoList(); EXPECT_GT(list.size(), 1U); bool foundEPSG = false; bool foundIGNF = false; bool found4326 = false; bool foundIAU_2015_19902 = false; for (const auto &info : list) { foundEPSG |= info.authName == "EPSG"; foundIGNF |= info.authName == "IGNF"; if (info.authName == "EPSG" && info.code == "4326") { found4326 = true; } else if (info.authName == "IAU_2015" && info.code == "19902") { foundIAU_2015_19902 = true; EXPECT_EQ(info.type, AuthorityFactory::ObjectType::GEODETIC_CRS); } } EXPECT_TRUE(foundEPSG); EXPECT_TRUE(foundIGNF); EXPECT_TRUE(found4326); EXPECT_TRUE(foundIAU_2015_19902); } { auto factory = AuthorityFactory::create(ctxt, "EPSG"); auto list = factory->getCRSInfoList(); EXPECT_GT(list.size(), 1U); bool found4326 = false; bool found4978 = false; bool found4979 = false; bool found32631 = false; bool found3855 = false; bool found6871 = false; for (const auto &info : list) { EXPECT_EQ(info.authName, "EPSG"); if (info.code == "4326") { EXPECT_EQ(info.name, "WGS 84"); EXPECT_EQ(info.type, AuthorityFactory::ObjectType::GEOGRAPHIC_2D_CRS); EXPECT_EQ(info.deprecated, false); EXPECT_EQ(info.bbox_valid, true); EXPECT_EQ(info.west_lon_degree, -180.0); EXPECT_EQ(info.south_lat_degree, -90.0); EXPECT_EQ(info.east_lon_degree, 180.0); EXPECT_EQ(info.north_lat_degree, 90.0); EXPECT_TRUE(std::string(info.areaName).find("World") == 0) << std::string(info.areaName); EXPECT_TRUE(info.projectionMethodName.empty()); found4326 = true; } else if (info.code == "4296") { // Soudan - deprecated EXPECT_EQ(info.bbox_valid, false); EXPECT_EQ(info.west_lon_degree, 0.0); EXPECT_EQ(info.south_lat_degree, 0.0); EXPECT_EQ(info.east_lon_degree, 0.0); EXPECT_EQ(info.north_lat_degree, 0.0); } else if (info.code == "4978") { EXPECT_EQ(info.name, "WGS 84"); EXPECT_EQ(info.type, AuthorityFactory::ObjectType::GEOCENTRIC_CRS); found4978 = true; } else if (info.code == "4979") { EXPECT_EQ(info.name, "WGS 84"); EXPECT_EQ(info.type, AuthorityFactory::ObjectType::GEOGRAPHIC_3D_CRS); found4979 = true; } else if (info.code == "32631") { EXPECT_EQ(info.name, "WGS 84 / UTM zone 31N"); EXPECT_EQ(info.type, AuthorityFactory::ObjectType::PROJECTED_CRS); EXPECT_EQ(info.deprecated, false); EXPECT_EQ(info.bbox_valid, true); EXPECT_EQ(info.west_lon_degree, 0.0); EXPECT_EQ(info.south_lat_degree, 0.0); EXPECT_EQ(info.east_lon_degree, 6.0); EXPECT_EQ(info.north_lat_degree, 84.0); EXPECT_TRUE(info.areaName.find("Between 0\xC2\xB0" "E and 6\xC2\xB0" "E, northern hemisphere") == 0) << info.areaName; EXPECT_EQ(info.projectionMethodName, "Transverse Mercator"); found32631 = true; } else if (info.code == "3855") { EXPECT_EQ(info.name, "EGM2008 height"); EXPECT_EQ(info.type, AuthorityFactory::ObjectType::VERTICAL_CRS); found3855 = true; } else if (info.code == "6871") { EXPECT_EQ(info.name, "WGS 84 / Pseudo-Mercator + EGM2008 geoid height"); EXPECT_EQ(info.type, AuthorityFactory::ObjectType::COMPOUND_CRS); found6871 = true; } } EXPECT_TRUE(found4326); EXPECT_TRUE(found4978); EXPECT_TRUE(found4979); EXPECT_TRUE(found32631); EXPECT_TRUE(found3855); EXPECT_TRUE(found6871); } } // --------------------------------------------------------------------------- TEST(factory, getUnitList) { auto ctxt = DatabaseContext::create(); { auto factory = AuthorityFactory::create(ctxt, std::string()); auto list = factory->getUnitList(); EXPECT_GT(list.size(), 1U); bool foundEPSG = false; bool foundPROJ = false; bool found1027 = false; bool found1028 = false; bool found1032 = false; bool found1036 = false; bool found9001 = false; bool found9101 = false; for (const auto &info : list) { foundEPSG |= info.authName == "EPSG"; foundPROJ |= info.authName == "PROJ"; if (info.authName == "EPSG" && info.code == "1027") { EXPECT_EQ(info.name, "millimetres per year"); EXPECT_EQ(info.category, "linear_per_time"); found1027 = true; } else if (info.authName == "EPSG" && info.code == "1028") { EXPECT_EQ(info.name, "parts per billion"); EXPECT_EQ(info.category, "scale"); found1028 = true; } else if (info.authName == "EPSG" && info.code == "1032") { EXPECT_EQ(info.name, "milliarc-seconds per year"); EXPECT_EQ(info.category, "angular_per_time"); found1032 = true; } else if (info.authName == "EPSG" && info.code == "1036") { EXPECT_EQ(info.name, "unity per second"); EXPECT_EQ(info.category, "scale_per_time"); found1036 = true; } else if (info.authName == "EPSG" && info.code == "9001") { EXPECT_EQ(info.name, "metre"); EXPECT_EQ(info.category, "linear"); EXPECT_EQ(info.convFactor, 1.0); EXPECT_EQ(info.projShortName, "m"); EXPECT_FALSE(info.deprecated); found9001 = true; } else if (info.authName == "EPSG" && info.code == "9101") { EXPECT_EQ(info.name, "radian"); EXPECT_EQ(info.category, "angular"); EXPECT_FALSE(info.deprecated); found9101 = true; } } EXPECT_TRUE(foundEPSG); EXPECT_TRUE(foundPROJ); EXPECT_TRUE(found1027); EXPECT_TRUE(found1028); EXPECT_TRUE(found1032); EXPECT_TRUE(found1036); EXPECT_TRUE(found9001); EXPECT_TRUE(found9101); } { auto factory = AuthorityFactory::create(ctxt, "EPSG"); auto list = factory->getUnitList(); EXPECT_GT(list.size(), 1U); for (const auto &info : list) { EXPECT_EQ(info.authName, "EPSG"); } } } // --------------------------------------------------------------------------- TEST(factory, getCelestialBodyList) { auto ctxt = DatabaseContext::create(); { auto factory = AuthorityFactory::create(ctxt, std::string()); auto list = factory->getCelestialBodyList(); EXPECT_GT(list.size(), 1U); bool foundPROJ = false; bool foundESRI = false; bool foundEarth = false; for (const auto &info : list) { foundESRI |= info.authName == "ESRI"; foundPROJ |= info.authName == "PROJ"; if (info.authName == "PROJ") { EXPECT_EQ(info.name, "Earth"); foundEarth = true; } } EXPECT_TRUE(foundESRI); EXPECT_TRUE(foundPROJ); EXPECT_TRUE(foundEarth); } { auto factory = AuthorityFactory::create(ctxt, "ESRI"); auto list = factory->getCelestialBodyList(); EXPECT_GT(list.size(), 1U); for (const auto &info : list) { EXPECT_EQ(info.authName, "ESRI"); } } } // --------------------------------------------------------------------------- TEST(factory, objectInsertion) { // Cannot nest startInsertStatementsSession { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); EXPECT_THROW(ctxt->startInsertStatementsSession(), FactoryException); } { auto ctxt = DatabaseContext::create(); // Tolerated withtout explicit stop ctxt->startInsertStatementsSession(); } { auto ctxt = DatabaseContext::create(); // Tolerated ctxt->stopInsertStatementsSession(); } // getInsertStatementsFor() must be preceded with // startInsertStatementsSession() { auto ctxt = DatabaseContext::create(); EXPECT_THROW(ctxt->getInsertStatementsFor(GeographicCRS::EPSG_4326, "EPSG", "4326", true), FactoryException); } { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); // Nothing to do EXPECT_TRUE(ctxt->getInsertStatementsFor(GeographicCRS::EPSG_4326, "EPSG", "4326", true) .empty()); ctxt->stopInsertStatementsSession(); } // Geographic 2D CRS { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4326"), GeographicCRS::EPSG_4326->datum(), GeographicCRS::EPSG_4326->datumEnsemble(), GeographicCRS::EPSG_4326->coordinateSystem()); EXPECT_EQ(ctxt->suggestsCodeFor(crs, "HOBU", true), "1"); EXPECT_EQ(ctxt->suggestsCodeFor(crs, "HOBU", false), "MY_EPSG_4326"); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "1234", true); EXPECT_EQ(ctxt->suggestsCodeFor(crs, "HOBU", true), "1235"); ASSERT_EQ(sql.size(), 2U); EXPECT_EQ(sql[0], "INSERT INTO geodetic_crs VALUES('HOBU','1234','my " "EPSG:4326','','geographic " "2D','EPSG','6422','EPSG','6326',NULL,0);"); EXPECT_EQ( sql[1], "INSERT INTO usage " "VALUES('HOBU','USAGE_GEODETIC_CRS_1234','geodetic_crs','HOBU','" "1234','PROJ','EXTENT_UNKNOWN','PROJ','SCOPE_UNKNOWN');"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "1234", true).empty()); ctxt->stopInsertStatementsSession(); AuthorityFactory::create(ctxt, std::string("EPSG")) ->createGeographicCRS("4326"); EXPECT_THROW(AuthorityFactory::create(ctxt, std::string("HOBU")) ->createGeographicCRS("1234"), NoSuchAuthorityCodeException); } // Geographic 3D CRS, with known usage { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto usages = AuthorityFactory::create(ctxt, std::string("EPSG")) ->createGeographicCRS("4979") ->domains(); auto array(ArrayOfBaseObject::create()); for (const auto &usage : usages) { array->add(usage); } auto props = PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4979"); props.set(ObjectUsage::OBJECT_DOMAIN_KEY, nn_static_pointer_cast<BaseObject>(array)); const auto crs = GeographicCRS::create(props, GeographicCRS::EPSG_4979->datum(), GeographicCRS::EPSG_4979->datumEnsemble(), GeographicCRS::EPSG_4979->coordinateSystem()); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "4979", false); ASSERT_EQ(sql.size(), 2U); EXPECT_EQ(sql[0], "INSERT INTO geodetic_crs VALUES('HOBU','4979','my " "EPSG:4979','','geographic " "3D','EPSG','6423','EPSG','6326',NULL,0);"); EXPECT_EQ( sql[1], "INSERT INTO usage " "VALUES('HOBU','USAGE_GEODETIC_CRS_4979','geodetic_crs','HOBU','" "4979','EPSG','1262','EPSG','1176');"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "4979", false).empty()); ctxt->stopInsertStatementsSession(); } // BoundCRS of Geocentric CRS, with new usage { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); auto props = PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4978"); auto array(ArrayOfBaseObject::create()); const auto extent = Extent::createFromBBOX(1, 2, 3, 4); optional<std::string> scope; scope = "my scope"; array->add(ObjectDomain::create(scope, extent)); props.set(ObjectUsage::OBJECT_DOMAIN_KEY, nn_static_pointer_cast<BaseObject>(array)); const auto crs = GeodeticCRS::create( props, NN_NO_CHECK(GeodeticCRS::EPSG_4978->datum()), NN_NO_CHECK(nn_dynamic_pointer_cast<CartesianCS>( GeodeticCRS::EPSG_4978->coordinateSystem()))); const auto boundCRS = BoundCRS::createFromTOWGS84( crs, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); const auto sql = ctxt->getInsertStatementsFor(boundCRS, "HOBU", "4978", false); ASSERT_EQ(sql.size(), 4U); EXPECT_EQ( sql[0], "INSERT INTO geodetic_crs VALUES('HOBU','4978','my " "EPSG:4978','','geocentric','EPSG','6500','EPSG','6326',NULL,0);"); EXPECT_EQ(sql[1], "INSERT INTO scope VALUES('HOBU','SCOPE_geodetic_crs_4978'," "'my scope',0);"); EXPECT_EQ(sql[2], "INSERT INTO extent VALUES('HOBU','EXTENT_geodetic_crs_4978'," "'unknown','unknown',2,4,1,3,0);"); EXPECT_EQ( sql[3], "INSERT INTO usage VALUES('HOBU','USAGE_GEODETIC_CRS_4978'," "'geodetic_crs','HOBU','4978','HOBU'," "'EXTENT_geodetic_crs_4978','HOBU','SCOPE_geodetic_crs_4978');"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(boundCRS, "HOBU", "4978", false) .empty()); ctxt->stopInsertStatementsSession(); } // Geographic 2D CRS with unknown datum, numeric code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto datum = GeodeticReferenceFrame::create( PropertyMap() .set(IdentifiedObject::NAME_KEY, "my datum") .set("ANCHOR_EPOCH", "2023"), Ellipsoid::WGS84, optional<std::string>("my anchor"), PrimeMeridian::GREENWICH); const auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4326"), datum, GeographicCRS::EPSG_4326->coordinateSystem()); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true); ASSERT_EQ(sql.size(), 4U); EXPECT_EQ(sql[0], "INSERT INTO geodetic_datum VALUES('HOBU','1','my " "datum','','EPSG','7030','EPSG','8901',NULL,NULL,NULL," "'my anchor',2023.000,0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true).empty()); ctxt->stopInsertStatementsSession(); } // Geographic 2D CRS with unknown datum, alpha code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my datum"), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH); const auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4326"), datum, GeographicCRS::EPSG_4326->coordinateSystem()); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "MY_EPSG_4326", false); EXPECT_EQ(ctxt->suggestsCodeFor(crs, "HOBU", false), "MY_EPSG_4326_2"); ASSERT_EQ(sql.size(), 4U); EXPECT_EQ(sql[0], "INSERT INTO geodetic_datum " "VALUES('HOBU','GEODETIC_DATUM_MY_EPSG_4326','my " "datum','','EPSG','7030','EPSG','8901',NULL,NULL,NULL,NULL," "NULL,0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "MY_EPSG_4326", false) .empty()); ctxt->stopInsertStatementsSession(); } // Geographic 2D CRS with unknown ellipsoid, numeric code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto ellipsoid = Ellipsoid::createFlattenedSphere( PropertyMap().set(IdentifiedObject::NAME_KEY, "my ellipsoid"), Length(6378137), Scale(295)); const auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my datum"), ellipsoid, optional<std::string>(), PrimeMeridian::GREENWICH); const auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4326"), datum, GeographicCRS::EPSG_4326->coordinateSystem()); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true); ASSERT_EQ(sql.size(), 5U); EXPECT_EQ(sql[0], "INSERT INTO ellipsoid VALUES('HOBU','1','my " "ellipsoid','','IAU_2015','399',6378137,'EPSG','9001'" ",295,NULL,0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true).empty()); ctxt->stopInsertStatementsSession(); } // Geographic 2D CRS with unknown ellipsoid, alpha code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto ellipsoid = Ellipsoid::createTwoAxis( PropertyMap().set(IdentifiedObject::NAME_KEY, "my ellipsoid"), Length(6378137), Length(6378136)); const auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my datum"), ellipsoid, optional<std::string>(), PrimeMeridian::GREENWICH); const auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4326"), datum, GeographicCRS::EPSG_4326->coordinateSystem()); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", false); ASSERT_EQ(sql.size(), 5U); EXPECT_EQ(sql[0], "INSERT INTO ellipsoid " "VALUES('HOBU','ELLPS_GEODETIC_DATUM_XXXX','my " "ellipsoid','','IAU_2015','399',6378137," "'EPSG','9001'," "NULL,6378136,0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", false).empty()); ctxt->stopInsertStatementsSession(); } // Geographic 2D CRS with unknown prime meridian, numeric code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto pm = PrimeMeridian::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "My meridian"), Angle(10)); const auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my datum"), Ellipsoid::WGS84, optional<std::string>(), pm); const auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4326"), datum, GeographicCRS::EPSG_4326->coordinateSystem()); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true); ASSERT_EQ(sql.size(), 5U); EXPECT_EQ(sql[0], "INSERT INTO prime_meridian VALUES('HOBU','1','My " "meridian',10,'EPSG','9122',0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true).empty()); ctxt->stopInsertStatementsSession(); } // Geographic 2D CRS with unknown prime meridian, alpha code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto pm = PrimeMeridian::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "My meridian"), Angle(10)); const auto datum = GeodeticReferenceFrame::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my datum"), Ellipsoid::WGS84, optional<std::string>(), pm); const auto crs = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my EPSG:4326"), datum, GeographicCRS::EPSG_4326->coordinateSystem()); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", false); ASSERT_EQ(sql.size(), 5U); EXPECT_EQ(sql[0], "INSERT INTO prime_meridian " "VALUES('HOBU','PM_GEODETIC_DATUM_XXXX','My " "meridian',10,'EPSG','9122',0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", false).empty()); ctxt->stopInsertStatementsSession(); } // Projected CRS, numeric code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto crs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my projected CRS"), GeographicCRS::EPSG_4807, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true); ASSERT_EQ(sql.size(), 4U); EXPECT_EQ(sql[0], "INSERT INTO conversion VALUES('HOBU','1'," "'UTM zone 31N',''," "'EPSG','9807','Transverse Mercator'," "'EPSG','8801','Latitude of natural origin',0,'EPSG','9122'," "'EPSG','8802','Longitude of natural origin',3,'EPSG','9122'," "'EPSG','8805','Scale factor at natural origin',0.9996," "'EPSG','9201'," "'EPSG','8806','False easting',500000,'EPSG','9001'," "'EPSG','8807','False northing',0,'EPSG','9001'," "NULL,NULL,NULL,NULL,NULL,NULL," "NULL,NULL,NULL,NULL,NULL,NULL,0);"); EXPECT_EQ(sql[1], "INSERT INTO usage " "VALUES('HOBU','USAGE_CONVERSION_1','conversion','HOBU','1','" "PROJ','EXTENT_UNKNOWN','PROJ','SCOPE_UNKNOWN');"); EXPECT_EQ( sql[2], "INSERT INTO projected_crs VALUES('HOBU','XXXX','my projected " "CRS','','EPSG','4400','EPSG','4807','HOBU','1',NULL,0);"); EXPECT_EQ( sql[3], "INSERT INTO usage " "VALUES('HOBU','USAGE_PROJECTED_CRS_XXXX','projected_crs','HOBU','" "XXXX','PROJ','EXTENT_UNKNOWN','PROJ','SCOPE_UNKNOWN');"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true).empty()); ctxt->stopInsertStatementsSession(); } // Vertical CRS, known vertical datum, numeric code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); PropertyMap propertiesVDatum; propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5101) .set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn"); auto vdatum = VerticalReferenceFrame::create(propertiesVDatum); PropertyMap propertiesCRS; propertiesCRS.set(IdentifiedObject::NAME_KEY, "my height"); const auto uom = UnitOfMeasure("my unit", 3.0, UnitOfMeasure::Type::LINEAR); const auto crs = VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(uom)); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true); ASSERT_EQ(sql.size(), 5U); EXPECT_EQ(sql[0], "INSERT INTO coordinate_system VALUES" "('HOBU','CS_VERTICAL_CRS_XXXX','vertical',1);"); EXPECT_EQ(sql[1], "INSERT INTO unit_of_measure VALUES" "('HOBU','MY_UNIT','my unit','length',3,NULL,0);"); EXPECT_EQ(sql[2], "INSERT INTO axis VALUES('HOBU'," "'CS_VERTICAL_CRS_XXXX_AXIS_1','Gravity-related height','H'," "'up','HOBU','CS_VERTICAL_CRS_XXXX',1,'HOBU','MY_UNIT');"); EXPECT_EQ(sql[3], "INSERT INTO vertical_crs VALUES('HOBU','XXXX','my height'," "'','HOBU','CS_VERTICAL_CRS_XXXX','EPSG','5101',0);"); EXPECT_EQ(sql[4], "INSERT INTO usage VALUES('HOBU','USAGE_VERTICAL_CRS_XXXX'," "'vertical_crs','HOBU','XXXX','PROJ','EXTENT_UNKNOWN'," "'PROJ','SCOPE_UNKNOWN');"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", true).empty()); ctxt->stopInsertStatementsSession(); } // Vertical CRS, unknown vertical datum, alpha code { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); PropertyMap propertiesVDatum; propertiesVDatum.set(IdentifiedObject::NAME_KEY, "my datum"); auto vdatum = VerticalReferenceFrame::create( propertiesVDatum, optional<std::string>("my anchor")); PropertyMap propertiesCRS; propertiesCRS.set(IdentifiedObject::NAME_KEY, "my height"); const auto crs = VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", false); ASSERT_EQ(sql.size(), 4U); EXPECT_EQ(sql[0], "INSERT INTO vertical_datum VALUES('HOBU'," "'VERTICAL_DATUM_XXXX','my datum','',NULL,NULL,NULL," "'my anchor',NULL,0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "XXXX", false).empty()); ctxt->stopInsertStatementsSession(); } // Same as above with ANCHOR_EPOCH { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); PropertyMap propertiesVDatum; propertiesVDatum.set(IdentifiedObject::NAME_KEY, "my datum"); propertiesVDatum.set("ANCHOR_EPOCH", "2023"); auto vdatum = VerticalReferenceFrame::create( propertiesVDatum, optional<std::string>("my anchor")); PropertyMap propertiesCRS; propertiesCRS.set(IdentifiedObject::NAME_KEY, "my height"); const auto crs = VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); const auto sql = ctxt->getInsertStatementsFor(crs, "HOBU", "YYYY", false); ASSERT_EQ(sql.size(), 4U); EXPECT_EQ(sql[0], "INSERT INTO vertical_datum VALUES('HOBU'," "'VERTICAL_DATUM_YYYY','my datum','',NULL,NULL,NULL," "'my anchor',2023.000,0);"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE( ctxt->getInsertStatementsFor(crs, "HOBU", "YYYY", false).empty()); ctxt->stopInsertStatementsSession(); } // Compound CRS { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto wkt = "COMPD_CS[\"unknown\"," "PROJCS[\"NAD_1983_2011_StatePlane_South_Carolina_FIPS_3900_USFT\"," "GEOGCS[\"NAD83(2011)\"," "DATUM[\"NAD83_National_Spatial_Reference_System_2011\"," "SPHEROID[\"GRS 1980\",6378137,298.257222101004," "AUTHORITY[\"EPSG\",\"7019\"]],AUTHORITY[\"EPSG\",\"1116\"]]," "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433," "AUTHORITY[\"EPSG\",\"9122\"]]]," "PROJECTION[\"Lambert_Conformal_Conic_2SP\"]," "PARAMETER[\"latitude_of_origin\",31.8333333333333]," "PARAMETER[\"central_meridian\",-81]," "PARAMETER[\"standard_parallel_1\",32.5]," "PARAMETER[\"standard_parallel_2\",34.8333333333333]," "PARAMETER[\"false_easting\",1999996]," "PARAMETER[\"false_northing\",0]," "UNIT[\"US survey foot\",0.304800609601219," "AUTHORITY[\"EPSG\",\"9003\"]]," "AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH]]," "VERT_CS[\"NAVD88 height (ftUS)\"," "VERT_DATUM[\"North American Vertical Datum 1988\",2005," "AUTHORITY[\"EPSG\",\"5103\"]]," "UNIT[\"US survey foot\",0.304800609601219," "AUTHORITY[\"EPSG\",\"9003\"]]," "AXIS[\"Up\",UP],AUTHORITY[\"EPSG\",\"6360\"]]]"; const auto crs = nn_dynamic_pointer_cast<CRS>(WKTParser().createFromWKT(wkt)); ASSERT_TRUE(crs != nullptr); const auto sql = ctxt->getInsertStatementsFor(NN_NO_CHECK(crs), "HOBU", "XXXX", false); ASSERT_EQ(sql.size(), 6U); EXPECT_EQ(sql[4], "INSERT INTO compound_crs VALUES('HOBU','XXXX','unknown'," "'','HOBU','COMPONENT_XXXX_1','EPSG','6360',0);"); EXPECT_EQ(sql[5], "INSERT INTO usage VALUES('HOBU','USAGE_COMPOUND_CRS_XXXX'," "'compound_crs','HOBU','XXXX','PROJ','EXTENT_UNKNOWN'," "'PROJ','SCOPE_UNKNOWN');"); const auto identified = crs->identify(AuthorityFactory::create(ctxt, std::string())); ASSERT_EQ(identified.size(), 1U); EXPECT_EQ( *(identified.front().first->identifiers().front()->codeSpace()), "HOBU"); EXPECT_TRUE(identified.front().first->isEquivalentTo( crs.get(), IComparable::Criterion::EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS)); EXPECT_EQ(identified.front().second, 100); EXPECT_TRUE(ctxt->getInsertStatementsFor(NN_NO_CHECK(crs), "HOBU", "XXXX", false) .empty()); ctxt->stopInsertStatementsSession(); } // DynamicGeodeticReferenceFrame { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto datum = AuthorityFactory::create(ctxt, "EPSG") ->createDatum("1165"); // ITRF2014 const auto sql = ctxt->getInsertStatementsFor(datum, "HOBU", "XXXX", false, {"HOBU"}); EXPECT_TRUE(!sql.empty()); const auto datumNew = AuthorityFactory::create(ctxt, "HOBU")->createDatum("XXXX"); EXPECT_TRUE(datumNew->isEquivalentTo( datum.get(), IComparable::Criterion::EQUIVALENT)); ctxt->stopInsertStatementsSession(); } // DynamicVerticalReferenceFrame { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto datum = AuthorityFactory::create(ctxt, "EPSG") ->createDatum("1096"); // Norway Normal Null 2000 const auto sql = ctxt->getInsertStatementsFor(datum, "HOBU", "XXXX", false, {"HOBU"}); EXPECT_TRUE(!sql.empty()); const auto datumNew = AuthorityFactory::create(ctxt, "HOBU")->createDatum("XXXX"); EXPECT_TRUE(datumNew->isEquivalentTo( datum.get(), IComparable::Criterion::EQUIVALENT)); ctxt->stopInsertStatementsSession(); } // geodetic DatumEnsemble, and add members inline { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto ensemble = AuthorityFactory::create(ctxt, "EPSG") ->createDatumEnsemble("6326"); // WGS84 const auto sql = ctxt->getInsertStatementsFor(ensemble, "HOBU", "XXXX", false, {"HOBU"}); EXPECT_TRUE(!sql.empty()); const auto ensembleNew = AuthorityFactory::create(ctxt, "HOBU")->createDatumEnsemble("XXXX"); EXPECT_TRUE(ensembleNew->isEquivalentTo( ensemble.get(), IComparable::Criterion::EQUIVALENT)); ctxt->stopInsertStatementsSession(); } // geodetic DatumEnsemble, and reference members { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto ensemble = AuthorityFactory::create(ctxt, "EPSG") ->createDatumEnsemble("6326"); // WGS84 const auto sql = ctxt->getInsertStatementsFor(ensemble, "HOBU", "XXXX", false); EXPECT_TRUE(!sql.empty()); const auto ensembleNew = AuthorityFactory::create(ctxt, "HOBU")->createDatumEnsemble("XXXX"); EXPECT_TRUE(ensembleNew->isEquivalentTo( ensemble.get(), IComparable::Criterion::EQUIVALENT)); ctxt->stopInsertStatementsSession(); } // vertical DatumEnsemble { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); // British Isles height ensemble const auto ensemble = AuthorityFactory::create(ctxt, "EPSG")->createDatumEnsemble("1288"); const auto sql = ctxt->getInsertStatementsFor(ensemble, "HOBU", "XXXX", false, {"HOBU"}); EXPECT_TRUE(!sql.empty()); const auto ensembleNew = AuthorityFactory::create(ctxt, "HOBU")->createDatumEnsemble("XXXX"); EXPECT_TRUE(ensembleNew->isEquivalentTo( ensemble.get(), IComparable::Criterion::EQUIVALENT)); ctxt->stopInsertStatementsSession(); } // non-EPSG projection method { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto crs = nn_dynamic_pointer_cast<CRS>( PROJStringParser().createFromPROJString( "+proj=sinu +lon_0=195 +x_0=0 +y_0=0 +R=3396000 +units=m " "+no_defs +type=crs")); ASSERT_TRUE(crs != nullptr); const auto statements = ctxt->getInsertStatementsFor( NN_NO_CHECK(crs), "HOBU", "XXXX", false); bool found = false; for (const auto &sql : statements) { if (sql.find("INSERT INTO conversion") != std::string::npos) { found = true; const char *expected = "VALUES('HOBU','CONVERSION_XXXX'," "'unknown','','PROJ','sinu','Sinusoidal',"; EXPECT_TRUE(sql.find(expected) != std::string::npos) << sql; } } EXPECT_TRUE(found); const auto crsNew = AuthorityFactory::create(ctxt, "HOBU")->createProjectedCRS("XXXX"); EXPECT_TRUE(crsNew->isEquivalentTo(crs.get(), IComparable::Criterion::EQUIVALENT)); ctxt->stopInsertStatementsSession(); } // Missing projection method and parameter id, and parameters not in // their nominal order { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto wkt = "PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\"],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]"; const auto crs = nn_dynamic_pointer_cast<CRS>(WKTParser().createFromWKT(wkt)); ASSERT_TRUE(crs != nullptr); const auto statements = ctxt->getInsertStatementsFor( NN_NO_CHECK(crs), "HOBU", "XXXX", false); bool found = false; const char *expected = "INSERT INTO conversion VALUES('HOBU','CONVERSION_XXXX'," "'UTM zone 31N','','EPSG','9807','Transverse Mercator'," "'EPSG','8801','Latitude of natural origin',0,'EPSG','9102'," "'EPSG','8802','Longitude of natural origin',3,'EPSG','9102'," "'EPSG','8805','Scale factor at natural origin',0.9996," "'EPSG','9201'," "'EPSG','8806','False easting',500000,'EPSG','9001'," "'EPSG','8807','False northing',0,'EPSG','9001'," "NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL," "NULL,0)"; for (const auto &sql : statements) { if (sql.find("INSERT INTO conversion") != std::string::npos) { found = true; EXPECT_TRUE(sql.find(expected) != std::string::npos) << sql; } } EXPECT_TRUE(found); const auto crsNew = AuthorityFactory::create(ctxt, "HOBU")->createProjectedCRS("XXXX"); EXPECT_TRUE(crsNew->isEquivalentTo(crs.get(), IComparable::Criterion::EQUIVALENT)); ctxt->stopInsertStatementsSession(); } // Error: unknown projection method. { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto wkt = "PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"unknown\"]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]"; const auto crs = nn_dynamic_pointer_cast<CRS>(WKTParser().createFromWKT(wkt)); ASSERT_TRUE(crs != nullptr); EXPECT_THROW(ctxt->getInsertStatementsFor(NN_NO_CHECK(crs), "HOBU", "XXXX", false), std::exception); } // Error: unknown projection parameter. { auto ctxt = DatabaseContext::create(); ctxt->startInsertStatementsSession(); const auto wkt = "PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Transverse Mercator\"],\n" " PARAMETER[\"unknown\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]"; const auto crs = nn_dynamic_pointer_cast<CRS>(WKTParser().createFromWKT(wkt)); ASSERT_TRUE(crs != nullptr); EXPECT_THROW(ctxt->getInsertStatementsFor(NN_NO_CHECK(crs), "HOBU", "XXXX", false), std::exception); } } // --------------------------------------------------------------------------- TEST(factory, ogc_timecrs) { auto ctxt = DatabaseContext::create(); auto factory = AuthorityFactory::create(ctxt, Identifier::OGC); factory->createCoordinateReferenceSystem("AnsiDate"); factory->createCoordinateReferenceSystem("JulianDate"); factory->createCoordinateReferenceSystem("UnixTime"); } // --------------------------------------------------------------------------- TEST(factory, ogc_crs) { auto ctxt = DatabaseContext::create(); auto factory = AuthorityFactory::create(ctxt, Identifier::OGC); factory->createCoordinateReferenceSystem("CRS84"); factory->createCoordinateReferenceSystem("84"); factory->createCoordinateReferenceSystem("CRS27"); factory->createCoordinateReferenceSystem("CRS83"); } // --------------------------------------------------------------------------- TEST(factory, getPointMotionOperationsFor) { auto ctxt = DatabaseContext::create(); auto factory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // "NAD83(CSRS)v7" auto crs = factory->createGeodeticCRS("8255"); auto opList = factory->getPointMotionOperationsFor(crs, false); ASSERT_TRUE(!opList.empty()); EXPECT_EQ(opList.front()->identifiers().front()->code(), "9483"); } // --------------------------------------------------------------------------- } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_operationfactory.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "test_primitives.hpp" // to be able to use internal::replaceAll #ifndef FROM_PROJ_CPP #define FROM_PROJ_CPP #endif #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinates.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj_constants.h" #include <string> #include <vector> using namespace osgeo::proj::common; using namespace osgeo::proj::coordinates; using namespace osgeo::proj::crs; using namespace osgeo::proj::cs; using namespace osgeo::proj::datum; using namespace osgeo::proj::io; using namespace osgeo::proj::internal; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS) { auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv +proj=longlat " "+ellps=clrk80ign +pm=paris +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_default) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::NEVER); // Directly found in database { auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4179"), // Pulkovo 42 authFactory->createCoordinateReferenceSystem("4258"), // ETRS89 ctxt); ASSERT_EQ(list.size(), 3U); // Romania has a larger area than Poland (given our approx formula) EXPECT_EQ(list[0]->getEPSGCode(), 15994); // Romania - 3m EXPECT_EQ(list[1]->getEPSGCode(), 1644); // Poland - 1m EXPECT_EQ(list[2]->nameStr(), "Ballpark geographic offset from Pulkovo 1942(58) to ETRS89"); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=krass +step +proj=helmert +x=2.3287 " "+y=-147.0425 +z=-92.0802 +rx=0.3092483 +ry=-0.32482185 " "+rz=-0.49729934 +s=5.68906266 +convention=coordinate_frame +step " "+inv +proj=cart +ellps=GRS80 +step +proj=pop +v_3 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // Reverse case { auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4258"), authFactory->createCoordinateReferenceSystem("4179"), ctxt); ASSERT_EQ(list.size(), 3U); // Romania has a larger area than Poland (given our approx formula) EXPECT_EQ(list[0]->nameStr(), "Inverse of Pulkovo 1942(58) to ETRS89 (4)"); // Romania - 3m EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=GRS80 +step +inv +proj=helmert +x=2.3287 " "+y=-147.0425 +z=-92.0802 +rx=0.3092483 +ry=-0.32482185 " "+rz=-0.49729934 +s=5.68906266 +convention=coordinate_frame +step " "+inv +proj=cart +ellps=krass +step +proj=pop +v_3 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_match_by_name) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::NEVER); auto NAD27 = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, GeographicCRS::EPSG_4267->nameStr()), GeographicCRS::EPSG_4267->datum(), GeographicCRS::EPSG_4267->datumEnsemble(), GeographicCRS::EPSG_4267->coordinateSystem()); auto list = CoordinateOperationFactory::create()->createOperations( NAD27, GeographicCRS::EPSG_4326, ctxt); auto listInv = CoordinateOperationFactory::create()->createOperations( GeographicCRS::EPSG_4326, NAD27, ctxt); auto listRef = CoordinateOperationFactory::create()->createOperations( GeographicCRS::EPSG_4267, GeographicCRS::EPSG_4326, ctxt); EXPECT_EQ(list.size(), listRef.size()); EXPECT_EQ(listInv.size(), listRef.size()); EXPECT_GE(listRef.size(), 2U); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_filter_accuracy) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 1.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4179"), authFactory->createCoordinateReferenceSystem("4258"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->getEPSGCode(), 1644); // Poland - 1m } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.9); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4179"), authFactory->createCoordinateReferenceSystem("4258"), ctxt); ASSERT_EQ(list.size(), 0U); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_filter_bbox) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // INSERT INTO "area" VALUES('EPSG','1197','Romania','Romania - onshore and // offshore.',43.44,48.27,20.26,31.41,0); { auto ctxt = CoordinateOperationContext::create( authFactory, Extent::createFromBBOX(20.26, 43.44, 31.41, 48.27), 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4179"), authFactory->createCoordinateReferenceSystem("4258"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->getEPSGCode(), 15994); // Romania - 3m } { auto ctxt = CoordinateOperationContext::create( authFactory, Extent::createFromBBOX(20.26 + .1, 43.44 + .1, 31.41 - .1, 48.27 - .1), 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4179"), authFactory->createCoordinateReferenceSystem("4258"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->getEPSGCode(), 15994); // Romania - 3m } { auto ctxt = CoordinateOperationContext::create( authFactory, Extent::createFromBBOX(20.26 - .1, 43.44 - .1, 31.41 + .1, 48.27 + .1), 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4179"), authFactory->createCoordinateReferenceSystem("4258"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_incompatible_area) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4267"), // NAD27 authFactory->createCoordinateReferenceSystem("4258"), // ETRS 89 ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_inverse_needed) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setUsePROJAlternativeGridNames(false); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4275"), // NTF authFactory->createCoordinateReferenceSystem("4258"), // ETRS89 ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign +step +proj=helmert +x=-168 " "+y=-60 +z=320 +step +inv +proj=cart +ellps=GRS80 +step +proj=pop " "+v_3 +step +proj=unitconvert +xy_in=rad +xy_out=deg +step " "+proj=axisswap +order=2,1"); EXPECT_EQ(list[1]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step " "+proj=hgridshift +grids=fr_ign_ntf_r93.tif +step " "+proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4275"), // NTF authFactory->createCoordinateReferenceSystem("4258"), // ETRS89 ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step " "+proj=hgridshift +grids=fr_ign_ntf_r93.tif +step " "+proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4258"), // ETRS89 authFactory->createCoordinateReferenceSystem("4275"), // NTF ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +inv " "+proj=hgridshift +grids=fr_ign_ntf_r93.tif +step " "+proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_ntv1_ntv2_ctable2) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4267"), // NAD27 authFactory->createCoordinateReferenceSystem("4269"), // NAD83 ctxt); ASSERT_EQ(list.size(), 10U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=hgridshift " "+grids=ca_nrc_ntv2_0.tif +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=hgridshift " "+grids=ca_nrc_ntv1_can.tif +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_EQ(list[2]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=hgridshift " "+grids=us_noaa_conus.tif +step +proj=unitconvert +xy_in=rad " "+xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_NAD27_to_WGS84) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4267"), // NAD27 authFactory->createCoordinateReferenceSystem("4326"), // WGS84 ctxt); ASSERT_EQ(list.size(), 79U); EXPECT_EQ(list[0]->nameStr(), "NAD27 to WGS 84 (33)"); // 1.0 m, Canada - NAD27 EXPECT_EQ(list[1]->nameStr(), "NAD27 to WGS 84 (3)"); // 20.0 m, Canada - NAD27 EXPECT_EQ(list[2]->nameStr(), "NAD27 to WGS 84 (79)"); // 5.0 m, USA - CONUS including EEZ EXPECT_EQ(list[3]->nameStr(), "NAD27 to WGS 84 (4)"); // 10.0 m, USA - CONUS - onshore } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_NAD27_to_WGS84_G1762) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto authFactoryEPSG = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto list = CoordinateOperationFactory::create()->createOperations( // NAD27 authFactoryEPSG->createCoordinateReferenceSystem("4267"), // WGS84 (G1762) authFactoryEPSG->createCoordinateReferenceSystem("9057"), ctxt); ASSERT_GE(list.size(), 78U); EXPECT_EQ(list[0]->nameStr(), "NAD27 to WGS 84 (33) + WGS 84 to WGS 84 (G1762)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=ca_nrc_ntv2_0.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(list[1]->nameStr(), "NAD27 to WGS 84 (3) + WGS 84 to WGS 84 (G1762)"); EXPECT_EQ(list[2]->nameStr(), "NAD27 to WGS 84 (79) + WGS 84 to WGS 84 (G1762)"); EXPECT_EQ(list[3]->nameStr(), "NAD27 to WGS 84 (4) + WGS 84 to WGS 84 (G1762)"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_WGS84_G1674_to_WGS84_G1762) { // Check that particular behavior with WGS 84 (Gxxx) related to // 'geodetic_datum_preferred_hub' table and custom no-op transformations // between WGS 84 and WGS 84 (Gxxx) doesn't affect direct transformations // to those realizations. auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto authFactoryEPSG = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto list = CoordinateOperationFactory::create()->createOperations( // WGS84 (G1674) authFactoryEPSG->createCoordinateReferenceSystem("9056"), // WGS84 (G1762) authFactoryEPSG->createCoordinateReferenceSystem("9057"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=-0.004 +y=0.003 +z=0.004 +rx=0.00027 " "+ry=-0.00027 +rz=0.00038 +s=-0.0069 " "+convention=coordinate_frame " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_EPSG_4240_Indian1975_to_EPSG_4326) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4240"), // Indian 1975 authFactory->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 3U); // Indian 1975 to WGS 84 (4), 3.0 m, Thailand - onshore EXPECT_EQ(list[0]->getEPSGCode(), 1812); // The following is the one we want to see. It has a lesser accuracy than // the above one and the same bbox, but the name of its area of use is // slightly different // Indian 1975 to WGS 84 (2), 5.0 m, Thailand - onshore and Gulf of Thailand EXPECT_EQ(list[1]->getEPSGCode(), 1304); // Indian 1975 to WGS 84 (3), 1.0 m, Thailand - Bongkot field EXPECT_EQ(list[2]->getEPSGCode(), 1537); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_helmert_geog3D_crs) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4939"), // GDA94 3D authFactory->createCoordinateReferenceSystem("7843"), // GDA2020 3D ctxt); ASSERT_EQ(list.size(), 1U); // Check there is no push / pop of v_3 EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=0.06155 +y=-0.01087 +z=-0.04019 " "+rx=-0.0394924 +ry=-0.0327221 +rz=-0.0328979 +s=-0.009994 " "+convention=coordinate_frame " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_helmert_geocentric_3D) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); auto list = CoordinateOperationFactory::create()->createOperations( // GDA94 geocentric authFactory->createCoordinateReferenceSystem("4348"), // GDA2020 geocentric authFactory->createCoordinateReferenceSystem("7842"), ctxt); ASSERT_EQ(list.size(), 1U); // Check there is no push / pop of v_3 EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=helmert +x=0.06155 +y=-0.01087 +z=-0.04019 " "+rx=-0.0394924 +ry=-0.0327221 +rz=-0.0328979 +s=-0.009994 " "+convention=coordinate_frame"); EXPECT_EQ(list[0]->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=helmert +x=0.06155 +y=-0.01087 +z=-0.04019 " "+rx=-0.0394924 +ry=-0.0327221 +rz=-0.0328979 +s=-0.009994 " "+convention=coordinate_frame"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_helmert_geog3D_to_geocentirc) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); auto list = CoordinateOperationFactory::create()->createOperations( // GDA94 3D authFactory->createCoordinateReferenceSystem("4939"), // GDA2020 geocentric authFactory->createCoordinateReferenceSystem("7842"), ctxt); ASSERT_GE(list.size(), 1U); // Check there is no push / pop of v_3 EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=0.06155 +y=-0.01087 +z=-0.04019 " "+rx=-0.0394924 +ry=-0.0327221 +rz=-0.0328979 +s=-0.009994 " "+convention=coordinate_frame"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_invalid_EPSG_ID) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); // EPSG:4656 is incorrect. Should be EPSG:8997 auto obj = WKTParser().createFromWKT( "GEOGCS[\"ITRF2000\"," "DATUM[\"International_Terrestrial_Reference_Frame_2000\"," "SPHEROID[\"GRS 1980\",6378137,298.257222101," "AUTHORITY[\"EPSG\",\"7019\"]],AUTHORITY[\"EPSG\",\"6656\"]]," "PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]," "AUTHORITY[\"EPSG\",\"4656\"]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(crs), GeographicCRS::EPSG_4326, ctxt); ASSERT_EQ(list.size(), 1U); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_datum_ensemble) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); auto dst_wkt = "GEOGCRS[\"unknown\"," " ENSEMBLE[\"World Geodetic System 1984 ensemble\"," " MEMBER[\"World Geodetic System 1984 (Transit)\"," " ID[\"EPSG\",1166]]," " MEMBER[\"World Geodetic System 1984 (G730)\"," " ID[\"EPSG\",1152]]," " MEMBER[\"World Geodetic System 1984 (G873)\"," " ID[\"EPSG\",1153]]," " MEMBER[\"World Geodetic System 1984 (G1150)\"," " ID[\"EPSG\",1154]]," " MEMBER[\"World Geodetic System 1984 (G1674)\"," " ID[\"EPSG\",1155]]," " MEMBER[\"World Geodetic System 1984 (G1762)\"," " ID[\"EPSG\",1156]]," " ELLIPSOID[\"WGS 84\",6378137,298.257223563," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]," " ID[\"EPSG\",7030]]," " ENSEMBLEACCURACY[2]]," " PRIMEM[\"Greenwich\",0," " ANGLEUNIT[\"degree\",0.0174532925199433,ID[\"EPSG\",9102]]," " ID[\"EPSG\",8901]]," " CS[ellipsoidal,2," " ID[\"EPSG\",6422]]," " AXIS[\"Geodetic latitude (Lat)\",north," " ORDER[1]]," " AXIS[\"Geodetic longitude (Lon)\",east," " ORDER[2]]," " ANGLEUNIT[\"degree (supplier to define representation)\"," "0.0174532925199433,ID[\"EPSG\",9122]]]"; auto dstObj = WKTParser().createFromWKT(dst_wkt); auto dstCRS = nn_dynamic_pointer_cast<CRS>(dstObj); ASSERT_TRUE(dstCRS != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4258"), // ETRS89 NN_NO_CHECK(dstCRS), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "ETRS89 to WGS 84 (1)"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_derived_geogCRS_3D) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto dst_wkt = "GEOGCRS[\"CH1903+ with 10m offset on ellipsoidal height\",\n" " BASEGEOGCRS[\"CH1903+\",\n" " DATUM[\"CH1903+\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6150]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " DERIVINGCONVERSION[\"Offset on ellipsoidal height\",\n" " METHOD[\"Geographic3D offsets\",\n" " ID[\"EPSG\",9660]],\n" " PARAMETER[\"Latitude offset\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8601]],\n" " PARAMETER[\"Longitude offset\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8602]],\n" " PARAMETER[\"Vertical Offset\",10,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8603]]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto dstObj = WKTParser().createFromWKT(dst_wkt); auto dstCRS = nn_dynamic_pointer_cast<CRS>(dstObj); ASSERT_TRUE(dstCRS != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 3D NN_NO_CHECK(dstCRS), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ( list[0]->nameStr(), "Inverse of CH1903+ to WGS 84 (1) + Offset on ellipsoidal height"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=-674.374 +y=-15.056 +z=-405.346 " "+step +inv +proj=cart +ellps=bessel " "+step +proj=geogoffset +dlat=0 +dlon=0 +dh=10 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, vertCRS_to_geogCRS_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setUsePROJAlternativeGridNames(false); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem( "3855"), // EGM2008 height authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 ctxt); ASSERT_EQ(list.size(), 3U); EXPECT_EQ( list[1]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm08_25.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem( "3855"), // EGM2008 height authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 ctxt); ASSERT_EQ(list.size(), 3U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm08_25.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 authFactory->createCoordinateReferenceSystem( "3855"), // EGM2008 height ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift +grids=us_nga_egm08_25.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // NGVD29 depth (ftUS) authFactory->createCoordinateReferenceSystem("6359"), authFactory->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=affine +s33=-0.304800609601219"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // NZVD2016 height authFactory->createCoordinateReferenceSystem("7839"), // NZGD2000 authFactory->createCoordinateReferenceSystem("4959"), ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=nz_linz_nzgeoid2016.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } { // Test actually the database where we derive records using the more // classic 'Geographic3D to GravityRelatedHeight' method from // records using EPSG:1088 //'Geog3D to Geog2D+GravityRelatedHeight (gtx)' method auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(DatabaseContext::create(), std::string()), nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // Baltic 1957 height authFactory->createCoordinateReferenceSystem("8357"), // ETRS89 authFactory->createCoordinateReferenceSystem("4937"), ctxt); ASSERT_EQ(list.size(), 3U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift " "+grids=cz_cuzk_CR-2005.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift " "+grids=sk_gku_Slovakia_ETRS89h_to_Baltic1957.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } } // --------------------------------------------------------------------------- TEST(operation, geog3DCRS_to_geog2DCRS_plus_vertCRS_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // ETRS89 (3D) authFactory->createCoordinateReferenceSystem("4937"), // ETRS89 + Baltic 1957 height authFactory->createCoordinateReferenceSystem("8360"), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift " "+grids=sk_gku_Slovakia_ETRS89h_to_Baltic1957.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(list[0]->inverse()->nameStr(), "Inverse of 'ETRS89 to ETRS89 + Baltic 1957 height (1)'"); } } // --------------------------------------------------------------------------- TEST(operation, geog3DCRS_to_vertCRS_depth_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4937"), // ETRS89 authFactory->createCoordinateReferenceSystem("9672"), // CD Norway deph ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift " "+grids=no_kv_CD_above_Ell_ETRS89_v2023b.tif +multiplier=1 " "+step +proj=axisswap +order=1,2,-3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("9672"), // CD Norway deph authFactory->createCoordinateReferenceSystem("4937"), // ETRS89 ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=axisswap +order=1,2,-3 " "+step +proj=vgridshift " "+grids=no_kv_CD_above_Ell_ETRS89_v2023b.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } } // --------------------------------------------------------------------------- TEST(operation, geog3DCRS_to_geog2DCRS_plus_vertCRS_depth_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4937"), // ETRS89 authFactory->createCoordinateReferenceSystem("9883"), // ETRS89 + CD Norway deph ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift " "+grids=no_kv_CD_above_Ell_ETRS89_v2023b.tif +multiplier=1 " "+step +proj=axisswap +order=1,2,-3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("9883"), // ETRS89 + CD Norway deph authFactory->createCoordinateReferenceSystem("4937"), // ETRS89 ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=axisswap +order=1,2,-3 " "+step +proj=vgridshift " "+grids=no_kv_CD_above_Ell_ETRS89_v2023b.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_noop) { auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->nameStr(), "Null geographic offset from WGS 84 to WGS 84"); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); EXPECT_EQ(op->inverse()->nameStr(), op->nameStr()); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_longitude_rotation) { auto src = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "A"), GeodeticReferenceFrame::create(PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto dest = GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "B"), GeodeticReferenceFrame::create(PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::PARIS), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto op = CoordinateOperationFactory::create()->createOperation(src, dest); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=longlat " "+ellps=WGS84 +pm=paris +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_EQ(op->inverse()->exportToWKT(WKTFormatter::create().get()), CoordinateOperationFactory::create() ->createOperation(dest, src) ->exportToWKT(WKTFormatter::create().get())); EXPECT_TRUE( op->inverse()->isEquivalentTo(CoordinateOperationFactory::create() ->createOperation(dest, src) .get())); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_longitude_rotation_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4807"), // NTF(Paris) authFactory->createCoordinateReferenceSystem("4275"), // NTF ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->nameStr(), "NTF (Paris) to NTF (1)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv " "+proj=longlat +ellps=clrk80ign +pm=paris +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); EXPECT_EQ(list[1]->nameStr(), "NTF (Paris) to NTF (2)"); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv " "+proj=longlat +ellps=clrk80ign +pm=2.33720833333333 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_lonlat_vs_latlon_crs) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4749"), // RGNC91-93 authFactory->createCoordinateReferenceSystem("10310"), // RGNC15 ctxt); ASSERT_EQ(list.size(), 3U); // Check that we get direct transformation, and not through WGS 84 // The difficulty here is that the transformation is registered between // "RGNC91-93 (lon-lat)" et "RGNC15 (lon-lat)" EXPECT_EQ(list[0]->nameStr(), "axis order change (2D) + RGNC91-93 to " "RGNC15 (2) + axis order change (2D)"); EXPECT_EQ(list[1]->nameStr(), "axis order change (2D) + RGNC91-93 to " "RGNC15 (1) + axis order change (2D)"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_concatenated_operation) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::ALWAYS); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4807"), // NTF(Paris) authFactory->createCoordinateReferenceSystem("4171"), // RGF93 ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->nameStr(), "NTF (Paris) to RGF93 v1 (1)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=grad +xy_out=rad " "+step +inv +proj=longlat +ellps=clrk80ign +pm=paris " "+step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign " "+step +proj=xyzgridshift +grids=fr_ign_gr3df97a.tif " "+grid_ref=output_crs +ellps=GRS80 " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(list[1]->nameStr(), "NTF (Paris) to RGF93 v1 (2)"); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv " "+proj=longlat +ellps=clrk80ign +pm=paris +step +proj=hgridshift " "+grids=fr_ign_ntf_r93.tif +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_TRUE(nn_dynamic_pointer_cast<ConcatenatedOperation>(list[0]) != nullptr); auto grids = list[0]->gridsNeeded(DatabaseContext::create(), false); EXPECT_EQ(grids.size(), 1U); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_concatenated_operation_Egypt1907_to_WGS84) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4229"), // Egypt 1907 authFactory->createCoordinateReferenceSystem("4326"), // WGS84 ctxt); ASSERT_EQ(list.size(), 3U); // Concatenated operation EXPECT_EQ(list[1]->nameStr(), "Egypt 1907 to WGS 84 (2)"); ASSERT_EQ(list[1]->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(list[1]->coordinateOperationAccuracies()[0]->value(), "6.0"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_ED50_to_WGS72_no_NTF_intermediate) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4230"), // ED50 authFactory->createCoordinateReferenceSystem("4322"), // WGS 72 ctxt); ASSERT_GE(list.size(), 2U); // We should not use the ancient NTF as an intermediate when looking for // ED50 -> WGS 72 operations. for (const auto &op : list) { EXPECT_TRUE(op->nameStr().find("NTF") == std::string::npos) << op->nameStr(); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_same_grid_name) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4314"), // DHDN authFactory->createCoordinateReferenceSystem("4258"), // ETRS89 ctxt); ASSERT_TRUE(!list.empty()); EXPECT_EQ(list[0]->nameStr(), "DHDN to ETRS89 (8)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=hgridshift " "+grids=de_adv_BETA2007.tif +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_geographic_offset_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4120"), // NTF(Paris) authFactory->createCoordinateReferenceSystem("4121"), // NTF ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Greek to GGRS87 (1)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=geogoffset " "+dlat=-5.86 +dlon=0.28 +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_CH1903_to_CH1903plus_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::ALWAYS); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4149"), // CH1903 authFactory->createCoordinateReferenceSystem("4150"), // CH1903+ ctxt); ASSERT_TRUE(list.size() == 1U); EXPECT_EQ(list[0]->nameStr(), "CH1903 to CH1903+ (1)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=ch_swisstopo_CHENyx06a.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_init_IGNF_to_init_IGNF_context) { auto dbContext = DatabaseContext::create(); auto sourceCRS_obj = PROJStringParser() .attachDatabaseContext(dbContext) .setUsePROJ4InitRules(true) .createFromPROJString("+init=IGNF:NTFG"); auto sourceCRS = nn_dynamic_pointer_cast<CRS>(sourceCRS_obj); ASSERT_TRUE(sourceCRS != nullptr); auto targetCRS_obj = PROJStringParser() .attachDatabaseContext(dbContext) .setUsePROJ4InitRules(true) .createFromPROJString("+init=IGNF:RGF93G"); auto targetCRS = nn_dynamic_pointer_cast<CRS>(targetCRS_obj); ASSERT_TRUE(targetCRS != nullptr); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( NN_CHECK_ASSERT(sourceCRS), NN_CHECK_ASSERT(targetCRS), ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->nameStr(), "NOUVELLE TRIANGULATION DE LA FRANCE (NTF) vers RGF93 (ETRS89)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=fr_ign_ntf_r93.tif +step " "+proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_context_deprecated) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem( "4226"), // Cote d'Ivoire (deprecated) authFactory->createCoordinateReferenceSystem("4258"), // ETRS89 ctxt); ASSERT_TRUE(!list.empty()); EXPECT_EQ(list[0]->nameStr(), "Ballpark geographic offset from Cote d'Ivoire to ETRS89"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_3D) { auto geogcrs_m_obj = PROJStringParser().createFromPROJString( "+proj=longlat +vunits=m +type=crs"); auto geogcrs_m = nn_dynamic_pointer_cast<CRS>(geogcrs_m_obj); ASSERT_TRUE(geogcrs_m != nullptr); auto geogcrs_ft_obj = PROJStringParser().createFromPROJString( "+proj=longlat +vunits=ft +type=crs"); auto geogcrs_ft = nn_dynamic_pointer_cast<CRS>(geogcrs_ft_obj); ASSERT_TRUE(geogcrs_ft != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(geogcrs_m), NN_CHECK_ASSERT(geogcrs_ft)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +z_in=m +z_out=ft"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(geogcrs_ft), NN_CHECK_ASSERT(geogcrs_m)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +z_in=ft +z_out=m"); } auto geogcrs_m_with_pm_obj = PROJStringParser().createFromPROJString( "+proj=longlat +pm=paris +vunits=m +type=crs"); auto geogcrs_m_with_pm = nn_dynamic_pointer_cast<CRS>(geogcrs_m_with_pm_obj); ASSERT_TRUE(geogcrs_m_with_pm != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(geogcrs_m_with_pm), NN_CHECK_ASSERT(geogcrs_ft)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +z_in=m " "+xy_out=rad +z_out=m +step +inv +proj=longlat +ellps=WGS84 " "+pm=paris +step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=ft"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_3D_lat_long_non_metre_to_geogCRS_longlat) { auto wkt = "GEOGCRS[\"my CRS\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563],\n" " ID[\"EPSG\",6326]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " LENGTHUNIT[\"my_vunit\",0.3]]]"; auto srcCRS_obj = WKTParser().createFromWKT(wkt); auto srcCRS = nn_dynamic_pointer_cast<CRS>(srcCRS_obj); ASSERT_TRUE(srcCRS != nullptr); auto dstCRS_obj = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +type=crs"); auto dstCRS = nn_dynamic_pointer_cast<CRS>(dstCRS_obj); ASSERT_TRUE(dstCRS != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(srcCRS), NN_CHECK_ASSERT(dstCRS)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +z_in=0.3 +z_out=m"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_without_id_to_geogCRS_3D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto src = authFactory->createCoordinateReferenceSystem("4289"); // Amersfoort auto dst = authFactory->createCoordinateReferenceSystem("4937"); // ETRS89 3D auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_GE(list.size(), 1U); auto wkt2 = "GEOGCRS[\"unnamed\",\n" " DATUM[\"Amersfoort\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]," " USAGE[\n" " SCOPE[\"unknown\"],\n" " AREA[\"Netherlands - onshore\"],\n" " BBOX[50.75,3.2,53.7,7.22]]]\n"; auto obj = WKTParser().createFromWKT(wkt2); auto src_from_wkt2 = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(src_from_wkt2 != nullptr); auto list2 = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src_from_wkt2), dst, ctxt); ASSERT_GE(list.size(), list2.size()); for (size_t i = 0; i < list.size(); i++) { const auto &op = list[i]; const auto &op2 = list2[i]; EXPECT_TRUE( op->isEquivalentTo(op2.get(), IComparable::Criterion::EQUIVALENT)) << op->nameStr() << " " << op2->nameStr(); } } // --------------------------------------------------------------------------- static GeodeticCRSNNPtr createGeocentricDatumWGS84() { PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 4328) .set(IdentifiedObject::NAME_KEY, "WGS 84"); return GeodeticCRS::create( propertiesCRS, GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- static GeodeticCRSNNPtr createGeocentricKM() { PropertyMap propertiesCRS; propertiesCRS.set(IdentifiedObject::NAME_KEY, "Based on WGS 84"); return GeodeticCRS::create( propertiesCRS, GeodeticReferenceFrame::EPSG_6326, CartesianCS::createGeocentric( UnitOfMeasure("kilometre", 1000.0, UnitOfMeasure::Type::LINEAR))); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geogCRS_same_datum) { auto op = CoordinateOperationFactory::create()->createOperation( createGeocentricDatumWGS84(), GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=cart +ellps=WGS84 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geogCRS_different_datum) { auto op = CoordinateOperationFactory::create()->createOperation( createGeocentricDatumWGS84(), GeographicCRS::EPSG_4269); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->nameStr(), "Conversion from WGS 84 to WGS 84 (geographic) + " "Ballpark geographic offset from WGS 84 (geographic) to NAD83"); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geocentricCRS_different_datum) { auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4269, createGeocentricDatumWGS84()); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->nameStr(), "Ballpark geographic offset from NAD83 to WGS 84 (geographic) + " "Conversion from WGS 84 (geographic) to WGS 84"); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geocentricCRS_same_noop) { auto op = CoordinateOperationFactory::create()->createOperation( createGeocentricDatumWGS84(), createGeocentricDatumWGS84()); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->nameStr(), "Null geocentric translation from WGS 84 to WGS 84"); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); EXPECT_EQ(op->inverse()->nameStr(), op->nameStr()); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geocentricCRS_different_ballpark) { PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 4328) .set(IdentifiedObject::NAME_KEY, "unknown"); auto otherGeocentricCRS = GeodeticCRS::create( propertiesCRS, GeodeticReferenceFrame::EPSG_6269, CartesianCS::createGeocentric(UnitOfMeasure::METRE)); auto op = CoordinateOperationFactory::create()->createOperation( createGeocentricKM(), otherGeocentricCRS); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->nameStr(), "Ballpark geocentric translation from Based on WGS 84 to unknown"); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +xy_in=km +z_in=km +xy_out=m +z_out=m"); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geogCRS_same_datum_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4326"), // WGS84 geocentric authFactory->createCoordinateReferenceSystem("4978"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Conversion from WGS 84 (geog2D) to WGS 84 (geocentric)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=cart " "+ellps=WGS84"); EXPECT_EQ(list[0]->inverse()->nameStr(), "Conversion from WGS 84 (geocentric) to WGS 84 (geog2D)"); EXPECT_EQ(list[0]->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=cart +ellps=WGS84 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geogCRS_same_datum_context_all_auth) { // This is to check we don't use OGC:CRS84 as a pivot auto authFactoryEPSG = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto authFactoryAll = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactoryAll, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactoryEPSG->createCoordinateReferenceSystem("4326"), // WGS84 geocentric authFactoryEPSG->createCoordinateReferenceSystem("4978"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Conversion from WGS 84 (geog2D) to WGS 84 (geocentric)"); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geocentricCRS_different_datum_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // ITRF2000 (geocentric) authFactory->createCoordinateReferenceSystem("4919"), // ITRF2005 (geocentric) authFactory->createCoordinateReferenceSystem("4896"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "ITRF2000 to ITRF2005 (1)"); EXPECT_PRED_FORMAT2( ComparePROJString, list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=helmert +x=-0.0001 " "+y=0.0008 +z=0.0058 +rx=0 +ry=0 +rz=0 +s=-0.0004 +dx=0.0002 " "+dy=-0.0001 +dz=0.0018 +drx=0 +dry=0 +drz=0 +ds=-8e-05 " "+t_epoch=2000 +convention=position_vector"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_geocentricCRS_same_datum_to_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // WGS84 geocentric authFactory->createCoordinateReferenceSystem("4978"), authFactory->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Conversion from WGS 84 (geocentric) to WGS 84 (geog2D)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=cart +ellps=WGS84 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geog2D_to_geog3D_same_datum_but_with_potential_other_pivot_context) { // Check that when going from geog2D to geog3D of same datum, we don't // try to go through a WGS84 pivot... auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("5365"), // CR 05 2D authFactory->createCoordinateReferenceSystem("5364"), // CR 05 3D ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_different_datum_though_geocentric_transform_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // ITRF2000 (geog3D) authFactory->createCoordinateReferenceSystem("7909"), // ITRF2005 (geog3D) authFactory->createCoordinateReferenceSystem("7910"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Conversion from ITRF2000 (geog3D) to ITRF2000 (geocentric) + " "ITRF2000 to ITRF2005 (1) + " "Conversion from ITRF2005 (geocentric) to ITRF2005 (geog3D)"); EXPECT_PRED_FORMAT2( ComparePROJString, list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 +step +proj=helmert +x=-0.0001 " "+y=0.0008 +z=0.0058 +rx=0 +ry=0 +rz=0 +s=-0.0004 +dx=0.0002 " "+dy=-0.0001 +dz=0.0018 +drx=0 +dry=0 +drz=0 +ds=-8e-05 " "+t_epoch=2000 +convention=position_vector +step +inv " "+proj=cart +ellps=GRS80 +step +proj=unitconvert +xy_in=rad " "+z_in=m +xy_out=deg +z_out=m +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geocentricCRS_different_datum_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // ITRF2000 (geog3D) authFactory->createCoordinateReferenceSystem("7909"), // ITRF2005 (geocentric) authFactory->createCoordinateReferenceSystem("4896"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Conversion from ITRF2000 (geog3D) to ITRF2000 (geocentric) + " "ITRF2000 to ITRF2005 (1)"); EXPECT_PRED_FORMAT2( ComparePROJString, list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 +step +proj=helmert +x=-0.0001 " "+y=0.0008 +z=0.0058 +rx=0 +ry=0 +rz=0 +s=-0.0004 +dx=0.0002 " "+dy=-0.0001 +dz=0.0018 +drx=0 +dry=0 +drz=0 +ds=-8e-05 " "+t_epoch=2000 +convention=position_vector"); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_geogCRS_different_datum_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // ITRF2000 (geocentric) authFactory->createCoordinateReferenceSystem("4919"), // ITRF2005 (geog3D) authFactory->createCoordinateReferenceSystem("7910"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "ITRF2000 to ITRF2005 (1) + " "Conversion from ITRF2005 (geocentric) to ITRF2005 (geog3D)"); EXPECT_PRED_FORMAT2( ComparePROJString, list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=helmert +x=-0.0001 " "+y=0.0008 +z=0.0058 +rx=0 +ry=0 +rz=0 +s=-0.0004 +dx=0.0002 " "+dy=-0.0001 +dz=0.0018 +drx=0 +dry=0 +drz=0 +ds=-8e-05 " "+t_epoch=2000 +convention=position_vector +step +inv " "+proj=cart +ellps=GRS80 +step +proj=unitconvert +xy_in=rad " "+z_in=m +xy_out=deg +z_out=m +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_3D_to_geogCRS_3D_different_datum_context) { // Test for https://github.com/OSGeo/PROJ/issues/2541 auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // RGF93 (3D) authFactory->createCoordinateReferenceSystem("4965"), // CH1903+ promoted to 3D authFactory->createCoordinateReferenceSystem("4150")->promoteTo3D( std::string(), dbContext), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "RGF93 v1 to ETRS89 (1) + Inverse of CH1903+ to ETRS89 (1)"); // Check that there is no +push +v_3 EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=-674.374 +y=-15.056 +z=-405.346 " "+step +inv +proj=cart +ellps=bessel " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(list[0]->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=674.374 +y=15.056 +z=405.346 " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geocentric_to_geogCRS_3D_different_datum_context) { // Test variant of https://github.com/OSGeo/PROJ/issues/2541 auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // RGF93 (geocentric) authFactory->createCoordinateReferenceSystem("4964"), // CH1903+ promoted to 3D authFactory->createCoordinateReferenceSystem("4150")->promoteTo3D( std::string(), dbContext), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Conversion from RGF93 v1 (geocentric) to RGF93 v1 (geog3D) + " "RGF93 v1 to ETRS89 (1) + " "Inverse of CH1903+ to ETRS89 (1)"); // Check that there is no +push +v_3 EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=helmert +x=-674.374 +y=-15.056 +z=-405.346 " "+step +inv +proj=cart +ellps=bessel " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(list[0]->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=674.374 +y=15.056 +z=405.346"); } // --------------------------------------------------------------------------- TEST(operation, createBetweenGeodeticCRSWithDatumBasedIntermediates) { auto dbContext = DatabaseContext::create(); auto authFactoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactoryEPSG, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // IG05/12 Intermediate CRS authFactoryEPSG->createCoordinateReferenceSystem("6990"), // ITRF2014 authFactoryEPSG->createCoordinateReferenceSystem("9000"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of ITRF2008 to IG05/12 Intermediate CRS + " "Conversion from ITRF2008 (geog2D) to ITRF2008 (geocentric) + " "ITRF2008 to ITRF2014 (1) + " "Conversion from ITRF2014 (geocentric) to ITRF2014 (geog2D)"); auto listInv = CoordinateOperationFactory::create()->createOperations( // ITRF2014 authFactoryEPSG->createCoordinateReferenceSystem("9000"), // IG05/12 Intermediate CRS authFactoryEPSG->createCoordinateReferenceSystem("6990"), ctxt); ASSERT_EQ(listInv.size(), 1U); EXPECT_EQ(listInv[0]->nameStr(), "Conversion from ITRF2014 (geog2D) to ITRF2014 (geocentric) + " "Inverse of ITRF2008 to ITRF2014 (1) + " "Conversion from ITRF2008 (geocentric) to ITRF2008 (geog2D) + " "ITRF2008 to IG05/12 Intermediate CRS"); } // --------------------------------------------------------------------------- TEST(operation, esri_projectedCRS_to_geogCRS_with_ITRF_intermediate_context) { auto dbContext = DatabaseContext::create(); auto authFactoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); auto authFactoryESRI = AuthorityFactory::create(dbContext, "ESRI"); auto ctxt = CoordinateOperationContext::create(authFactoryEPSG, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // NAD_1983_CORS96_StatePlane_North_Carolina_FIPS_3200_Ft_US (projected) authFactoryESRI->createCoordinateReferenceSystem("103501"), // ITRF2005 (geog3D) authFactoryEPSG->createCoordinateReferenceSystem("7910"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of NAD_1983_CORS96_StatePlane_North_Carolina_" "FIPS_3200_Ft_US + " "Conversion from NAD83(CORS96) (geog2D) to NAD83(CORS96) " "(geocentric) + Inverse of ITRF2000 to NAD83(CORS96) (1) + " "ITRF2000 to ITRF2005 (1) + " "Conversion from ITRF2005 (geocentric) to ITRF2005 (geog3D)"); EXPECT_PRED_FORMAT2( ComparePROJString, list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=us-ft " "+xy_out=m +step +inv +proj=lcc +lat_0=33.75 +lon_0=-79 " "+lat_1=34.3333333333333 +lat_2=36.1666666666667 " "+x_0=609601.219202438 +y_0=0 +ellps=GRS80 +step +proj=cart " "+ellps=GRS80 +step +inv +proj=helmert +x=0.9956 +y=-1.9013 " "+z=-0.5215 +rx=0.025915 +ry=0.009426 +rz=0.011599 +s=0.00062 " "+dx=0.0007 +dy=-0.0007 +dz=0.0005 +drx=6.7e-05 +dry=-0.000757 " "+drz=-5.1e-05 +ds=-0.00018 +t_epoch=1997 " "+convention=coordinate_frame +step +proj=helmert +x=-0.0001 " "+y=0.0008 +z=0.0058 +rx=0 +ry=0 +rz=0 +s=-0.0004 +dx=0.0002 " "+dy=-0.0001 +dz=0.0018 +drx=0 +dry=0 +drz=0 +ds=-8e-05 " "+t_epoch=2000 +convention=position_vector +step +inv +proj=cart " "+ellps=GRS80 +step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=m +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_WGS84_to_GDA2020) { // 2D reduction of use case of https://github.com/OSGeo/PROJ/issues/2348 auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); { auto list = CoordinateOperationFactory::create()->createOperations( // GDA2020 authFactory->createCoordinateReferenceSystem("7844"), // WGS 84 authFactory->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "GDA2020 to WGS 84 (2)"); } // Inverse { auto list = CoordinateOperationFactory::create()->createOperations( // WGS 84 authFactory->createCoordinateReferenceSystem("4326"), // GDA2020 authFactory->createCoordinateReferenceSystem("7844"), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of GDA2020 to WGS 84 (2)"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_geogCRS_with_intermediate_no_ids) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto objSrc = WKTParser().createFromWKT( "GEOGCRS[\"input\",\n" " DATUM[\"International Terrestrial Reference Frame 2014\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",1165]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]]]"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = WKTParser().createFromWKT( "GEOGCRS[\"output\",\n" " DATUM[\"Estonia 1997\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6180]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]]]"); auto dest = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dest != nullptr); { auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dest), ctxt); ASSERT_GE(list.size(), 1U); // Test that a non-noop operation is returned EXPECT_EQ( list[0]->nameStr(), "axis order change (geographic3D horizontal) + " "Conversion from ITRF2014 (geog3D) to ITRF2014 (geocentric) + " "ITRF2014 to ETRF2014 (1) + " "Inverse of NKG_ETRF14 to ETRF2014 + " "NKG_ETRF14 to [email protected] + " "[email protected] to [email protected] + " "Conversion from ETRS89 (geocentric) to ETRS89 (geog2D) + " "Inverse of EST97 to ETRS89 (1) + " "Null geographic offset from EST97 (geog2D) to EST97 (geog3D) + " "axis order change (geographic3D horizontal)"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_3D_source_datum_name_is_alias_to_geogCRS) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto objSrc = WKTParser().createFromWKT( "GEOGCRS[\"something\",\n" " DATUM[\"WGS84\",\n" " ELLIPSOID[\"WGS84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"Meter\",1,\n" " ID[\"EPSG\",9001]]]]"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), authFactory->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); EXPECT_EQ(list[0]->nameStr(), "Null geographic offset from something to WGS 84"); } // --------------------------------------------------------------------------- static ProjectedCRSNNPtr createUTM31_WGS84() { return ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- static ProjectedCRSNNPtr createUTM32_WGS84() { return ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 32, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_projCRS) { auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, createUTM31_WGS84()); ASSERT_TRUE(op != nullptr); EXPECT_TRUE(std::dynamic_pointer_cast<Conversion>(op) != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=utm " "+zone=31 +ellps=WGS84"); PJ_CONTEXT *ctx = proj_context_create(); auto transformer = op->coordinateTransformer(ctx); PJ_COORD c; c.v[0] = 49; c.v[1] = 2; c.v[2] = 0; c.v[3] = HUGE_VAL; c = transformer->transform(c); EXPECT_NEAR(c.v[0], 426857.98771728, 1e-8); EXPECT_NEAR(c.v[1], 5427937.52346492, 1e-8); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_longlat_to_geogCS_latlong) { auto sourceCRS = GeographicCRS::OGC_CRS84; auto targetCRS = GeographicCRS::EPSG_4326; auto op = CoordinateOperationFactory::create()->createOperation(sourceCRS, targetCRS); ASSERT_TRUE(op != nullptr); auto conv = std::dynamic_pointer_cast<Conversion>(op); ASSERT_TRUE(conv != nullptr); EXPECT_TRUE(op->sourceCRS() && op->sourceCRS()->isEquivalentTo(sourceCRS.get())); EXPECT_TRUE(op->targetCRS() && op->targetCRS()->isEquivalentTo(targetCRS.get())); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=2,1"); auto convInverse = nn_dynamic_pointer_cast<Conversion>(conv->inverse()); ASSERT_TRUE(convInverse != nullptr); EXPECT_TRUE(convInverse->sourceCRS() && convInverse->sourceCRS()->isEquivalentTo(targetCRS.get())); EXPECT_TRUE(convInverse->targetCRS() && convInverse->targetCRS()->isEquivalentTo(sourceCRS.get())); EXPECT_EQ(conv->method()->exportToWKT(WKTFormatter::create().get()), convInverse->method()->exportToWKT(WKTFormatter::create().get())); EXPECT_TRUE(conv->method()->isEquivalentTo(convInverse->method().get())); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_longlat_to_geogCS_latlong_database) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( AuthorityFactory::create(DatabaseContext::create(), "OGC") ->createCoordinateReferenceSystem("CRS84"), AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_longlat_to_projCRS) { auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::OGC_CRS84, createUTM31_WGS84()); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=utm +zone=31 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_different_from_baseCRS_to_projCRS) { auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4807, createUTM31_WGS84()); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv +proj=longlat " "+ellps=clrk80ign +pm=paris +step +proj=utm +zone=31 " "+ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_with_towgs84_to_geocentric) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto objSrc = WKTParser().createFromWKT( "GEOGCS[\"WGS84 Coordinate System\",DATUM[\"WGS_1984\"," "SPHEROID[\"WGS 1984\",6378137,298.257223563]," "TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]," "AXIS[\"Latitude\",NORTH],AXIS[\"Longitude\",EAST]," "AUTHORITY[\"EPSG\",\"4326\"]]"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto src3D = src->promoteTo3D(std::string(), dbContext); auto objDst = WKTParser().createFromWKT( "GEOCCS[\"WGS 84\",DATUM[\"WGS_1984\"," "SPHEROID[\"WGS 84\",6378137,298.257223563," "AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]]," "AXIS[\"Geocentric X\",OTHER],AXIS[\"Geocentric Y\",OTHER]," "AXIS[\"Geocentric Z\",NORTH],AUTHORITY[\"EPSG\",\"4978\"]]"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); { auto list = CoordinateOperationFactory::create()->createOperations( src3D, NN_NO_CHECK(dst), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m " "+xy_out=rad +z_out=m " "+step +proj=cart +ellps=WGS84"); } { auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(dst), src3D, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } } // --------------------------------------------------------------------------- TEST(operation, geogCRS_different_from_baseCRS_to_projCRS_context_compatible_area) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::ALWAYS); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4807"), // NTF(Paris) authFactory->createCoordinateReferenceSystem("32631"), // UTM31 WGS84 ctxt); ASSERT_EQ(list.size(), 4U); EXPECT_EQ( list[0]->nameStr(), "NTF (Paris) to NTF (1) + Inverse of WGS 84 to NTF (3) + UTM zone 31N"); ASSERT_EQ(list[0]->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(list[0]->coordinateOperationAccuracies()[0]->value(), "1"); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv " "+proj=longlat +ellps=clrk80ign +pm=paris +step +proj=hgridshift " "+grids=fr_ign_ntf_r93.tif +step +proj=utm +zone=31 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, geocentricCRS_to_projCRS) { auto op = CoordinateOperationFactory::create()->createOperation( createGeocentricDatumWGS84(), createUTM31_WGS84()); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=cart +ellps=WGS84 +step " "+proj=utm +zone=31 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_geogCRS) { auto op = CoordinateOperationFactory::create()->createOperation( createUTM31_WGS84(), GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=31 +ellps=WGS84 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_no_id_to_geogCRS_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto src = authFactory->createCoordinateReferenceSystem( "28992"); // Amersfoort / RD New auto dst = authFactory->createCoordinateReferenceSystem("4258"); // ETRS89 2D auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_GE(list.size(), 1U); auto wkt2 = "PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"Amersfoort\",\n" " DATUM[\"Amersfoort\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Oblique Stereographic\"],\n" " PARAMETER[\"Latitude of natural origin\",52.1561605555556],\n" " PARAMETER[\"Longitude of natural origin\",5.38763888888889],\n" " PARAMETER[\"Scale factor at natural origin\",0.9999079],\n" " PARAMETER[\"False easting\",155000],\n" " PARAMETER[\"False northing\",463000]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",28992]]"; auto obj = WKTParser().createFromWKT(wkt2); auto src_from_wkt2 = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(src_from_wkt2 != nullptr); auto list2 = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src_from_wkt2), dst, ctxt); ASSERT_GE(list.size(), list2.size() - 1); for (size_t i = 0; i < list.size(); i++) { const auto &op = list[i]; const auto &op2 = list2[i]; EXPECT_TRUE( op->isEquivalentTo(op2.get(), IComparable::Criterion::EQUIVALENT)); } } // --------------------------------------------------------------------------- TEST(operation, projCRS_3D_to_geogCRS_3D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto wkt = "PROJCRS[\"NAD83(HARN) / Oregon GIC Lambert (ft)\",\n" " BASEGEOGCRS[\"NAD83(HARN)\",\n" " DATUM[\"NAD83 (High Accuracy Reference Network)\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4957]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Lambert Conic Conformal (2SP)\",\n" " ID[\"EPSG\",9802]],\n" " PARAMETER[\"Latitude of false origin\",41.75,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",-120.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",43,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\",45.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",1312335.958,\n" " LENGTHUNIT[\"foot\",0.3048],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",0,\n" " LENGTHUNIT[\"foot\",0.3048],\n" " ID[\"EPSG\",8827]]],\n" " CS[Cartesian,3],\n" " AXIS[\"easting\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"foot\",0.3048]],\n" " AXIS[\"northing\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"foot\",0.3048]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"foot\",0.3048]]]"; auto obj = WKTParser().createFromWKT(wkt); auto src = NN_CHECK_ASSERT(nn_dynamic_pointer_cast<CRS>(obj)); auto dst = authFactory->createCoordinateReferenceSystem( "4957"); // NAD83(HARN) (3D) auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " // Check that z ft->m conversion is done (and just once) "+step +proj=unitconvert +xy_in=ft +z_in=ft +xy_out=m +z_out=m " "+step +inv +proj=lcc +lat_0=41.75 +lon_0=-120.5 +lat_1=43 " "+lat_2=45.5 +x_0=399999.9999984 +y_0=0 +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_3D_to_projCRS_2D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto wkt = "PROJCRS[\"Projected 3d CRS\",\n" " BASEGEOGCRS[\"JGD2000\",\n" " DATUM[\"Japanese Geodetic Datum 2000\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4947]],\n" // the code is what triggered the bug " CONVERSION[\"Japan Plane Rectangular CS zone VII\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",36,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",137.166666666667,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",17807]],\n" " CS[Cartesian,3],\n" " AXIS[\"northing (X)\",north,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"easting (Y)\",east,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto src = NN_CHECK_ASSERT(nn_dynamic_pointer_cast<CRS>(obj)); auto dst = authFactory->createCoordinateReferenceSystem("32653"); // WGS 84 UTM 53 // We just want to check that we don't get inconsistent chaining exception auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_GE(list.size(), 1U); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_3D_to_projCRS_with_2D_geocentric_translation) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto src = authFactory->createCoordinateReferenceSystem("4979"); // WGS 84 3D // Azores Central 1948 / UTM zone 26N auto dst = authFactory->createCoordinateReferenceSystem("2189"); auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=push +v_3 " // this is what we check. Due to the // target system being 2D only "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=104 +y=-167 +z=38 " "+step +inv +proj=cart +ellps=intl " "+step +proj=pop +v_3 " // this is what we check "+step +proj=utm +zone=26 +ellps=intl"); auto listReverse = CoordinateOperationFactory::create()->createOperations(dst, src, ctxt); ASSERT_GE(listReverse.size(), 1U); EXPECT_EQ( listReverse[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=26 +ellps=intl " "+step +proj=push +v_3 " // this is what we check "+step +proj=cart +ellps=intl " "+step +proj=helmert +x=-104 +y=167 +z=-38 " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " // this is what we check "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS) { auto op = CoordinateOperationFactory::create()->createOperation( createUTM31_WGS84(), createUTM32_WGS84()); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=31 +ellps=WGS84 +step " "+proj=utm +zone=32 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_different_baseCRS) { auto utm32 = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4807, Conversion::createUTM(PropertyMap(), 32, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto op = CoordinateOperationFactory::create()->createOperation( createUTM31_WGS84(), utm32); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=31 +ellps=WGS84 +step " "+proj=utm +zone=32 +ellps=clrk80ign +pm=paris"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_context_compatible_area) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("32634"), // UTM 34 authFactory->createCoordinateReferenceSystem( "2171"), // Pulkovo 42 Poland I ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->nameStr(), "Inverse of UTM zone 34N + Inverse of Pulkovo 1942(58) to WGS 84 " "(1) + Poland zone I"); ASSERT_EQ(list[0]->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(list[0]->coordinateOperationAccuracies()[0]->value(), "1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_context_compatible_area_bis) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem( "3844"), // Pulkovo 42 Stereo 70 (Romania) authFactory->createCoordinateReferenceSystem("32634"), // UTM 34 ctxt); ASSERT_EQ(list.size(), 3U); EXPECT_EQ(list[0]->nameStr(), "Inverse of Stereo 70 + " "Pulkovo 1942(58) to WGS 84 " "(19) + UTM zone 34N"); ASSERT_EQ(list[0]->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(list[0]->coordinateOperationAccuracies()[0]->value(), "3"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_context_one_incompatible_area) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("32631"), // UTM 31 authFactory->createCoordinateReferenceSystem( "2171"), // Pulkovo 42 Poland I ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->nameStr(), "Inverse of UTM zone 31N + Inverse of Pulkovo 1942(58) to WGS 84 " "(1) + Poland zone I"); ASSERT_EQ(list[0]->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(list[0]->coordinateOperationAccuracies()[0]->value(), "1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_context_incompatible_areas) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("32631"), // UTM 31 authFactory->createCoordinateReferenceSystem("32633"), // UTM 33 ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of UTM zone 31N + UTM zone 33N"); ASSERT_EQ(list[0]->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(list[0]->coordinateOperationAccuracies()[0]->value(), "0"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_context_incompatible_areas_ballpark) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("26711"), // UTM 11 NAD27 authFactory->createCoordinateReferenceSystem( "3034"), // ETRS89 / LCC Europe ctxt); ASSERT_GE(list.size(), 1U); EXPECT_TRUE(list[0]->hasBallparkTransformation()); } // --------------------------------------------------------------------------- TEST( operation, projCRS_to_projCRS_context_incompatible_areas_crs_extent_use_intersection) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSourceAndTargetCRSExtentUse( CoordinateOperationContext::SourceTargetCRSExtentUse::INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("26711"), // UTM 11 NAD27 authFactory->createCoordinateReferenceSystem( "3034"), // ETRS89 / LCC Europe ctxt); ASSERT_GE(list.size(), 0U); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_geogCRS_crs_extent_use_none) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("23031"), // ED50 UTM31 authFactory->createCoordinateReferenceSystem("4326"), ctxt); bool found_EPSG_15964 = false; for (const auto &op : list) { if (op->nameStr().find("ED50 to WGS 84 (42)") != std::string::npos) { found_EPSG_15964 = true; } } // not expected since doesn't intersect EPSG:23031 area of use EXPECT_FALSE(found_EPSG_15964); } { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); // Ignore source and target CRS extent ctxt->setSourceAndTargetCRSExtentUse( CoordinateOperationContext::SourceTargetCRSExtentUse::NONE); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("23031"), // ED50 UTM31 authFactory->createCoordinateReferenceSystem("4326"), ctxt); bool found_EPSG_15964 = false; for (const auto &op : list) { if (op->nameStr().find("ED50 to WGS 84 (42)") != std::string::npos) { found_EPSG_15964 = true; } } EXPECT_TRUE(found_EPSG_15964); } } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_north_pole_inverted_axis) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createCoordinateReferenceSystem("32661"), AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createCoordinateReferenceSystem("5041"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_south_pole_inverted_axis) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createCoordinateReferenceSystem("32761"), AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createCoordinateReferenceSystem("5042"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_to_projCRS_through_geog3D) { // Check that when going from projCRS to projCRS, using // geog2D-->geog3D-->geog3D-->geog2D we do not have issues with // inconsistent CRS chaining, due to how we 'hack' a bit some intermediate // steps auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("5367"), // CR05 / CRTM05 authFactory->createCoordinateReferenceSystem( "8908"), // CR-SIRGAS / CRTM05 ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +inv +proj=tmerc +lat_0=0 +lon_0=-84 +k=0.9999 " "+x_0=500000 +y_0=0 +ellps=WGS84 " "+step +proj=push +v_3 " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=-0.16959 +y=0.35312 +z=0.51846 " "+rx=-0.03385 +ry=0.16325 +rz=-0.03446 +s=0.03693 " "+convention=coordinate_frame " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=pop +v_3 " "+step +proj=tmerc +lat_0=0 +lon_0=-84 +k=0.9999 +x_0=500000 " "+y_0=0 +ellps=GRS80"); } // --------------------------------------------------------------------------- TEST(operation, transform_from_amersfoort_rd_new_to_epsg_4326) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("28992"), authFactory->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 2U); // The order matters: "Amersfoort to WGS 84 (4)" replaces "Amersfoort to WGS // 84 (3)" EXPECT_EQ(list[0]->nameStr(), "Inverse of RD New + Amersfoort to WGS 84 (4)"); EXPECT_EQ(list[1]->nameStr(), "Inverse of RD New + Amersfoort to WGS 84 (3)"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_geogCRS_to_geogCRS) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto op = CoordinateOperationFactory::create()->createOperation( boundCRS, GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv " "+proj=longlat +ellps=clrk80ign +pm=paris +step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign +step +proj=helmert +x=1 +y=2 " "+z=3 +rx=4 +ry=5 +rz=6 +s=7 +convention=position_vector +step " "+inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_geogCRS_to_geodCRS) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto op = CoordinateOperationFactory::create()->createOperation( boundCRS, GeodeticCRS::EPSG_4978); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step " "+proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=grad +xy_out=rad " "+step +inv +proj=longlat +ellps=clrk80ign +pm=paris " "+step +proj=cart +ellps=clrk80ign " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 " "+convention=position_vector"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_geogCRS_to_geodCRS_not_related_to_hub) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( boundCRS, // ETRS89 geocentric authFactory->createCoordinateReferenceSystem("4936"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step " "+proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=grad +xy_out=rad " "+step +inv +proj=longlat +ellps=clrk80ign +pm=paris " "+step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 " "+convention=position_vector " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=pop +v_3 " "+step +proj=cart +ellps=GRS80"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_geogCRS_to_geogCRS_with_area) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4267, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto op = CoordinateOperationFactory::create()->createOperation( boundCRS, authFactory->createCoordinateReferenceSystem("4326")); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=clrk66 +step +proj=helmert +x=1 +y=2 " "+z=3 +rx=4 +ry=5 +rz=6 +s=7 +convention=position_vector +step " "+inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_geogCRS_to_unrelated_geogCRS) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto op = CoordinateOperationFactory::create()->createOperation( boundCRS, GeographicCRS::EPSG_4269); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), CoordinateOperationFactory::create() ->createOperation(GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4269) ->exportToPROJString(PROJStringFormatter::create().get())); } // --------------------------------------------------------------------------- TEST(operation, createOperation_boundCRS_identified_by_datum) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +type=crs"); auto src = nn_dynamic_pointer_cast<GeographicCRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=utm +zone=32 +a=6378249.2 +b=6356515 " "+towgs84=-263.0,6.0,431.0 +no_defs +type=crs"); auto dest = nn_dynamic_pointer_cast<BoundCRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=push +v_3 +step +proj=cart +ellps=WGS84 +step " "+proj=helmert +x=263 +y=-6 +z=-431 +step +inv +proj=cart " "+ellps=clrk80ign +step +proj=pop +v_3 +step +proj=utm +zone=32 " "+ellps=clrk80ign"); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_TRUE(list[0]->isEquivalentTo(op.get())); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_clrk_66_geogCRS_to_nad83_geogCRS) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=latlong +ellps=clrk66 +nadgrids=ntv1_can.dat,conus +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=latlong +datum=NAD83 +type=crs"); auto dest = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=ntv1_can.dat,conus " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_clrk_66_projCRS_to_nad83_geogCRS) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=17 +ellps=clrk66 +nadgrids=ntv1_can.dat,conus " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=latlong +datum=NAD83 +type=crs"); auto dest = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=17 +ellps=clrk66 " "+step +proj=hgridshift +grids=ntv1_can.dat,conus " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_projCRS_to_geogCRS) { auto utm31 = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4807, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto boundCRS = BoundCRS::createFromTOWGS84( utm31, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto op = CoordinateOperationFactory::create()->createOperation( boundCRS, GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=31 +ellps=clrk80ign " "+pm=paris +step +proj=push +v_3 +step +proj=cart " "+ellps=clrk80ign +step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 " "+rz=6 +s=7 +convention=position_vector +step +inv +proj=cart " "+ellps=WGS84 +step +proj=pop +v_3 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_geogCRS_to_projCRS) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto utm31 = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto op = CoordinateOperationFactory::create()->createOperation(boundCRS, utm31); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv " "+proj=longlat +ellps=clrk80ign +pm=paris +step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign +step +proj=helmert +x=1 +y=2 " "+z=3 +rx=4 +ry=5 +rz=6 +s=7 +convention=position_vector +step " "+inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 +step " "+proj=utm +zone=31 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_geogCRS_to_unrelated_geogCRS_context) { auto src = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // ETRS89 auto dst = authFactory->createCoordinateReferenceSystem("4258"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_EQ(list.size(), 1U); // Check with it is a concatenated operation, since it doesn't particularly // show up in the PROJ string EXPECT_TRUE(dynamic_cast<ConcatenatedOperation *>(list[0].get()) != nullptr); EXPECT_EQ(list[0]->nameStr(), "Transformation from NTF (Paris) to WGS84 + " "Inverse of ETRS89 to WGS 84 (1)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=grad +xy_out=rad " "+step +inv +proj=longlat +ellps=clrk80ign +pm=paris " "+step +proj=push +v_3 +step +proj=cart +ellps=clrk80ign " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 " "+convention=position_vector " "+step +inv +proj=cart +ellps=GRS80 +step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geogCRS_to_boundCRS_of_geogCRS) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, boundCRS); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 " "+step +proj=cart +ellps=WGS84 +step +inv +proj=helmert +x=1 " "+y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 +convention=position_vector " "+step +inv +proj=cart +ellps=clrk80ign +step +proj=pop +v_3 " "+step +proj=longlat +ellps=clrk80ign +pm=paris +step " "+proj=unitconvert +xy_in=rad +xy_out=grad +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_to_geogCRS_same_datum_context) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4269, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( boundCRS, GeographicCRS::EPSG_4269, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_to_geogCRS_hubCRS_and_targetCRS_same_but_baseCRS_not) { const char *wkt = "COMPD_CS[\"NAD83 + Ellipsoid (US Feet)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"Ellipsoid (US Feet)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Up\",UP]]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(boundCRS), GeographicCRS::EPSG_4979, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=deg +z_out=m"); } // --------------------------------------------------------------------------- TEST( operation, boundCRS_to_derived_geog_with_transformation_with_source_crs_being_base_crs_of_source_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"BoundCRS\",\n" " \"source_crs\": {\n" " \"type\": \"DerivedGeographicCRS\",\n" " \"name\": \"CH1903+ with height offset\",\n" " \"base_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"CH1903+\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"CH1903+\",\n" " \"ellipsoid\": {\n" " \"name\": \"Bessel 1841\",\n" " \"semi_major_axis\": 6377397.155,\n" " \"inverse_flattening\": 299.1528128\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"Ellipsoidal to gravity related height\",\n" " \"method\": {\n" " \"name\": \"Geographic3D offsets\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9660\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude offset\",\n" " \"value\": 0,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8601\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude offset\",\n" " \"value\": 0,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8602\n" " }\n" " },\n" " {\n" " \"name\": \"Vertical Offset\",\n" " \"value\": 10,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8603\n" " }\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"target_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum_ensemble\": {\n" " \"name\": \"World Geodetic System 1984 ensemble\",\n" " \"members\": [\n" " {\n" " \"name\": \"World Geodetic System 1984 (Transit)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1166\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G730)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1152\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G873)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1153\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1150)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1154\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1674)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1155\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1762)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1156\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G2139)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1309\n" " }\n" " }\n" " ],\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"accuracy\": \"2.0\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4979\n" " }\n" " },\n" " \"transformation\": {\n" " \"name\": \"CH1903+ to WGS 84 (1)\",\n" " \"source_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"CH1903+\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"CH1903+\",\n" " \"ellipsoid\": {\n" " \"name\": \"Bessel 1841\",\n" " \"semi_major_axis\": 6377397.155,\n" " \"inverse_flattening\": 299.1528128\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"method\": {\n" " \"name\": \"Geocentric translations (geog2D domain)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9603\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"X-axis translation\",\n" " \"value\": 674.374,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8605\n" " }\n" " },\n" " {\n" " \"name\": \"Y-axis translation\",\n" " \"value\": 15.056,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8606\n" " }\n" " },\n" " {\n" " \"name\": \"Z-axis translation\",\n" " \"value\": 405.346,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8607\n" " }\n" " }\n" " ],\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1676\n" " }\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(boundCRS), GeographicCRS::EPSG_4979, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +inv +proj=geogoffset +dlat=0 +dlon=0 +dh=10 " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=674.374 +y=15.056 +z=405.346 " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_to_boundCRS) { auto utm31 = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4807, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto utm32 = ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4269, Conversion::createUTM(PropertyMap(), 32, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto boundCRS1 = BoundCRS::createFromTOWGS84( utm31, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto boundCRS2 = BoundCRS::createFromTOWGS84( utm32, std::vector<double>{8, 9, 10, 11, 12, 13, 14}); auto op = CoordinateOperationFactory::create()->createOperation(boundCRS1, boundCRS2); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=31 +ellps=clrk80ign " "+pm=paris +step +proj=push +v_3 +step +proj=cart " "+ellps=clrk80ign +step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 " "+rz=6 +s=7 +convention=position_vector +step +inv +proj=helmert " "+x=8 +y=9 +z=10 +rx=11 +ry=12 +rz=13 +s=14 " "+convention=position_vector +step +inv +proj=cart +ellps=GRS80 " "+step +proj=pop +v_3 +step +proj=utm +zone=32 +ellps=GRS80"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_to_boundCRS_noop_for_TOWGS84) { auto boundCRS1 = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto boundCRS2 = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4269, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto op = CoordinateOperationFactory::create()->createOperation(boundCRS1, boundCRS2); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv " "+proj=longlat +ellps=clrk80ign +pm=paris +step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign +step +inv +proj=cart " "+ellps=GRS80 +step +proj=pop +v_3 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_to_boundCRS_unralated_hub) { auto boundCRS1 = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto boundCRS2 = BoundCRS::create( GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4979, Transformation::createGeocentricTranslations( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4979, 1.0, 2.0, 3.0, std::vector<PositionalAccuracyNNPtr>())); auto op = CoordinateOperationFactory::create()->createOperation(boundCRS1, boundCRS2); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), CoordinateOperationFactory::create() ->createOperation(boundCRS1->baseCRS(), boundCRS2->baseCRS()) ->exportToPROJString(PROJStringFormatter::create().get())); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_projCRS_towgs84_to_boundCRS_of_projCRS_nadgrids) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=15 +datum=NAD83 +units=m +no_defs +ellps=GRS80 " "+towgs84=0,0,0 +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=utm +zone=15 +datum=NAD27 +units=m +no_defs +ellps=clrk66 " "+nadgrids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=15 +ellps=GRS80 +step " "+inv +proj=hgridshift " "+grids=@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat +step +proj=utm " "+zone=15 +ellps=clrk66"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_of_projCRS_towgs84_non_metre_unit_to_geocentric) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=merc +ellps=GRS80 +towgs84=0,0,0 +units=ft +vunits=ft " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=geocent +datum=WGS84 +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=ft +z_in=ft +xy_out=m +z_out=m " "+step +inv +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=GRS80 " "+step +proj=cart +ellps=WGS84"); } // --------------------------------------------------------------------------- static CRSNNPtr buildCRSFromProjStrThroughWKT(const std::string &projStr) { auto crsFromProj = nn_dynamic_pointer_cast<CRS>( PROJStringParser().createFromPROJString(projStr)); if (crsFromProj == nullptr) { throw "crsFromProj == nullptr"; } auto crsFromWkt = nn_dynamic_pointer_cast<CRS>( WKTParser().createFromWKT(crsFromProj->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()))); if (crsFromWkt == nullptr) { throw "crsFromWkt == nullptr"; } return NN_NO_CHECK(crsFromWkt); } TEST(operation, boundCRS_to_boundCRS_with_base_geog_crs_different_from_source_of_transf) { auto src = buildCRSFromProjStrThroughWKT( "+proj=lcc +lat_1=49 +lat_0=49 +lon_0=0 +k_0=0.999877499 +x_0=600000 " "+y_0=200000 +ellps=clrk80ign +pm=paris +towgs84=-168,-60,320,0,0,0,0 " "+units=m +no_defs +type=crs"); auto dst = buildCRSFromProjStrThroughWKT( "+proj=longlat +ellps=clrk80ign +pm=paris " "+towgs84=-168,-60,320,0,0,0,0 +no_defs +type=crs"); auto op = CoordinateOperationFactory::create()->createOperation(src, dst); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=lcc +lat_1=49 +lat_0=49 +lon_0=0 " "+k_0=0.999877499 +x_0=600000 +y_0=200000 +ellps=clrk80ign " "+pm=paris " "+step +proj=longlat +ellps=clrk80ign +pm=paris " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_with_basecrs_with_extent_to_geogCRS) { auto wkt = "BOUNDCRS[\n" " SOURCECRS[\n" " PROJCRS[\"NAD83 / California zone 3 (ftUS)\",\n" " BASEGEODCRS[\"NAD83\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"SPCS83 California zone 3 (US Survey " "feet)\",\n" " METHOD[\"Lambert Conic Conformal (2SP)\",\n" " ID[\"EPSG\",9802]],\n" " PARAMETER[\"Latitude of false origin\",36.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",-120.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard parallel\"," " 38.4333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\"," " 37.0666666666667,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",6561666.667,\n" " LENGTHUNIT[\"US survey foot\"," " 0.304800609601219],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",1640416.667,\n" " LENGTHUNIT[\"US survey foot\"," " 0.304800609601219],\n" " ID[\"EPSG\",8827]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (X)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"US survey foot\"," " 0.304800609601219]],\n" " AXIS[\"northing (Y)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"US survey foot\"," " 0.304800609601219]],\n" " SCOPE[\"unknown\"],\n" " AREA[\"USA - California - SPCS - 3\"],\n" " BBOX[36.73,-123.02,38.71,-117.83],\n" " ID[\"EPSG\",2227]]],\n" " TARGETCRS[\n" " GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]]],\n" " ABRIDGEDTRANSFORMATION[\"NAD83 to WGS 84 (1)\",\n" " METHOD[\"Geocentric translations (geog2D domain)\",\n" " ID[\"EPSG\",9603]],\n" " PARAMETER[\"X-axis translation\",0,\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",0,\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",0,\n" " ID[\"EPSG\",8607]],\n" " SCOPE[\"unknown\"],\n" " AREA[\"North America - Canada and USA (CONUS, Alaska " "mainland)\"],\n" " BBOX[23.81,-172.54,86.46,-47.74],\n" " ID[\"EPSG\",1188]]]"; auto obj = WKTParser().createFromWKT(wkt); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(boundCRS), GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->nameStr(), "Inverse of SPCS83 California zone 3 (US Survey " "feet) + NAD83 to WGS 84 (1)"); } // --------------------------------------------------------------------------- TEST(operation, ETRS89_3D_to_proj_string_with_geoidgrids_nadgrids) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // ETRS89 3D auto src = authFactory->createCoordinateReferenceSystem("4937"); auto objDst = PROJStringParser().createFromPROJString( "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 " "+k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel " "+nadgrids=rdtrans2008.gsb +geoidgrids=naptrans2008.gtx " "+geoid_crs=horizontal_crs +units=m " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( src, NN_NO_CHECK(dst), ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +inv +proj=hgridshift +grids=rdtrans2008.gsb " "+step +inv +proj=vgridshift +grids=naptrans2008.gtx " "+multiplier=1 " "+step +proj=sterea +lat_0=52.1561605555556 " "+lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 " "+y_0=463000 +ellps=bessel"); } // --------------------------------------------------------------------------- TEST(operation, nadgrids_with_pm) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto objSrc = PROJStringParser().createFromPROJString( "+proj=tmerc +lat_0=39.66666666666666 +lon_0=1 +k=1 +x_0=200000 " "+y_0=300000 +ellps=intl +nadgrids=foo.gsb +pm=lisbon " "+units=m +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto dst = authFactory->createCoordinateReferenceSystem("4326"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=39.6666666666667 +lon_0=1 " "+k=1 +x_0=200000 +y_0=300000 +ellps=intl +pm=lisbon " // Check that there is no extra +step +proj=longlat +pm=lisbon "+step +proj=hgridshift +grids=foo.gsb " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); // ETRS89 dst = authFactory->createCoordinateReferenceSystem("4258"); list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=39.6666666666667 +lon_0=1 " "+k=1 +x_0=200000 +y_0=300000 +ellps=intl +pm=lisbon " // Check that there is no extra +step +proj=longlat +pm=lisbon "+step +proj=hgridshift +grids=foo.gsb " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); // From WKT BOUNDCRS auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); auto src_wkt = src->exportToWKT(formatter.get()); auto objFromWkt = WKTParser().createFromWKT(src_wkt); auto crsFromWkt = nn_dynamic_pointer_cast<BoundCRS>(objFromWkt); ASSERT_TRUE(crsFromWkt); list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(crsFromWkt), dst, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=39.6666666666667 +lon_0=1 " "+k=1 +x_0=200000 +y_0=300000 +ellps=intl +pm=lisbon " // Check that there is no extra +step +proj=longlat +pm=lisbon "+step +proj=hgridshift +grids=foo.gsb " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, towgs84_pm_3d) { // Test fix for https://github.com/OSGeo/gdal/issues/5408 auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto objSrc = PROJStringParser().createFromPROJString( "+proj=tmerc +lat_0=0 +lon_0=34 +k=1 +x_0=0 +y_0=-5000000 " "+ellps=bessel +pm=ferro " "+towgs84=1,2,3,4,5,6,7 " "+units=m +no_defs +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto src3D = src->promoteTo3D(std::string(), dbContext); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto dst3D = dst->promoteTo3D(std::string(), dbContext); // Import thing to check is that there's no push/pop v_3 const std::string expected_pipeline = "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=0 +lon_0=34 +k=1 +x_0=0 +y_0=-5000000 " "+ellps=bessel +pm=ferro " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 " "+ry=5 +rz=6 +s=7 +convention=position_vector " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m"; auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); { auto list = CoordinateOperationFactory::create()->createOperations( src3D, dst3D, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), expected_pipeline); } // Retry when creating objects from WKT { auto objSrcFromWkt = WKTParser().createFromWKT(src3D->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get())); auto srcFromWkt = nn_dynamic_pointer_cast<CRS>(objSrcFromWkt); ASSERT_TRUE(srcFromWkt != nullptr); auto objDstFromWkt = WKTParser().createFromWKT(dst3D->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get())); auto dstFromWkt = nn_dynamic_pointer_cast<CRS>(objDstFromWkt); ASSERT_TRUE(dstFromWkt != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcFromWkt), NN_NO_CHECK(dstFromWkt), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), expected_pipeline); } } // --------------------------------------------------------------------------- TEST(operation, WGS84_G1762_to_compoundCRS_with_bound_vertCRS) { auto authFactoryEPSG = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // WGS 84 (G1762) 3D auto src = authFactoryEPSG->createCoordinateReferenceSystem("7665"); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=NAD83 [email protected] +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( src, NN_NO_CHECK(dst), ctxt); ASSERT_GE(list.size(), 53U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- static VerticalCRSNNPtr createVerticalCRS() { PropertyMap propertiesVDatum; propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5101) .set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn"); auto vdatum = VerticalReferenceFrame::create(propertiesVDatum); PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5701) .set(IdentifiedObject::NAME_KEY, "ODN height"); return VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS) { auto compound = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{GeographicCRS::EPSG_4326, createVerticalCRS()}); auto op = CoordinateOperationFactory::create()->createOperation( compound, GeographicCRS::EPSG_4807); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), CoordinateOperationFactory::create() ->createOperation(GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4807) ->exportToPROJString(PROJStringFormatter::create().get())); } // --------------------------------------------------------------------------- static BoundCRSNNPtr createBoundVerticalCRS() { auto vertCRS = createVerticalCRS(); auto transformation = Transformation::createGravityRelatedHeightToGeographic3D( PropertyMap(), vertCRS, GeographicCRS::EPSG_4979, nullptr, "us_nga_egm08_25.tif", std::vector<PositionalAccuracyNNPtr>()); return BoundCRS::create(vertCRS, GeographicCRS::EPSG_4979, transformation); } // --------------------------------------------------------------------------- TEST(operation, transformation_height_to_PROJ_string) { auto transf = createBoundVerticalCRS()->transformation(); EXPECT_EQ(transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm08_25.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); auto grids = transf->gridsNeeded(DatabaseContext::create(), false); ASSERT_EQ(grids.size(), 1U); auto gridDesc = *(grids.begin()); EXPECT_EQ(gridDesc.shortName, "us_nga_egm08_25.tif"); EXPECT_TRUE(gridDesc.packageName.empty()); EXPECT_EQ(gridDesc.url, "https://cdn.proj.org/us_nga_egm08_25.tif"); if (gridDesc.available) { EXPECT_TRUE(!gridDesc.fullName.empty()) << gridDesc.fullName; EXPECT_TRUE(gridDesc.fullName.find(gridDesc.shortName) != std::string::npos) << gridDesc.fullName; } else { EXPECT_TRUE(gridDesc.fullName.empty()) << gridDesc.fullName; } EXPECT_EQ(gridDesc.directDownload, true); EXPECT_EQ(gridDesc.openLicense, true); } // --------------------------------------------------------------------------- TEST(operation, transformation_Geographic3D_to_GravityRelatedHeight_gtx) { auto wkt = "COORDINATEOPERATION[\"ETRS89 to NAP height (1)\",\n" " VERSION[\"RDNAP-Nld 2008\"],\n" " SOURCECRS[\n" " GEOGCRS[\"ETRS89\",\n" " DATUM[\"European Terrestrial Reference System 1989\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4937]]],\n" " TARGETCRS[\n" " VERTCRS[\"NAP height\",\n" " VDATUM[\"Normaal Amsterdams Peil\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5709]]],\n" " METHOD[\"Geographic3D to GravityRelatedHeight (US .gtx)\",\n" " ID[\"EPSG\",9665]],\n" " PARAMETERFILE[\"Geoid (height correction) model " "file\",\"naptrans2008.gtx\"],\n" " OPERATIONACCURACY[0.01],\n" " USAGE[\n" " SCOPE[\"unknown\"],\n" " AREA[\"Netherlands - onshore\"],\n" " BBOX[50.75,3.2,53.7,7.22]],\n" " ID[\"EPSG\",7001]]"; auto obj = WKTParser().createFromWKT(wkt); auto transf = nn_dynamic_pointer_cast<Transformation>(obj); ASSERT_TRUE(transf != nullptr); // Check that we correctly inverse files in the case of // "Geographic3D to GravityRelatedHeight (US .gtx)" EXPECT_EQ(transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift " "+grids=naptrans2008.gtx +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_ntv2_to_PROJ_string) { auto transformation = Transformation::createNTv2( PropertyMap(), GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326, "foo.gsb", std::vector<PositionalAccuracyNNPtr>()); EXPECT_EQ( transformation->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step " "+proj=hgridshift +grids=foo.gsb +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_VERTCON_to_PROJ_string) { auto verticalCRS1 = createVerticalCRS(); auto verticalCRS2 = VerticalCRS::create( PropertyMap(), VerticalReferenceFrame::create(PropertyMap()), VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); // Use of this type of transformation is a bit of nonsense here // since it should normally be used with NGVD29 and NAVD88 for VerticalCRS, // and NAD27/NAD83 as horizontal CRS... auto vtransformation = Transformation::createVERTCON( PropertyMap(), verticalCRS1, verticalCRS2, "bla.gtx", std::vector<PositionalAccuracyNNPtr>()); EXPECT_EQ(vtransformation->exportToPROJString( PROJStringFormatter::create().get()), "+proj=vgridshift +grids=bla.gtx +multiplier=0.001"); } // --------------------------------------------------------------------------- TEST(operation, transformation_NZLVD_to_PROJ_string) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto op = factory->createCoordinateOperation("7860", false); EXPECT_EQ(op->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, dbContext) .get()), "+proj=vgridshift +grids=nz_linz_auckht1946-nzvd2016.tif " "+multiplier=1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_BEV_AT_to_PROJ_string) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); auto op = factory->createCoordinateOperation("9275", false); EXPECT_EQ(op->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, dbContext) .get()), "+proj=vgridshift +grids=at_bev_GV_Hoehengrid_V1.tif " "+multiplier=1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_longitude_rotation_to_PROJ_string) { auto src = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::create(PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto dest = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::create(PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::PARIS), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto transformation = Transformation::createLongitudeRotation( PropertyMap(), src, dest, Angle(10)); EXPECT_TRUE(transformation->validateParameters().empty()); EXPECT_EQ( transformation->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +inv " "+proj=longlat +ellps=WGS84 +pm=10 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_EQ(transformation->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +inv " "+proj=longlat +ellps=WGS84 +pm=-10 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_Geographic2D_offsets_to_PROJ_string) { auto transformation = Transformation::createGeographic2DOffsets( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4326, Angle(0.5), Angle(-1), {}); EXPECT_TRUE(transformation->validateParameters().empty()); EXPECT_EQ( transformation->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=geogoffset " "+dlat=1800 +dlon=-3600 +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_EQ(transformation->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=geogoffset " "+dlat=-1800 +dlon=3600 +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_Geographic3D_offsets_to_PROJ_string) { auto transformation = Transformation::createGeographic3DOffsets( PropertyMap(), GeographicCRS::EPSG_4326, GeographicCRS::EPSG_4326, Angle(0.5), Angle(-1), Length(2), {}); EXPECT_TRUE(transformation->validateParameters().empty()); EXPECT_EQ( transformation->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=geogoffset " "+dlat=1800 +dlon=-3600 +dh=2 +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_EQ(transformation->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=geogoffset " "+dlat=-1800 +dlon=3600 +dh=-2 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_Geographic2D_with_height_offsets_to_PROJ_string) { auto transformation = Transformation::createGeographic2DWithHeightOffsets( PropertyMap(), CompoundCRS::create(PropertyMap(), {GeographicCRS::EPSG_4326, createVerticalCRS()}), GeographicCRS::EPSG_4326, Angle(0.5), Angle(-1), Length(2), {}); EXPECT_TRUE(transformation->validateParameters().empty()); EXPECT_EQ( transformation->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=geogoffset " "+dlat=1800 +dlon=-3600 +dh=2 +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_EQ(transformation->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=geogoffset " "+dlat=-1800 +dlon=3600 +dh=-2 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, transformation_vertical_offset_to_PROJ_string) { auto transformation = Transformation::createVerticalOffset( PropertyMap(), createVerticalCRS(), createVerticalCRS(), Length(1), {}); EXPECT_TRUE(transformation->validateParameters().empty()); EXPECT_EQ( transformation->exportToPROJString(PROJStringFormatter::create().get()), "+proj=geogoffset +dh=1"); EXPECT_EQ(transformation->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=geogoffset +dh=-1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundVerticalCRS_to_geogCRS) { auto compound = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{GeographicCRS::EPSG_4326, createBoundVerticalCRS()}); auto op = CoordinateOperationFactory::create()->createOperation( compound, GeographicCRS::EPSG_4979); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=vgridshift " "+grids=us_nga_egm08_25.tif +multiplier=1 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundGeogCRS_to_geogCRS) { auto geogCRS = GeographicCRS::create( PropertyMap(), GeodeticReferenceFrame::create(PropertyMap(), Ellipsoid::WGS84, optional<std::string>(), PrimeMeridian::GREENWICH), EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)); auto horizBoundCRS = BoundCRS::createFromTOWGS84( geogCRS, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto compound = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{horizBoundCRS, createVerticalCRS()}); auto op = CoordinateOperationFactory::create()->createOperation( compound, GeographicCRS::EPSG_4979); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=push +v_3 " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 " "+convention=position_vector " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundGeogCRS_and_boundVerticalCRS_to_geogCRS) { auto horizBoundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4807, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto compound = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{horizBoundCRS, createBoundVerticalCRS()}); auto op = CoordinateOperationFactory::create()->createOperation( compound, GeographicCRS::EPSG_4979); ASSERT_TRUE(op != nullptr); // Not completely sure the order of horizontal and vertical operations // makes sense EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=grad +xy_out=rad " "+step +inv +proj=longlat +ellps=clrk80ign +pm=paris " "+step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 " "+convention=position_vector " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=vgridshift +grids=us_nga_egm08_25.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); auto grids = op->gridsNeeded(DatabaseContext::create(), false); EXPECT_EQ(grids.size(), 1U); auto opInverse = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4979, compound); ASSERT_TRUE(opInverse != nullptr); EXPECT_TRUE(opInverse->inverse()->isEquivalentTo(op.get())); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundProjCRS_and_boundVerticalCRS_to_geogCRS) { auto horizBoundCRS = BoundCRS::createFromTOWGS84( ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4807, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)), std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto compound = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{horizBoundCRS, createBoundVerticalCRS()}); auto op = CoordinateOperationFactory::create()->createOperation( compound, GeographicCRS::EPSG_4979); ASSERT_TRUE(op != nullptr); // Not completely sure the order of horizontal and vertical operations // makes sense EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=31 +ellps=clrk80ign +pm=paris " "+step +proj=push +v_3 " "+step +proj=cart +ellps=clrk80ign " "+step +proj=helmert +x=1 +y=2 +z=3 +rx=4 +ry=5 +rz=6 +s=7 " "+convention=position_vector " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=vgridshift +grids=us_nga_egm08_25.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); auto opInverse = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4979, compound); ASSERT_TRUE(opInverse != nullptr); EXPECT_TRUE(opInverse->inverse()->isEquivalentTo(op.get())); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundVerticalCRS_from_geoidgrids_with_m_to_geogCRS) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 [email protected] +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_NO_CHECK(src), GeographicCRS::EPSG_4979); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundVerticalCRS_from_geoidgrids_with_ftus_to_geogCRS) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 [email protected] +vunits=us-ft " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_NO_CHECK(src), GeographicCRS::EPSG_4979); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=rad +z_out=m " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundProjCRS_with_ftus_and_boundVerticalCRS_to_geogCRS) { auto wkt = "COMPD_CS[\"NAD_1983_StatePlane_Alabama_West_FIPS_0102_Feet + " "NAVD88 height - Geoid12B (US Feet)\",\n" " PROJCS[\"NAD_1983_StatePlane_Alabama_West_FIPS_0102_Feet\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"Degree\",0.0174532925199433]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",30],\n" " PARAMETER[\"central_meridian\",-87.5],\n" " PARAMETER[\"scale_factor\",0.999933333333333],\n" " PARAMETER[\"false_easting\",1968500],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"ESRI\",\"102630\"]],\n" " VERT_CS[\"NAVD88 height (ftUS)\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"foo.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"6360\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_NO_CHECK(crs), GeographicCRS::EPSG_4979); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=us-ft +xy_out=m " "+step +inv +proj=tmerc +lat_0=30 +lon_0=-87.5 " "+k=0.999933333333333 +x_0=600000 +y_0=0 +ellps=GRS80 " "+step +proj=unitconvert +z_in=us-ft +z_out=m " "+step +proj=vgridshift +grids=foo.gtx +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundVerticalCRS_from_grids_to_geogCRS_with_ftus_ctxt) { auto dbContext = DatabaseContext::create(); const char *wktSrc = "COMPD_CS[\"NAD83 + NAVD88 height - Geoid12B (Meters)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"NAVD88 height - Geoid12B (Meters)\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"@foo.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"metre\",1.0,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5703\"]]]"; auto objSrc = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktSrc); auto srcCRS = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCRS != nullptr); const char *wktDst = "COMPD_CS[\"NAD83 + Ellipsoid (US Feet)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"Ellipsoid (US Feet)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Up\",UP]]]"; auto objDst = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktDst); auto dstCRS = nn_dynamic_pointer_cast<GeographicCRS>(objDst); ASSERT_TRUE(dstCRS != nullptr); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCRS), NN_NO_CHECK(dstCRS), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=us-ft " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_with_boundGeogCRS_boundVerticalCRS_from_grids_to_boundGeogCRS_with_ftus_ctxt) { // Variant of above but with TOWGS84 in source & target CRS auto dbContext = DatabaseContext::create(); const char *wktSrc = "COMPD_CS[\"NAD83 + NAVD88 height - Geoid12B (Meters)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"NAVD88 height - Geoid12B (Meters)\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"@foo.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"metre\",1.0,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5703\"]]]"; auto objSrc = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktSrc); auto srcCRS = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCRS != nullptr); const char *wktDst = "COMPD_CS[\"NAD83 + Ellipsoid (US Feet)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"Ellipsoid (US Feet)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Up\",UP]]]"; auto objDst = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktDst); auto dstCRS = nn_dynamic_pointer_cast<BoundCRS>(objDst); ASSERT_TRUE(dstCRS != nullptr); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCRS), NN_NO_CHECK(dstCRS), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=us-ft " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_with_boundVerticalCRS_from_grids_to_boundGeogCRS_with_ftus_ctxt) { // Variant of above but with TOWGS84 in target CRS only auto dbContext = DatabaseContext::create(); const char *wktSrc = "COMPD_CS[\"NAD83 + NAVD88 height - Geoid12B (Meters)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"NAVD88 height - Geoid12B (Meters)\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"@foo.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"metre\",1.0,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5703\"]]]"; auto objSrc = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktSrc); auto srcCRS = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCRS != nullptr); const char *wktDst = "COMPD_CS[\"NAD83 + Ellipsoid (US Feet)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"Ellipsoid (US Feet)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Up\",UP]]]"; auto objDst = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktDst); auto dstCRS = nn_dynamic_pointer_cast<BoundCRS>(objDst); ASSERT_TRUE(dstCRS != nullptr); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCRS), NN_NO_CHECK(dstCRS), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=us-ft " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_bound_of_projected_and_bound_of_vertical_to_geog3D) { auto dbContext = DatabaseContext::create(); const char *wktSrc = "COMPD_CS[\"TempTM + CGVD28 height - HT2_0\",\n" " PROJCS[\"Custom\",\n" " GEOGCS[\"NAD83(CSRS)\",\n" " DATUM[\"NAD83_Canadian_Spatial_Reference_System\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6140\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4617\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",49.351346659616],\n" " PARAMETER[\"central_meridian\",-123.20266499149],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",15307.188],\n" " PARAMETER[\"false_northing\",6540.975],\n" " UNIT[\"Meters\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]],\n" " VERT_CS[\"CGVD28 height - HT2_0\",\n" " VERT_DATUM[\"Canadian Geodetic Vertical Datum of " "1928\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"HT2_0.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5114\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5713\"]]]"; auto objSrc = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktSrc); auto srcCRS = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCRS != nullptr); auto authFactoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); // NAD83(CSRS) 3D auto dstCRS = authFactoryEPSG->createCoordinateReferenceSystem("4955"); auto ctxt = CoordinateOperationContext::create(authFactoryEPSG, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCRS), dstCRS, ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=49.351346659616 " "+lon_0=-123.20266499149 +k=1 " "+x_0=15307.188 +y_0=6540.975 +ellps=GRS80 " "+step +proj=vgridshift +grids=HT2_0.gtx +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_boundGeogCRS_and_geoid_to_geodCRS_NAD2011_ctxt) { auto dbContext = DatabaseContext::create(); const char *wktSrc = "COMPD_CS[\"NAD83 / California zone 5 (ftUS) + " "NAVD88 height - Geoid12B (ftUS)\"," " PROJCS[\"NAD83 / California zone 5 (ftUS)\"," " GEOGCS[\"NAD83\"," " DATUM[\"North_American_Datum_1983\"," " SPHEROID[\"GRS 1980\",6378137,298.257222101," " AUTHORITY[\"EPSG\",\"7019\"]]," " TOWGS84[0,0,0,0,0,0,0]," " AUTHORITY[\"EPSG\",\"6269\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9122\"]]," " AUTHORITY[\"EPSG\",\"4269\"]]," " PROJECTION[\"Lambert_Conformal_Conic_2SP\"]," " PARAMETER[\"standard_parallel_1\",35.46666666666667]," " PARAMETER[\"standard_parallel_2\",34.03333333333333]," " PARAMETER[\"latitude_of_origin\",33.5]," " PARAMETER[\"central_meridian\",-118]," " PARAMETER[\"false_easting\",6561666.667]," " PARAMETER[\"false_northing\",1640416.667]," " UNIT[\"US survey foot\",0.3048006096012192," " AUTHORITY[\"EPSG\",\"9003\"]]," " AXIS[\"X\",EAST]," " AXIS[\"Y\",NORTH]," " AUTHORITY[\"EPSG\",\"2229\"]]," "VERT_CS[\"NAVD88 height - Geoid12B (ftUS)\"," " VERT_DATUM[\"North American Vertical Datum 1988\",2005," " AUTHORITY[\"EPSG\",\"5103\"]]," " UNIT[\"US survey foot\",0.3048006096012192," " AUTHORITY[\"EPSG\",\"9003\"]]," " AXIS[\"Gravity-related height\",UP]," " AUTHORITY[\"EPSG\",\"6360\"]]]"; auto objSrc = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktSrc); auto srcCRS = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCRS != nullptr); auto authFactoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); // NAD83(2011) geocentric auto dstCRS = authFactoryEPSG->createCoordinateReferenceSystem("6317"); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCRS), dstCRS, ctxt); bool found = false; for (const auto &op : list) { if (op->nameStr() == "Inverse of unnamed + " "Transformation from NAD83 to WGS84 + " "Inverse of NAD83(2011) to WGS 84 (1) + " "Conversion from NAVD88 height (ftUS) to NAVD88 height + " "Inverse of NAD83(2011) to NAVD88 height (1) + " "Conversion from NAD83(2011) (geog3D) to NAD83(2011) " "(geocentric)") { found = true; EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=us-ft +xy_out=m " "+step +inv +proj=lcc +lat_0=33.5 +lon_0=-118 " "+lat_1=35.4666666666667 +lat_2=34.0333333333333 " "+x_0=2000000.0001016 +y_0=500000.0001016 +ellps=GRS80 " "+step +proj=unitconvert +z_in=us-ft +z_out=m " "+step +proj=vgridshift +grids=us_noaa_g2012bu0.tif " "+multiplier=1 " "+step +proj=cart +ellps=GRS80"); } } EXPECT_TRUE(found); if (!found) { for (const auto &op : list) { std::cerr << op->nameStr() << std::endl; } } } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_vert_bound_to_bound_geog3D) { // Test case of https://github.com/OSGeo/PROJ/issues/3927 auto dbContext = DatabaseContext::create(); const char *wktSrc = "COMPOUNDCRS[\"ENU (-77.410692720411:39.4145340892321) + EGM96 geoid " "height\",\n" " PROJCRS[\"ENU (-77.410692720411:39.4145340892321)\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"unknown\",\n" " ELLIPSOID[\"WGS84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Orthographic\",\n" " ID[\"EPSG\",9840]],\n" " PARAMETER[\"Latitude of natural " "origin\",39.4145340892321,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural " "origin\",-77.410692720411,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"northing\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " BOUNDCRS[\n" " SOURCECRS[\n" " VERTCRS[\"EGM96 geoid height\",\n" " VDATUM[\"EGM96 geoid\"],\n" " CS[vertical,1],\n" " AXIS[\"up\",up,\n" " LENGTHUNIT[\"m\",1]],\n" " ID[\"EPSG\",5773]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[\"EGM96 geoid height to WGS 84 " "ellipsoidal height\",\n" " METHOD[\"GravityRelatedHeight to Geographic3D\"],\n" " PARAMETERFILE[\"Geoid (height correction) model " "file\",\"egm96_15.gtx\",\n" " ID[\"EPSG\",8666]]]]]"; auto objSrc = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktSrc); auto srcCRS = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCRS != nullptr); const char *wktDst = "BOUNDCRS[\n" " SOURCECRS[\n" " GEOGCRS[\"WGS84 Coordinate System\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 1984\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " REMARK[\"Promoted to 3D from EPSG:4326\"]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " MEMBER[\"World Geodetic System 1984 (G2139)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"Geodesy. Navigation and positioning using GPS " "satellite system.\"],\n" " AREA[\"World.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[\"Transformation from WGS84 Coordinate " "System to WGS84\",\n" " METHOD[\"Position Vector transformation (geog2D domain)\",\n" " ID[\"EPSG\",9606]],\n" " PARAMETER[\"X-axis translation\",0,\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",0,\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",0,\n" " ID[\"EPSG\",8607]],\n" " PARAMETER[\"X-axis rotation\",0,\n" " ID[\"EPSG\",8608]],\n" " PARAMETER[\"Y-axis rotation\",0,\n" " ID[\"EPSG\",8609]],\n" " PARAMETER[\"Z-axis rotation\",0,\n" " ID[\"EPSG\",8610]],\n" " PARAMETER[\"Scale difference\",1,\n" " ID[\"EPSG\",8611]]]]"; auto objDst = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wktDst); auto dstCRS = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dstCRS != nullptr); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCRS), NN_NO_CHECK(dstCRS), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=ortho +lat_0=39.4145340892321 " "+lon_0=-77.410692720411 +x_0=0 +y_0=0 +ellps=WGS84 " "+step +proj=vgridshift +grids=egm96_15.gtx +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, geocent_to_compoundCRS) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=geocent +datum=WGS84 +units=m +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=cart +ellps=WGS84 " "+step +inv +proj=hgridshift [email protected] " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, geocent_to_compoundCRS_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // WGS84 geocentric auto src = authFactory->createCoordinateReferenceSystem("4978"); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( src, NN_CHECK_ASSERT(dst), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=cart +ellps=WGS84 " "+step +inv +proj=hgridshift [email protected] " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS) { auto compound1 = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{createUTM31_WGS84(), createVerticalCRS()}); auto compound2 = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{createUTM32_WGS84(), createVerticalCRS()}); auto op = CoordinateOperationFactory::create()->createOperation(compound1, compound2); ASSERT_TRUE(op != nullptr); auto opRef = CoordinateOperationFactory::create()->createOperation( createUTM31_WGS84(), createUTM32_WGS84()); ASSERT_TRUE(opRef != nullptr); EXPECT_TRUE(op->isEquivalentTo(opRef.get())); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_with_vertical_transform) { auto verticalCRS1 = createVerticalCRS(); auto verticalCRS2 = VerticalCRS::create( PropertyMap(), VerticalReferenceFrame::create(PropertyMap()), VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); // Use of this type of transformation is a bit of nonsense here // since it should normally be used with NGVD29 and NAVD88 for VerticalCRS, // and NAD27/NAD83 as horizontal CRS... auto vtransformation = Transformation::createVERTCON( PropertyMap(), verticalCRS1, verticalCRS2, "bla.gtx", std::vector<PositionalAccuracyNNPtr>()); auto compound1 = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{ ProjectedCRS::create( PropertyMap(), GeographicCRS::EPSG_4326, Conversion::createTransverseMercator(PropertyMap(), Angle(1), Angle(2), Scale(3), Length(4), Length(5)), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)), BoundCRS::create(verticalCRS1, verticalCRS2, vtransformation)}); auto compound2 = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{createUTM32_WGS84(), verticalCRS2}); auto op = CoordinateOperationFactory::create()->createOperation(compound1, compound2); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=tmerc +lat_0=1 +lon_0=2 +k=3 " "+x_0=4 +y_0=5 +ellps=WGS84 +step " "+proj=vgridshift +grids=bla.gtx +multiplier=0.001 +step " "+proj=utm +zone=32 " "+ellps=WGS84"); { auto formatter = PROJStringFormatter::create(); formatter->setUseApproxTMerc(true); EXPECT_EQ( op->exportToPROJString(formatter.get()), "+proj=pipeline +step +inv +proj=tmerc +approx +lat_0=1 +lon_0=2 " "+k=3 +x_0=4 +y_0=5 +ellps=WGS84 +step " "+proj=vgridshift +grids=bla.gtx +multiplier=0.001 +step " "+proj=utm +approx +zone=32 " "+ellps=WGS84"); } { auto formatter = PROJStringFormatter::create(); formatter->setUseApproxTMerc(true); EXPECT_EQ( op->inverse()->exportToPROJString(formatter.get()), "+proj=pipeline +step +inv +proj=utm +approx +zone=32 +ellps=WGS84 " "+step +inv +proj=vgridshift +grids=bla.gtx " "+multiplier=0.001 +step +proj=tmerc +approx +lat_0=1 +lon_0=2 " "+k=3 +x_0=4 +y_0=5 +ellps=WGS84"); } auto opInverse = CoordinateOperationFactory::create()->createOperation( compound2, compound1); ASSERT_TRUE(opInverse != nullptr); { auto formatter = PROJStringFormatter::create(); auto formatter2 = PROJStringFormatter::create(); EXPECT_EQ(opInverse->inverse()->exportToPROJString(formatter.get()), op->exportToPROJString(formatter2.get())); } } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=hgridshift [email protected] " "+step +inv +proj=hgridshift [email protected] " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert_same_geoidgrids) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=hgridshift [email protected] " "+step +inv +proj=hgridshift [email protected] " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert_same_geoidgrids_different_vunits) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+vunits=us-ft +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=hgridshift [email protected] " "+step +inv +proj=hgridshift [email protected] " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=us-ft"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert_same_nadgrids_same_geoidgrids) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert_same_towgs84_same_geoidgrids) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 +towgs84=0,0,0 [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +towgs84=0,0,0 [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=cart +ellps=GRS67 " "+step +inv +proj=cart +ellps=GRS80 " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert_same_ellsp_but_different_towgs84_different_geoidgrids) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +towgs84=1,2,3 [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +towgs84=4,5,6 [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto srcGeog = src->extractGeographicCRS(); ASSERT_TRUE(srcGeog != nullptr); ASSERT_TRUE(srcGeog->datum() != nullptr); auto dstGeog = dst->extractGeographicCRS(); ASSERT_TRUE(dstGeog != nullptr); ASSERT_TRUE(dstGeog->datum() != nullptr); EXPECT_FALSE(srcGeog->datum()->isEquivalentTo( dstGeog->datum().get(), IComparable::Criterion::EQUIVALENT)); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); // Check there's no proj=push +v_1 +v_2 EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=-3 +y=-3 +z=-3 " "+step +inv +proj=cart +ellps=GRS80 " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_with_bound_crs_in_horiz_and_vert_WKT1_same_geoidgrids_context) { auto objSrc = WKTParser().createFromWKT( "COMPD_CS[\"NAD83 / Alabama West + NAVD88 height - Geoid12B " "(Meters)\",\n" " PROJCS[\"NAD83 / Alabama West\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",30],\n" " PARAMETER[\"central_meridian\",-87.5],\n" " PARAMETER[\"scale_factor\",0.999933333],\n" " PARAMETER[\"false_easting\",600000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"X\",EAST],\n" " AXIS[\"Y\",NORTH],\n" " AUTHORITY[\"EPSG\",\"26930\"]],\n" " VERT_CS[\"NAVD88 height\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " " "EXTENSION[\"PROJ4_GRIDS\",\"g2012a_alaska.gtx,g2012a_hawaii.gtx," "g2012a_conus.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5703\"]]]"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = WKTParser().createFromWKT( "COMPD_CS[\"NAD_1983_StatePlane_Alabama_West_FIPS_0102_Feet + NAVD88 " "height - Geoid12B (US Feet)\",\n" " PROJCS[\"NAD_1983_StatePlane_Alabama_West_FIPS_0102_Feet\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"Degree\",0.0174532925199433]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",30],\n" " PARAMETER[\"central_meridian\",-87.5],\n" " PARAMETER[\"scale_factor\",0.999933333333333],\n" " PARAMETER[\"false_easting\",1968500],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"ESRI\",\"102630\"]],\n" " VERT_CS[\"NAVD88 height (ftUS)\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " " "EXTENSION[\"PROJ4_GRIDS\",\"g2012a_alaska.gtx,g2012a_hawaii.gtx," "g2012a_conus.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"6360\"]]]"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=30 +lon_0=-87.5 +k=0.999933333 " "+x_0=600000 +y_0=0 +ellps=GRS80 " "+step +proj=unitconvert +z_in=m +z_out=us-ft " "+step +proj=tmerc +lat_0=30 +lon_0=-87.5 +k=0.999933333333333 " "+x_0=600000 +y_0=0 +ellps=GRS80 " "+step +proj=unitconvert +xy_in=m +xy_out=us-ft"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_issue_2232) { auto objSrc = WKTParser().createFromWKT( "COMPD_CS[\"NAD83 / Alabama West + NAVD88 height - Geoid12B " "(Meters)\",\n" " PROJCS[\"NAD83 / Alabama West\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",30],\n" " PARAMETER[\"central_meridian\",-87.5],\n" " PARAMETER[\"scale_factor\",0.999933333],\n" " PARAMETER[\"false_easting\",600000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"X\",EAST],\n" " AXIS[\"Y\",NORTH],\n" " AUTHORITY[\"EPSG\",\"26930\"]],\n" " VERT_CS[\"NAVD88 height - Geoid12B (Meters)\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"foo.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"metre\",1.0,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5703\"]]]"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = WKTParser().createFromWKT( "COMPD_CS[\"NAD83 + some CRS (US Feet)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"some CRS (US Feet)\",\n" " VERT_DATUM[\"some datum\",2005],\n" " UNIT[\"US survey foot\",0.3048006096012192,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Up\",UP]]]"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst), ctxt); EXPECT_GE(list.size(), 1U); auto list2 = CoordinateOperationFactory::create()->createOperations( NN_CHECK_ASSERT(dst), NN_CHECK_ASSERT(src), ctxt); EXPECT_EQ(list2.size(), list.size()); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // NAD27 + NGVD29 height (ftUS) authFactory->createCoordinateReferenceSystem("7406"), // NAD83(NSRS2007) + NAVD88 height authFactory->createCoordinateReferenceSystem("5500"), ctxt); // 152 or 155 depending if the VERTCON grids are there ASSERT_GE(list.size(), 152U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->nameStr(), "NGVD29 height (ftUS) to NAVD88 height (3) + " "NAD27 to WGS 84 (79) + Inverse of " "NAD83(NSRS2007) to WGS 84 (1)"); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=rad +z_out=m " "+step +proj=vgridshift +grids=us_noaa_vertcone.tif +multiplier=1 " "+step +proj=hgridshift +grids=us_noaa_conus.tif +step " "+proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1"); { // Test that we can round-trip this through WKT and still get the same // PROJ string. auto wkt = list[0]->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); auto obj = WKTParser().createFromWKT(wkt); auto co = nn_dynamic_pointer_cast<CoordinateOperation>(obj); ASSERT_TRUE(co != nullptr); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), co->exportToPROJString(PROJStringFormatter::create().get())); } bool foundApprox = false; for (size_t i = 0; i < list.size(); i++) { auto projString = list[i]->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_TRUE( projString.find("+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=us-ft " "+xy_out=rad +z_out=m") == 0) << list[i]->nameStr(); if (list[i]->nameStr().find("Transformation from NGVD29 height (ftUS) " "to NAVD88 height (ballpark vertical " "transformation)") == 0) { EXPECT_TRUE(list[i]->hasBallparkTransformation()); EXPECT_EQ(list[i]->nameStr(), "Transformation from NGVD29 height (ftUS) to NAVD88 " "height (ballpark vertical transformation) + NAD27 to " "WGS 84 (79) + Inverse of NAD83(NSRS2007) to WGS 84 (1)"); EXPECT_EQ( projString, "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=rad " "+z_out=m +step +proj=hgridshift +grids=us_noaa_conus.tif " "+step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); foundApprox = true; break; } } EXPECT_TRUE(foundApprox); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_context_helmert_noop) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); // WGS84 + EGM96 auto objSrc = createFromUserInput("EPSG:4326+5773", dbContext); auto srcCrs = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCrs != nullptr); // ETRS89 + EGM96 auto objDest = createFromUserInput("EPSG:4258+5773", dbContext); auto destCrs = nn_dynamic_pointer_cast<CompoundCRS>(objDest); ASSERT_TRUE(destCrs != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCrs), NN_NO_CHECK(destCrs), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- // EGM96 has a geoid model referenced to WGS84, and Belfast height has a // geoid model referenced to ETRS89 TEST(operation, compoundCRS_to_compoundCRS_WGS84_EGM96_to_ETRS89_Belfast) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); // WGS84 + EGM96 auto objSrc = createFromUserInput("EPSG:4326+5773", dbContext); auto srcCrs = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCrs != nullptr); // ETRS89 + Belfast height auto objDest = createFromUserInput("EPSG:4258+5732", dbContext); auto destCrs = nn_dynamic_pointer_cast<CompoundCRS>(objDest); ASSERT_TRUE(destCrs != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCrs), NN_NO_CHECK(destCrs), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of WGS 84 to EGM96 height (1) + " "Inverse of ETRS89 to WGS 84 (1) + " "ETRS89 to Belfast height (2)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +inv +proj=vgridshift +grids=uk_os_OSGM15_Belfast.tif " "+multiplier=1 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- // Variant of above where source intermediate geog3D CRS == target intermediate // geog3D CRS TEST(operation, compoundCRS_to_compoundCRS_WGS84_EGM96_to_WGS84_Belfast) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); // WGS84 + EGM96 auto objSrc = createFromUserInput("EPSG:4326+5773", dbContext); auto srcCrs = nn_dynamic_pointer_cast<CompoundCRS>(objSrc); ASSERT_TRUE(srcCrs != nullptr); // WGS84 + Belfast height auto objDest = createFromUserInput("EPSG:4326+5732", dbContext); auto destCrs = nn_dynamic_pointer_cast<CompoundCRS>(objDest); ASSERT_TRUE(destCrs != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCrs), NN_NO_CHECK(destCrs), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of WGS 84 to EGM96 height (1) + " "ETRS89 to Belfast height (2) using ETRS89 to WGS 84 (1)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +inv +proj=vgridshift +grids=uk_os_OSGM15_Belfast.tif " "+multiplier=1 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_OSGB36_BNG_ODN_height_to_WGS84_EGM96) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // "OSGB36 / British National Grid + ODN height auto srcObj = createFromUserInput("EPSG:27700+5701", dbContext, false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto authFactoryEPSG = AuthorityFactory::create(dbContext, std::string("EPSG")); auto dst = authFactoryEPSG->createCoordinateReferenceSystem( "9707"); // "WGS 84 + EGM96 height" { auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of British National Grid + " "OSGB36 to ETRS89 (2) + " "Inverse of ETRS89 to ODN height (2) + " "ETRS89 to WGS 84 (1) + " "WGS 84 to EGM96 height (1)"); const char *expected_proj = "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 " "+x_0=400000 +y_0=-100000 +ellps=airy " "+step +proj=hgridshift +grids=uk_os_OSTN15_NTv2_OSGBtoETRS.tif " "+step +proj=vgridshift +grids=uk_os_OSGM15_GB.tif +multiplier=1 " "+step +inv +proj=vgridshift +grids=us_nga_egm96_15.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"; EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), expected_proj); } { auto list = CoordinateOperationFactory::create()->createOperations( dst, NN_NO_CHECK(src), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of WGS 84 to EGM96 height (1) + " "Inverse of ETRS89 to WGS 84 (1) + " "ETRS89 to ODN height (2) + " "Inverse of OSGB36 to ETRS89 (2) + " "British National Grid"); const char *expected_proj = "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +inv +proj=vgridshift +grids=uk_os_OSGM15_GB.tif " "+multiplier=1 " "+step +inv +proj=hgridshift " "+grids=uk_os_OSTN15_NTv2_OSGBtoETRS.tif " "+step +proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 " "+x_0=400000 +y_0=-100000 +ellps=airy"; EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), expected_proj); } } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_concatenated_operation_with_two_vert_transformation) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // ETRS89 + Baltic 1957 height authFactory->createCoordinateReferenceSystem("8360"), // ETRS89 + EVRF2007 height authFactory->createCoordinateReferenceSystem("7423"), ctxt); ASSERT_GE(list.size(), 2U); // For Czechia EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vertoffset +lat_0=49.9166666666667 " "+lon_0=15.25 +dh=0.13 +slope_lat=0.026 +slope_lon=0 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(list[0]->nameStr(), "Baltic 1957 height to EVRF2007 height (1)"); // For Slovakia EXPECT_EQ( list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift " "+grids=sk_gku_Slovakia_ETRS89h_to_Baltic1957.tif +multiplier=1 " "+step +inv +proj=vgridshift " "+grids=sk_gku_Slovakia_ETRS89h_to_EVRF2007.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( list[1]->nameStr(), "ETRS89 + Baltic 1957 height to ETRS89 + EVRF2007 height (1)"); EXPECT_EQ(list[1]->inverse()->nameStr(), "Inverse of 'ETRS89 + Baltic " "1957 height to ETRS89 + " "EVRF2007 height (1)'"); } } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_concatenated_operation_with_two_vert_transformation_and_different_source_dest_interp) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // "BD72 + Ostend height" auto srcObj = createFromUserInput("EPSG:4313+5710", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); // "Amersfoort + NAP height" auto dstObj = createFromUserInput("EPSG:4289+5709", authFactory->databaseContext(), false); auto dst = nn_dynamic_pointer_cast<CRS>(dstObj); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "BD72 to ETRS89 (3) + " "Inverse of ETRS89 to Ostend height (1) + " "ETRS89 to NAP height (2) + " "Inverse of Amersfoort to ETRS89 (9)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=be_ign_bd72lb72_etrs89lb08.tif " "+step +proj=vgridshift +grids=be_ign_hBG18.tif +multiplier=1 " "+step +inv +proj=vgridshift +grids=nl_nsgi_nlgeo2018.tif " "+multiplier=1 " "+step +inv +proj=hgridshift +grids=nl_nsgi_rdtrans2018.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_issue_2720) { auto dbContext = DatabaseContext::create(); auto objSrc = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "COMPD_CS[\"Orthographic + EGM96 geoid height\"," "PROJCS[\"Orthographic\"," "GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_unknown\"," "SPHEROID[\"WGS84\",6378137,298.257223563]]," "PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]," "PROJECTION[\"Orthographic\"]," "PARAMETER[\"Latitude_Of_Center\",36.1754430555555000]," "PARAMETER[\"Longitude_Of_Center\",-86.7740944444444000]," "PARAMETER[\"false_easting\",0]," "PARAMETER[\"false_northing\",0]," "UNIT[\"Meter\",1]]," "VERT_CS[\"EGM96 geoid height\"," "VERT_DATUM[\"EGM96 geoid\",2005," "EXTENSION[\"PROJ4_GRIDS\",\"egm96_15.gtx\"]," "AUTHORITY[\"EPSG\",\"5171\"]]," "UNIT[\"metre\",1," "AUTHORITY[\"EPSG\",\"9001\"]]," "AXIS[\"Up\",UP]," "AUTHORITY[\"EPSG\",\"5773\"]]]"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = WKTParser().attachDatabaseContext(dbContext).createFromWKT( "COMPD_CS[\"WGS84 Coordinate System + EGM96 geoid height\"," "GEOGCS[\"WGS84 Coordinate System\"," "DATUM[\"WGS 1984\"," "SPHEROID[\"WGS 1984\",6378137,298.257223563]," "TOWGS84[0,0,0,0,0,0,0]," "AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0]," "UNIT[\"degree\",0.0174532925199433]," "AUTHORITY[\"EPSG\",\"4326\"]]," "VERT_CS[\"EGM96 geoid height\"," "VERT_DATUM[\"EGM96 geoid\",2005," "EXTENSION[\"PROJ4_GRIDS\",\"egm96_15.gtx\"]," "AUTHORITY[\"EPSG\",\"5171\"]]," "UNIT[\"metre\",1," "AUTHORITY[\"EPSG\",\"9001\"]]," "AXIS[\"Up\",UP]," "AUTHORITY[\"EPSG\",\"5773\"]]]"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst), ctxt); EXPECT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=ortho +f=0 +lat_0=36.1754430555555 " "+lon_0=-86.7740944444444 +x_0=0 +y_0=0 +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_issue_3328) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); // "WGS 84 + EGM96 height" auto srcObj = createFromUserInput("EPSG:4326+5773", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); // "WGS 84 + CGVD28 height" auto dstObj = createFromUserInput("EPSG:4326+5713", authFactory->databaseContext(), false); auto dst = nn_dynamic_pointer_cast<CRS>(dstObj); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of WGS 84 to EGM96 height (1) + " "NAD83(CSRS) to CGVD28 height (1) " "using NAD83(CSRS) to WGS 84 (2)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=push +v_1 +v_2 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +proj=cart +ellps=WGS84 " "+step +inv +proj=helmert +x=-0.991 +y=1.9072 +z=0.5129 " "+rx=-0.0257899075194932 " "+ry=-0.0096500989602704 +rz=-0.0116599432323421 +s=0 " "+convention=coordinate_frame " "+step +inv +proj=cart +ellps=GRS80 " "+step +inv +proj=vgridshift +grids=ca_nrc_HT2_1997.tif " "+multiplier=1 " "+step +proj=push +v_3 " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=-0.991 +y=1.9072 +z=0.5129 " "+rx=-0.0257899075194932 " "+ry=-0.0096500989602704 +rz=-0.0116599432323421 +s=0 " "+convention=coordinate_frame " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1 " "+step +proj=pop +v_1 +v_2"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_compoundCRS_concatenated_operation_with_two_vert_transformation_and_ballpark_geog) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // "NAD83(CSRS) + CGVD28 height" auto srcObj = createFromUserInput("EPSG:4617+5713", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); // "NAD83(CSRS) + CGVD2013(CGG2013) height" auto dstObj = createFromUserInput("EPSG:4617+6647", authFactory->databaseContext(), false); auto dst = nn_dynamic_pointer_cast<CRS>(dstObj); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); { auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of NAD83(CSRS)v6 to CGVD28 height (1) + " "NAD83(CSRS)v6 to CGVD2013(CGG2013) height (1) " "using Ballpark geographic offset " "from NAD83(CSRS) to NAD83(CSRS)v6"); } #if 0 // Note: below situation is no longer triggered since EPSG v10.066 update // Not obvious to find an equivalent one. // That transformation involves doing CGVD28 height to CGVD2013(CGG2013) // height by doing: // - CGVD28 height to NAD83(CSRS): EPSG registered operation // - NAD83(CSRS) to CGVD2013(CGG2013) height by doing: // * NAD83(CSRS) to NAD83(CSRS)v6: ballpark // * NAD83(CSRS)v6 to CGVD2013(CGG2013): EPSG registered operation auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); { auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GE(list.size(), 1U); // Check that we have the transformation using NAD83(CSRS)v6 first // (as well as the one between NAD83(CSRS) to CGVD28 height) EXPECT_EQ(list[0]->nameStr(), "Inverse of NAD83(CSRS) to CGVD28 height (1) + " "Inverse of Ballpark geographic offset from NAD83(CSRS)v6 to " "NAD83(CSRS) + " "NAD83(CSRS)v6 to CGVD2013(CGG2013) height (1) + " "Inverse of Ballpark geographic offset from NAD83(CSRS) to " "NAD83(CSRS)v6"); } { auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(dst), NN_NO_CHECK(src), ctxt); ASSERT_GE(list.size(), 1U); // Check that we have the transformation using NAD83(CSRS)v6 first // (as well as the one between NAD83(CSRS) to CGVD28 height) EXPECT_EQ( list[0]->nameStr(), "Ballpark geographic offset from NAD83(CSRS) to NAD83(CSRS)v6 + " "Inverse of NAD83(CSRS)v6 to CGVD2013(CGG2013) height (1) + " "Ballpark geographic offset from NAD83(CSRS)v6 to NAD83(CSRS) + " "NAD83(CSRS) to CGVD28 height (1)"); } #endif } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_issue_3152_ch1903lv03_ln02_bound) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "COMPOUNDCRS[\"CH1903 / LV03 + LN02 height\",\n" " BOUNDCRS[\n" " SOURCECRS[\n" " PROJCRS[\"CH1903 / LV03\",\n" " BASEGEOGCRS[\"CH1903\",\n" " DATUM[\"CH1903\",\n" " ELLIPSOID[\"Bessel " "1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4149]],\n" " CONVERSION[\"Map projection of CH1903 / LV03\",\n" " METHOD[\"Hotine Oblique Mercator (variant B)\",\n" " ID[\"EPSG\",9815]],\n" " PARAMETER[\"Latitude of projection " "centre\",46.9524055555556,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of projection " "centre\",7.43958333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8812]],\n" " PARAMETER[\"Azimuth of initial line\",90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8813]],\n" " PARAMETER[\"Angle from Rectified to Skew " "Grid\",90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8814]],\n" " PARAMETER[\"Scale factor on initial line\",1,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]],\n" " PARAMETER[\"Easting at projection " "centre\",600000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8816]],\n" " PARAMETER[\"Northing at projection " "centre\",200000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8817]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",21781]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]]],\n" " ABRIDGEDTRANSFORMATION[\"MyTransformation from CH1903 to " "WGS84\",\n" " METHOD[\"Position Vector transformation (geog2D " "domain)\",\n" " ID[\"EPSG\",9606]],\n" " PARAMETER[\"X-axis translation\",674.374,\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",15.056,\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",405.346,\n" " ID[\"EPSG\",8607]],\n" " PARAMETER[\"X-axis rotation\",0,\n" " ID[\"EPSG\",8608]],\n" " PARAMETER[\"Y-axis rotation\",0,\n" " ID[\"EPSG\",8609]],\n" " PARAMETER[\"Z-axis rotation\",0,\n" " ID[\"EPSG\",8610]],\n" " PARAMETER[\"Scale difference\",1,\n" " ID[\"EPSG\",8611]]]],\n" " VERTCRS[\"LN02 height\",\n" " VDATUM[\"Landesnivellement 1902\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5728]]]"; auto srcObj = createFromUserInput(wkt, dbContext, false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto authFactoryEPSG = AuthorityFactory::create(dbContext, std::string("EPSG")); auto dst = authFactoryEPSG->createCoordinateReferenceSystem( "9518"); // "WGS 84 + EGM2008 height" auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_GE(list.size(), 1U); // Check that BoundCRS helmert transformation is used EXPECT_EQ(list[0]->nameStr(), "Inverse of Map projection of CH1903 / LV03 + " "MyTransformation from CH1903 to WGS84 + " "Inverse of ETRS89 to WGS 84 (1) + " "Inverse of ETRS89 to LN02 height + " "ETRS89 to WGS 84 (1) + " "WGS 84 to EGM2008 height (1)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=somerc +lat_0=46.9524055555556 " "+lon_0=7.43958333333333 +k_0=1 " "+x_0=600000 +y_0=200000 +ellps=bessel " "+step +proj=push +v_3 " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=674.374 +y=15.056 +z=405.346 " "+rx=0 +ry=0 +rz=0 +s=0 +convention=position_vector " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=pop +v_3 " "+step +proj=vgridshift " "+grids=ch_swisstopo_chgeo2004_ETRS89_LN02.tif " "+multiplier=1 " "+step +inv +proj=vgridshift +grids=us_nga_egm08_25.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); auto listInv = CoordinateOperationFactory::create()->createOperations( dst, NN_NO_CHECK(src), ctxt); ASSERT_GE(listInv.size(), 1U); EXPECT_EQ(listInv[0]->nameStr(), "Inverse of WGS 84 to EGM2008 height (1) + " "Inverse of ETRS89 to WGS 84 (1) + " "ETRS89 to LN02 height + " "ETRS89 to WGS 84 (1) + " "Inverse of MyTransformation from CH1903 to WGS84 + " "Map projection of CH1903 / LV03"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_compoundCRS_issue_3191_BD72_Ostend_height_to_WGS84_EGM96) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // BD72 + Ostend height auto srcObj = createFromUserInput("EPSG:4313+5710", dbContext, false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto authFactoryEPSG = AuthorityFactory::create(dbContext, std::string("EPSG")); auto dst = authFactoryEPSG->createCoordinateReferenceSystem( "9707"); // "WGS 84 + EGM96 height" { auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "BD72 to ETRS89 (3) + " "Inverse of ETRS89 to Ostend height (1) + " "ETRS89 to WGS 84 (1) + " "WGS 84 to EGM96 height (1)"); const char *expected_proj = "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=be_ign_bd72lb72_etrs89lb08.tif " "+step +proj=vgridshift +grids=be_ign_hBG18.tif +multiplier=1 " "+step +inv +proj=vgridshift +grids=us_nga_egm96_15.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"; EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), expected_proj); } { auto list = CoordinateOperationFactory::create()->createOperations( dst, NN_NO_CHECK(src), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of WGS 84 to EGM96 height (1) + " "Inverse of ETRS89 to WGS 84 (1) + " "ETRS89 to Ostend height (1) + " "Inverse of BD72 to ETRS89 (3)"); const char *expected_proj = "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +inv +proj=vgridshift +grids=be_ign_hBG18.tif +multiplier=1 " "+step +inv +proj=hgridshift +grids=be_ign_bd72lb72_etrs89lb08.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"; EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), expected_proj); } } // --------------------------------------------------------------------------- TEST(operation, vertCRS_to_vertCRS) { auto vertcrs_m_obj = PROJStringParser().createFromPROJString("+vunits=m"); auto vertcrs_m = nn_dynamic_pointer_cast<VerticalCRS>(vertcrs_m_obj); ASSERT_TRUE(vertcrs_m != nullptr); auto vertcrs_ft_obj = PROJStringParser().createFromPROJString("+vunits=ft"); auto vertcrs_ft = nn_dynamic_pointer_cast<VerticalCRS>(vertcrs_ft_obj); ASSERT_TRUE(vertcrs_ft != nullptr); auto vertcrs_us_ft_obj = PROJStringParser().createFromPROJString("+vunits=us-ft"); auto vertcrs_us_ft = nn_dynamic_pointer_cast<VerticalCRS>(vertcrs_us_ft_obj); ASSERT_TRUE(vertcrs_us_ft != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(vertcrs_m), NN_CHECK_ASSERT(vertcrs_ft)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +z_in=m +z_out=ft"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(vertcrs_m), NN_CHECK_ASSERT(vertcrs_ft)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=unitconvert +z_in=ft +z_out=m"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(vertcrs_ft), NN_CHECK_ASSERT(vertcrs_m)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +z_in=ft +z_out=m"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(vertcrs_ft), NN_CHECK_ASSERT(vertcrs_us_ft)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +z_in=ft +z_out=us-ft"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(vertcrs_us_ft), NN_CHECK_ASSERT(vertcrs_ft)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=unitconvert +z_in=us-ft +z_out=ft"); } auto vertCRSMetreUp = nn_dynamic_pointer_cast<VerticalCRS>(WKTParser().createFromWKT( "VERTCRS[\"my height\",VDATUM[\"my datum\"],CS[vertical,1]," "AXIS[\"gravity-related height (H)\",up," "LENGTHUNIT[\"metre\",1]]]")); ASSERT_TRUE(vertCRSMetreUp != nullptr); auto vertCRSMetreDown = nn_dynamic_pointer_cast<VerticalCRS>(WKTParser().createFromWKT( "VERTCRS[\"my depth\",VDATUM[\"my datum\"],CS[vertical,1]," "AXIS[\"depth (D)\",down,LENGTHUNIT[\"metre\",1]]]")); ASSERT_TRUE(vertCRSMetreDown != nullptr); auto vertCRSMetreDownFtUS = nn_dynamic_pointer_cast<VerticalCRS>(WKTParser().createFromWKT( "VERTCRS[\"my depth (ftUS)\",VDATUM[\"my datum\"],CS[vertical,1]," "AXIS[\"depth (D)\",down,LENGTHUNIT[\"US survey " "foot\",0.304800609601219]]]")); ASSERT_TRUE(vertCRSMetreDownFtUS != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(vertCRSMetreUp), NN_CHECK_ASSERT(vertCRSMetreDown)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=1,2,-3"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(vertCRSMetreUp), NN_CHECK_ASSERT(vertCRSMetreDownFtUS)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=affine +s33=-3.28083333333333"); } } // --------------------------------------------------------------------------- TEST(operation, vertCRS_to_vertCRS_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // NGVD29 height (m) authFactory->createCoordinateReferenceSystem("7968"), // NAVD88 height (1) authFactory->createCoordinateReferenceSystem("5703"), ctxt); ASSERT_EQ(list.size(), 4U); EXPECT_EQ(list[0]->nameStr(), "NGVD29 height (m) to NAVD88 height (3)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=vgridshift +grids=us_noaa_vertcone.tif +multiplier=1"); } // --------------------------------------------------------------------------- TEST(operation, vertCRS_to_vertCRS_New_Zealand_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( // NZVD2016 height authFactory->createCoordinateReferenceSystem("7839"), // Auckland 1946 height authFactory->createCoordinateReferenceSystem("5759"), ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=vgridshift +grids=nz_linz_auckht1946-nzvd2016.tif " "+multiplier=1"); } // --------------------------------------------------------------------------- TEST(operation, projCRS_3D_to_geogCRS_3D) { auto compoundcrs_ft_obj = PROJStringParser().createFromPROJString( "+proj=merc +vunits=ft +type=crs"); auto proj3DCRS_ft = nn_dynamic_pointer_cast<CRS>(compoundcrs_ft_obj); ASSERT_TRUE(proj3DCRS_ft != nullptr); auto geogcrs_m_obj = PROJStringParser().createFromPROJString( "+proj=longlat +vunits=m +type=crs"); auto geogcrs_m = nn_dynamic_pointer_cast<CRS>(geogcrs_m_obj); ASSERT_TRUE(geogcrs_m != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(proj3DCRS_ft), NN_CHECK_ASSERT(geogcrs_m)); ASSERT_TRUE(op != nullptr); EXPECT_FALSE(op->hasBallparkTransformation()); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=m +z_in=ft " "+xy_out=m +z_out=m " "+step +inv +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 " "+ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +z_in=m " "+xy_out=deg +z_out=m"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(geogcrs_m), NN_CHECK_ASSERT(proj3DCRS_ft)); ASSERT_TRUE(op != nullptr); EXPECT_FALSE(op->hasBallparkTransformation()); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 " "+step +proj=unitconvert +xy_in=m +z_in=m " "+xy_out=m +z_out=ft"); } } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D) { auto compoundcrs_ft_obj = WKTParser().createFromWKT( "COMPOUNDCRS[\"unknown\",\n" " PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Mercator (variant A)\",\n" " ID[\"EPSG\",9804]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",1,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " VERTCRS[\"unknown\",\n" " VDATUM[\"unknown\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"foot\",0.3048,\n" " ID[\"EPSG\",9002]]]]]"); auto compoundcrs_ft = nn_dynamic_pointer_cast<CRS>(compoundcrs_ft_obj); ASSERT_TRUE(compoundcrs_ft != nullptr); auto geogcrs_m_obj = PROJStringParser().createFromPROJString( "+proj=longlat +vunits=m +type=crs"); auto geogcrs_m = nn_dynamic_pointer_cast<CRS>(geogcrs_m_obj); ASSERT_TRUE(geogcrs_m != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(compoundcrs_ft), NN_CHECK_ASSERT(geogcrs_m)); ASSERT_TRUE(op != nullptr); EXPECT_TRUE(op->hasBallparkTransformation()); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=merc +lon_0=0 +k=1 +x_0=0 " "+y_0=0 +ellps=WGS84 +step +proj=unitconvert +xy_in=rad " "+z_in=ft +xy_out=deg +z_out=m"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(geogcrs_m), NN_CHECK_ASSERT(compoundcrs_ft)); ASSERT_TRUE(op != nullptr); EXPECT_TRUE(op->hasBallparkTransformation()); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +z_in=m " "+xy_out=rad +z_out=ft +step +proj=merc +lon_0=0 +k=1 +x_0=0 " "+y_0=0 +ellps=WGS84"); } } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); // CompoundCRS to Geog3DCRS, with vertical unit change, but without // ellipsoid height <--> vertical height correction { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem( "7406"), // NAD27 + NGVD29 height (ftUS) authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 ctxt); ASSERT_GE(list.size(), 1U); EXPECT_TRUE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->nameStr(), "NAD27 to WGS 84 (79) + Transformation from NGVD29 height " "(ftUS) to WGS 84 (ballpark vertical transformation, without " "ellipsoid height to vertical height correction)"); EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step " "+proj=hgridshift +grids=us_noaa_conus.tif " "+step +proj=unitconvert " "+xy_in=rad +z_in=us-ft +xy_out=deg +z_out=m +step " "+proj=axisswap +order=2,1"); } // CompoundCRS to Geog3DCRS, with same vertical unit, and with // direct ellipsoid height <--> vertical height correction and // direct horizontal transform (no-op here) { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem( "5500"), // NAD83(NSRS2007) + NAVD88 height authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 ctxt); ASSERT_GE(list.size(), 2U); EXPECT_EQ(list[1]->nameStr(), "Inverse of NAD83(NSRS2007) to NAVD88 height (1) + " "NAD83(NSRS2007) to WGS 84 (1)"); EXPECT_EQ(list[1]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_noaa_geoid09_conus.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(list[1]->remarks(), "For NAD83(NSRS2007) to NAVD88 height (1) (EPSG:9173): Uses " "Geoid09 hybrid model. Replaced by 2012 model (CT code 6326)." "\n" "For NAD83(NSRS2007) to WGS 84 (1) (EPSG:15931): " "Approximation assuming that NAD83(NSRS2007) is equivalent " "to WGS 84 within the accuracy of the transformation."); } // NAD83 + NAVD88 height --> WGS 84 { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83 + NAVD88 height auto srcObj = createFromUserInput( "EPSG:4269+5703", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto list = CoordinateOperationFactory::create()->createOperations( nnSrc, authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 ctxt); ASSERT_GE(list.size(), 2U); EXPECT_EQ(list[0]->nameStr(), "NAD83 to NAD83(HARN) (47) + " "NAD83(HARN) to NAD83(FBN) (1) + " "Inverse of NAD83(FBN) to NAVD88 height (1) + " "Inverse of NAD83(HARN) to NAD83(FBN) (1) + " "NAD83(HARN) to WGS 84 (3)"); EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=gridshift " "+grids=us_noaa_nadcon5_nad83_1986_nad83_harn_conus.tif " "+step +proj=gridshift +no_z_transform " "+grids=us_noaa_nadcon5_nad83_harn_nad83_fbn_conus.tif " "+step +proj=vgridshift +grids=us_noaa_geoid03_conus.tif " "+multiplier=1 " "+step +inv +proj=gridshift " "+grids=us_noaa_nadcon5_nad83_harn_nad83_fbn_conus.tif " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=-0.991 +y=1.9072 +z=0.5129 " "+rx=-0.0257899075194932 " "+ry=-0.0096500989602704 +rz=-0.0116599432323421 +s=0 " "+convention=coordinate_frame " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // Another variation, but post horizontal adjustment is in two steps { auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 height auto srcObj = createFromUserInput( "EPSG:6318+5703", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto list = CoordinateOperationFactory::create()->createOperations( nnSrc, authFactory->createCoordinateReferenceSystem("4985"), // WGS 72 3D ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of NAD83(2011) to NAVD88 height (3) + " "NAD83(2011) to WGS 84 (1) + " "Inverse of WGS 72 to WGS 84 (2)"); EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_noaa_g2018u0.tif " "+multiplier=1 " "+step +proj=cart +ellps=WGS84 " "+step +inv +proj=helmert +x=0 +y=0 +z=4.5 +rx=0 +ry=0 " "+rz=0.554 +s=0.219 +convention=position_vector " "+step +inv +proj=cart +ellps=WGS72 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // Check that we can handle vertical transformations where there is a // mix of available ones in the PROJ namespace (mx_inegi_ggm10) and in // in the EPSG namespace (us_noaa_g2018u0) // This test might no longer test this scenario if mx_inegi_ggm10 is // referenced one day by EPSG, but at least this tests a common use case. { auto authFactoryAll = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactoryAll, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 height auto srcObj = createFromUserInput( "EPSG:6318+5703", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto list = CoordinateOperationFactory::create()->createOperations( nnSrc, authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 3D ctxt); bool foundGeoid2018 = false; bool foundGGM10 = false; for (const auto &op : list) { try { const auto projString = op->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()); if (projString.find("us_noaa_g2018u0.tif") != std::string::npos) foundGeoid2018 = true; else if (projString.find("mx_inegi_ggm10.tif") != std::string::npos) foundGGM10 = true; } catch (const std::exception &) { } } EXPECT_TRUE(foundGeoid2018); EXPECT_TRUE(foundGGM10); } } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D_with_3D_helmert_context) { // Use case of https://github.com/OSGeo/PROJ/issues/2225 auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // WGS84 + EGM96 height auto srcObj = createFromUserInput("EPSG:4326+5773", dbContext, false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), // CH1903+ authFactory->createCoordinateReferenceSystem("4150")->promoteTo3D( std::string(), dbContext), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of WGS 84 to EGM96 height (1) + " "Inverse of CH1903+ to WGS 84 (1)"); // Check that there is no push v_3 / pop v_3 const char *expected_proj = "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=-674.374 +y=-15.056 +z=-405.346 " "+step +inv +proj=cart +ellps=bessel " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"; EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, dbContext) .get()), expected_proj); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D_with_3D_helmert_same_geog_src_target_context) { // Use case of https://github.com/OSGeo/PROJ/pull/2584 // From EPSG:XXXX+YYYY to EPSG:XXXX (3D), with a vertical shift grid // operation in another datum ZZZZ, and the XXXX<--->ZZZZ being an Helmert auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // CH1903+ + EGM96 height auto srcObj = createFromUserInput("EPSG:4150+5773", dbContext, false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), // CH1903+ authFactory->createCoordinateReferenceSystem("4150")->promoteTo3D( std::string(), dbContext), ctxt); ASSERT_GE(list.size(), 1U); // Check that there is push v_3 / pop v_3 in the step before vgridshift // Check that there is *no* push v_3 / pop v_3 after vgridshift const char *expected_proj = "+proj=pipeline " "+step +proj=push +v_1 +v_2 " // avoid any horizontal change "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=push +v_3 " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=674.374 +y=15.056 +z=405.346 " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=-674.374 +y=-15.056 +z=-405.346 " "+step +inv +proj=cart +ellps=bessel " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1 " "+step +proj=pop +v_1 +v_2" // avoid any horizontal change ; EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, dbContext) .get()), expected_proj); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D_with_null_helmert_same_geog_src_target_context) { // Variation of previous case // From EPSG:XXXX+YYYY to EPSG:XXXX (3D), with a vertical shift grid // operation in another datum ZZZZ, and the XXXX<--->ZZZZ being a // null Helmert auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // ETRS89 + EGM96 height auto srcObj = createFromUserInput("EPSG:4258+5773", dbContext, false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), // ETRS89 3D authFactory->createCoordinateReferenceSystem("4937"), ctxt); ASSERT_GE(list.size(), 1U); // No push/pop needed const char *expected_proj = "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"; EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, dbContext) .get()), expected_proj); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D_with_same_geog_src_target_interp_context) { auto dbContext = DatabaseContext::create(); // Tests a mix of Datum and DatumEnsemble regarding WGS 84 when we compare // the datums used in the source -> interpolation_crs and // interpolation_crs -> target transformations. auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto dstObj = WKTParser().createFromWKT( "COMPOUNDCRS[\"WGS 84 + my_height\",\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]],\n" " BOUNDCRS[\n" " SOURCECRS[\n" " VERTCRS[\"my_height\",\n" " VDATUM[\"my_height\"],\n" " CS[vertical,1],\n" " AXIS[\"up\",up,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[" "\"my_height to WGS84 ellipsoidal height\",\n" " METHOD[\"GravityRelatedHeight to Geographic3D\"],\n" " PARAMETERFILE[\"Geoid (height correction) model file\"," "\"fake.gtx\",\n" " ID[\"EPSG\",8666]]]]]"); auto dst = nn_dynamic_pointer_cast<CRS>(dstObj); ASSERT_TRUE(dst != nullptr); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem("4979"), // WGS 84 3D NN_NO_CHECK(dst), ctxt); ASSERT_EQ(list.size(), 1U); const char *expected_proj = "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift +grids=fake.gtx +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"; EXPECT_EQ(list[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, dbContext) .get()), expected_proj); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D_WGS84_to_GDA2020_AHD_Height) { // Use case of https://github.com/OSGeo/PROJ/issues/2348 auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); { auto list = CoordinateOperationFactory::create()->createOperations( // GDA2020 + AHD height authFactory->createCoordinateReferenceSystem("9463"), // WGS 84 3D authFactory->createCoordinateReferenceSystem("4979"), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of GDA2020 to AHD height (1) + " "GDA2020 to WGS 84 (2)"); } // Inverse { auto list = CoordinateOperationFactory::create()->createOperations( // WGS 84 3D authFactory->createCoordinateReferenceSystem("4979"), // GDA2020 + AHD height authFactory->createCoordinateReferenceSystem("9463"), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Inverse of GDA2020 to WGS 84 (2) + " "GDA2020 to AHD height (1)"); } } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_2D_promote_to_3D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83 + NAVD88 height auto srcObj = createFromUserInput("EPSG:4269+5703", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("4269")->promoteTo3D( std::string(), authFactory->databaseContext()); // NAD83 auto listCompoundToGeog2D = CoordinateOperationFactory::create()->createOperations(nnSrc, dst, ctxt); // The checked value is not that important, but in case this changes, // likely due to a EPSG upgrade, worth checking EXPECT_EQ(listCompoundToGeog2D.size(), 199U); auto listGeog2DToCompound = CoordinateOperationFactory::create()->createOperations(dst, nnSrc, ctxt); EXPECT_EQ(listGeog2DToCompound.size(), listCompoundToGeog2D.size()); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_of_projCRS_to_geogCRS_3D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // SPCS83 California zone 1 (US Survey feet) + NAVD88 height (ftUS) auto srcObj = createFromUserInput("EPSG:2225+6360", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("4269")->promoteTo3D( std::string(), authFactory->databaseContext()); // NAD83 auto list = CoordinateOperationFactory::create()->createOperations( nnSrc, dst, ctxt); // The checked value is not that important, but in case this changes, // likely due to a EPSG upgrade, worth checking // We want to make sure that the horizontal adjustments before and after // the vertical transformation are the reverse of each other, and there are // not mixes with different alternative operations (like California grid // forward and Nevada grid reverse) ASSERT_EQ(list.size(), 21U); // Check that unit conversion is OK auto op_proj = list[0]->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_EQ(op_proj, "+proj=pipeline " "+step +proj=unitconvert +xy_in=us-ft +xy_out=m " "+step +inv +proj=lcc +lat_0=39.3333333333333 +lon_0=-122 " "+lat_1=41.6666666666667 +lat_2=40 +x_0=2000000.0001016 " "+y_0=500000.0001016 +ellps=GRS80 " "+step +proj=hgridshift +grids=us_noaa_cnhpgn.tif " "+step +proj=gridshift +no_z_transform " "+grids=us_noaa_nadcon5_nad83_harn_nad83_fbn_conus.tif " "+step +proj=unitconvert +z_in=us-ft +z_out=m " "+step +proj=vgridshift +grids=us_noaa_geoid03_conus.tif " "+multiplier=1 " "+step +inv +proj=gridshift " "+grids=us_noaa_nadcon5_nad83_harn_nad83_fbn_conus.tif " "+step +inv +proj=hgridshift +grids=us_noaa_cnhpgn.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_3D_KNOWN_AVAILABLE_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse::KNOWN_AVAILABLE); auto list = CoordinateOperationFactory::create()->createOperations( authFactory->createCoordinateReferenceSystem( "9537"), // RGAF09 + Martinique 1987 height authFactory->createCoordinateReferenceSystem("4557"), // RRAF 1991 ctxt); ASSERT_GE(list.size(), 2U); // Make sure that "RGAF09 to Martinique 1987 height (2)" (using RAMART2016) // is listed first EXPECT_EQ(list[0]->nameStr(), "Inverse of RGAF09 to Martinique 1987 height (2) + " "Inverse of RRAF 1991 to RGAF09 (1)"); EXPECT_EQ(list[1]->nameStr(), "Inverse of RRAF 1991 to RGAF09 (1) + " "Inverse of RRAF 1991 to Martinique 1987 height (1)"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_from_wkt_without_id_to_geogCRS) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "COMPOUNDCRS[\"NAD83(2011) + NAVD88 height\",\n" " GEOGCRS[\"NAD83(2011)\",\n" " DATUM[\"NAD83 (National Spatial Reference System 2011)\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " VERTCRS[\"NAVD88 height\",\n" " VDATUM[\"North American Vertical Datum 1988\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]]]"; auto srcObj = createFromUserInput(wkt, authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto dst = authFactory->createCoordinateReferenceSystem("6319"); // NAD83(2011) auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); // NAD83(2011) + NAVD88 height auto srcRefObj = createFromUserInput("EPSG:6318+5703", authFactory->databaseContext(), false); auto srcRef = nn_dynamic_pointer_cast<CRS>(srcRefObj); ASSERT_TRUE(srcRef != nullptr); ASSERT_TRUE( src->isEquivalentTo(srcRef.get(), IComparable::Criterion::EQUIVALENT)); auto listRef = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcRef), dst, ctxt); EXPECT_EQ(list.size(), listRef.size()); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_of_projCRS_from_wkt_without_id_or_extent_to_geogCRS) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "COMPOUNDCRS[\"NAD83 / Pennsylvania South + NAVD88 height\",\n" " PROJCRS[\"NAD83 / Pennsylvania South\",\n" " BASEGEOGCRS[\"NAD83\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"SPCS83 Pennsylvania South zone (meters)\",\n" " METHOD[\"Lambert Conic Conformal (2SP)\",\n" " ID[\"EPSG\",9802]],\n" " PARAMETER[\"Latitude of false origin\",39.3333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",-77.75,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard " "parallel\",40.9666666666667,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard " "parallel\",39.9333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",600000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (X)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (Y)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]],\n" " VERTCRS[\"NAVD88 height\",\n" " VDATUM[\"North American Vertical Datum 1988\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]]]"; auto srcObj = createFromUserInput(wkt, authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto dst = authFactory->createCoordinateReferenceSystem("4269"); // NAD83 auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); // NAD83 / Pennsylvania South + NAVD88 height auto srcRefObj = createFromUserInput("EPSG:32129+5703", authFactory->databaseContext(), false); auto srcRef = nn_dynamic_pointer_cast<CRS>(srcRefObj); ASSERT_TRUE(srcRef != nullptr); ASSERT_TRUE( src->isEquivalentTo(srcRef.get(), IComparable::Criterion::EQUIVALENT)); auto listRef = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcRef), dst, ctxt); EXPECT_EQ(list.size(), listRef.size()); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_with_vertical_unit_change) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 height (ftUS) auto srcObj = createFromUserInput("EPSG:6318+6360", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("6319"); // NAD83(2011) 3D auto listCompoundToGeog = CoordinateOperationFactory::create()->createOperations(nnSrc, dst, ctxt); ASSERT_TRUE(!listCompoundToGeog.empty()); // NAD83(2011) + NAVD88 height auto srcObjCompoundVMetre = createFromUserInput( "EPSG:6318+5703", authFactory->databaseContext(), false); auto srcCompoundVMetre = nn_dynamic_pointer_cast<CRS>(srcObjCompoundVMetre); ASSERT_TRUE(srcCompoundVMetre != nullptr); auto listCompoundMetreToGeog = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCompoundVMetre), dst, ctxt); // Check that we get the same and similar results whether we start from // regular NAVD88 height or its ftUs variant ASSERT_EQ(listCompoundToGeog.size(), listCompoundMetreToGeog.size()); EXPECT_EQ(listCompoundToGeog[0]->nameStr(), "Conversion from NAVD88 height (ftUS) to NAVD88 height + " + listCompoundMetreToGeog[0]->nameStr()); EXPECT_EQ( listCompoundToGeog[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), replaceAll(listCompoundMetreToGeog[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+step +proj=unitconvert +xy_in=deg +xy_out=rad", "+step +proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=rad " "+z_out=m")); // Check reverse path auto listGeogToCompound = CoordinateOperationFactory::create()->createOperations(dst, nnSrc, ctxt); EXPECT_EQ(listGeogToCompound.size(), listCompoundToGeog.size()); } // --------------------------------------------------------------------------- // Use case of https://github.com/OSGeo/PROJ/issues/3938 TEST(operation, compoundCRS_ftUS_to_geogCRS_ft) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 height (ftUS) auto srcObj = createFromUserInput("EPSG:6318+6360", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("6319")->alterCSLinearUnit( UnitOfMeasure::FOOT); // NAD83(2011) with foot auto res = CoordinateOperationFactory::create()->createOperations( nnSrc, dst, ctxt); ASSERT_TRUE(!res.empty()); EXPECT_EQ( res[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=rad +z_out=m " "+step +proj=vgridshift +grids=us_noaa_g2018u0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=ft " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( res.back()->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=deg +z_out=ft"); auto resInv = CoordinateOperationFactory::create()->createOperations( dst, nnSrc, ctxt); ASSERT_TRUE(!resInv.empty()); EXPECT_EQ( resInv[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=m " "+step +inv +proj=vgridshift +grids=us_noaa_g2018u0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=us-ft " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( resInv.back()->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=unitconvert +xy_in=deg +z_in=ft +xy_out=deg +z_out=us-ft"); } // --------------------------------------------------------------------------- // Use case of https://github.com/OSGeo/PROJ/issues/3938 TEST(operation, compoundCRS_ft_to_geogCRS_ft) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 height (ft) auto srcObj = createFromUserInput("EPSG:6318+8228", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("6319")->alterCSLinearUnit( UnitOfMeasure::FOOT); // NAD83(2011) with foot auto res = CoordinateOperationFactory::create()->createOperations( nnSrc, dst, ctxt); ASSERT_TRUE(!res.empty()); EXPECT_EQ( res[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=m " "+step +proj=vgridshift +grids=us_noaa_g2018u0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=ft " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( res.back()->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=noop"); auto resInv = CoordinateOperationFactory::create()->createOperations( dst, nnSrc, ctxt); ASSERT_TRUE(!resInv.empty()); EXPECT_EQ( resInv[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=m " "+step +inv +proj=vgridshift +grids=us_noaa_g2018u0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=ft " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( resInv.back()->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=noop"); } // --------------------------------------------------------------------------- // Use case of https://github.com/OSGeo/PROJ/issues/3938 TEST(operation, compoundCRS_m_to_geogCRS_ft) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 height auto srcObj = createFromUserInput("EPSG:6318+5703", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("6319")->alterCSLinearUnit( UnitOfMeasure::FOOT); // NAD83(2011) with foot auto res = CoordinateOperationFactory::create()->createOperations( nnSrc, dst, ctxt); ASSERT_TRUE(!res.empty()); EXPECT_EQ( res[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_noaa_g2018u0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=ft " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( res.back()->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=unitconvert +z_in=m +z_out=ft"); auto resInv = CoordinateOperationFactory::create()->createOperations( dst, nnSrc, ctxt); ASSERT_TRUE(!resInv.empty()); EXPECT_EQ( resInv[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=m " "+step +inv +proj=vgridshift +grids=us_noaa_g2018u0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); EXPECT_EQ( resInv.back()->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+proj=unitconvert +z_in=ft +z_out=m"); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_geogCRS_with_vertical_unit_change_and_complex_horizontal_change) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 height (ftUS) auto srcObj = createFromUserInput("EPSG:6318+6360", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("7665"); // WGS84(G1762) 3D auto listCompoundToGeog = CoordinateOperationFactory::create()->createOperations(nnSrc, dst, ctxt); // NAD83(2011) + NAVD88 height auto srcObjCompoundVMetre = createFromUserInput( "EPSG:6318+5703", authFactory->databaseContext(), false); auto srcCompoundVMetre = nn_dynamic_pointer_cast<CRS>(srcObjCompoundVMetre); ASSERT_TRUE(srcCompoundVMetre != nullptr); auto listCompoundMetreToGeog = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCompoundVMetre), dst, ctxt); // Check that we get the same and similar results whether we start from // regular NAVD88 height or its ftUs variant ASSERT_EQ(listCompoundToGeog.size(), listCompoundMetreToGeog.size()); ASSERT_GE(listCompoundToGeog.size(), 1U); EXPECT_EQ(listCompoundToGeog[0]->nameStr(), "Conversion from NAVD88 height (ftUS) to NAVD88 height + " + listCompoundMetreToGeog[0]->nameStr()); EXPECT_EQ( listCompoundToGeog[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), replaceAll(listCompoundMetreToGeog[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+step +proj=unitconvert +xy_in=deg +xy_out=rad", "+step +proj=unitconvert +xy_in=deg +z_in=us-ft +xy_out=rad " "+z_out=m")); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_geogCRS_with_height_depth_reversal) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 depth auto srcObj = createFromUserInput("EPSG:6318+6357", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("6319"); // NAD83(2011) 3D auto listCompoundToGeog = CoordinateOperationFactory::create()->createOperations(nnSrc, dst, ctxt); ASSERT_TRUE(!listCompoundToGeog.empty()); // NAD83(2011) + NAVD88 height auto srcObjCompoundVMetre = createFromUserInput( "EPSG:6318+5703", authFactory->databaseContext(), false); auto srcCompoundVMetre = nn_dynamic_pointer_cast<CRS>(srcObjCompoundVMetre); ASSERT_TRUE(srcCompoundVMetre != nullptr); auto listCompoundMetreToGeog = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCompoundVMetre), dst, ctxt); // Check that we get the same and similar results whether we start from // regular NAVD88 height or its depth variant ASSERT_EQ(listCompoundToGeog.size(), listCompoundMetreToGeog.size()); EXPECT_EQ(listCompoundToGeog[0]->nameStr(), "Conversion from NAVD88 depth to NAVD88 height + " + listCompoundMetreToGeog[0]->nameStr()); EXPECT_EQ( listCompoundToGeog[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), replaceAll(listCompoundMetreToGeog[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+step +proj=unitconvert +xy_in=deg +xy_out=rad", "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=axisswap +order=1,2,-3")); // Check reverse path auto listGeogToCompound = CoordinateOperationFactory::create()->createOperations(dst, nnSrc, ctxt); EXPECT_EQ(listGeogToCompound.size(), listCompoundToGeog.size()); } // --------------------------------------------------------------------------- TEST( operation, compoundCRS_to_geogCRS_with_vertical_unit_change_and_height_depth_reversal) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); // NAD83(2011) + NAVD88 depth (ftUS) auto srcObj = createFromUserInput("EPSG:6318+6358", authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto nnSrc = NN_NO_CHECK(src); auto dst = authFactory->createCoordinateReferenceSystem("6319"); // NAD83(2011) 3D auto listCompoundToGeog = CoordinateOperationFactory::create()->createOperations(nnSrc, dst, ctxt); ASSERT_TRUE(!listCompoundToGeog.empty()); // NAD83(2011) + NAVD88 height auto srcObjCompoundVMetre = createFromUserInput( "EPSG:6318+5703", authFactory->databaseContext(), false); auto srcCompoundVMetre = nn_dynamic_pointer_cast<CRS>(srcObjCompoundVMetre); ASSERT_TRUE(srcCompoundVMetre != nullptr); auto listCompoundMetreToGeog = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(srcCompoundVMetre), dst, ctxt); // Check that we get the same and similar results whether we start from // regular NAVD88 height or its depth (ftUS) variant ASSERT_EQ(listCompoundToGeog.size(), listCompoundMetreToGeog.size()); EXPECT_EQ(listCompoundToGeog[0]->nameStr(), "Conversion from NAVD88 depth (ftUS) to NAVD88 height + " + listCompoundMetreToGeog[0]->nameStr()); EXPECT_EQ( listCompoundToGeog[0]->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), replaceAll(listCompoundMetreToGeog[0]->exportToPROJString( PROJStringFormatter::create( PROJStringFormatter::Convention::PROJ_5, authFactory->databaseContext()) .get()), "+step +proj=unitconvert +xy_in=deg +xy_out=rad", "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=affine +s33=-0.304800609601219")); // Check reverse path auto listGeogToCompound = CoordinateOperationFactory::create()->createOperations(dst, nnSrc, ctxt); EXPECT_EQ(listGeogToCompound.size(), listCompoundToGeog.size()); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_of_vertCRS_with_geoid_model_to_geogCRS) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "COMPOUNDCRS[\"NAD83 / Pennsylvania South + NAVD88 height\",\n" " PROJCRS[\"NAD83 / Pennsylvania South\",\n" " BASEGEOGCRS[\"NAD83\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"SPCS83 Pennsylvania South zone (meters)\",\n" " METHOD[\"Lambert Conic Conformal (2SP)\",\n" " ID[\"EPSG\",9802]],\n" " PARAMETER[\"Latitude of false origin\",39.3333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8821]],\n" " PARAMETER[\"Longitude of false origin\",-77.75,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8822]],\n" " PARAMETER[\"Latitude of 1st standard " "parallel\",40.9666666666667,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard " "parallel\",39.9333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"Easting at false origin\",600000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8826]],\n" " PARAMETER[\"Northing at false origin\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8827]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (X)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (Y)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]],\n" " VERTCRS[\"NAVD88 height\",\n" " VDATUM[\"North American Vertical Datum 1988\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " GEOIDMODEL[\"GEOID12B\"]]]"; auto srcObj = createFromUserInput(wkt, authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto dst = authFactory->createCoordinateReferenceSystem("4269")->promoteTo3D( std::string(), authFactory->databaseContext()); // NAD83 auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_TRUE(!list.empty()); EXPECT_EQ(list[0]->nameStr(), "Inverse of SPCS83 Pennsylvania South zone (meters) + " "Ballpark geographic offset from NAD83 to NAD83(2011) + " "Inverse of NAD83(2011) to NAVD88 height (1) + " "Ballpark geographic offset from NAD83(2011) to NAD83"); auto op_proj = list[0]->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_EQ( op_proj, "+proj=pipeline " "+step +inv +proj=lcc +lat_0=39.3333333333333 +lon_0=-77.75 " "+lat_1=40.9666666666667 +lat_2=39.9333333333333 +x_0=600000 " "+y_0=0 +ellps=GRS80 " "+step +proj=vgridshift +grids=us_noaa_g2012bu0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_of_horizCRS_with_TOWGS84_vertCRS_with_geoid_model_to_geogCRS) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "COMPD_CS[\"NAD83(CSRS) + CGVD28 height - HT2_0\",\n" " GEOGCS[\"NAD83(CSRS)\",\n" " DATUM[\"NAD83_Canadian_Spatial_Reference_System\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6140\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4617\"]],\n" " VERT_CS[\"CGVD28 height - HT2_0\",\n" " VERT_DATUM[\"Canadian Geodetic Vertical Datum of " "1928\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"HT2_0.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5114\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5713\"]]]"; auto srcObj = createFromUserInput(wkt, authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); // NAD83(CSRS) 3D auto dst = authFactory->createCoordinateReferenceSystem("4955"); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_EQ(list.size(), 1U); auto op_proj = list[0]->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_EQ(op_proj, "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=HT2_0.gtx +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_of_vertCRS_with_geoid_model_by_id_to_geogCRS) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "COMPOUNDCRS[\"NAD83(CSRS) / MTM zone 7 + CGVD28 height\",\n" " PROJCRS[\"NAD83(CSRS) / MTM zone 7\",\n" " BASEGEOGCRS[\"NAD83(CSRS)\",\n" " DATUM[\"North American Datum of 1983 (CSRS)\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"MTM zone 7\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-70.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",304800,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (E(X))\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (N(Y))\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]],\n" " VERTCRS[\"CGVD28 height\",\n" " VDATUM[\"Canadian Geodetic Vertical Datum of 1928\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " GEOIDMODEL[\"HT2_2002v70\",\n" " ID[\"EPSG\",9985]],\n" " ID[\"EPSG\",5713]]]"; auto srcObj = createFromUserInput(wkt, authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto dst = authFactory->createCoordinateReferenceSystem("4955")->promoteTo3D( std::string(), authFactory->databaseContext()); // NAD83(CSRS) 3d auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_TRUE(!list.empty()); EXPECT_EQ(list[0]->nameStr(), "Inverse of MTM zone 7 + " "Ballpark geographic offset from NAD83(CSRS) to NAD83(CSRS)v4 + " "Inverse of NAD83(CSRS)v4 to CGVD28 height (1) + " "Ballpark geographic offset from NAD83(CSRS)v4 to NAD83(CSRS)"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_of_bound_horizCRS_and_bound_vertCRS_to_geogCRS) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "COMPOUNDCRS[\"CH1903 / LV03 + EGM96 height\",\n" " BOUNDCRS[\n" " SOURCECRS[\n" " PROJCRS[\"CH1903 / LV03\",\n" " BASEGEOGCRS[\"CH1903\",\n" " DATUM[\"CH1903\",\n" " ELLIPSOID[\"Bessel " "1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4149]],\n" " CONVERSION[\"Swiss Oblique Mercator 1903M\",\n" " METHOD[\"Hotine Oblique Mercator (variant B)\",\n" " ID[\"EPSG\",9815]],\n" " PARAMETER[\"Latitude of projection " "centre\",46.9524055555556,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of projection " "centre\",7.43958333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8812]],\n" " PARAMETER[\"Azimuth of initial line\",90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8813]],\n" " PARAMETER[\"Angle from Rectified to Skew " "Grid\",90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8814]],\n" " PARAMETER[\"Scale factor on initial line\",1,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]],\n" " PARAMETER[\"Easting at projection " "centre\",600000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8816]],\n" " PARAMETER[\"Northing at projection " "centre\",200000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8817]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (Y)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (X)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]]],\n" " ABRIDGEDTRANSFORMATION[\"CH1903 to WGS 84 (2)\",\n" " VERSION[\"BfL-CH 2\"],\n" " METHOD[\"Geocentric translations (geog2D domain)\",\n" " ID[\"EPSG\",9603]],\n" " PARAMETER[\"X-axis translation\",674.374,\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",15.056,\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",405.346,\n" " ID[\"EPSG\",8607]]]],\n" " BOUNDCRS[\n" " SOURCECRS[\n" " VERTCRS[\"EGM96 height\",\n" " VDATUM[\"EGM96 geoid\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"Geodesy.\"],\n" " AREA[\"World.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",5773]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[\"WGS 84 to EGM96 height (1)\",\n" " METHOD[\"Geographic3D to GravityRelatedHeight (EGM)\",\n" " ID[\"EPSG\",9661]],\n" " PARAMETERFILE[\"Geoid (height correction) model " "file\",\"us_nga_egm96_15.tif\"]]]]"; auto srcObj = createFromUserInput(wkt, authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); // WGS 84 3D auto dst = authFactory->createCoordinateReferenceSystem("4979"); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_EQ(list.size(), 1U); auto op_proj = list[0]->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_EQ(op_proj, "+proj=pipeline " "+step +inv +proj=somerc +lat_0=46.9524055555556 " "+lon_0=7.43958333333333 +k_0=1 " "+x_0=600000 +y_0=200000 +ellps=bessel " "+step +proj=push +v_3 " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=674.374 +y=15.056 +z=405.346 " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=vgridshift +grids=us_nga_egm96_15.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_from_WKT2_to_geogCRS_3D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto src = authFactory->createCoordinateReferenceSystem( "7415"); // Amersfoort / RD New + NAP height auto dst = authFactory->createCoordinateReferenceSystem("4937"); // ETRS89 3D auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_GE(list.size(), 1U); auto wkt2 = src->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); auto obj = WKTParser().createFromWKT(wkt2); auto src_from_wkt2 = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(src_from_wkt2 != nullptr); auto list2 = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src_from_wkt2), dst, ctxt); ASSERT_GE(list.size(), list2.size()); for (size_t i = 0; i < list.size(); i++) { const auto &op = list[i]; const auto &op2 = list2[i]; EXPECT_TRUE( op->isEquivalentTo(op2.get(), IComparable::Criterion::EQUIVALENT)); } } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_from_WKT2_no_id_to_geogCRS_3D_context) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto src = authFactory->createCoordinateReferenceSystem( "7415"); // Amersfoort / RD New + NAP height auto dst = authFactory->createCoordinateReferenceSystem("4937"); // ETRS89 3D auto list = CoordinateOperationFactory::create()->createOperations(src, dst, ctxt); ASSERT_GE(list.size(), 1U); { auto op_proj = list[0]->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_EQ( op_proj, "+proj=pipeline +step +inv +proj=sterea +lat_0=52.1561605555556 " "+lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 " "+ellps=bessel " "+step +proj=hgridshift +grids=nl_nsgi_rdtrans2018.tif " "+step +proj=vgridshift +grids=nl_nsgi_nlgeo2018.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } auto wkt2 = "COMPOUNDCRS[\"unknown\",\n" " PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"Amersfoort\",\n" " DATUM[\"Amersfoort\",\n" " ELLIPSOID[\"Bessel " "1841\",6377397.155,299.1528128]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Oblique Stereographic\"],\n" " PARAMETER[\"Latitude of natural origin\",52.1561605555556],\n" " PARAMETER[\"Longitude of natural origin\",5.38763888888889],\n" " PARAMETER[\"Scale factor at natural origin\",0.9999079],\n" " PARAMETER[\"False easting\",155000],\n" " PARAMETER[\"False northing\",463000]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " LENGTHUNIT[\"metre\",1]],\n" " VERTCRS[\"NAP height\",\n" " VDATUM[\"Normaal Amsterdams Peil\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]],\n" " USAGE[\n" " SCOPE[\"unknown\"],\n" " AREA[\"Netherlands - onshore\"],\n" " BBOX[50.75,3.2,53.7,7.22]]]"; auto obj = WKTParser().createFromWKT(wkt2); auto src_from_wkt2 = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(src_from_wkt2 != nullptr); auto list2 = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src_from_wkt2), dst, ctxt); ASSERT_EQ(list.size(), list2.size()); for (size_t i = 0; i < list.size(); i++) { const auto &op = list[i]; const auto &op2 = list2[i]; auto op_proj = op->exportToPROJString(PROJStringFormatter::create().get()); auto op2_proj = op2->exportToPROJString(PROJStringFormatter::create().get()); EXPECT_EQ(op_proj, op2_proj) << "op=" << op->nameStr() << " op2=" << op2->nameStr(); } } // --------------------------------------------------------------------------- TEST(operation, proj3DCRS_with_non_meter_horiz_and_vertical_to_geog) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=31 +datum=WGS84 +units=us-ft +vunits=us-ft +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), authFactory->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 1U); // Check that vertical unit conversion is done just once EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=us-ft +z_in=us-ft " "+xy_out=m +z_out=m " "+step +inv +proj=utm +zone=31 +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_non_meter_horiz_and_vertical_to_geog) { auto objSrc = WKTParser().createFromWKT( "COMPOUNDCRS[\"unknown\",\n" " PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",16031]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219,\n" " ID[\"EPSG\",9003]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219,\n" " ID[\"EPSG\",9003]]]],\n" " VERTCRS[\"unknown\",\n" " VDATUM[\"unknown\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219,\n" " ID[\"EPSG\",9003]]]]]" ); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), authFactory->createCoordinateReferenceSystem("4979"), ctxt); ASSERT_EQ(list.size(), 1U); // Check that vertical unit conversion is done just once EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=us-ft +xy_out=m " "+step +inv +proj=utm +zone=31 +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +z_in=us-ft " "+xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_to_compoundCRS) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS67 [email protected] +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 [email protected] [email protected] " "+geoid_crs=horizontal_crs " "+type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift [email protected] " "+step +inv +proj=hgridshift [email protected] " "+step +inv +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); auto opInverse = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(dst), NN_CHECK_ASSERT(src)); ASSERT_TRUE(opInverse != nullptr); EXPECT_TRUE(opInverse->inverse()->_isEquivalentTo(op.get())); } // --------------------------------------------------------------------------- TEST(operation, boundCRS_to_compoundCRS_with_hubCRS_same_as_compound_geographicCRS) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto wkt = "BOUNDCRS[\n" " SOURCECRS[\n" " PROJCRS[\"CH1903 / LV03\",\n" " BASEGEOGCRS[\"CH1903\",\n" " DATUM[\"CH1903\",\n" " ELLIPSOID[\"Bessel " "1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6149]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Hotine Oblique Mercator (variant B)\",\n" " ID[\"EPSG\",9815]],\n" " PARAMETER[\"Latitude of projection " "centre\",46.9524055555556,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of projection " "centre\",7.43958333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8812]],\n" " PARAMETER[\"Azimuth of initial line\",90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8813]],\n" " PARAMETER[\"Angle from Rectified to Skew Grid\",90,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8814]],\n" " PARAMETER[\"Scale factor on initial line\",1,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]],\n" " PARAMETER[\"Easting at projection centre\",600000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8816]],\n" " PARAMETER[\"Northing at projection centre\",200000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8817]]],\n" " CS[Cartesian,3],\n" " AXIS[\"y\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"x\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " MEMBER[\"World Geodetic System 1984 (G2139)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[\"Transformation from CH1903 to WGS84\",\n" " METHOD[\"Position Vector transformation (geog2D domain)\",\n" " ID[\"EPSG\",9606]],\n" " PARAMETER[\"X-axis translation\",674.4,\n" " ID[\"EPSG\",8605]],\n" " PARAMETER[\"Y-axis translation\",15.1,\n" " ID[\"EPSG\",8606]],\n" " PARAMETER[\"Z-axis translation\",405.3,\n" " ID[\"EPSG\",8607]],\n" " PARAMETER[\"X-axis rotation\",0,\n" " ID[\"EPSG\",8608]],\n" " PARAMETER[\"Y-axis rotation\",0,\n" " ID[\"EPSG\",8609]],\n" " PARAMETER[\"Z-axis rotation\",0,\n" " ID[\"EPSG\",8610]],\n" " PARAMETER[\"Scale difference\",1,\n" " ID[\"EPSG\",8611]]]]"; auto srcObj = createFromUserInput(wkt, authFactory->databaseContext(), false); auto src = nn_dynamic_pointer_cast<CRS>(srcObj); ASSERT_TRUE(src != nullptr); auto dst = authFactory->createCoordinateReferenceSystem( "9518"); // "WGS 84 + EGM2008 height" auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), dst, ctxt); ASSERT_GE(list.size(), 1U); // Check that BoundCRS helmert transformation is used EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=somerc +lat_0=46.9524055555556 " "+lon_0=7.43958333333333 +k_0=1 " "+x_0=600000 +y_0=200000 +ellps=bessel " "+step +proj=cart +ellps=bessel " "+step +proj=helmert +x=674.4 +y=15.1 +z=405.3 +rx=0 +ry=0 +rz=0 " "+s=0 +convention=position_vector " "+step +inv +proj=cart +ellps=WGS84 " "+step +inv +proj=vgridshift +grids=us_nga_egm08_25.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, IGNF_LAMB1_TO_EPSG_4326) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), std::string()); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); ctxt->setAllowUseIntermediateCRS( CoordinateOperationContext::IntermediateCRSUse::ALWAYS); auto list = CoordinateOperationFactory::create()->createOperations( AuthorityFactory::create(DatabaseContext::create(), "IGNF") ->createCoordinateReferenceSystem("LAMB1"), AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=lcc +lat_1=49.5 +lat_0=49.5 " "+lon_0=0 +k_0=0.99987734 +x_0=600000 +y_0=200000 " "+ellps=clrk80ign +pm=paris +step +proj=hgridshift " "+grids=fr_ign_ntf_r93.tif +step +proj=unitconvert +xy_in=rad " "+xy_out=deg +step +proj=axisswap +order=2,1"); EXPECT_FALSE(list[1]->hasBallparkTransformation()); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=lcc +lat_1=49.5 +lat_0=49.5 " "+lon_0=0 +k_0=0.99987734 +x_0=600000 +y_0=200000 " "+ellps=clrk80ign +pm=paris +step +proj=push +v_3 +step " "+proj=cart +ellps=clrk80ign +step +proj=helmert +x=-168 +y=-60 " "+z=320 +step +inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg +step " "+proj=axisswap +order=2,1"); auto list2 = CoordinateOperationFactory::create()->createOperations( AuthorityFactory::create(DatabaseContext::create(), "EPSG") // NTF (Paris) / Lambert Nord France equivalent to IGNF:LAMB1 ->createCoordinateReferenceSystem("27561"), AuthorityFactory::create(DatabaseContext::create(), "EPSG") ->createCoordinateReferenceSystem("4326"), ctxt); ASSERT_GE(list2.size(), 3U); EXPECT_EQ(replaceAll(list2[0]->exportToPROJString( PROJStringFormatter::create().get()), "0.999877341", "0.99987734"), list[0]->exportToPROJString(PROJStringFormatter::create().get())); // The second entry in list2 (list2[1]) uses the // weird +pm=2.33720833333333 from "NTF (Paris) to NTF (2)" // so skip to the 3th method EXPECT_EQ(replaceAll(list2[2]->exportToPROJString( PROJStringFormatter::create().get()), "0.999877341", "0.99987734"), list[1]->exportToPROJString(PROJStringFormatter::create().get())); } // --------------------------------------------------------------------------- TEST(operation, NAD83_to_projeted_CRS_based_on_NAD83_2011) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( // NAD83 authFactory->createCoordinateReferenceSystem("4269"), // NAD83(2011) / California Albers authFactory->createCoordinateReferenceSystem("6414"), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "Ballpark geographic offset from NAD83 to " "NAD83(2011) + California Albers"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=aea +lat_0=0 +lon_0=-120 +lat_1=34 " "+lat_2=40.5 +x_0=0 +y_0=-4000000 +ellps=GRS80"); } // --------------------------------------------------------------------------- TEST(operation, isPROJInstantiable) { { auto transformation = Transformation::createGeocentricTranslations( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, 1.0, 2.0, 3.0, {}); EXPECT_TRUE(transformation->isPROJInstantiable( DatabaseContext::create(), false)); } // Missing grid { auto transformation = Transformation::createNTv2( PropertyMap(), GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326, "foo.gsb", std::vector<PositionalAccuracyNNPtr>()); EXPECT_FALSE(transformation->isPROJInstantiable( DatabaseContext::create(), false)); } // Unsupported method { auto transformation = Transformation::create( PropertyMap(), GeographicCRS::EPSG_4269, GeographicCRS::EPSG_4326, nullptr, OperationMethod::create(PropertyMap(), std::vector<OperationParameterNNPtr>{}), std::vector<GeneralParameterValueNNPtr>{}, std::vector<PositionalAccuracyNNPtr>{}); EXPECT_FALSE(transformation->isPROJInstantiable( DatabaseContext::create(), false)); } } // --------------------------------------------------------------------------- TEST(operation, createOperation_on_crs_with_canonical_bound_crs) { auto boundCRS = BoundCRS::createFromTOWGS84( GeographicCRS::EPSG_4267, std::vector<double>{1, 2, 3, 4, 5, 6, 7}); auto crs = boundCRS->baseCRSWithCanonicalBoundCRS(); { auto op = CoordinateOperationFactory::create()->createOperation( crs, GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_TRUE(op->isEquivalentTo(boundCRS->transformation().get())); { auto wkt1 = op->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019) .get()); auto wkt2 = boundCRS->transformation()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019) .get()); EXPECT_EQ(wkt1, wkt2); } } { auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, crs); ASSERT_TRUE(op != nullptr); EXPECT_TRUE( op->isEquivalentTo(boundCRS->transformation()->inverse().get())); { auto wkt1 = op->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019) .get()); auto wkt2 = boundCRS->transformation()->inverse()->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019) .get()); EXPECT_EQ(wkt1, wkt2); } } } // --------------------------------------------------------------------------- TEST(operation, createOperation_fallback_to_proj4_strings) { auto objDest = PROJStringParser().createFromPROJString( "+proj=longlat +over +datum=WGS84 +type=crs"); auto dest = nn_dynamic_pointer_cast<GeographicCRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=longlat +over +datum=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_fallback_to_proj4_strings_bound_of_geog) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +over +ellps=GRS80 +towgs84=0,0,0 +type=crs"); auto src = nn_dynamic_pointer_cast<BoundCRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=longlat +over +ellps=clrk66 +towgs84=0,0,0 +type=crs"); auto dest = nn_dynamic_pointer_cast<BoundCRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=longlat +over +ellps=GRS80 +towgs84=0,0,0 " "+step +proj=longlat +over +ellps=clrk66 +towgs84=0,0,0 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST( operation, createOperation_fallback_to_proj4_strings_regular_with_datum_to_projliteral) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=11 +datum=NAD27 +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +over +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=11 +datum=NAD27 " "+step +proj=longlat +datum=WGS84 +over " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_fallback_to_proj4_strings_proj_NAD83_to_projliteral) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=11 +datum=NAD83 +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +over +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=11 +ellps=GRS80 " "+step +proj=longlat +datum=WGS84 +over " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_fallback_to_proj4_strings_geog_NAD83_to_projliteral) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +datum=NAD83 +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +over +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=longlat +datum=WGS84 +over " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST( operation, createOperation_fallback_to_proj4_strings_regular_with_nadgrids_to_projliteral) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=11 +ellps=clrk66 +nadgrids=@conus +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +over +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=11 +ellps=clrk66 +nadgrids=@conus " "+step +proj=longlat +datum=WGS84 +over " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_fallback_to_proj4_strings_projliteral_to_projliteral) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=11 +datum=NAD27 +over +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +over +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=11 +datum=NAD27 +over " "+step +proj=longlat +datum=WGS84 +over " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST( operation, createOperation_fallback_to_proj4_strings_regular_to_projliteral_with_towgs84) { auto objSrc = createFromUserInput("EPSG:4326", DatabaseContext::create(), false); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=utm +zone=31 +ellps=GRS80 +towgs84=1,2,3 +over +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=utm +zone=31 +ellps=GRS80 +towgs84=1,2,3 +over"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_on_crs_with_bound_crs_and_wktext) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=utm +zone=55 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 " "+units=m +no_defs +nadgrids=@GDA94_GDA2020_conformal.gsb +ignored1 " "+ignored2=val +wktext +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=utm +zone=55 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 " "+units=m +no_defs +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=55 +south " "+ellps=GRS80 +step +proj=hgridshift " "+grids=@GDA94_GDA2020_conformal.gsb +step +proj=utm +zone=55 " "+south +ellps=GRS80"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_fallback_to_proj4_strings_with_axis_inverted_projCRS) { auto objSrc = createFromUserInput("EPSG:2193", DatabaseContext::create(), false); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=WGS84 +lon_wrap=180 +type=crs"); auto dest = nn_dynamic_pointer_cast<GeographicCRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +inv +proj=tmerc +lat_0=0 +lon_0=173 +k=0.9996 " "+x_0=1600000 +y_0=10000000 +ellps=GRS80 " "+step +proj=longlat +ellps=WGS84 +lon_wrap=180 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_proj_string_with_non_metre_height) { auto objSrc = createFromUserInput("EPSG:6318+5703", DatabaseContext::create(), false); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +vunits=us-ft +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GT(list.size(), 1U); // What is important to check here is the vertical unit conversion EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=us_noaa_g2018u0.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=us-ft"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_with_derived_vertical_CRS) { auto dbContext = DatabaseContext::create(); auto authFactory = AuthorityFactory::create(dbContext, "EPSG"); // ETRS89 + EGM2008 height auto objSrc = createFromUserInput("EPSG:4258+3855", dbContext, false); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto wkt = "COMPOUNDCRS[\"WGS 84 + Custom Vertical\",\n" " GEOGCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " MEMBER[\"World Geodetic System 1984 (G2139)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " VERTCRS[\"Custom Vertical\",\n" " BASEVERTCRS[\"EGM2008 height\",\n" " VDATUM[\"EGM2008 geoid\"]],\n" " DERIVINGCONVERSION[\"vertical offs. and slope\",\n" " METHOD[\"Vertical Offset and Slope\",\n" " ID[\"EPSG\",1046]],\n" " PARAMETER[\"Ordinate 1 of evaluation point\",47,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8617]],\n" " PARAMETER[\"Ordinate 2 of evaluation point\",8,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8618]],\n" " PARAMETER[\"Vertical Offset\",-0.245,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8603]],\n" " PARAMETER[\"Inclination in latitude\",-0.21,\n" " ANGLEUNIT[\"arc-second\",4.84813681109536E-06],\n" " ID[\"EPSG\",8730]],\n" " PARAMETER[\"Inclination in longitude\",-0.032,\n" " ANGLEUNIT[\"arc-second\",4.84813681109536E-06],\n" " ID[\"EPSG\",8731]],\n" " PARAMETER[\"EPSG code for Horizontal CRS\",4326,\n" " ID[\"EPSG\",1037]]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"unknown\"],\n" " AREA[\"World\"],\n" " BBOX[-90,-180,90,180]]]]"; auto objDst = createFromUserInput(wkt, dbContext, false); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_EQ(list.size(), 1U); EXPECT_EQ(list[0]->nameStr(), "ETRS89 to WGS 84 (1) + vertical offs. and slope"); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vertoffset +lat_0=47 +lon_0=8 +dh=-0.245 +slope_lat=-0.21 " "+slope_lon=-0.032 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, compoundCRS_to_PROJJSON_with_non_metre_height) { auto srcPROJJSON = "{\n" " \"$schema\": " "\"https://proj.org/schemas/v0.2/projjson.schema.json\",\n" " \"type\": \"CompoundCRS\",\n" " \"name\": \"Compound CRS NAD83(2011) / Nebraska (ftUS) + North " "American Vertical Datum 1988 + PROJ us_noaa_g2012bu0.tif\",\n" " \"components\": [\n" " {\n" " \"type\": \"ProjectedCRS\",\n" " \"name\": \"NAD83(2011) / Nebraska (ftUS)\",\n" " \"base_crs\": {\n" " \"name\": \"NAD83(2011)\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"NAD83 (National Spatial Reference System " "2011)\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 6318\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"SPCS83 Nebraska zone (US Survey feet)\",\n" " \"method\": {\n" " \"name\": \"Lambert Conic Conformal (2SP)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9802\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude of false origin\",\n" " \"value\": 39.8333333333333,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8821\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude of false origin\",\n" " \"value\": -100,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8822\n" " }\n" " },\n" " {\n" " \"name\": \"Latitude of 1st standard parallel\",\n" " \"value\": 43,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8823\n" " }\n" " },\n" " {\n" " \"name\": \"Latitude of 2nd standard parallel\",\n" " \"value\": 40,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8824\n" " }\n" " },\n" " {\n" " \"name\": \"Easting at false origin\",\n" " \"value\": 1640416.6667,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8826\n" " }\n" " },\n" " {\n" " \"name\": \"Northing at false origin\",\n" " \"value\": 0,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8827\n" " }\n" " }\n" " ],\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 15396\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"X\",\n" " \"direction\": \"east\",\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " }\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"Y\",\n" " \"direction\": \"north\",\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " }\n" " }\n" " ]\n" " }\n" " },\n" " {\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"North American Vertical Datum 1988 + PROJ " "us_noaa_g2012bu0.tif\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"North American Vertical Datum 1988\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 5103\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " }\n" " }\n" " ]\n" " },\n" " \"geoid_model\": {\n" " \"name\": \"PROJ us_noaa_g2012bu0.tif\",\n" " \"interpolation_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"NAD83(2011)\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"NAD83 (National Spatial Reference System " "2011)\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 6319\n" " }\n" " }\n" " }\n" " }\n" " ]\n" "}"; auto objSrc = createFromUserInput(srcPROJJSON, DatabaseContext::create(), false); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); // The untypical potentially a bit buggy thing (and what caused a bug) // is the US-ft unit for the vertical axis of the base CRS ... // When outputting that to WKT, and // re-exporting to PROJJSON, one gets metre, which conforms more to the // official definition of NAD83(2011) 3D. // The vertical unit of the base CRS shouldn't matter much anyway, so this // is valid. auto dstPROJJSON = "{\n" " \"$schema\": " "\"https://proj.org/schemas/v0.2/projjson.schema.json\",\n" " \"type\": \"ProjectedCRS\",\n" " \"name\": \"Projected CRS NAD83(2011) / UTM zone 14N with " "ellipsoidal NAD83(2011) height\",\n" " \"base_crs\": {\n" " \"name\": \"NAD83(2011)\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"NAD83 (National Spatial Reference System 2011)\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1116\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " }\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"UTM zone 14N\",\n" " \"method\": {\n" " \"name\": \"Transverse Mercator\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9807\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude of natural origin\",\n" " \"value\": 0,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8801\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude of natural origin\",\n" " \"value\": -99,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8802\n" " }\n" " },\n" " {\n" " \"name\": \"Scale factor at natural origin\",\n" " \"value\": 0.9996,\n" " \"unit\": \"unity\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8805\n" " }\n" " },\n" " {\n" " \"name\": \"False easting\",\n" " \"value\": 500000,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8806\n" " }\n" " },\n" " {\n" " \"name\": \"False northing\",\n" " \"value\": 0,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8807\n" " }\n" " }\n" " ],\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 16014\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " }\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " }\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"US survey foot\",\n" " \"conversion_factor\": 0.304800609601219\n" " }\n" " }\n" " ]\n" " }\n" "}"; auto objDst = createFromUserInput(dstPROJJSON, DatabaseContext::create(), false); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto ctxt = CoordinateOperationContext::create(authFactory, nullptr, 0.0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GT(list.size(), 1U); // What is important to check here is the vertical unit conversion EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=us-ft +xy_out=m " "+step +inv +proj=lcc +lat_0=39.8333333333333 +lon_0=-100 +lat_1=43 " "+lat_2=40 +x_0=500000.00001016 +y_0=0 +ellps=GRS80 " "+step +proj=unitconvert +z_in=us-ft +z_out=m " "+step +proj=vgridshift +grids=us_noaa_g2012bu0.tif +multiplier=1 " "+step +proj=utm +zone=14 +ellps=GRS80 " "+step +proj=unitconvert +xy_in=m +z_in=m +xy_out=us-ft +z_out=us-ft"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_ossfuzz_18587) { auto objSrc = createFromUserInput("EPSG:4326", DatabaseContext::create(), false); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); // Extremely weird string ! We should likely reject it auto objDst = PROJStringParser().createFromPROJString( "type=crs proj=pipeline step proj=merc vunits=m nadgrids=@x " "proj=\"\nproj=pipeline step\n\""); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); // Just check that we don't go into an infinite recursion try { CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); } catch (const std::exception &) { } } // --------------------------------------------------------------------------- class derivedGeographicCRS_with_to_wgs84_to_geographicCRS : public ::testing::Test { protected: void run(const CRSNNPtr &src) { auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( src, NN_CHECK_ASSERT(dst)); ASSERT_TRUE(op != nullptr); std::string pipeline( "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=ob_tran +o_proj=latlon +over +lat_0=0 " "+lon_0=180 " "+o_lat_p=18 +o_lon_p=-200 +ellps=WGS84 " "+step +proj=push +v_3 " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=1 +y=2 +z=3 " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), pipeline); auto op2 = CoordinateOperationFactory::create()->createOperation( src, nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326)); ASSERT_TRUE(op2 != nullptr); EXPECT_EQ( op2->exportToPROJString(PROJStringFormatter::create().get()), pipeline + " +step +proj=axisswap +order=2,1"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(dst), src); ASSERT_TRUE(op != nullptr); std::string pipeline( "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=push +v_3 " "+step +proj=cart +ellps=WGS84 " "+step +proj=helmert +x=-1 +y=-2 +z=-3 " "+step +inv +proj=cart +ellps=WGS84 " "+step +proj=pop +v_3 " "+step +proj=ob_tran +o_proj=latlon +over +lat_0=0 +lon_0=180 " "+o_lat_p=18 +o_lon_p=-200 +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " + pipeline); auto op2 = CoordinateOperationFactory::create()->createOperation( nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), src); ASSERT_TRUE(op2 != nullptr); EXPECT_EQ( op2->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 " + pipeline); } } }; // --------------------------------------------------------------------------- TEST_F(derivedGeographicCRS_with_to_wgs84_to_geographicCRS, src_from_proj) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=ob_tran +o_proj=latlon +lat_0=0 +lon_0=180 +o_lat_p=18.0 " "+o_lon_p=-200.0 +ellps=WGS84 +towgs84=1,2,3 +over +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); run(NN_CHECK_ASSERT(src)); } // --------------------------------------------------------------------------- TEST_F(derivedGeographicCRS_with_to_wgs84_to_geographicCRS, src_from_wkt2) { // Same as above, but testing with a WKT CRS source // The subtle difference is that the base CRS of the DerivedGeographicCRS // will have a lat, long axis order auto objSrcProj = PROJStringParser().createFromPROJString( "+proj=ob_tran +o_proj=latlon +lat_0=0 +lon_0=180 +o_lat_p=18.0 " "+o_lon_p=-200.0 +ellps=WGS84 +towgs84=1,2,3 +over +type=crs"); auto srcFromProj = nn_dynamic_pointer_cast<CRS>(objSrcProj); ASSERT_TRUE(srcFromProj != nullptr); auto srcWkt = srcFromProj->exportToWKT(WKTFormatter::create().get()); auto objSrc = createFromUserInput(srcWkt, DatabaseContext::create(), false); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); run(NN_CHECK_ASSERT(src)); } // --------------------------------------------------------------------------- TEST(operation, createOperation_spherical_ocentric_to_geographic) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +geoc +datum=WGS84 +type=crs"); auto src = nn_dynamic_pointer_cast<GeodeticCRS>(objSrc); ASSERT_TRUE(src != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), GeographicCRS::EPSG_4326); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=geoc +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_geographic_to_spherical_ocentric) { auto objDest = PROJStringParser().createFromPROJString( "+proj=longlat +geoc +datum=WGS84 +type=crs"); auto dest = nn_dynamic_pointer_cast<GeodeticCRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=geoc +ellps=WGS84 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_spherical_ocentric_to_geocentric) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +geoc +datum=WGS84 +type=crs"); auto src = nn_dynamic_pointer_cast<GeodeticCRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=geocent +datum=WGS84 +type=crs"); auto dest = nn_dynamic_pointer_cast<GeodeticCRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=geoc +ellps=WGS84 " "+step +proj=cart +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_bound_of_spherical_ocentric_to_same_type) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +geoc +ellps=GRS80 +towgs84=1,2,3 +type=crs"); auto src = nn_dynamic_pointer_cast<BoundCRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=longlat +geoc +ellps=clrk66 +towgs84=4,5,6 +type=crs"); auto dest = nn_dynamic_pointer_cast<BoundCRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=geoc +ellps=GRS80 " "+step +proj=push +v_3 " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=-3 +y=-3 +z=-3 " "+step +inv +proj=cart +ellps=clrk66 " "+step +proj=pop +v_3 " "+step +proj=geoc +ellps=clrk66 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_spherical_ocentric_to_projected) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +geoc +datum=WGS84 +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=utm +zone=11 +datum=WGS84 +type=crs"); auto dest = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=geoc +ellps=WGS84 " "+step +proj=utm +zone=11 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_spherical_ocentric_to_projected_of_spherical_ocentric) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=longlat +geoc +datum=WGS84 +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = PROJStringParser().createFromPROJString( "+proj=utm +geoc +zone=11 +datum=WGS84 +type=crs"); auto dest = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dest != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=geoc +ellps=WGS84 " "+step +proj=utm +zone=11 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_spherical_ocentric_spherical_to_ellipsoidal_north_west) { auto objSrc = WKTParser().createFromWKT( "GEODCRS[\"Mercury (2015) - Sphere / Ocentric\",\n" " DATUM[\"Mercury (2015) - Sphere\",\n" " ELLIPSOID[\"Mercury (2015) - Sphere\",2440530,0,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Reference Meridian\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[spherical,2],\n" " AXIS[\"planetocentric latitude (U)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"planetocentric longitude (V)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = WKTParser().createFromWKT( "GEOGCRS[\"Mercury (2015) / Ographic\",\n" " DATUM[\"Mercury (2015)\",\n" " ELLIPSOID[\"Mercury (2015)\",2440530,1075.12334801762,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Reference Meridian\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",west,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]" ); auto dest = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dest != nullptr); { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dest)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=1,-2"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(dest), NN_CHECK_ASSERT(src)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=1,-2"); } } // --------------------------------------------------------------------------- TEST( operation, createOperation_ellipsoidal_ographic_west_to_projected_of_ellipsoidal_ographic_west) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "IAU_2015"); auto op = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19901"), authFactory->createCoordinateReferenceSystem("19911")); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=-2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260 " "+step +proj=axisswap +order=-1,2"); // Inverse auto op2 = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19911"), authFactory->createCoordinateReferenceSystem("19901")); ASSERT_TRUE(op2 != nullptr); EXPECT_EQ(op2->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=axisswap +order=-1,2 " "+step +inv +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,-1"); } // --------------------------------------------------------------------------- TEST( operation, createOperation_ellipsoidal_ographic_west_to_projected_of_ellipsoidal_ocentric) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "IAU_2015"); auto op = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19901"), authFactory->createCoordinateReferenceSystem("19912")); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=-2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260"); // Inverse auto op2 = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19912"), authFactory->createCoordinateReferenceSystem("19901")); ASSERT_TRUE(op2 != nullptr); EXPECT_EQ(op2->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,-1"); } // --------------------------------------------------------------------------- TEST( operation, createOperation_ellipsoidal_ocentric_to_projected_of_ellipsoidal_ocentric) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "IAU_2015"); auto op = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19902"), authFactory->createCoordinateReferenceSystem("19912")); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=geoc +a=2440530 +b=2438260 " "+step +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260"); // Inverse auto op2 = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19912"), authFactory->createCoordinateReferenceSystem("19902")); ASSERT_TRUE(op2 != nullptr); EXPECT_EQ(op2->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260 " "+step +proj=geoc +a=2440530 +b=2438260 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST( operation, createOperation_ellipsoidal_ocentric_to_projected_of_ellipsoidal_ographic_west) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "IAU_2015"); auto op = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19902"), authFactory->createCoordinateReferenceSystem("19911")); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=geoc +a=2440530 +b=2438260 " "+step +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260 " "+step +proj=axisswap +order=-1,2"); // Inverse auto op2 = CoordinateOperationFactory::create()->createOperation( authFactory->createCoordinateReferenceSystem("19911"), authFactory->createCoordinateReferenceSystem("19902")); ASSERT_TRUE(op2 != nullptr); EXPECT_EQ(op2->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=axisswap +order=-1,2 " "+step +inv +proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+a=2440530 +b=2438260 " "+step +proj=geoc +a=2440530 +b=2438260 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_ossfuzz_47873) { auto objSrc = PROJStringParser().createFromPROJString( "+proj=ob_tran +o_proj=longlat +o_lat_1=1 +o_lat_2=2 +datum=WGS84 " "+geoidgrids=@x +geoid_crs=horizontal_crs +type=crs"); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDst = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +geoidgrids=@y +type=crs"); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); // Just check that we don't go into an infinite recursion try { CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), NN_CHECK_ASSERT(dst)); } catch (const std::exception &) { } } // --------------------------------------------------------------------------- TEST(operation, createOperation_ossfuzz_47873_simplified_if_i_might_say) { auto wkt = "BOUNDCRS[\n" " SOURCECRS[\n" " VERTCRS[\"unknown\",\n" " VDATUM[\"unknown using geoidgrids=@x\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"unnamed\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " DERIVINGCONVERSION[\"unknown\",\n" " METHOD[\"PROJ ob_tran o_proj=longlat\"],\n" " PARAMETER[\"o_lat_1\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"o_lat_2\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]],\n" " ABRIDGEDTRANSFORMATION[\"unknown to unnamed ellipsoidal " "height\",\n" " METHOD[\"GravityRelatedHeight to Geographic3D\"],\n" " PARAMETERFILE[\"Geoid (height correction) model " "file\",\"@x\",\n" " ID[\"EPSG\",8666]]]]"; auto objSrc = WKTParser().createFromWKT(wkt); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto dst = authFactory->createCoordinateReferenceSystem("4979"); // Just check that we don't go into an infinite recursion try { CoordinateOperationFactory::create()->createOperation( NN_CHECK_ASSERT(src), dst); } catch (const std::exception &) { } } // --------------------------------------------------------------------------- TEST(operation, createOperation_derived_projected_crs) { auto authFactory = AuthorityFactory::create(DatabaseContext::create(), "EPSG"); auto src = authFactory->createCoordinateReferenceSystem("6507"); auto wkt = "DERIVEDPROJCRS[\"Custom Site Calibrated CRS\",\n" " BASEPROJCRS[\"NAD83(2011) / Mississippi East (ftUS)\",\n" " BASEGEOGCRS[\"NAD83(2011)\",\n" " DATUM[\"NAD83 (National Spatial Reference System " "2011)\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"SPCS83 Mississippi East zone (US Survey " "feet)\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",29.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural " "origin\",-88.8333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.99995,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",984250,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219],\n" " ID[\"EPSG\",8807]]]],\n" " DERIVINGCONVERSION[\"Affine transformation as PROJ-based\",\n" " METHOD[\"PROJ-based operation method: " "+proj=pipeline +step +proj=unitconvert +xy_in=m +xy_out=us-ft " "+step +proj=affine +xoff=20 " "+step +proj=unitconvert +xy_in=us-ft +xy_out=m\"]],\n" " CS[Cartesian,2],\n" " AXIS[\"northing (Y)\",north,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219]],\n" " AXIS[\"easting (X)\",east,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219]],\n" " REMARK[\"EPSG:6507 with 20 feet offset and axis inversion\"]]"; auto objDst = WKTParser().createFromWKT(wkt); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( src, NN_NO_CHECK(dst)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=affine +xoff=20 " "+step +proj=axisswap +order=2,1"); } TEST(operation, geogCRS_to_compoundCRS_with_boundVerticalCRS_and_derivedProjected) { auto wkt = "DERIVEDPROJCRS[\"Custom Site Calibrated CRS\",\n" " BASEPROJCRS[\"NAD83(2011) / Mississippi East (ftUS)\",\n" " BASEGEOGCRS[\"NAD83(2011)\",\n" " DATUM[\"NAD83 (National Spatial Reference System " "2011)\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"SPCS83 Mississippi East zone (US Survey " "feet)\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",29.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural " "origin\",-88.8333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.99995,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",984250,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219],\n" " ID[\"EPSG\",8807]]]],\n" " DERIVINGCONVERSION[\"Affine transformation as PROJ-based\",\n" " METHOD[\"PROJ-based operation method: " "+proj=pipeline +step +proj=unitconvert +xy_in=m +xy_out=us-ft " "+step +proj=affine +xoff=20 " "+step +proj=unitconvert +xy_in=us-ft +xy_out=m\"]],\n" " CS[Cartesian,2],\n" " AXIS[\"northing (Y)\",north,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219]],\n" " AXIS[\"easting (X)\",east,\n" " LENGTHUNIT[\"US survey foot\",0.304800609601219]],\n" " REMARK[\"EPSG:6507 with 20 feet offset and axis inversion\"]]"; auto objDst = WKTParser().createFromWKT(wkt); auto dst = nn_dynamic_pointer_cast<CRS>(objDst); ASSERT_TRUE(dst != nullptr); auto compound = CompoundCRS::create( PropertyMap(), std::vector<CRSNNPtr>{NN_NO_CHECK(dst), createBoundVerticalCRS()}); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4979, compound); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=vgridshift +grids=us_nga_egm08_25.tif " "+multiplier=1 " "+step +proj=tmerc +lat_0=29.5 +lon_0=-88.8333333333333 " "+k=0.99995 +x_0=300000 +y_0=0 +ellps=GRS80 " "+step +proj=unitconvert +xy_in=m +xy_out=us-ft " "+step +proj=affine +xoff=20 " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_point_motion_operation_geog2D) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); // "NAD83(CSRS)v7" auto crs = factory->createCoordinateReferenceSystem("8255"); auto crs_2002 = CoordinateMetadata::create(crs, 2002.0, dbContext); auto crs_2010 = CoordinateMetadata::create(crs, 2010.0, dbContext); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( crs_2002, crs_2010, ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=2002 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_fwd " "+step +proj=deformation +dt=8 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2010 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1 " "+step +proj=set +v_4=2010"); EXPECT_TRUE(list[1]->hasBallparkTransformation()); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_point_motion_operation_geog3D) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); // "NAD83(CSRS)v7" auto crs = factory->createCoordinateReferenceSystem("8254"); auto crs_2002 = CoordinateMetadata::create(crs, 2002.0, dbContext); auto crs_2010 = CoordinateMetadata::create(crs, 2010.0, dbContext); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( crs_2002, crs_2010, ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_fwd " "+step +proj=deformation +dt=8 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2010 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); EXPECT_TRUE(list[1]->hasBallparkTransformation()); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_point_motion_operation_geocentric) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); // "NAD83(CSRS)v7" auto crs = factory->createCoordinateReferenceSystem("8253"); auto crs_2002 = CoordinateMetadata::create(crs, 2002.0, dbContext); auto crs_2010 = CoordinateMetadata::create(crs, 2010.0, dbContext); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( crs_2002, crs_2010, ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=2002 " "+step +proj=set +v_4=2002 +omit_fwd " "+step +proj=deformation +dt=8 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2010 +omit_inv " "+step +proj=set +v_4=2010"); EXPECT_EQ(list[0]->inverse()->exportToPROJString( PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=2010 " "+step +proj=set +v_4=2010 +omit_fwd " "+step +proj=deformation +dt=-8 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_inv " "+step +proj=set +v_4=2002"); EXPECT_TRUE(list[1]->hasBallparkTransformation()); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_point_motion_operation_geocentric_to_geog3D) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); // "NAD83(CSRS)v7" auto crs_geocentric = factory->createCoordinateReferenceSystem("8253"); auto crs_2002 = CoordinateMetadata::create(crs_geocentric, 2002.0, dbContext); auto crs_geog3d = factory->createCoordinateReferenceSystem("8254"); auto crs_2010 = CoordinateMetadata::create(crs_geog3d, 2010.0, dbContext); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( crs_2002, crs_2010, ctxt); ASSERT_EQ(list.size(), 2U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=2002 " "+step +proj=set +v_4=2002 +omit_fwd " "+step +proj=deformation +dt=8 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2010 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1 " "+step +proj=set +v_4=2010"); EXPECT_TRUE(list[1]->hasBallparkTransformation()); EXPECT_EQ(list[1]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_point_motion_operation_NAD83_CSRS_v7_TO_ITRF2014) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); // "NAD83(CSRS)v7" auto sourceCRS = factory->createCoordinateReferenceSystem("8254"); auto crs_2002 = CoordinateMetadata::create(sourceCRS, 2002.0, dbContext); // ITRF2014 auto targetCRS = factory->createCoordinateReferenceSystem("7912"); auto crs_2005 = CoordinateMetadata::create(targetCRS, 2005.0, dbContext); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( crs_2002, crs_2005, ctxt); ASSERT_GE(list.size(), 2U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=2002 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_fwd " "+step +proj=deformation +dt=3 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2005 +omit_inv " "+step +inv +proj=helmert " "+x=1.0053 +y=-1.90921 +z=-0.54157 +rx=-0.02678138 " "+ry=0.00042027 +rz=-0.01093206 +s=0.00036891 +dx=0.00079 +dy=-0.0006 " "+dz=-0.00144 +drx=-6.667e-05 +dry=0.00075744 +drz=5.133e-05 " "+ds=-7.201e-05 +t_epoch=2010 +convention=position_vector " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1 " "+step +proj=set +v_4=2005"); EXPECT_TRUE(list[1]->hasBallparkTransformation()); } // --------------------------------------------------------------------------- TEST(operation, createOperation_point_motion_operation_ITRF2014_to_NAD83_CSRS_v7) { auto dbContext = DatabaseContext::create(); auto factory = AuthorityFactory::create(dbContext, "EPSG"); // ITRF2014 auto sourceCRS = factory->createCoordinateReferenceSystem("7912"); auto crs_2005 = CoordinateMetadata::create(sourceCRS, 2005.0, dbContext); // "NAD83(CSRS)v7" auto targetCRS = factory->createCoordinateReferenceSystem("8254"); auto crs_2002 = CoordinateMetadata::create(targetCRS, 2002.0, dbContext); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( crs_2005, crs_2002, ctxt); ASSERT_GE(list.size(), 2U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=2005 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=helmert +x=1.0053 +y=-1.90921 +z=-0.54157 +rx=-0.02678138 " "+ry=0.00042027 +rz=-0.01093206 +s=0.00036891 +dx=0.00079 +dy=-0.0006 " "+dz=-0.00144 +drx=-6.667e-05 +dry=0.00075744 +drz=5.133e-05 " "+ds=-7.201e-05 +t_epoch=2010 +convention=position_vector " "+step +proj=set +v_4=2005 +omit_fwd " "+step +proj=deformation +dt=-3 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1 " "+step +proj=set +v_4=2002"); EXPECT_TRUE(list[1]->hasBallparkTransformation()); } // --------------------------------------------------------------------------- TEST(operation, createOperation_compound_to_compound_with_point_motion_operation) { auto dbContext = DatabaseContext::create(); auto factoryNRCAN = AuthorityFactory::create(dbContext, "NRCAN"); auto sourceCM = factoryNRCAN->createCoordinateMetadata("NAD83_CSRS_1997_MTM7_HT2_1997"); auto targetCM = factoryNRCAN->createCoordinateMetadata( "NAD83_CSRS_2010_UTM19_CGVD2013_2010"); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( sourceCM, targetCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=1997 " "+step +inv +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80 " "+step +proj=vgridshift +grids=ca_nrc_HT2_1997.tif +multiplier=1 " "+step +proj=cart +ellps=GRS80 " "+step +proj=set +v_4=1997 +omit_fwd " "+step +proj=deformation +dt=13 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2010 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +inv +proj=vgridshift +grids=ca_nrc_CGG2013an83.tif " "+multiplier=1 " "+step +proj=utm +zone=19 +ellps=GRS80 " "+step +proj=set +v_4=2010"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_compound_to_compound_with_epoch_HT2_1997_CGG2013a) { auto dbContext = DatabaseContext::create(); auto factoryNRCAN = AuthorityFactory::create(dbContext, "NRCAN"); auto sourceCM = factoryNRCAN->createCoordinateMetadata("NAD83_CSRS_1997_MTM7_HT2_1997"); auto targetCM = factoryNRCAN->createCoordinateMetadata( "NAD83_CSRS_1997_UTM19_CGVD2013_1997"); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); { auto list = CoordinateOperationFactory::create()->createOperations( sourceCM, targetCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80 " "+step +proj=vgridshift +grids=ca_nrc_HT2_1997_CGG2013a.tif " "+multiplier=-1 " "+step +proj=utm +zone=19 +ellps=GRS80"); } { auto list = CoordinateOperationFactory::create()->createOperations( targetCM, sourceCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=19 +ellps=GRS80 " "+step +inv +proj=vgridshift " "+grids=ca_nrc_HT2_1997_CGG2013a.tif " "+multiplier=-1 " "+step +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80"); } } // --------------------------------------------------------------------------- TEST(operation, createOperation_compound_to_compound_with_epoch_HT2_2002_CGG2013a) { auto dbContext = DatabaseContext::create(); auto factoryNRCAN = AuthorityFactory::create(dbContext, "NRCAN"); auto sourceCM = factoryNRCAN->createCoordinateMetadata("NAD83_CSRS_2002_MTM7_HT2_2002"); auto targetCM = factoryNRCAN->createCoordinateMetadata( "NAD83_CSRS_2002_UTM19_CGVD2013_2002"); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); { auto list = CoordinateOperationFactory::create()->createOperations( sourceCM, targetCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80 " "+step +proj=vgridshift +grids=ca_nrc_HT2_2002v70_CGG2013a.tif " "+multiplier=-1 " "+step +proj=utm +zone=19 +ellps=GRS80"); } { auto list = CoordinateOperationFactory::create()->createOperations( targetCM, sourceCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=19 +ellps=GRS80 " "+step +inv +proj=vgridshift " "+grids=ca_nrc_HT2_2002v70_CGG2013a.tif " "+multiplier=-1 " "+step +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80"); } } // --------------------------------------------------------------------------- TEST(operation, createOperation_compound_to_compound_with_epoch_HT2_2010_CGG2013a) { auto dbContext = DatabaseContext::create(); auto factoryNRCAN = AuthorityFactory::create(dbContext, "NRCAN"); auto sourceCM = factoryNRCAN->createCoordinateMetadata("NAD83_CSRS_2010_MTM7_HT2_2010"); auto targetCM = factoryNRCAN->createCoordinateMetadata( "NAD83_CSRS_2010_UTM19_CGVD2013_2010"); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); { auto list = CoordinateOperationFactory::create()->createOperations( sourceCM, targetCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80 " "+step +proj=vgridshift +grids=ca_nrc_HT2_2010v70_CGG2013a.tif " "+multiplier=-1 " "+step +proj=utm +zone=19 +ellps=GRS80"); } { auto list = CoordinateOperationFactory::create()->createOperations( targetCM, sourceCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ( list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=utm +zone=19 +ellps=GRS80 " "+step +inv +proj=vgridshift " "+grids=ca_nrc_HT2_2010v70_CGG2013a.tif " "+multiplier=-1 " "+step +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80"); } } // --------------------------------------------------------------------------- TEST( operation, createOperation_compound_to_compound_with_Geographic3D_Offset_by_velocity_grid) { auto dbContext = DatabaseContext::create(); auto wkt = "COMPOUNDCRS[\"NAD83(CSRS)v3 / MTM zone 7 + CGVD28 height\",\n" " PROJCRS[\"NAD83(CSRS)v3 / MTM zone 7\",\n" " BASEGEOGCRS[\"NAD83(CSRS)v3\",\n" " DATUM[\"North American Datum of 1983 (CSRS) version 3\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",8240]],\n" " CONVERSION[\"MTM zone 7\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-70.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",304800,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (E(X))\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"northing (N(Y))\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " VERTCRS[\"CGVD28 height\",\n" " VDATUM[\"Canadian Geodetic Vertical Datum of 1928\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " GEOIDMODEL[\"HT2_1997\",\n" " ID[\"EPSG\",9983]],\n" " ID[\"EPSG\",5713]]]"; auto objSrc = WKTParser().createFromWKT(wkt); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = createFromUserInput( "NAD83(CSRS)v7 / UTM zone 19 + CGVD2013a(2010) height", dbContext); auto dst = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); // Very similar output pipeline as // createOperation_compound_to_compound_with_point_motion_operation EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=tmerc +lat_0=0 +lon_0=-70.5 +k=0.9999 " "+x_0=304800 +y_0=0 +ellps=GRS80 " "+step +proj=vgridshift +grids=ca_nrc_HT2_1997.tif +multiplier=1 " "+step +proj=cart +ellps=GRS80 " "+step +inv +proj=deformation +dt=-13 " "+grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +inv +proj=cart +ellps=GRS80 " "+step +inv +proj=vgridshift +grids=ca_nrc_CGG2013an83.tif " "+multiplier=1 " "+step +proj=utm +zone=19 +ellps=GRS80"); } // --------------------------------------------------------------------------- TEST( operation, createOperation_compound_to_compound_with_point_motion_operation_special_case_CGVD2013a) { auto dbContext = DatabaseContext::create(); auto factoryNRCAN = AuthorityFactory::create(dbContext, "NRCAN"); auto sourceCM = factoryNRCAN->createCoordinateMetadata( "NAD83_CSRS_1997_UTM17_CGVD2013_1997"); auto targetCM = factoryNRCAN->createCoordinateMetadata( "NAD83_CSRS_2002_UTM17_CGVD2013_2002"); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( sourceCM, targetCM, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=set +v_4=1997 " "+step +inv +proj=utm +zone=17 +ellps=GRS80 " "+step +proj=vgridshift +grids=ca_nrc_CGG2013an83.tif " "+multiplier=1 " "+step +proj=cart +ellps=GRS80 " "+step +proj=set +v_4=1997 +omit_fwd " "+step +proj=deformation +dt=5 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +proj=set +v_4=2002 +omit_inv " "+step +inv +proj=cart +ellps=GRS80 " "+step +inv +proj=vgridshift +grids=ca_nrc_CGG2013an83.tif " "+multiplier=1 " "+step +proj=utm +zone=17 +ellps=GRS80 " "+step +proj=set +v_4=2002"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_Geographic3D_Offset_by_velocity_grid) { auto dbContext = DatabaseContext::create(); auto factoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); auto sourceCRS = factoryEPSG->createCoordinateReferenceSystem("8254"); // NAD83(CSRS)v7 auto targetCRS = factoryEPSG->createCoordinateReferenceSystem("8239"); // NAD83(CSRS)v3 auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( sourceCRS, targetCRS, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=GRS80 " "+step +proj=deformation +dt=-13 +grids=ca_nrc_NAD83v70VG.tif " "+ellps=GRS80 " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_test_createOperationsWithDatumPivot_iter_1) { // Test // CoordinateOperationFactory::Private::createOperationsWithDatumPivot() // iter=1, ie getType(candidateSrcGeod) == getType(candidateDstGeod) auto dbContext = DatabaseContext::create(); auto factoryEPSG = AuthorityFactory::create(dbContext, "EPSG"); // NAD83(CSRS)v2 (2D) auto sourceCRS = factoryEPSG->createCoordinateReferenceSystem("8237"); // NAD83(CSRS)v3 (2D) auto targetCRS = factoryEPSG->createCoordinateReferenceSystem("8240"); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); // Do *NOT* set SpatialCriterion::PARTIAL_INTERSECTION, otherwise we'd // get the direct operations ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( sourceCRS, targetCRS, ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_STREQ(list[0]->nameStr().c_str(), "Conversion from NAD83(CSRS)v2 (geog2D) to " "NAD83(CSRS)v2 (geocentric) + " "NAD83(CSRS)v2 to NAD83(CSRS)v3 (1) + " "Conversion from NAD83(CSRS)v3 (geocentric) to " "NAD83(CSRS)v3 (geog2D)"); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(operation, createOperation_Vrtical_Offset_by_velocity_grid) { auto dbContext = DatabaseContext::create(); auto objSrc = createFromUserInput("NAD83(CSRS)v7 + CGVD2013a(2002) height", dbContext); auto src = nn_dynamic_pointer_cast<CRS>(objSrc); ASSERT_TRUE(src != nullptr); auto objDest = createFromUserInput("NAD83(CSRS)v7 + CGVD2013a(2010) height", dbContext); auto dst = nn_dynamic_pointer_cast<CRS>(objDest); ASSERT_TRUE(dst != nullptr); auto ctxt = CoordinateOperationContext::create( AuthorityFactory::create(dbContext, std::string()), nullptr, 0); ctxt->setSpatialCriterion( CoordinateOperationContext::SpatialCriterion::PARTIAL_INTERSECTION); ctxt->setGridAvailabilityUse( CoordinateOperationContext::GridAvailabilityUse:: IGNORE_GRID_AVAILABILITY); auto list = CoordinateOperationFactory::create()->createOperations( NN_NO_CHECK(src), NN_NO_CHECK(dst), ctxt); ASSERT_GE(list.size(), 1U); EXPECT_FALSE(list[0]->hasBallparkTransformation()); EXPECT_EQ(list[0]->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=push +v_1 +v_2 " "+step +proj=cart +ellps=GRS80 " "+step +inv +proj=deformation +dt=-8 " "+grids=ca_nrc_NAD83v70VG.tif +ellps=GRS80 " "+step +inv +proj=cart +ellps=GRS80 " "+step +proj=pop +v_1 +v_2 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); }
cpp
PROJ
data/projects/PROJ/test/unit/test_io.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" // to be able to use internal::toString #define FROM_PROJ_CPP #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinates.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include "proj/internal/internal.hpp" #include "proj_constants.h" #include <string> using namespace osgeo::proj::common; using namespace osgeo::proj::coordinates; using namespace osgeo::proj::crs; using namespace osgeo::proj::cs; using namespace osgeo::proj::datum; using namespace osgeo::proj::internal; using namespace osgeo::proj::io; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; // --------------------------------------------------------------------------- TEST(io, wkt_parsing) { { auto n = WKTNode::createFrom("MYNODE[]"); EXPECT_EQ(n->value(), "MYNODE"); EXPECT_TRUE(n->children().empty()); EXPECT_EQ(n->toString(), "MYNODE"); } { auto n = WKTNode::createFrom(" MYNODE [ ] "); EXPECT_EQ(n->value(), "MYNODE"); EXPECT_TRUE(n->children().empty()); } EXPECT_THROW(WKTNode::createFrom(""), ParsingException); EXPECT_THROW(WKTNode::createFrom("x"), ParsingException); EXPECT_THROW(WKTNode::createFrom("x,"), ParsingException); EXPECT_THROW(WKTNode::createFrom("x["), ParsingException); EXPECT_THROW(WKTNode::createFrom("["), ParsingException); { auto n = WKTNode::createFrom("MYNODE[\"x\"]"); EXPECT_EQ(n->value(), "MYNODE"); ASSERT_EQ(n->children().size(), 1U); EXPECT_EQ(n->children()[0]->value(), "\"x\""); EXPECT_EQ(n->toString(), "MYNODE[\"x\"]"); } EXPECT_THROW(WKTNode::createFrom("MYNODE[\"x\""), ParsingException); { auto n = WKTNode::createFrom("MYNODE[ \"x\" ]"); EXPECT_EQ(n->value(), "MYNODE"); ASSERT_EQ(n->children().size(), 1U); EXPECT_EQ(n->children()[0]->value(), "\"x\""); } { auto n = WKTNode::createFrom("MYNODE[\"x[\",1]"); EXPECT_EQ(n->value(), "MYNODE"); ASSERT_EQ(n->children().size(), 2U); EXPECT_EQ(n->children()[0]->value(), "\"x[\""); EXPECT_EQ(n->children()[1]->value(), "1"); EXPECT_EQ(n->toString(), "MYNODE[\"x[\",1]"); } EXPECT_THROW(WKTNode::createFrom("MYNODE[\"x\","), ParsingException); { auto n = WKTNode::createFrom("A[B[y]]"); EXPECT_EQ(n->value(), "A"); ASSERT_EQ(n->children().size(), 1U); EXPECT_EQ(n->children()[0]->value(), "B"); ASSERT_EQ(n->children()[0]->children().size(), 1U); EXPECT_EQ(n->children()[0]->children()[0]->value(), "y"); EXPECT_EQ(n->toString(), "A[B[y]]"); } EXPECT_THROW(WKTNode::createFrom("A[B["), ParsingException); std::string str; for (int i = 0; i < 17; i++) { str = "A[" + str + "]"; } EXPECT_THROW(WKTNode::createFrom(str), ParsingException); { auto wkt = "A[\"a\",B[\"b\",C[\"c\"]],D[\"d\"]]"; EXPECT_EQ(WKTNode::createFrom(wkt)->toString(), wkt); } } // --------------------------------------------------------------------------- TEST(io, wkt_parsing_with_parenthesis) { auto n = WKTNode::createFrom("A(\"x\",B(\"y\"))"); EXPECT_EQ(n->toString(), "A[\"x\",B[\"y\"]]"); } // --------------------------------------------------------------------------- TEST(io, wkt_parsing_with_double_quotes_inside) { auto n = WKTNode::createFrom("A[\"xy\"\"z\"]"); EXPECT_EQ(n->children()[0]->value(), "\"xy\"z\""); EXPECT_EQ(n->toString(), "A[\"xy\"\"z\"]"); EXPECT_THROW(WKTNode::createFrom("A[\"x\""), ParsingException); } // --------------------------------------------------------------------------- TEST(io, wkt_parsing_with_printed_quotes) { static const std::string startPrintedQuote("\xE2\x80\x9C"); static const std::string endPrintedQuote("\xE2\x80\x9D"); auto n = WKTNode::createFrom("A[" + startPrintedQuote + "x" + endPrintedQuote + "]"); EXPECT_EQ(n->children()[0]->value(), "\"x\""); EXPECT_EQ(n->toString(), "A[\"x\"]"); } // --------------------------------------------------------------------------- TEST(wkt_parse, sphere) { auto obj = WKTParser().createFromWKT( "ELLIPSOID[\"Sphere\",6378137,0,LENGTHUNIT[\"metre\",1]]"); auto ellipsoid = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellipsoid != nullptr); EXPECT_TRUE(ellipsoid->isSphere()); } // --------------------------------------------------------------------------- TEST(wkt_parse, datum_with_ANCHOR) { auto obj = WKTParser().createFromWKT( "DATUM[\"WGS_1984 with anchor\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]],\n" " ID[\"EPSG\",7030]],\n" " ANCHOR[\"My anchor\"]]"); auto datum = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(datum != nullptr); EXPECT_EQ(datum->ellipsoid()->celestialBody(), "Earth"); EXPECT_EQ(datum->primeMeridian()->nameStr(), "Greenwich"); auto anchor = datum->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "My anchor"); EXPECT_FALSE(datum->anchorEpoch().has_value()); } // --------------------------------------------------------------------------- TEST(wkt_parse, datum_with_ANCHOREPOCH) { auto obj = WKTParser().createFromWKT( "DATUM[\"my_datum\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ANCHOREPOCH[2002.5]]"); auto datum = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(datum != nullptr); auto anchorEpoch = datum->anchorEpoch(); EXPECT_TRUE(anchorEpoch.has_value()); ASSERT_EQ(anchorEpoch->convertToUnit(UnitOfMeasure::YEAR), 2002.5); EXPECT_FALSE(datum->anchorDefinition().has_value()); } // --------------------------------------------------------------------------- TEST(wkt_parse, datum_with_invalid_ANCHOREPOCH) { auto wkt = "DATUM[\"my_datum\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ANCHOREPOCH[invalid]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, datum_with_invalid_ANCHOREPOCH_too_many_children) { auto wkt = "DATUM[\"my_datum\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ANCHOREPOCH[2002.5,invalid]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, datum_with_pm) { const char *wkt = "DATUM[\"Nouvelle Triangulation Francaise (Paris)\",\n" " ELLIPSOID[\"Clarke 1880 (IGN)\",6378249.2,293.466021293627,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6807]],\n" "PRIMEM[\"Paris\",2.5969213,\n" " ANGLEUNIT[\"grad\",0.0157079632679489],\n" " ID[\"EPSG\",8903]]"; auto obj = WKTParser().createFromWKT(wkt); auto datum = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(datum != nullptr); EXPECT_EQ(datum->primeMeridian()->nameStr(), "Paris"); EXPECT_EQ( datum->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, datum_no_pm_not_earth) { auto obj = WKTParser().createFromWKT("DATUM[\"unnamed\",\n" " ELLIPSOID[\"unnamed\",1,0,\n" " LENGTHUNIT[\"metre\",1]]]"); auto datum = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(datum != nullptr); EXPECT_EQ(datum->ellipsoid()->celestialBody(), "Non-Earth body"); EXPECT_EQ(datum->primeMeridian()->nameStr(), "Reference meridian"); } // --------------------------------------------------------------------------- TEST(wkt_parse, dynamic_geodetic_reference_frame) { auto obj = WKTParser().createFromWKT( "GEOGCRS[\"WGS 84 (G1762)\"," "DYNAMIC[FRAMEEPOCH[2005.0]]," "TRF[\"World Geodetic System 1984 (G1762)\"," " ELLIPSOID[\"WGS 84\",6378137,298.257223563]," " ANCHOR[\"My anchor\"]]," "CS[ellipsoidal,3]," " AXIS[\"(lat)\",north,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"(lon)\",east,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"ellipsoidal height (h)\",up,LENGTHUNIT[\"metre\",1.0]]" "]"); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto dgrf = std::dynamic_pointer_cast<DynamicGeodeticReferenceFrame>(crs->datum()); ASSERT_TRUE(dgrf != nullptr); auto anchor = dgrf->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "My anchor"); EXPECT_TRUE(dgrf->frameReferenceEpoch() == Measure(2005.0, UnitOfMeasure::YEAR)); auto model = dgrf->deformationModelName(); EXPECT_TRUE(!model.has_value()); } // --------------------------------------------------------------------------- TEST(wkt_parse, dynamic_geodetic_reference_frame_with_model) { auto obj = WKTParser().createFromWKT( "GEOGCRS[\"WGS 84 (G1762)\"," "DYNAMIC[FRAMEEPOCH[2005.0],MODEL[\"my_model\"]]," "TRF[\"World Geodetic System 1984 (G1762)\"," " ELLIPSOID[\"WGS 84\",6378137,298.257223563]," " ANCHOR[\"My anchor\"]]," "CS[ellipsoidal,3]," " AXIS[\"(lat)\",north,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"(lon)\",east,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"ellipsoidal height (h)\",up,LENGTHUNIT[\"metre\",1.0]]" "]"); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto dgrf = std::dynamic_pointer_cast<DynamicGeodeticReferenceFrame>(crs->datum()); ASSERT_TRUE(dgrf != nullptr); auto anchor = dgrf->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "My anchor"); EXPECT_TRUE(dgrf->frameReferenceEpoch() == Measure(2005.0, UnitOfMeasure::YEAR)); auto model = dgrf->deformationModelName(); EXPECT_TRUE(model.has_value()); EXPECT_EQ(*model, "my_model"); } // --------------------------------------------------------------------------- TEST(wkt_parse, dynamic_geodetic_reference_frame_with_velocitygrid) { auto obj = WKTParser().createFromWKT( "GEOGCRS[\"WGS 84 (G1762)\"," "DYNAMIC[FRAMEEPOCH[2005.0],VELOCITYGRID[\"my_model\"]]," "TRF[\"World Geodetic System 1984 (G1762)\"," " ELLIPSOID[\"WGS 84\",6378137,298.257223563]," " ANCHOR[\"My anchor\"]]," "CS[ellipsoidal,3]," " AXIS[\"(lat)\",north,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"(lon)\",east,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"ellipsoidal height (h)\",up,LENGTHUNIT[\"metre\",1.0]]" "]"); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto dgrf = std::dynamic_pointer_cast<DynamicGeodeticReferenceFrame>(crs->datum()); ASSERT_TRUE(dgrf != nullptr); auto anchor = dgrf->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "My anchor"); EXPECT_TRUE(dgrf->frameReferenceEpoch() == Measure(2005.0, UnitOfMeasure::YEAR)); auto model = dgrf->deformationModelName(); EXPECT_TRUE(model.has_value()); EXPECT_EQ(*model, "my_model"); } // --------------------------------------------------------------------------- TEST(wkt_parse, geogcrs_with_ensemble) { auto obj = WKTParser().createFromWKT( "GEOGCRS[\"WGS 84\"," "ENSEMBLE[\"WGS 84 ensemble\"," " MEMBER[\"WGS 84 (TRANSIT)\"]," " MEMBER[\"WGS 84 (G730)\"]," " MEMBER[\"WGS 84 (G834)\"]," " MEMBER[\"WGS 84 (G1150)\"]," " MEMBER[\"WGS 84 (G1674)\"]," " MEMBER[\"WGS 84 (G1762)\"]," " ELLIPSOID[\"WGS " "84\",6378137,298.2572236,LENGTHUNIT[\"metre\",1.0]]," " ENSEMBLEACCURACY[2]" "]," "CS[ellipsoidal,3]," " AXIS[\"(lat)\",north,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"(lon)\",east,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"ellipsoidal height (h)\",up,LENGTHUNIT[\"metre\",1.0]]" "]"); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); ASSERT_TRUE(crs->datum() == nullptr); ASSERT_TRUE(crs->datumEnsemble() != nullptr); EXPECT_EQ(crs->datumEnsemble()->datums().size(), 6U); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_geogcrs_with_ensemble) { auto wkt = "GEOGCRS[\"WGS 84\"," "ENSEMBLE[\"WGS 84 ensemble\"," " MEMBER[\"WGS 84 (TRANSIT)\"]," " MEMBER[\"WGS 84 (G730)\"]," " MEMBER[\"WGS 84 (G834)\"]," " MEMBER[\"WGS 84 (G1150)\"]," " MEMBER[\"WGS 84 (G1674)\"]," " MEMBER[\"WGS 84 (G1762)\"]," " ENSEMBLEACCURACY[2]" "]," "CS[ellipsoidal,3]," " AXIS[\"(lat)\",north,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"(lon)\",east,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"ellipsoidal height (h)\",up,LENGTHUNIT[\"metre\",1.0]]" "]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- static void checkEPSG_4326(GeographicCRSPtr crs, bool latLong = true, bool checkEPSGCodes = true) { if (checkEPSGCodes) { ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "4326"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); } EXPECT_EQ(crs->nameStr(), "WGS 84"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); if (latLong) { EXPECT_TRUE(cs->axisList()[0]->nameStr() == "Latitude" || cs->axisList()[0]->nameStr() == "Geodetic latitude") << cs->axisList()[0]->nameStr(); EXPECT_EQ(tolower(cs->axisList()[0]->abbreviation()), "lat"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::NORTH); EXPECT_TRUE(cs->axisList()[1]->nameStr() == "Longitude" || cs->axisList()[1]->nameStr() == "Geodetic longitude") << cs->axisList()[1]->nameStr(); EXPECT_EQ(tolower(cs->axisList()[1]->abbreviation()), "lon"); EXPECT_EQ(cs->axisList()[1]->direction(), AxisDirection::EAST); } else { EXPECT_EQ(cs->axisList()[0]->nameStr(), "Longitude"); EXPECT_EQ(cs->axisList()[0]->abbreviation(), "lon"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::EAST); EXPECT_EQ(cs->axisList()[1]->nameStr(), "Latitude"); EXPECT_EQ(cs->axisList()[1]->abbreviation(), "lat"); EXPECT_EQ(cs->axisList()[1]->direction(), AxisDirection::NORTH); } auto datum = crs->datum(); if (checkEPSGCodes) { ASSERT_EQ(datum->identifiers().size(), 1U); EXPECT_EQ(datum->identifiers()[0]->code(), "6326"); EXPECT_EQ(*(datum->identifiers()[0]->codeSpace()), "EPSG"); } EXPECT_EQ(datum->nameStr(), "World Geodetic System 1984"); auto ellipsoid = datum->ellipsoid(); EXPECT_EQ(ellipsoid->semiMajorAxis().value(), 6378137.0); EXPECT_EQ(ellipsoid->semiMajorAxis().unit(), UnitOfMeasure::METRE); EXPECT_EQ(ellipsoid->inverseFlattening()->value(), 298.257223563); if (checkEPSGCodes) { ASSERT_EQ(ellipsoid->identifiers().size(), 1U); EXPECT_EQ(ellipsoid->identifiers()[0]->code(), "7030"); EXPECT_EQ(*(ellipsoid->identifiers()[0]->codeSpace()), "EPSG"); } EXPECT_EQ(ellipsoid->nameStr(), "WGS 84"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_EPSG_4326) { auto obj = WKTParser().createFromWKT( "GEOGCS[\"WGS 84\"," " DATUM[\"WGS_1984\"," " SPHEROID[\"WGS 84\",6378137,298.257223563," " AUTHORITY[\"EPSG\",\"7030\"]]," " AUTHORITY[\"EPSG\",\"6326\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9122\"]]," " AUTHORITY[\"EPSG\",\"4326\"]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs, false /* longlat order */); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_EPSG_4267) { auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT( "GEOGCS[\"NAD27\"," " DATUM[\"North_American_Datum_1927\"," " SPHEROID[\"Clarke 1866\",6378206.4,294.978698213898," " AUTHORITY[\"EPSG\",\"7008\"]]," " AUTHORITY[\"EPSG\",\"6267\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9122\"]]," " AUTHORITY[\"EPSG\",\"4267\"]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); ASSERT_EQ(datum->identifiers().size(), 1U); EXPECT_EQ(datum->identifiers()[0]->code(), "6267"); EXPECT_EQ(*(datum->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(datum->nameStr(), "North American Datum 1927"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_EPSG_4807_grad_mess) { auto obj = WKTParser().createFromWKT( "GEOGCS[\"NTF (Paris)\",\n" " DATUM[\"Nouvelle_Triangulation_Francaise_Paris\",\n" " SPHEROID[\"Clarke 1880 (IGN)\",6378249.2,293.466021293627,\n" " AUTHORITY[\"EPSG\",\"6807\"]],\n" " AUTHORITY[\"EPSG\",\"6807\"]],\n" /* WKT1_GDAL weirdness: PRIMEM is converted to degree */ " PRIMEM[\"Paris\",2.33722917,\n" " AUTHORITY[\"EPSG\",\"8903\"]],\n" " UNIT[\"grad\",0.015707963267949,\n" " AUTHORITY[\"EPSG\",\"9105\"]],\n" " AXIS[\"latitude\",NORTH],\n" " AXIS[\"longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4807\"]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); auto primem = datum->primeMeridian(); EXPECT_EQ(primem->longitude().unit(), UnitOfMeasure::GRAD); // Check that we have corrected the value that was in degree into grad. EXPECT_EQ(primem->longitude().value(), 2.5969213); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_EPSG_4901_grad) { auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT("GEOGCS[\"GCS_ATF_Paris\",DATUM[\"D_ATF\"," "SPHEROID[\"Plessis_1817\",6376523.0,308.64]]," "PRIMEM[\"Paris_RGS\",2.33720833333333]," "UNIT[\"Grad\",0.0157079632679489]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); auto primem = datum->primeMeridian(); EXPECT_EQ(primem->nameStr(), "Paris RGS"); // The PRIMEM is really in degree EXPECT_EQ(primem->longitude().unit(), UnitOfMeasure::DEGREE); EXPECT_NEAR(primem->longitude().value(), 2.33720833333333, 1e-14); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_LINUNIT) { const auto wkt = "GEOGCS[\"WGS_1984_3D\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]," "LINUNIT[\"Meter\",1.0]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); const auto &axisList = crs->coordinateSystem()->axisList(); ASSERT_EQ(axisList.size(), 3U); EXPECT_NEAR(axisList[0]->unit().conversionToSI(), 0.0174532925199433, 1e-15); EXPECT_NEAR(axisList[1]->unit().conversionToSI(), 0.0174532925199433, 1e-15); EXPECT_EQ(axisList[2]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_epsg_org_EPSG_4901_PRIMEM_weird_sexagesimal_DMS) { // Current epsg.org output may use the EPSG:9110 "sexagesimal DMS" // unit and a DD.MMSSsss value, but this will likely be changed to // use decimal degree. auto obj = WKTParser().createFromWKT( "GEOGCRS[\"ATF (Paris)\"," " DATUM[\"Ancienne Triangulation Francaise (Paris)\"," " ELLIPSOID[\"Plessis 1817\",6376523,308.64," " LENGTHUNIT[\"metre\",1,ID[\"EPSG\",9001]]," " ID[\"EPSG\",7027]]," " ID[\"EPSG\",6901]]," " PRIMEM[\"Paris RGS\",2.201395," " ANGLEUNIT[\"sexagesimal DMS\",1,ID[\"EPSG\",9110]]," " ID[\"EPSG\",8914]]," " CS[ellipsoidal,2," " ID[\"EPSG\",6403]]," " AXIS[\"Geodetic latitude (Lat)\",north," " ORDER[1]]," " AXIS[\"Geodetic longitude (Lon)\",east," " ORDER[2]]," " ANGLEUNIT[\"grad\",0.015707963267949,ID[\"EPSG\",9105]]," " USAGE[SCOPE[\"Geodesy.\"],AREA[\"France - mainland onshore.\"]," " BBOX[42.33,-4.87,51.14,8.23]]," "ID[\"EPSG\",4901]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); auto primem = datum->primeMeridian(); EXPECT_EQ(primem->longitude().unit(), UnitOfMeasure::DEGREE); EXPECT_NEAR(primem->longitude().value(), 2.33720833333333, 1e-14); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geographic_old_datum_name_from_EPSG_code) { auto wkt = "GEOGCS[\"S-JTSK (Ferro)\",\n" " " "DATUM[\"System_Jednotne_Trigonometricke_Site_Katastralni_Ferro\",\n" " SPHEROID[\"Bessel 1841\",6377397.155,299.1528128,\n" " AUTHORITY[\"EPSG\",\"7004\"]],\n" " AUTHORITY[\"EPSG\",\"6818\"]],\n" " PRIMEM[\"Ferro\",-17.66666666666667,\n" " AUTHORITY[\"EPSG\",\"8909\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4818\"]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); EXPECT_EQ( datum->nameStr(), "System of the Unified Trigonometrical Cadastral Network (Ferro)"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geographic_old_datum_name_without_EPSG_code) { auto wkt = "GEOGCS[\"S-JTSK (Ferro)\",\n" " " "DATUM[\"System_Jednotne_Trigonometricke_Site_Katastralni_Ferro\",\n" " SPHEROID[\"Bessel 1841\",6377397.155,299.1528128]],\n" " PRIMEM[\"Ferro\",-17.66666666666667],\n" " UNIT[\"degree\",0.0174532925199433]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); EXPECT_EQ( datum->nameStr(), "System of the Unified Trigonometrical Cadastral Network (Ferro)"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geographic_deprecated) { auto wkt = "GEOGCS[\"SAD69 (deprecated)\",\n" " DATUM[\"South_American_Datum_1969\",\n" " SPHEROID[\"GRS 1967\",6378160,298.247167427,\n" " AUTHORITY[\"EPSG\",\"7036\"]],\n" " AUTHORITY[\"EPSG\",\"6291\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9108\"]],\n" " AUTHORITY[\"EPSG\",\"4291\"]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "SAD69"); EXPECT_TRUE(crs->isDeprecated()); } // --------------------------------------------------------------------------- static std::string contentWKT2_EPSG_4326( "[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]],\n" " ID[\"EPSG\",7030]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " ID[\"EPSG\",4326]]"); // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geographic_with_PROJ4_extension) { auto wkt = "GEOGCS[\"WGS 84\",\n" " DATUM[\"unknown\",\n" " SPHEROID[\"WGS84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433],\n" " EXTENSION[\"PROJ4\",\"+proj=longlat +foo=bar +wktext\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), wkt); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=longlat +foo=bar +wktext +type=crs"); EXPECT_TRUE( crs->exportToWKT(WKTFormatter::create().get()).find("EXTENSION") == std::string::npos); EXPECT_TRUE( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI).get()) .find("EXTENSION") == std::string::npos); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geographic_epsg_org_api_4326) { // Output from // https://apps.epsg.org/api/v1/CoordRefSystem/4326/export/?format=wkt&formatVersion=1 // using a datum ensemble name auto wkt = "GEOGCS[\"WGS 84\",DATUM[\"World Geodetic System 1984 ensemble\"," "SPHEROID[\"WGS 84\",6378137,298.257223563," "AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"degree (supplier to define representation)\"," "0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]]," "AXIS[\"Lat\",north],AXIS[\"Lon\",east]," "AUTHORITY[\"EPSG\",\"4326\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "World Geodetic System 1984"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geographic_epsg_org_api_4258) { // Output from // https://apps.epsg.org/api/v1/CoordRefSystem/4258/export/?format=wkt&formatVersion=1 // using a datum ensemble name auto wkt = "GEOGCS[\"ETRS89\"," "DATUM[\"European Terrestrial Reference System 1989 ensemble\"," "SPHEROID[\"GRS 1980\",6378137,298.257222101," "AUTHORITY[\"EPSG\",\"7019\"]],AUTHORITY[\"EPSG\",\"6258\"]]," "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"degree (supplier to define representation)\"," "0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]]," "AXIS[\"Lat\",north],AXIS[\"Lon\",east]," "AUTHORITY[\"EPSG\",\"4258\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "European Terrestrial Reference System 1989"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geographic_missing_unit_and_axis) { auto wkt = "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\"," "SPHEROID[\"WGS 84\",6378137,298.257223563]]]]"; // Missing UNIT[] is illegal in strict mode EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); auto obj = WKTParser().setStrict(false).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_EQ(cs->axisList()[0]->unit(), UnitOfMeasure::DEGREE); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geocentric_with_PROJ4_extension) { auto wkt = "GEOCCS[\"WGS 84\",\n" " DATUM[\"unknown\",\n" " SPHEROID[\"WGS84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"Meter\",1],\n" " AXIS[\"Geocentric X\",OTHER],\n" " AXIS[\"Geocentric Y\",OTHER],\n" " AXIS[\"Geocentric Z\",NORTH],\n" " EXTENSION[\"PROJ4\",\"+proj=geocent +foo=bar +wktext\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), wkt); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=geocent +foo=bar +wktext +type=crs"); EXPECT_TRUE( crs->exportToWKT(WKTFormatter::create().get()).find("EXTENSION") == std::string::npos); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geocentric_missing_unit_and_axis) { auto wkt = "GEOCCS[\"WGS 84\",DATUM[\"WGS_1984\"," "SPHEROID[\"WGS 84\",6378137,298.257223563]]]]"; // Missing UNIT[] is illegal in strict mode EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); auto obj = WKTParser().setStrict(false).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 3U); EXPECT_EQ(cs->axisList()[0]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_non_conformant_inf_inverse_flattening) { // Some WKT in the wild use "inf". Cf SPHEROID["unnamed",6370997,"inf"] // in https://zenodo.org/record/3878979#.Y_P4g4CZNH4, // https://zenodo.org/record/5831940#.Y_P4i4CZNH5 // or https://grasswiki.osgeo.org/wiki/Marine_Science auto obj = WKTParser().setStrict(false).createFromWKT( "GEOGCS[\"GCS_sphere\",DATUM[\"D_unknown\"," "SPHEROID[\"Spherical_Earth\",6370997,\"inf\"]]," "PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->ellipsoid()->inverseFlattening()->value(), 0.0); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_GCS_unknown_D_unknown) { auto obj = WKTParser().setStrict(false).createFromWKT( "GEOGCS[\"GCS_unknown\",DATUM[\"D_unknown\"," "SPHEROID[\"unknown\",6370997,0]]," "PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "unknown"); EXPECT_EQ(crs->datum()->nameStr(), "unknown"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_GEODCRS_EPSG_4326) { auto obj = WKTParser().createFromWKT("GEODCRS" + contentWKT2_EPSG_4326); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_long_GEODETICCRS_EPSG_4326) { auto obj = WKTParser().createFromWKT("GEODETICCRS" + contentWKT2_EPSG_4326); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_GEOGCRS_EPSG_4326) { auto obj = WKTParser().createFromWKT("GEOGCRS" + contentWKT2_EPSG_4326); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_long_GEOGRAPHICCRS_EPSG_4326) { auto obj = WKTParser().createFromWKT("GEOGRAPHICCRS" + contentWKT2_EPSG_4326); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_simplified_EPSG_4326) { auto obj = WKTParser().createFromWKT( "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude (lat)\",north],\n" // test "name // (abbreviation)" " AXIS[\"longitude (lon)\",east],\n" " UNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",4326]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs, true /* latlong */, false /* no EPSG codes */); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_GEODETICDATUM) { auto obj = WKTParser().createFromWKT( "GEODCRS[\"WGS 84\",\n" " GEODETICDATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"(lat)\",north],\n" // test "(abbreviation)" " AXIS[\"(lon)\",east],\n" " UNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",4326]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs, true /* latlong */, false /* no EPSG codes */); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_TRF) { auto obj = WKTParser().createFromWKT( "GEODCRS[\"WGS 84\",\n" " TRF[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north],\n" " AXIS[\"longitude\",east],\n" " UNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",4326]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4326(crs, true /* latlong */, false /* no EPSG codes */); } // --------------------------------------------------------------------------- static void checkEPSG_4979(GeographicCRSPtr crs) { ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "4979"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(crs->nameStr(), "WGS 84"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 3U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Latitude"); EXPECT_EQ(cs->axisList()[0]->abbreviation(), "lat"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(cs->axisList()[1]->nameStr(), "Longitude"); EXPECT_EQ(cs->axisList()[1]->abbreviation(), "lon"); EXPECT_EQ(cs->axisList()[1]->direction(), AxisDirection::EAST); EXPECT_EQ(cs->axisList()[2]->nameStr(), "Ellipsoidal height"); EXPECT_EQ(cs->axisList()[2]->abbreviation(), "h"); EXPECT_EQ(cs->axisList()[2]->direction(), AxisDirection::UP); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "World Geodetic System 1984"); auto ellipsoid = datum->ellipsoid(); EXPECT_EQ(ellipsoid->semiMajorAxis().value(), 6378137.0); EXPECT_EQ(ellipsoid->semiMajorAxis().unit(), UnitOfMeasure::METRE); EXPECT_EQ(ellipsoid->inverseFlattening()->value(), 298.257223563); EXPECT_EQ(ellipsoid->nameStr(), "WGS 84"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_EPSG_4979) { auto obj = WKTParser().createFromWKT( "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " UNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); checkEPSG_4979(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_spherical_planetocentric) { const auto wkt = "GEODCRS[\"Mercury (2015) / Ocentric\",\n" " DATUM[\"Mercury (2015)\",\n" " ELLIPSOID[\"Mercury (2015)\",2440530,1075.12334801762,\n" " LENGTHUNIT[\"metre\",1]],\n" " ANCHOR[\"Hun Kal: 20.0\"]],\n" " PRIMEM[\"Reference Meridian\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[spherical,2],\n" " AXIS[\"planetocentric latitude (U)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"planetocentric longitude (V)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"IAU\",19902,2015],\n" " REMARK[\"Source of IAU Coordinate systems: " "doi://10.1007/s10569-017-9805-5\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->isSphericalPlanetocentric()); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); } // --------------------------------------------------------------------------- static void checkGeocentric(GeodeticCRSPtr crs) { // Explicitly check this is NOT a GeographicCRS EXPECT_TRUE(!dynamic_cast<GeographicCRS *>(crs.get())); EXPECT_EQ(crs->nameStr(), "WGS 84 (geocentric)"); EXPECT_TRUE(crs->isGeocentric()); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 3U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Geocentric X"); EXPECT_EQ(cs->axisList()[0]->abbreviation(), "X"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::GEOCENTRIC_X); EXPECT_EQ(cs->axisList()[1]->nameStr(), "Geocentric Y"); EXPECT_EQ(cs->axisList()[1]->abbreviation(), "Y"); EXPECT_EQ(cs->axisList()[1]->direction(), AxisDirection::GEOCENTRIC_Y); EXPECT_EQ(cs->axisList()[2]->nameStr(), "Geocentric Z"); EXPECT_EQ(cs->axisList()[2]->abbreviation(), "Z"); EXPECT_EQ(cs->axisList()[2]->direction(), AxisDirection::GEOCENTRIC_Z); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "World Geodetic System 1984"); auto ellipsoid = datum->ellipsoid(); EXPECT_EQ(ellipsoid->semiMajorAxis().value(), 6378137.0); EXPECT_EQ(ellipsoid->semiMajorAxis().unit(), UnitOfMeasure::METRE); EXPECT_EQ(ellipsoid->inverseFlattening()->value(), 298.257223563); EXPECT_EQ(ellipsoid->nameStr(), "WGS 84"); auto primem = datum->primeMeridian(); ASSERT_EQ(primem->longitude().unit(), UnitOfMeasure::DEGREE); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_geocentric) { auto wkt = "GEODCRS[\"WGS 84 (geocentric)\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]],\n" " ID[\"EPSG\",7030]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]],\n" " ID[\"EPSG\",8901]],\n" " CS[Cartesian,3],\n" // nominal value is 'geocentricX' with g lower case. " AXIS[\"(X)\",GeocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " ID[\"EPSG\",4328]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); checkGeocentric(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_simplified_geocentric) { auto wkt = "GEODCRS[\"WGS 84 (geocentric)\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX],\n" " AXIS[\"(Y)\",geocentricY],\n" " AXIS[\"(Z)\",geocentricZ],\n" " UNIT[\"metre\",1],\n" " ID[\"EPSG\",4328]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); checkGeocentric(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geocentric) { auto wkt = "GEOCCS[\"WGS 84 (geocentric)\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Geocentric X\",OTHER],\n" " AXIS[\"Geocentric Y\",OTHER],\n" " AXIS[\"Geocentric Z\",NORTH],\n" " AUTHORITY[\"EPSG\",\"4328\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); checkGeocentric(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_geocentric_with_z_OTHER) { auto wkt = "GEOCCS[\"WGS 84 (geocentric)\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Geocentric X\",OTHER],\n" " AXIS[\"Geocentric Y\",OTHER],\n" " AXIS[\"Geocentric Z\",OTHER],\n" " AUTHORITY[\"EPSG\",\"4328\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); checkGeocentric(crs); } // --------------------------------------------------------------------------- static void checkProjected(ProjectedCRSPtr crs, bool checkEPSGCodes = true) { EXPECT_EQ(crs->nameStr(), "WGS 84 / UTM zone 31N"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "32631"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); auto geogCRS = nn_dynamic_pointer_cast<GeographicCRS>(crs->baseCRS()); ASSERT_TRUE(geogCRS != nullptr); checkEPSG_4326(NN_CHECK_ASSERT(geogCRS), true, checkEPSGCodes); auto conversion = crs->derivingConversion(); EXPECT_EQ(conversion->nameStr(), "UTM zone 31N"); auto method = conversion->method(); EXPECT_EQ(method->nameStr(), "Transverse Mercator"); auto values = conversion->parameterValues(); ASSERT_EQ(values.size(), 5U); { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[0]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_EQ(paramName, "Latitude of natural origin"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(measure.value(), 0); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[1]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_EQ(paramName, "Longitude of natural origin"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::DEGREE); EXPECT_EQ(measure.value(), 3); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[2]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_EQ(paramName, "Scale factor at natural origin"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::SCALE_UNITY); EXPECT_EQ(measure.value(), 0.9996); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[3]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_EQ(paramName, "False easting"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::METRE); EXPECT_EQ(measure.value(), 500000); } { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[4]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_EQ(paramName, "False northing"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.unit(), UnitOfMeasure::METRE); EXPECT_EQ(measure.value(), 0); } auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Easting"); EXPECT_EQ(cs->axisList()[0]->abbreviation(), "E"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::EAST); EXPECT_EQ(cs->axisList()[1]->nameStr(), "Northing"); EXPECT_EQ(cs->axisList()[1]->abbreviation(), "N"); EXPECT_EQ(cs->axisList()[1]->direction(), AxisDirection::NORTH); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_projected) { auto wkt = "PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"(E)\",East],\n" // should normally be uppercase " AXIS[\"(N)\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); checkProjected(crs); EXPECT_TRUE(!crs->baseCRS()->identifiers().empty()); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_projected_no_axis) { auto wkt = "PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"latitude\",NORTH],\n" " AXIS[\"longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AUTHORITY[\"EPSG\",\"32631\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); checkProjected(crs); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_projected_wrong_axis_geogcs) { auto wkt = "PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"longitude\",EAST],\n" " AXIS[\"latitude\",NORTH],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AUTHORITY[\"EPSG\",\"32631\"]]"; { WKTParser parser; parser.setStrict(false).attachDatabaseContext( DatabaseContext::create()); auto obj = parser.createFromWKT(wkt); EXPECT_TRUE(!parser.warningList().empty()); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->baseCRS()->identifiers().empty()); auto cs = crs->baseCRS()->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::EAST); EXPECT_EQ(cs->axisList()[1]->direction(), AxisDirection::NORTH); } { WKTParser parser; parser.setStrict(false) .setUnsetIdentifiersIfIncompatibleDef(false) .attachDatabaseContext(DatabaseContext::create()); auto obj = parser.createFromWKT(wkt); EXPECT_TRUE(parser.warningList().empty()); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(!crs->baseCRS()->identifiers().empty()); } } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_projected_wrong_angular_unit) { auto wkt = "PROJCS[\"Merchich / Nord Maroc\"," " GEOGCS[\"Merchich\"," " DATUM[\"Merchich\"," " SPHEROID[\"Clarke 1880 (IGN)\"," "6378249.2,293.466021293627]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"grad\",0.015707963267949," " AUTHORITY[\"EPSG\",\"9105\"]]," " AUTHORITY[\"EPSG\",\"4261\"]]," " PROJECTION[\"Lambert_Conformal_Conic_1SP\"]," " PARAMETER[\"latitude_of_origin\",37]," " PARAMETER[\"central_meridian\",-6]," " PARAMETER[\"scale_factor\",0.999625769]," " PARAMETER[\"false_easting\",500000]," " PARAMETER[\"false_northing\",300000]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Easting\",EAST]," " AXIS[\"Northing\",NORTH]]"; { WKTParser parser; parser.setStrict(false).attachDatabaseContext( DatabaseContext::create()); auto obj = parser.createFromWKT(wkt); EXPECT_TRUE(!parser.warningList().empty()); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); // No base CRS identifiers EXPECT_TRUE(crs->baseCRS()->identifiers().empty()); auto cs = crs->baseCRS()->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_NEAR(cs->axisList()[0]->unit().conversionToSI(), UnitOfMeasure::GRAD.conversionToSI(), 1e-10); } { WKTParser parser; parser.setUnsetIdentifiersIfIncompatibleDef(false) .attachDatabaseContext(DatabaseContext::create()); auto obj = parser.createFromWKT(wkt); EXPECT_TRUE(parser.warningList().empty()); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); // Base CRS identifier preserved EXPECT_TRUE(!crs->baseCRS()->identifiers().empty()); auto cs = crs->baseCRS()->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_NEAR(cs->axisList()[0]->unit().conversionToSI(), UnitOfMeasure::GRAD.conversionToSI(), 1e-10); } } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_projected_with_PROJ4_extension) { auto wkt = "PROJCS[\"unnamed\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"unknown\",\n" " SPHEROID[\"WGS84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",0],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"Meter\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " EXTENSION[\"PROJ4\",\"+proj=merc +wktext\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), wkt); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=merc +wktext +type=crs"); EXPECT_TRUE( crs->exportToWKT(WKTFormatter::create().get()).find("EXTENSION") == std::string::npos); EXPECT_TRUE( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI).get()) .find("EXTENSION") == std::string::npos); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_projected_missing_unit_and_axis) { auto wkt = "PROJCS[\"WGS 84 / UTM zone 31N\",GEOGCS[\"WGS 84\"," "DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563," "AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"degree\",0.0174532925199433," "AUTHORITY[\"EPSG\",\"9122\"]]," "AUTHORITY[\"EPSG\",\"4326\"]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"latitude_of_origin\",0]," "PARAMETER[\"central_meridian\",3]," "PARAMETER[\"scale_factor\",0.9996]," "PARAMETER[\"false_easting\",500000]," "PARAMETER[\"false_northing\",0]]"; // Missing UNIT[] is illegal in strict mode EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); auto obj = WKTParser().setStrict(false).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); EXPECT_EQ(cs->axisList()[0]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_Mercator_1SP_with_latitude_origin_0) { auto wkt = "PROJCS[\"unnamed\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"unknown\",\n" " SPHEROID[\"WGS84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",0],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"Meter\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(got_wkt.find("Mercator_1SP") != std::string::npos) << got_wkt; } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_Mercator_1SP_without_scale_factor) { // See https://github.com/OSGeo/PROJ/issues/1700 auto wkt = "PROJCS[\"unnamed\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"unknown\",\n" " SPHEROID[\"WGS84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Mercator_1SP\"],\n" " PARAMETER[\"central_meridian\",0],\n" " PARAMETER[\"false_easting\",0],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"Meter\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; WKTParser parser; parser.setStrict(false).attachDatabaseContext(DatabaseContext::create()); auto obj = parser.createFromWKT(wkt); EXPECT_TRUE(!parser.warningList().empty()); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(got_wkt.find("PARAMETER[\"scale_factor\",1]") != std::string::npos) << got_wkt; EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +units=m " "+no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_krovak_south_west) { auto wkt = "PROJCS[\"S-JTSK / Krovak\"," " GEOGCS[\"S-JTSK\"," " DATUM[\"System_Jednotne_Trigonometricke_Site_Katastralni\"," " SPHEROID[\"Bessel 1841\",6377397.155,299.1528128," " AUTHORITY[\"EPSG\",\"7004\"]]," " AUTHORITY[\"EPSG\",\"6156\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9122\"]]," " AUTHORITY[\"EPSG\",\"4156\"]]," " PROJECTION[\"Krovak\"]," " PARAMETER[\"latitude_of_center\",49.5]," " PARAMETER[\"longitude_of_center\",24.83333333333333]," " PARAMETER[\"azimuth\",30.2881397527778]," " PARAMETER[\"pseudo_standard_parallel_1\",78.5]," " PARAMETER[\"scale_factor\",0.9999]," " PARAMETER[\"false_easting\",0]," " PARAMETER[\"false_northing\",0]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"X\",SOUTH]," " AXIS[\"Y\",WEST]," " AUTHORITY[\"EPSG\",\"5513\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Krovak"); auto expected_wkt2 = "PROJCRS[\"S-JTSK / Krovak\",\n" " BASEGEODCRS[\"S-JTSK\",\n" " DATUM[\"System_Jednotne_Trigonometricke_Site_Katastralni\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Krovak\",\n" " ID[\"EPSG\",9819]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",24.8333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard " "parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"x\",south,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"y\",west,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5513]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), expected_wkt2); auto projString = crs->exportToPROJString(PROJStringFormatter::create().get()); auto expectedPROJString = "+proj=krovak +axis=swu +lat_0=49.5 " "+lon_0=24.8333333333333 +alpha=30.2881397527778 " "+k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +units=m " "+no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); obj = PROJStringParser().createFromPROJString(projString); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs2 != nullptr); auto wkt2 = crs2->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt2.find("METHOD[\"Krovak\"") != std::string::npos) << wkt2; EXPECT_TRUE( wkt2.find("PARAMETER[\"Latitude of pseudo standard parallel\",78.5,") != std::string::npos) << wkt2; EXPECT_TRUE( wkt2.find("PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,") != std::string::npos) << wkt2; EXPECT_EQ(crs2->exportToPROJString(PROJStringFormatter::create().get()), expectedPROJString); obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=unitconvert +xy_in=deg " "+xy_out=rad " "+step +proj=krovak +lat_0=49.5 " "+lon_0=24.8333333333333 +alpha=30.2881397527778 " "+k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+step +proj=axisswap +order=-2,-1"); crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs2 != nullptr); wkt2 = crs2->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt2.find("METHOD[\"Krovak\"") != std::string::npos) << wkt2; } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_krovak_north_oriented) { auto wkt = "PROJCS[\"S-JTSK / Krovak East North\"," " GEOGCS[\"S-JTSK\"," " DATUM[\"System_Jednotne_Trigonometricke_Site_Katastralni\"," " SPHEROID[\"Bessel 1841\",6377397.155,299.1528128," " AUTHORITY[\"EPSG\",\"7004\"]]," " AUTHORITY[\"EPSG\",\"6156\"]]," " PRIMEM[\"Greenwich\",0," " AUTHORITY[\"EPSG\",\"8901\"]]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9122\"]]," " AUTHORITY[\"EPSG\",\"4156\"]]," " PROJECTION[\"Krovak\"]," " PARAMETER[\"latitude_of_center\",49.5]," " PARAMETER[\"longitude_of_center\",24.83333333333333]," " PARAMETER[\"azimuth\",30.2881397527778]," " PARAMETER[\"pseudo_standard_parallel_1\",78.5]," " PARAMETER[\"scale_factor\",0.9999]," " PARAMETER[\"false_easting\",0]," " PARAMETER[\"false_northing\",0]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"X\",EAST]," " AXIS[\"Y\",NORTH]," " AUTHORITY[\"EPSG\",\"5514\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Krovak (North Orientated)"); EXPECT_EQ( crs->exportToWKT(WKTFormatter::create().get()), "PROJCRS[\"S-JTSK / Krovak East North\",\n" " BASEGEODCRS[\"S-JTSK\",\n" " DATUM[\"System_Jednotne_Trigonometricke_Site_Katastralni\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Krovak (North Orientated)\",\n" " ID[\"EPSG\",1041]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",24.8333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard " "parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"x\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"y\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5514]]"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=krovak +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_krovak_modified_south_west) { auto wkt = "PROJCRS[\"S-JTSK/05 / Modified Krovak\",\n" " BASEGEOGCRS[\"S-JTSK/05\",\n" " DATUM[\"System of the Unified Trigonometrical Cadastral " "Network/05\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",5228]],\n" " CONVERSION[\"Modified Krovak (Greenwich)\",\n" " METHOD[\"Krovak Modified\",\n" " ID[\"EPSG\",1042]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",24.8333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397222222,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard " "parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",5000000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5000000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"southing (X)\",south,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"westing (Y)\",west,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"Engineering survey, topographic mapping.\"],\n" " AREA[\"Czechia.\"],\n" " BBOX[48.58,12.09,51.06,18.86]],\n" " ID[\"EPSG\",5515]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Krovak Modified"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); auto projString = crs->exportToPROJString(PROJStringFormatter::create().get()); auto expectedPROJString = "+proj=mod_krovak +axis=swu +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397222222 +k=0.9999 +x_0=5000000 +y_0=5000000 " "+ellps=bessel +units=m +no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); obj = PROJStringParser().createFromPROJString(projString); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs2 != nullptr); auto wkt2 = crs2->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt2.find("METHOD[\"Krovak Modified\"") != std::string::npos) << wkt2; EXPECT_TRUE( wkt2.find("PARAMETER[\"Latitude of pseudo standard parallel\",78.5,") != std::string::npos) << wkt2; EXPECT_TRUE( wkt2.find("PARAMETER[\"Co-latitude of cone axis\",30.2881397222222,") != std::string::npos) << wkt2; EXPECT_EQ(crs2->exportToPROJString(PROJStringFormatter::create().get()), expectedPROJString); obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=unitconvert +xy_in=deg " "+xy_out=rad " "+step +proj=mod_krovak +lat_0=49.5 " "+lon_0=24.8333333333333 +alpha=30.2881397222222 " "+k=0.9999 +x_0=5000000 +y_0=5000000 +ellps=bessel " "+step +proj=axisswap +order=-2,-1"); crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs2 != nullptr); wkt2 = crs2->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt2.find("METHOD[\"Krovak Modified\"") != std::string::npos) << wkt2; } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_krovak_modified_east_north) { auto wkt = "PROJCRS[\"S-JTSK/05 / Modified Krovak East North\",\n" " BASEGEOGCRS[\"S-JTSK/05\",\n" " DATUM[\"System of the Unified Trigonometrical Cadastral " "Network/05\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",5228]],\n" " CONVERSION[\"Modified Krovak East North (Greenwich)\",\n" " METHOD[\"Krovak Modified (North Orientated)\",\n" " ID[\"EPSG\",1043]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",24.8333333333333,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397222222,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard " "parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",5000000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",5000000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (X)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (Y)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"GIS.\"],\n" " AREA[\"Czechia.\"],\n" " BBOX[48.58,12.09,51.06,18.86]],\n" " ID[\"EPSG\",5516]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Krovak Modified (North Orientated)"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); auto projString = crs->exportToPROJString(PROJStringFormatter::create().get()); auto expectedPROJString = "+proj=mod_krovak +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397222222 +k=0.9999 +x_0=5000000 +y_0=5000000 " "+ellps=bessel +units=m +no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); obj = PROJStringParser().createFromPROJString(projString); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs2 != nullptr); auto wkt2 = crs2->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt2.find("METHOD[\"Krovak Modified (North Orientated)\"") != std::string::npos) << wkt2; EXPECT_TRUE( wkt2.find("PARAMETER[\"Latitude of pseudo standard parallel\",78.5,") != std::string::npos) << wkt2; EXPECT_TRUE( wkt2.find("PARAMETER[\"Co-latitude of cone axis\",30.2881397222222,") != std::string::npos) << wkt2; EXPECT_EQ(crs2->exportToPROJString(PROJStringFormatter::create().get()), expectedPROJString); obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=unitconvert +xy_in=deg " "+xy_out=rad " "+step +proj=mod_krovak +lat_0=49.5 " "+lon_0=24.8333333333333 +alpha=30.2881397222222 " "+k=0.9999 +x_0=5000000 +y_0=5000000 +ellps=bessel"); crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs2 != nullptr); wkt2 = crs2->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt2.find("METHOD[\"Krovak Modified (North Orientated)\"") != std::string::npos) << wkt2; } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_polar_stereographic_latitude_of_origin_70) { auto wkt = "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",70],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto projString = crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()); auto expectedPROJString = "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=2 " "+x_0=3 +y_0=4 +datum=WGS84 +units=m +no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->nameStr(), "Easting"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->direction(), AxisDirection::SOUTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->nameStr(), "Northing"); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->direction(), AxisDirection::SOUTH); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_polar_stereographic_latitude_of_origin_minus_70) { auto wkt = "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",-70],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->nameStr(), "Easting"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->nameStr(), "Northing"); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->direction(), AxisDirection::NORTH); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_polar_stereographic_latitude_of_origin_90) { auto wkt = "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",90],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto projString = crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()); auto expectedPROJString = "+proj=stere +lat_0=90 +lat_ts=90 +lon_0=2 " "+x_0=3 +y_0=4 +datum=WGS84 +units=m +no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_polar_stereographic_latitude_of_origin_90_scale_factor_1) { auto wkt = "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",90],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",1],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto projString = crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()); auto expectedPROJString = "+proj=stere +lat_0=90 +lat_ts=90 +lon_0=2 " "+x_0=3 +y_0=4 +datum=WGS84 +units=m +no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_polar_stereographic_scale_factor) { auto wkt = "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Polar_Stereographic\"],\n" " PARAMETER[\"latitude_of_origin\",90],\n" " PARAMETER[\"central_meridian\",2],\n" " PARAMETER[\"scale_factor\",0.99],\n" " PARAMETER[\"false_easting\",3],\n" " PARAMETER[\"false_northing\",4],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto projString = crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()); auto expectedPROJString = "+proj=stere +lat_0=90 +lon_0=2 +k=0.99 +x_0=3 " "+y_0=4 +datum=WGS84 +units=m +no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_Spherical_Cross_Track_Height) { auto wkt = "PROJCS[\"unknown\",\n" " GEOGCS[\"unknown\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]]],\n" " PROJECTION[\"Spherical_Cross_Track_Height\"],\n" " PARAMETER[\"peg_point_latitude\",1],\n" " PARAMETER[\"peg_point_longitude\",2],\n" " PARAMETER[\"peg_point_heading\",3],\n" " PARAMETER[\"peg_point_height\",4],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto projString = crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()); auto expectedPROJString = "+proj=sch +plat_0=1 +plon_0=2 +phdg_0=3 +h_0=4 " "+datum=WGS84 +units=m +no_defs +type=crs"; EXPECT_EQ(projString, expectedPROJString); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_hotine_oblique_mercator_without_rectified_grid_angle) { auto wkt = "PROJCS[\"NAD_1983_Michigan_GeoRef_Meters\"," "GEOGCS[\"NAD83(1986)\"," "DATUM[\"North_American_Datum_1983\"," "SPHEROID[\"GRS_1980\",6378137,298.257222101]]," "PRIMEM[\"Greenwich\",0]," "UNIT[\"Degree\",0.017453292519943295]]," "PROJECTION[\"Hotine_Oblique_Mercator\"]," "PARAMETER[\"false_easting\",2546731.496]," "PARAMETER[\"false_northing\",-4354009.816]," "PARAMETER[\"latitude_of_center\",45.30916666666666]," "PARAMETER[\"longitude_of_center\",-86]," "PARAMETER[\"azimuth\",-22.74444]," "PARAMETER[\"scale_factor\",0.9996]," "UNIT[\"Meter\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); // Check that we have added automatically rectified_grid_angle auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(got_wkt.find("PARAMETER[\"rectified_grid_angle\",-22.74444]") != std::string::npos) << got_wkt; } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_hotine_oblique_mercator_with_rectified_grid_angle) { auto wkt = "PROJCS[\"NAD_1983_Michigan_GeoRef_Meters\"," "GEOGCS[\"NAD83(1986)\"," "DATUM[\"North_American_Datum_1983\"," "SPHEROID[\"GRS_1980\",6378137,298.257222101]]," "PRIMEM[\"Greenwich\",0]," "UNIT[\"Degree\",0.017453292519943295]]," "PROJECTION[\"Hotine_Oblique_Mercator\"]," "PARAMETER[\"false_easting\",2546731.496]," "PARAMETER[\"false_northing\",-4354009.816]," "PARAMETER[\"latitude_of_center\",45.30916666666666]," "PARAMETER[\"longitude_of_center\",-86]," "PARAMETER[\"azimuth\",-22.74444]," "PARAMETER[\"rectified_grid_angle\",-23]," "PARAMETER[\"scale_factor\",0.9996]," "UNIT[\"Meter\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); // Check that we have not overridden rectified_grid_angle auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(got_wkt.find("PARAMETER[\"rectified_grid_angle\",-23]") != std::string::npos) << got_wkt; } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_hotine_oblique_mercator_azimuth_center_with_rectified_grid_angle) { auto wkt = "PROJCS[\"unknown\"," "GEOGCS[\"unknown\"," " DATUM[\"WGS_1984\"," " SPHEROID[\"WGS 84\",6378137,298.257223563]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"degree\",0.0174532925199433]]," "PROJECTION[\"Hotine_Oblique_Mercator_Azimuth_Center\"]," "PARAMETER[\"latitude_of_center\",0]," "PARAMETER[\"longitude_of_center\",0]," "PARAMETER[\"azimuth\",30]," "PARAMETER[\"rectified_grid_angle\",0]," "PARAMETER[\"scale_factor\",1]," "PARAMETER[\"false_easting\",0]," "PARAMETER[\"false_northing\",0]," "UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); // Check that we have not overridden rectified_grid_angle auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(got_wkt.find("PARAMETER[\"rectified_grid_angle\",0]") != std::string::npos) << got_wkt; } // --------------------------------------------------------------------------- TEST(proj_export, wkt2_hotine_oblique_mercator_without_rectified_grid_angle) { auto wkt = "PROJCRS[\"NAD_1983_Michigan_GeoRef_Meters\",\n" " BASEGEOGCRS[\"NAD83(1986)\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS_1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6269]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Hotine Oblique Mercator (variant A)\",\n" " ID[\"EPSG\",9812]],\n" " PARAMETER[\"False easting\",2546731.496,\n" " LENGTHUNIT[\"Meter\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",-4354009.816,\n" " LENGTHUNIT[\"Meter\",1],\n" " ID[\"EPSG\",8807]],\n" " PARAMETER[\"Latitude of projection centre\"," " 45.3091666666667,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of projection centre\",-86,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8812]],\n" " PARAMETER[\"Azimuth of initial line\",-22.74444,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8813]],\n" " PARAMETER[\"Scale factor on initial line\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8815]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"Meter\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"Meter\",1]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); // We don't do any particular handling of missing Angle from Rectified // to Skew Grid on import, but on export to PROJ string, // check that we don't add a dummy gamma value. auto expectedPROJString = "+proj=omerc +no_uoff +lat_0=45.3091666666667 " "+lonc=-86 +alpha=-22.74444 " "+k=0.9996 +x_0=2546731.496 +y_0=-4354009.816 " "+datum=NAD83 +units=m +no_defs +type=crs"; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), expectedPROJString); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_projected) { auto wkt = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]],\n" " ID[\"EPSG\",7030]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" // Voluntary omit LENGTHUNIT to check the WKT grammar accepts // Check that we default to degree //" ANGLEUNIT[\"degree\",0.0174532925199433,\n" //" ID[\"EPSG\",9122]],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" // Check that we default to unity //" SCALEUNIT[\"unity\",1,\n" //" ID[\"EPSG\",9201]],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" // Voluntary omit LENGTHUNIT to check the WKT grammar accepts // Check that we default to metre //" LENGTHUNIT[\"metre\",1,\n" //" ID[\"EPSG\",9001]],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",16031]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " ID[\"EPSG\",32631]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); checkProjected(crs, /*checkEPSGCodes = */ false); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_projected_with_id_in_basegeodcrs) { auto wkt = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " ID[\"EPSG\",4326]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\"],\n" " PARAMETER[\"Latitude of natural origin\",0],\n" " PARAMETER[\"Longitude of natural origin\",3],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996],\n" " PARAMETER[\"False easting\",500000],\n" " PARAMETER[\"False northing\",0]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1],\n" " ID[\"EPSG\",32631]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); ASSERT_EQ(crs->baseCRS()->identifiers().size(), 1U); EXPECT_EQ(crs->baseCRS()->identifiers().front()->code(), "4326"); { auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_TRUE(got_wkt.find("ID[\"EPSG\",4326]]") != std::string::npos) << got_wkt; } { auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019_SIMPLIFIED) .get()); EXPECT_TRUE(got_wkt.find("ID[\"EPSG\",4326]]") == std::string::npos) << got_wkt; } } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_projected_no_id_but_id_in_basegeodcrs) { auto wkt = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " ID[\"EPSG\",4326]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\"],\n" " PARAMETER[\"Latitude of natural origin\",0],\n" " PARAMETER[\"Longitude of natural origin\",3],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996],\n" " PARAMETER[\"False easting\",500000],\n" " PARAMETER[\"False northing\",0]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto got_wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_TRUE(got_wkt.find("ID[\"EPSG\",4326]]") != std::string::npos) << got_wkt; } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_simplified_projected) { auto wkt = "PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\"],\n" " PARAMETER[\"Latitude of natural origin\",0],\n" " PARAMETER[\"Longitude of natural origin\",3],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996],\n" " PARAMETER[\"False easting\",500000],\n" " PARAMETER[\"False northing\",0]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1],\n" " ID[\"EPSG\",32631]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); checkProjected(crs, /*checkEPSGCodes = */ false); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_projected_3D) { auto wkt = "PROJCRS[\"WGS 84 (G1762) / UTM zone 31N 3D\"," " BASEGEOGCRS[\"WGS 84\"," " DATUM[\"World Geodetic System of 1984 (G1762)\"," " ELLIPSOID[\"WGS 84\",6378137,298.257223563," " LENGTHUNIT[\"metre\",1.0]]]]," " CONVERSION[\"Some conversion 3D\"," " METHOD[\"Transverse Mercator (3D)\"]," " PARAMETER[\"Latitude of origin\",0.0," " ANGLEUNIT[\"degree\",0.0174532925199433]]," " PARAMETER[\"Longitude of origin\",3.0," " ANGLEUNIT[\"degree\",0.0174532925199433]]," " PARAMETER[\"Scale factor\",1,SCALEUNIT[\"unity\",1.0]]," " PARAMETER[\"False easting\",0.0," " LENGTHUNIT[\"metre\",1.0]]," " PARAMETER[\"False northing\",0.0,LENGTHUNIT[\"metre\",1.0]]]," " CS[Cartesian,3]," " AXIS[\"(E)\",east,ORDER[1]]," " AXIS[\"(N)\",north,ORDER[2]]," " AXIS[\"ellipsoidal height (h)\",up,ORDER[3]]," " LENGTHUNIT[\"metre\",1.0]" "]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=tmerc +lat_0=0 +lon_0=3 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 " "+units=m +no_defs +type=crs"); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2015).get()), FormattingException); EXPECT_NO_THROW(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get())); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_projected_utm_3D) { // Example from WKT2:2019 auto wkt = "PROJCRS[\"WGS 84 (G1762) / UTM zone 31N 3D\"," " BASEGEOGCRS[\"WGS 84\"," " DATUM[\"World Geodetic System of 1984 (G1762)\"," " ELLIPSOID[\"WGS 84\",6378137,298.257223563," " LENGTHUNIT[\"metre\",1.0]]]]," " CONVERSION[\"UTM zone 31N 3D\"," " METHOD[\"Transverse Mercator (3D)\"]," " PARAMETER[\"Latitude of origin\",0.0," " ANGLEUNIT[\"degree\",0.0174532925199433]]," " PARAMETER[\"Longitude of origin\",3.0," " ANGLEUNIT[\"degree\",0.0174532925199433]]," " PARAMETER[\"Scale factor\",0.9996,SCALEUNIT[\"unity\",1.0]]," " PARAMETER[\"False easting\",500000.0," " LENGTHUNIT[\"metre\",1.0]]," " PARAMETER[\"False northing\",0.0,LENGTHUNIT[\"metre\",1.0]]]," " CS[Cartesian,3]," " AXIS[\"(E)\",east,ORDER[1]]," " AXIS[\"(N)\",north,ORDER[2]]," " AXIS[\"ellipsoidal height (h)\",up,ORDER[3]]," " LENGTHUNIT[\"metre\",1.0]" "]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=utm +zone=31 +ellps=WGS84 +units=m +no_defs +type=crs"); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2015).get()), FormattingException); EXPECT_NO_THROW(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get())); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_projected_with_base_geocentric) { auto wkt = "PROJCRS[\"EPSG topocentric example B\",\n" " BASEGEODCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4978]],\n" " CONVERSION[\"EPSG topocentric example B\",\n" " METHOD[\"Geocentric/topocentric conversions\",\n" " ID[\"EPSG\",9836]],\n" " PARAMETER[\"Geocentric X of topocentric origin\",3771793.97,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8837]],\n" " PARAMETER[\"Geocentric Y of topocentric origin\",140253.34,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8838]],\n" " PARAMETER[\"Geocentric Z of topocentric origin\",5124304.35,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8839]]],\n" " CS[Cartesian,3],\n" " AXIS[\"topocentric East (U)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"topocentric North (V)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"topocentric height (W)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " USAGE[\n" " SCOPE[\"Example only (fictitious).\"],\n" " AREA[\"Description of the extent of the CRS.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",5820]]"; auto dbContext = DatabaseContext::create(); // Need a database so that EPSG:4978 is resolved auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->baseCRS()->isGeocentric()); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt2_2019_eqdc_non_epsg) { // Example from WKT2:2019 auto wkt = "PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Equidistant Conic\"],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Latitude of 1st standard parallel\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8823]],\n" " PARAMETER[\"Latitude of 2nd standard parallel\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8824]],\n" " PARAMETER[\"False easting\",5,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",6,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=eqdc +lat_0=1 +lon_0=2 +lat_1=3 +lat_2=4 +x_0=5 +y_0=6 " "+datum=WGS84 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(crs, projected_angular_unit_from_primem) { auto obj = WKTParser().createFromWKT( "PROJCRS[\"NTF (Paris) / Lambert Nord France\",\n" " BASEGEODCRS[\"NTF (Paris)\",\n" " DATUM[\"Nouvelle Triangulation Francaise (Paris)\",\n" " ELLIPSOID[\"Clarke 1880 " "(IGN)\",6378249.2,293.4660213,LENGTHUNIT[\"metre\",1.0]]],\n" " PRIMEM[\"Paris\",2.5969213,ANGLEUNIT[\"grad\",0.015707963268]]],\n" " CONVERSION[\"Lambert Nord France\",\n" " METHOD[\"Lambert Conic Conformal (1SP)\",ID[\"EPSG\",9801]],\n" " PARAMETER[\"Latitude of natural " "origin\",55,ANGLEUNIT[\"grad\",0.015707963268]],\n" " PARAMETER[\"Longitude of natural " "origin\",0,ANGLEUNIT[\"grad\",0.015707963268]],\n" " PARAMETER[\"Scale factor at natural " "origin\",0.999877341,SCALEUNIT[\"unity\",1.0]],\n" " PARAMETER[\"False easting\",600000,LENGTHUNIT[\"metre\",1.0]],\n" " PARAMETER[\"False northing\",200000,LENGTHUNIT[\"metre\",1.0]]],\n" " CS[cartesian,2],\n" " AXIS[\"easting (X)\",east,ORDER[1]],\n" " AXIS[\"northing (Y)\",north,ORDER[2]],\n" " LENGTHUNIT[\"metre\",1.0],\n" " ID[\"EPSG\",27561]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->coordinateSystem()->axisList()[0]->unit(), UnitOfMeasure::GRAD); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_MERIDIAN) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1.0]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting " "(X)\",south,MERIDIAN[90,ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " AXIS[\"northing (Y)\",north],\n" " UNIT[\"metre\",1],\n" " ID[\"EPSG\",32631]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); ASSERT_EQ(crs->coordinateSystem()->axisList().size(), 2U); auto axis = crs->coordinateSystem()->axisList()[0]; auto meridian = axis->meridian(); ASSERT_TRUE(meridian != nullptr); EXPECT_EQ(meridian->longitude().value(), 90.0); EXPECT_EQ(meridian->longitude().unit(), UnitOfMeasure::DEGREE); ASSERT_TRUE(crs->coordinateSystem()->axisList()[1]->meridian() == nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_multiple_ID) { auto wkt = "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX],\n" " AXIS[\"(Y)\",geocentricY],\n" " AXIS[\"(Z)\",geocentricZ],\n" " UNIT[\"metre\",1],\n" " ID[\"authorityA\",\"codeA\"],\n" " ID[\"authorityB\",\"codeB\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84"); ASSERT_EQ(crs->identifiers().size(), 2U); EXPECT_EQ(crs->identifiers()[0]->code(), "codeA"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "authorityA"); EXPECT_EQ(crs->identifiers()[1]->code(), "codeB"); EXPECT_EQ(*(crs->identifiers()[1]->codeSpace()), "authorityB"); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_AXISMINVAL_AXISMAXVAL_RANGEMEANING) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1]],\n" " CS[Cartesian,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " AXISMINVALUE[0],\n" " AXISMAXVALUE[360],\n" // nominal value is 'wraparound' lower case " RANGEMEANING[wrapAround]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); ASSERT_EQ(crs->coordinateSystem()->axisList().size(), 2U); { auto axis = crs->coordinateSystem()->axisList()[0]; EXPECT_FALSE(axis->minimumValue().has_value()); EXPECT_FALSE(axis->maximumValue().has_value()); EXPECT_FALSE(axis->rangeMeaning().has_value()); } { auto axis = crs->coordinateSystem()->axisList()[1]; ASSERT_TRUE(axis->minimumValue().has_value()); EXPECT_EQ(*axis->minimumValue(), 0); ASSERT_TRUE(axis->maximumValue().has_value()); EXPECT_EQ(*axis->maximumValue(), 360); ASSERT_TRUE(axis->rangeMeaning().has_value()); EXPECT_EQ(axis->rangeMeaning()->toString(), "wraparound"); } EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), replaceAll(wkt, "wrapAround", "wraparound")); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_invalid_AXISMINVAL_string) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1]],\n" " CS[Cartesian,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " AXISMINVALUE[invalid]]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_invalid_AXISMINVAL_too_many_children) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1]],\n" " CS[Cartesian,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " AXISMINVALUE[1,2]]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_invalid_AXISMAXVAL_string) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1]],\n" " CS[Cartesian,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " AXISMAXVALUE[invalid]]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_invalid_AXISMAXVAL_too_many_children) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1]],\n" " CS[Cartesian,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " AXISMAXVALUE[1,2]]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_invalid_RANGEMEANING) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1]],\n" " CS[Cartesian,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " AXISMINVALUE[0],\n" " AXISMAXVALUE[360],\n" " RANGEMEANING[invalid]]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, cs_with_invalid_RANGEMEANING_too_many_children) { auto wkt = "PROJCRS[\"dummy\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"dummy\",\n" " METHOD[\"dummy\"],\n" " PARAMETER[\"dummy\",1]],\n" " CS[Cartesian,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " AXISMINVALUE[0],\n" " AXISMAXVALUE[360],\n" " RANGEMEANING[exact,unexpected_value]]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_WKT2) { auto wkt = "VERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5701]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "ODN height"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "5701"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "Ordnance Datum Newlyn"); // ASSERT_EQ(datum->identifiers().size(), 1U); // EXPECT_EQ(datum->identifiers()[0]->code(), "5101"); // EXPECT_EQ(*(datum->identifiers()[0]->codeSpace()), "EPSG"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Gravity-related height"); EXPECT_EQ(cs->axisList()[0]->abbreviation(), "H"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::UP); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_VRF_WKT2) { auto wkt = "VERTCRS[\"ODN height\",\n" " VRF[\"Ordnance Datum Newlyn\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5701]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_with_GEOIDMODEL) { auto wkt = "VERTCRS[\"CGVD2013\",\n" " VDATUM[\"Canadian Geodetic Vertical Datum of 2013\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " GEOIDMODEL[\"CGG2013\",\n" " ID[\"EPSG\",6648]],\n" " GEOIDMODEL[\"other\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_WKT1_GDAL) { auto wkt = "VERT_CS[\"ODN height\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005,\n" " AUTHORITY[\"EPSG\",\"5101\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5701\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "ODN height"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "5701"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "Ordnance Datum Newlyn"); ASSERT_EQ(datum->identifiers().size(), 1U); EXPECT_EQ(datum->identifiers()[0]->code(), "5101"); EXPECT_EQ(*(datum->identifiers()[0]->codeSpace()), "EPSG"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Gravity-related height"); EXPECT_EQ(cs->axisList()[0]->abbreviation(), ""); // "H" in WKT2 EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::UP); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_WKT1_GDAL_minimum) { auto wkt = "VERT_CS[\"ODN height\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005],\n" " UNIT[\"metre\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); EXPECT_EQ(crs->nameStr(), "ODN height"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "Ordnance Datum Newlyn"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Gravity-related height"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::UP); EXPECT_EQ(cs->axisList()[0]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_WKT1_GDAL_missing_unit_and_axis) { auto wkt = "VERT_CS[\"ODN height\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005]]"; // Missing UNIT[] is illegal in strict mode EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); auto obj = WKTParser().setStrict(false).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); EXPECT_EQ(crs->nameStr(), "ODN height"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "Ordnance Datum Newlyn"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Gravity-related height"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::UP); EXPECT_EQ(cs->axisList()[0]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_WKT1_GDAl_missing_unit_with_axis) { auto wkt = "VERT_CS[\"ODN height\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005],\n" " AXIS[\"gravity-related height\",UP]]"; // Missing UNIT[] is illegal in strict mode EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); auto obj = WKTParser().setStrict(false).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); EXPECT_EQ(crs->nameStr(), "ODN height"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "Ordnance Datum Newlyn"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->nameStr(), "Gravity-related height"); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::UP); EXPECT_EQ(cs->axisList()[0]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, VERTCS_WKT1_ESRI) { auto wkt = "VERTCS[\"EGM2008_Geoid\",VDATUM[\"EGM2008_Geoid\"]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "EGM2008_Geoid"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "EGM2008_Geoid"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::UP); EXPECT_EQ(WKTParser().guessDialect(wkt), WKTParser::WKTGuessedDialect::WKT1_ESRI); } // --------------------------------------------------------------------------- TEST(wkt_parse, VERTCS_WKT1_ESRI_context) { auto wkt = "VERTCS[\"EGM2008_Geoid\",VDATUM[\"EGM2008_Geoid\"]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "EGM2008 height"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "EGM2008 geoid"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::UP); EXPECT_EQ(WKTParser().guessDialect(wkt), WKTParser::WKTGuessedDialect::WKT1_ESRI); } // --------------------------------------------------------------------------- TEST(wkt_parse, VERTCS_WKT1_ESRI_down) { auto wkt = "VERTCS[\"Caspian\",VDATUM[\"Caspian_Sea\"]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",-1.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); EXPECT_EQ(cs->axisList()[0]->direction(), AxisDirection::DOWN); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_WKT1_LAS_ftUS) { auto wkt = "VERT_CS[\"NAVD88 - Geoid03 (Feet)\"," " VERT_DATUM[\"unknown\",2005]," " UNIT[\"US survey foot\",0.3048006096012192," " AUTHORITY[\"EPSG\",\"9003\"]]," " AXIS[\"Up\",UP]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 height (ftUS)"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "6360"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); const auto &geoidModel = crs->geoidModel(); ASSERT_TRUE(!geoidModel.empty()); EXPECT_EQ(geoidModel[0]->nameStr(), "GEOID03"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "North American Vertical Datum 1988"); ASSERT_EQ(datum->identifiers().size(), 1U); EXPECT_EQ(datum->identifiers()[0]->code(), "5103"); EXPECT_EQ(*(datum->identifiers()[0]->codeSpace()), "EPSG"); const auto &axis = crs->coordinateSystem()->axisList()[0]; EXPECT_EQ(axis->direction(), AxisDirection::UP); EXPECT_EQ(axis->unit().name(), "US survey foot"); EXPECT_NEAR(axis->unit().conversionToSI(), 0.3048006096012192, 1e-16); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_WKT1_LAS_metre) { auto wkt = "VERT_CS[\"NAVD88 via Geoid09\"," " VERT_DATUM[\"unknown\",2005]," " UNIT[\"metre\",1.0," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Up\",UP]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 height"); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "5703"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "EPSG"); const auto &geoidModel = crs->geoidModel(); ASSERT_TRUE(!geoidModel.empty()); EXPECT_EQ(geoidModel[0]->nameStr(), "GEOID09"); auto datum = crs->datum(); EXPECT_EQ(datum->nameStr(), "North American Vertical Datum 1988"); ASSERT_EQ(datum->identifiers().size(), 1U); EXPECT_EQ(datum->identifiers()[0]->code(), "5103"); EXPECT_EQ(*(datum->identifiers()[0]->codeSpace()), "EPSG"); const auto &axis = crs->coordinateSystem()->axisList()[0]; EXPECT_EQ(axis->direction(), AxisDirection::UP); EXPECT_EQ(axis->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, dynamic_vertical_reference_frame) { auto obj = WKTParser().createFromWKT( "VERTCRS[\"RH2000\"," " DYNAMIC[FRAMEEPOCH[2000.0],MODEL[\"NKG2016LU\"]]," " VDATUM[\"Rikets Hojdsystem 2000\",ANCHOR[\"my anchor\"]]," " CS[vertical,1]," " AXIS[\"gravity-related height (H)\",up]," " LENGTHUNIT[\"metre\",1.0]" "]"); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); auto dgrf = std::dynamic_pointer_cast<DynamicVerticalReferenceFrame>(crs->datum()); ASSERT_TRUE(dgrf != nullptr); auto anchor = dgrf->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "my anchor"); EXPECT_TRUE(dgrf->frameReferenceEpoch() == Measure(2000.0, UnitOfMeasure::YEAR)); auto model = dgrf->deformationModelName(); EXPECT_TRUE(model.has_value()); EXPECT_EQ(*model, "NKG2016LU"); } // --------------------------------------------------------------------------- TEST(wkt_parse, vertcrs_with_ensemble) { auto obj = WKTParser().createFromWKT( "VERTCRS[\"unnamed\",\n" " ENSEMBLE[\"unnamed\",\n" " MEMBER[\"vdatum1\"],\n" " MEMBER[\"vdatum2\"],\n" " ENSEMBLEACCURACY[100]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]]"); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); ASSERT_TRUE(crs->datum() == nullptr); ASSERT_TRUE(crs->datumEnsemble() != nullptr); EXPECT_EQ(crs->datumEnsemble()->datums().size(), 2U); } // --------------------------------------------------------------------------- TEST(wkt_parse, vdatum_with_ANCHOR) { auto obj = WKTParser().createFromWKT("VDATUM[\"Ordnance Datum Newlyn\",\n" " ANCHOR[\"my anchor\"],\n" " ID[\"EPSG\",5101]]"); auto datum = nn_dynamic_pointer_cast<VerticalReferenceFrame>(obj); ASSERT_TRUE(datum != nullptr); auto anchor = datum->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "my anchor"); EXPECT_FALSE(datum->anchorEpoch().has_value()); } // --------------------------------------------------------------------------- TEST(wkt_parse, vdatum_with_ANCHOREPOCH) { auto obj = WKTParser().createFromWKT("VDATUM[\"my_datum\",\n" " ANCHOREPOCH[2002.5]]"); auto datum = nn_dynamic_pointer_cast<VerticalReferenceFrame>(obj); ASSERT_TRUE(datum != nullptr); auto anchorEpoch = datum->anchorEpoch(); EXPECT_TRUE(anchorEpoch.has_value()); ASSERT_EQ(anchorEpoch->convertToUnit(UnitOfMeasure::YEAR), 2002.5); EXPECT_FALSE(datum->anchorDefinition().has_value()); } // --------------------------------------------------------------------------- TEST(wkt_parse, engineeringCRS_WKT2_affine_CS) { auto wkt = "ENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"],\n" " CS[affine,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2).get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPOUNDCRS) { auto obj = WKTParser().createFromWKT( "COMPOUNDCRS[\"horizontal + vertical\",\n" " PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]],\n" " VERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]],\n" " ID[\"codespace\",\"code\"]]"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "horizontal + vertical"); EXPECT_EQ(crs->componentReferenceSystems().size(), 2U); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "code"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "codespace"); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPOUNDCRS_spatio_parametric_2015) { auto obj = WKTParser().createFromWKT( "COMPOUNDCRS[\"ICAO layer 0\",\n" " GEODETICCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " PARAMETRICCRS[\"WMO standard atmosphere\",\n" " PARAMETRICDATUM[\"Mean Sea Level\",\n" " ANCHOR[\"Mean Sea Level = 1013.25 hPa\"]],\n" " CS[parametric,1],\n" " AXIS[\"pressure (P)\",unspecified,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]]"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPOUNDCRS_spatio_parametric_2019) { auto obj = WKTParser().createFromWKT( "COMPOUNDCRS[\"ICAO layer 0\",\n" " GEOGRAPHICCRS[\"WGS 84\",\n" " DYNAMIC[FRAMEEPOCH[2005]],\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " PARAMETRICCRS[\"WMO standard atmosphere\",\n" " PARAMETRICDATUM[\"Mean Sea Level\",\n" " ANCHOR[\"Mean Sea Level = 1013.25 hPa\"]],\n" " CS[parametric,1],\n" " AXIS[\"pressure (P)\",unspecified,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]]"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPOUNDCRS_spatio_temporal_2015) { auto obj = WKTParser().createFromWKT( "COMPOUNDCRS[\"GPS position and time\",\n" " GEODCRS[\"WGS 84 (G1762)\",\n" " DATUM[\"World Geodetic System 1984 (G1762)\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " TIMECRS[\"GPS Time\",\n" " TIMEDATUM[\"Time origin\",TIMEORIGIN[1980-01-01]],\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]]"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPOUNDCRS_spatio_temporal_2019) { auto obj = WKTParser().createFromWKT( "COMPOUNDCRS[\"2D GPS position with civil time in ISO 8601 format\",\n" " GEOGCRS[\"WGS 84 (G1762)\",\n" " DATUM[\"World Geodetic System 1984 (G1762)\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " TIMECRS[\"DateTime\",\n" " TDATUM[\"Gregorian Calendar\"],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]]"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPD_CS) { auto obj = WKTParser().createFromWKT( "COMPD_CS[\"horizontal + vertical\",\n" " PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"Latitude\",NORTH],\n" " AXIS[\"Longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]],\n" " VERT_CS[\"ODN height\",\n" " VERT_DATUM[\"Ordnance Datum Newlyn\",2005,\n" " AUTHORITY[\"EPSG\",\"5101\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5701\"]],\n" " AUTHORITY[\"codespace\",\"code\"]]"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "horizontal + vertical"); EXPECT_EQ(crs->componentReferenceSystems().size(), 2U); ASSERT_EQ(crs->identifiers().size(), 1U); EXPECT_EQ(crs->identifiers()[0]->code(), "code"); EXPECT_EQ(*(crs->identifiers()[0]->codeSpace()), "codespace"); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPD_CS_non_conformant_horizontal_plus_horizontal_as_in_LAS) { auto obj = WKTParser().createFromWKT( "COMPD_CS[\"horizontal + vertical\",\n" " PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"Latitude\",NORTH],\n" " AXIS[\"Longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]],\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"Latitude\",NORTH],\n" " AXIS[\"Longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4326\"]]]"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / UTM zone 31N"); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPD_CS_non_conformant_horizontal_TOWGS84_plus_horizontal_as_in_LAS) { const auto wkt = "COMPD_CS[\"WGS 84 + WGS 84\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto baseCRS = nn_dynamic_pointer_cast<GeographicCRS>(crs->baseCRS()); ASSERT_TRUE(baseCRS != nullptr); EXPECT_EQ(baseCRS->nameStr(), "WGS 84"); EXPECT_EQ(baseCRS->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPD_CS_horizontal_bound_geog_plus_vertical_ellipsoidal_height) { // See https://github.com/OSGeo/PROJ/issues/2228 const char *wkt = "COMPD_CS[\"NAD83 + Ellipsoid (Meters)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " TOWGS84[0,0,0,0,0,0,0],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"Ellipsoid (Meters)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Up\",UP]]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto baseCRS = nn_dynamic_pointer_cast<GeographicCRS>(crs->baseCRS()); ASSERT_TRUE(baseCRS != nullptr); EXPECT_EQ(baseCRS->nameStr(), "NAD83"); EXPECT_EQ(baseCRS->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ(replaceAll(crs->exportToWKT( WKTFormatter::create( WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()), "ellipsoidal height", "Up"), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPD_CS_horizontal_projected_plus_vertical_ellipsoidal_height) { // Variant of above const char *wkt = "COMPD_CS[\"WGS 84 / UTM zone 31N + Ellipsoid (Meters)\",\n" " PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]],\n" " VERT_CS[\"Ellipsoid (Meters)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Up\",UP]]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / UTM zone 31N"); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ(replaceAll(crs->exportToWKT( WKTFormatter::create( WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()), "ellipsoidal height", "Up"), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, COMPD_CS_horizontal_geog_plus_vertical_ellipsoidal_height_non_metre) { // See https://github.com/OSGeo/PROJ/issues/2232 const char *wkt = "COMPD_CS[\"NAD83 + Ellipsoid (US Feet)\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"Ellipsoid (US Feet)\",\n" " VERT_DATUM[\"Ellipsoid\",2002],\n" " UNIT[\"US survey foot\",0.304800609601219,\n" " AUTHORITY[\"EPSG\",\"9003\"]],\n" " AXIS[\"Up\",UP]]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAD83 (Ellipsoid (US Feet))"); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); EXPECT_NEAR(crs->coordinateSystem()->axisList()[2]->unit().conversionToSI(), 0.304800609601219, 1e-15); EXPECT_EQ(replaceAll(crs->exportToWKT( WKTFormatter::create( WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()), "ellipsoidal height", "Up"), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, implicit_compound_CRS_ESRI) { // See https://lists.osgeo.org/pipermail/gdal-dev/2020-October/052843.html // and https://pro.arcgis.com/en/pro-app/arcpy/classes/spatialreference.htm const char *wkt = "PROJCS[\"NAD_1983_2011_StatePlane_Colorado_Central_FIPS_0502_Ft_US\"," "GEOGCS[\"GCS_NAD_1983_2011\",DATUM[\"D_NAD_1983_2011\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",3000000.00031608]," "PARAMETER[\"False_Northing\",999999.999996]," "PARAMETER[\"Central_Meridian\",-105.5]," "PARAMETER[\"Standard_Parallel_1\",38.45]," "PARAMETER[\"Standard_Parallel_2\",39.75]," "PARAMETER[\"Latitude_Of_Origin\",37.8333333333333]," "UNIT[\"US survey foot\",0.304800609601219]]," "VERTCS[\"CGVD2013_height\"," "VDATUM[\"Canadian_Geodetic_Vertical_Datum_of_2013\"]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAD83(2011) / Colorado Central (ftUS) + " "CGVD2013(CGG2013) height"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, VERTCS_with_ellipsoidal_height_ESRI) { const char *wkt = "VERTCS[\"WGS_1984\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); const char *expected_wkt1 = "VERT_CS[\"WGS_1984\",\n" " VERT_DATUM[\"World Geodetic System 1984\",2002],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"ellipsoidal height\",UP]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()), expected_wkt1); } // --------------------------------------------------------------------------- TEST(wkt_parse, implicit_compound_CRS_geographic_with_ellipsoidal_height_ESRI) { const char *wkt = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "VERTCS[\"WGS_1984\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0],UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext)); f->setAllowLINUNITNode(false); EXPECT_EQ(crs->exportToWKT(f.get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, implicit_compound_CRS_projected_with_ellipsoidal_height_ESRI) { const char *wkt = "PROJCS[\"WGS_1984_UTM_Zone_31N\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"False_Easting\",500000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",3.0]," "PARAMETER[\"Scale_Factor\",0.9996]," "PARAMETER[\"Latitude_Of_Origin\",0.0]," "UNIT[\"Meter\",1.0]]," "VERTCS[\"WGS_1984\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PARAMETER[\"Vertical_Shift\",0.0]," "PARAMETER[\"Direction\",1.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, COORDINATEOPERATION) { std::string src_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); src_wkt = GeographicCRS::EPSG_4326->exportToWKT(formatter.get()); } std::string dst_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); dst_wkt = GeographicCRS::EPSG_4807->exportToWKT(formatter.get()); } std::string interpolation_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); interpolation_wkt = GeographicCRS::EPSG_4979->exportToWKT(formatter.get()); } auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[" + dst_wkt + "],\n" " METHOD[\"operationMethodName\",\n" " ID[\"codeSpaceOperationMethod\",\"codeOperationMethod\"]],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"],\n" " INTERPOLATIONCRS[" + interpolation_wkt + "],\n" " OPERATIONACCURACY[0.1],\n" " ID[\"codeSpaceTransformation\",\"codeTransformation\"],\n" " REMARK[\"my remarks\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto transf = nn_dynamic_pointer_cast<Transformation>(obj); ASSERT_TRUE(transf != nullptr); EXPECT_EQ(transf->nameStr(), "transformationName"); ASSERT_EQ(transf->identifiers().size(), 1U); EXPECT_EQ(transf->identifiers()[0]->code(), "codeTransformation"); EXPECT_EQ(*(transf->identifiers()[0]->codeSpace()), "codeSpaceTransformation"); ASSERT_EQ(transf->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(transf->coordinateOperationAccuracies()[0]->value(), "0.1"); EXPECT_EQ(transf->sourceCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), GeographicCRS::EPSG_4807->nameStr()); ASSERT_TRUE(transf->interpolationCRS() != nullptr); EXPECT_EQ(transf->interpolationCRS()->nameStr(), GeographicCRS::EPSG_4979->nameStr()); EXPECT_EQ(transf->method()->nameStr(), "operationMethodName"); EXPECT_EQ(transf->parameterValues().size(), 1U); { auto outWkt = transf->exportToWKT(WKTFormatter::create().get()); EXPECT_EQ(replaceAll(replaceAll(outWkt, "\n", ""), " ", ""), replaceAll(replaceAll(wkt, "\n", ""), " ", "")); } } // --------------------------------------------------------------------------- TEST(wkt_parse, COORDINATEOPERATION_with_interpolation_as_parameter) { auto wkt = "COORDINATEOPERATION[\"SHGD2015 to SHGD2015 + SHVD2015 height (1)\",\n" " VERSION[\"ENRD-Shn Hel\"],\n" " SOURCECRS[\n" " GEOGCRS[\"SHGD2015\",\n" " DATUM[\"St. Helena Geodetic Datum 2015\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",7885]]],\n" " TARGETCRS[\n" " COMPOUNDCRS[\"SHMG2015 + SHVD2015 height\",\n" " PROJCRS[\"SHMG2015\",\n" " BASEGEOGCRS[\"SHGD2015\",\n" " DATUM[\"St. Helena Geodetic Datum 2015\",\n" " ELLIPSOID[\"GRS " "1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",7886]],\n" " CONVERSION[\"UTM zone 30S\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural " "origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",10000000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]],\n" " VERTCRS[\"SHVD2015 height\",\n" " VDATUM[\"St. Helena Vertical Datum 2015\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]],\n" " ID[\"EPSG\",7956]]],\n" " METHOD[\"Geog3D to Geog2D+GravityRelatedHeight (EGM2008)\",\n" " ID[\"EPSG\",1092]],\n" " PARAMETERFILE[\"Geoid (height correction) model file\"," "\"Und_min2.5x2.5_egm2008_isw=82_WGS84_TideFree.gz\"],\n" " PARAMETER[\"EPSG code for Interpolation CRS\",7886,\n" " ID[\"EPSG\",1048]],\n" " OPERATIONACCURACY[0],\n" " ID[\"EPSG\",9617]]"; { auto obj = WKTParser().createFromWKT(wkt); auto transf = nn_dynamic_pointer_cast<Transformation>(obj); ASSERT_TRUE(transf != nullptr); EXPECT_TRUE(transf->interpolationCRS() == nullptr); EXPECT_EQ(transf->parameterValues().size(), 2U); } { auto dbContext = DatabaseContext::create(); // Need a database so that the interpolation CRS EPSG:7886 is resolved auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto transf = nn_dynamic_pointer_cast<Transformation>(obj); ASSERT_TRUE(transf != nullptr); EXPECT_TRUE(transf->interpolationCRS() != nullptr); EXPECT_EQ(transf->parameterValues().size(), 1U); } } // --------------------------------------------------------------------------- TEST(wkt_parse, COORDINATEOPERATION_wkt2_2019) { std::string src_wkt; { auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); formatter->setOutputId(false); src_wkt = GeographicCRS::EPSG_4326->exportToWKT(formatter.get()); } std::string dst_wkt; { auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); formatter->setOutputId(false); dst_wkt = GeographicCRS::EPSG_4807->exportToWKT(formatter.get()); } std::string interpolation_wkt; { auto formatter = WKTFormatter::create(WKTFormatter::Convention::WKT2_2019); formatter->setOutputId(false); interpolation_wkt = GeographicCRS::EPSG_4979->exportToWKT(formatter.get()); } auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " VERSION[\"my version\"],\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[" + dst_wkt + "],\n" " METHOD[\"operationMethodName\",\n" " ID[\"codeSpaceOperationMethod\",\"codeOperationMethod\"]],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"],\n" " INTERPOLATIONCRS[" + interpolation_wkt + "],\n" " OPERATIONACCURACY[0.1],\n" " ID[\"codeSpaceTransformation\",\"codeTransformation\"],\n" " REMARK[\"my remarks\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto transf = nn_dynamic_pointer_cast<Transformation>(obj); ASSERT_TRUE(transf != nullptr); EXPECT_EQ(transf->nameStr(), "transformationName"); EXPECT_EQ(*transf->operationVersion(), "my version"); ASSERT_EQ(transf->identifiers().size(), 1U); EXPECT_EQ(transf->identifiers()[0]->code(), "codeTransformation"); EXPECT_EQ(*(transf->identifiers()[0]->codeSpace()), "codeSpaceTransformation"); ASSERT_EQ(transf->coordinateOperationAccuracies().size(), 1U); EXPECT_EQ(transf->coordinateOperationAccuracies()[0]->value(), "0.1"); EXPECT_EQ(transf->sourceCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); EXPECT_EQ(transf->targetCRS()->nameStr(), GeographicCRS::EPSG_4807->nameStr()); ASSERT_TRUE(transf->interpolationCRS() != nullptr); EXPECT_EQ(transf->interpolationCRS()->nameStr(), GeographicCRS::EPSG_4979->nameStr()); EXPECT_EQ(transf->method()->nameStr(), "operationMethodName"); EXPECT_EQ(transf->parameterValues().size(), 1U); { auto outWkt = transf->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_EQ(replaceAll(replaceAll(outWkt, "\n", ""), " ", ""), replaceAll(replaceAll(wkt, "\n", ""), " ", "")); } { auto outWkt = transf->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2015).get()); EXPECT_FALSE(outWkt.find("VERSION[\"my version\"],") != std::string::npos); } } // --------------------------------------------------------------------------- TEST(wkt_parse, conversion_proj_based) { auto wkt = "CONVERSION[\"PROJ-based coordinate operation\",\n" " METHOD[\"PROJ-based operation method: +proj=merc\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto transf = nn_dynamic_pointer_cast<SingleOperation>(obj); ASSERT_TRUE(transf != nullptr); EXPECT_EQ(transf->exportToPROJString(PROJStringFormatter::create().get()), "+proj=merc"); } // --------------------------------------------------------------------------- TEST(wkt_parse, CONCATENATEDOPERATION) { auto transf_1 = Transformation::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "transf_1"), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), nullptr, PropertyMap().set(IdentifiedObject::NAME_KEY, "operationMethodName"), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>()); auto transf_2 = Transformation::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "transf_2"), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4979), nullptr, PropertyMap().set(IdentifiedObject::NAME_KEY, "operationMethodName"), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>()); auto concat_in = ConcatenatedOperation::create( PropertyMap() .set(Identifier::CODESPACE_KEY, "codeSpace") .set(Identifier::CODE_KEY, "code") .set(IdentifiedObject::NAME_KEY, "name") .set(IdentifiedObject::REMARKS_KEY, "my remarks"), std::vector<CoordinateOperationNNPtr>{transf_1, transf_2}, std::vector<PositionalAccuracyNNPtr>{ PositionalAccuracy::create("0.1")}); auto wkt = concat_in->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); auto obj = WKTParser().createFromWKT(wkt); auto concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(obj); ASSERT_TRUE(concat != nullptr); EXPECT_EQ(concat->nameStr(), "name"); EXPECT_FALSE(concat->operationVersion().has_value()); ASSERT_EQ(concat->identifiers().size(), 1U); EXPECT_EQ(concat->identifiers()[0]->code(), "code"); EXPECT_EQ(*(concat->identifiers()[0]->codeSpace()), "codeSpace"); ASSERT_EQ(concat->operations().size(), 2U); ASSERT_EQ(concat->operations()[0]->nameStr(), transf_1->nameStr()); ASSERT_EQ(concat->operations()[1]->nameStr(), transf_2->nameStr()); ASSERT_TRUE(concat->sourceCRS() != nullptr); ASSERT_TRUE(concat->targetCRS() != nullptr); ASSERT_EQ(concat->sourceCRS()->nameStr(), transf_1->sourceCRS()->nameStr()); ASSERT_EQ(concat->targetCRS()->nameStr(), transf_2->targetCRS()->nameStr()); } // --------------------------------------------------------------------------- TEST(wkt_parse, CONCATENATEDOPERATION_with_conversion_and_conversion) { auto wkt = "CONCATENATEDOPERATION[\"Inverse of UTM zone 31N + UTM zone 32N\",\n" " SOURCECRS[\n" " PROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",32631]]],\n" " TARGETCRS[\n" " PROJCRS[\"WGS 84 / UTM zone 32N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 32N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",9,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",32632]]],\n" " STEP[\n" " CONVERSION[\"Inverse of UTM zone 31N\",\n" " METHOD[\"Inverse of Transverse Mercator\",\n" " ID[\"INVERSE(EPSG)\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"INVERSE(EPSG)\",16031]]],\n" " STEP[\n" " CONVERSION[\"UTM zone 32N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",9,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",16032]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(obj); ASSERT_TRUE(concat != nullptr); EXPECT_EQ(concat->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=31 +ellps=WGS84 " "+step +proj=utm +zone=32 +ellps=WGS84"); auto outWkt = concat->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_EQ(wkt, outWkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, CONCATENATEDOPERATION_with_conversion_coordinateoperation_conversion) { auto wkt = "CONCATENATEDOPERATION[\"Inverse of UTM zone 11N + NAD27 to WGS 84 " "(79) + UTM zone 11N\",\n" " VERSION[\"my version\"],\n" " SOURCECRS[\n" " PROJCRS[\"NAD27 / UTM zone 11N\",\n" " BASEGEOGCRS[\"NAD27\",\n" " DATUM[\"North American Datum 1927\",\n" " ELLIPSOID[\"Clarke " "1866\",6378206.4,294.978698213898,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 11N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",26711]]],\n" " TARGETCRS[\n" " PROJCRS[\"WGS 84 / UTM zone 11N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 11N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",32611]]],\n" " STEP[\n" " CONVERSION[\"Inverse of UTM zone 11N\",\n" " METHOD[\"Inverse of Transverse Mercator\",\n" " ID[\"INVERSE(EPSG)\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"INVERSE(EPSG)\",16011]]],\n" " STEP[\n" " COORDINATEOPERATION[\"NAD27 to WGS 84 (79)\",\n" " SOURCECRS[\n" " GEOGCRS[\"NAD27\",\n" " DATUM[\"North American Datum 1927\",\n" " ELLIPSOID[\"Clarke " "1866\",6378206.4,294.978698213898,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]]]],\n" " METHOD[\"CTABLE2\"],\n" " PARAMETERFILE[\"Latitude and longitude difference " "file\",\"conus\"],\n" " ID[\"DERIVED_FROM(EPSG)\",15851]]],\n" " STEP[\n" " CONVERSION[\"UTM zone 11N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",16011]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(obj); ASSERT_TRUE(concat != nullptr); EXPECT_EQ(*concat->operationVersion(), "my version"); EXPECT_EQ(concat->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=11 +ellps=clrk66 " "+step +proj=hgridshift +grids=conus +step +proj=utm " "+zone=11 +ellps=WGS84"); auto outWkt = concat->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_EQ(wkt, outWkt); } // --------------------------------------------------------------------------- TEST( wkt_parse, CONCATENATEDOPERATION_with_conversion_coordinateoperation_to_inverse_conversion) { auto wkt = "CONCATENATEDOPERATION[\"Inverse of UTM zone 11N + NAD27 to WGS 84 " "(79) + UTM zone 11N\",\n" " SOURCECRS[\n" " PROJCRS[\"WGS 84 / UTM zone 11N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 11N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",32611]]],\n" " TARGETCRS[\n" " PROJCRS[\"NAD27 / UTM zone 11N\",\n" " BASEGEOGCRS[\"NAD27\",\n" " DATUM[\"North American Datum 1927\",\n" " ELLIPSOID[\"Clarke " "1866\",6378206.4,294.978698213898,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 11N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",26711]]],\n" " STEP[\n" " CONVERSION[\"Inverse of UTM zone 11N\",\n" " METHOD[\"Inverse of Transverse Mercator\",\n" " ID[\"INVERSE(EPSG)\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"INVERSE(EPSG)\",16011]]],\n" " STEP[\n" " COORDINATEOPERATION[\"NAD27 to WGS 84 (79)\",\n" " SOURCECRS[\n" " GEOGCRS[\"NAD27\",\n" " DATUM[\"North American Datum 1927\",\n" " ELLIPSOID[\"Clarke " "1866\",6378206.4,294.978698213898,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]]]],\n" " METHOD[\"CTABLE2\"],\n" " PARAMETERFILE[\"Latitude and longitude difference " "file\",\"conus\"],\n" " ID[\"DERIVED_FROM(EPSG)\",15851]]],\n" " STEP[\n" " CONVERSION[\"UTM zone 11N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",16011]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(obj); ASSERT_TRUE(concat != nullptr); EXPECT_EQ(concat->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +inv +proj=utm +zone=11 +ellps=WGS84 " "+step +inv +proj=hgridshift +grids=conus +step " "+proj=utm +zone=11 +ellps=clrk66"); } // --------------------------------------------------------------------------- TEST(wkt_parse, CONCATENATEDOPERATION_with_inverse_conversion_of_compound) { auto wkt = "CONCATENATEDOPERATION[\"Inverse of RD New + Amersfoort to ETRS89 (9) " "+ Inverse of ETRS89 to NAP height (2) + ETRS89 to WGS 84 (1)\",\n" " SOURCECRS[\n" " COMPOUNDCRS[\"Amersfoort / RD New + NAP height\",\n" " PROJCRS[\"Amersfoort / RD New\",\n" " BASEGEOGCRS[\"Amersfoort\",\n" " DATUM[\"Amersfoort\",\n" " ELLIPSOID[\"Bessel " "1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4289]],\n" " CONVERSION[\"RD New\",\n" " METHOD[\"Oblique Stereographic\",\n" " ID[\"EPSG\",9809]],\n" " PARAMETER[\"Latitude of natural " "origin\",52.1561605555556,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural " "origin\",5.38763888888889,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural " "origin\",0.9999079,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",155000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",463000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"easting (X)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"northing (Y)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]],\n" " VERTCRS[\"NAP height\",\n" " VDATUM[\"Normaal Amsterdams Peil\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]]],\n" " ID[\"EPSG\",7415]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84 (3D)\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " MEMBER[\"World Geodetic System 1984 (G2139)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree minute second " "hemisphere\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Long)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree minute second " "hemisphere\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4329]]],\n" " STEP[\n" " CONVERSION[\"Inverse of RD New\",\n" " METHOD[\"Inverse of Oblique Stereographic\",\n" " ID[\"INVERSE(EPSG)\",9809]],\n" " PARAMETER[\"Latitude of natural " "origin\",52.1561605555556,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural " "origin\",5.38763888888889,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9999079,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",155000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",463000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"INVERSE(EPSG)\",19914]]],\n" " STEP[\n" " COORDINATEOPERATION[\"PROJ-based coordinate operation\",\n" " SOURCECRS[\n" " COMPOUNDCRS[\"Amersfoort + NAP height\",\n" " GEOGCRS[\"Amersfoort\",\n" " DATUM[\"Amersfoort\",\n" " ELLIPSOID[\"Bessel " "1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " " "ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4289]],\n" " VERTCRS[\"NAP height\",\n" " VDATUM[\"Normaal Amsterdams Peil\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",5709]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84 (3D)\",\n" " ENSEMBLE[\"World Geodetic System 1984 " "ensemble\",\n" " MEMBER[\"World Geodetic System 1984 " "(Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 " "(G730)\"],\n" " MEMBER[\"World Geodetic System 1984 " "(G873)\"],\n" " MEMBER[\"World Geodetic System 1984 " "(G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 " "(G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 " "(G1762)\"],\n" " MEMBER[\"World Geodetic System 1984 " "(G2139)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree minute second " "hemisphere\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Long)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree minute second " "hemisphere\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4329]]],\n" " METHOD[\"PROJ-based operation method: +proj=pipeline " "+step +proj=axisswap +order=2,1 +step +proj=unitconvert +xy_in=deg " "+xy_out=rad +step +proj=hgridshift +grids=nl_nsgi_rdtrans2018.tif " "+step +proj=vgridshift +grids=nl_nsgi_nlgeo2018.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap " "+order=2,1\"],\n" " OPERATIONACCURACY[1.002]]],\n" " USAGE[\n" " SCOPE[\"unknown\"],\n" " AREA[\"Netherlands - onshore, including Waddenzee, Dutch " "Wadden Islands and 12-mile offshore coastal zone.\"],\n" " BBOX[50.75,3.2,53.7,7.22]]]"; auto obj = WKTParser().createFromWKT(wkt); auto concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(obj); ASSERT_TRUE(concat != nullptr); EXPECT_EQ(concat->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +inv +proj=sterea +lat_0=52.1561605555556 " "+lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 " "+ellps=bessel " "+step +proj=hgridshift +grids=nl_nsgi_rdtrans2018.tif " "+step +proj=vgridshift +grids=nl_nsgi_nlgeo2018.tif " "+multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(wkt_parse, BOUNDCRS_transformation_from_names) { auto projcrs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my PROJCRS"), GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my GEOGCRS"), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)), Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto wkt = "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" + "TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) + "],\n" " ABRIDGEDTRANSFORMATION[\"Transformation to WGS84\",\n" " METHOD[\"Coordinate Frame\"],\n" " PARAMETER[\"X-axis translation\",1],\n" " PARAMETER[\"Y-axis translation\",2],\n" " PARAMETER[\"Z-axis translation\",3],\n" " PARAMETER[\"X-axis rotation\",-4],\n" " PARAMETER[\"Y-axis rotation\",-5],\n" " PARAMETER[\"Z-axis rotation\",-6],\n" " PARAMETER[\"Scale difference\",1.000007]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->nameStr(), projcrs->nameStr()); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); ASSERT_TRUE(crs->transformation()->sourceCRS() != nullptr); EXPECT_EQ(crs->transformation()->sourceCRS()->nameStr(), projcrs->baseCRS()->nameStr()); auto params = crs->transformation()->getTOWGS84Parameters(); auto expected = std::vector<double>{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}; ASSERT_EQ(params.size(), expected.size()); for (int i = 0; i < 7; i++) { EXPECT_NEAR(params[i], expected[i], 1e-10); } } // --------------------------------------------------------------------------- TEST(wkt_parse, BOUNDCRS_transformation_from_codes) { auto projcrs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my PROJCRS"), GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my GEOGCRS"), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)), Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto wkt = "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" + "TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) + "],\n" " ABRIDGEDTRANSFORMATION[\"Transformation to WGS84\",\n" " METHOD[\"bla\",ID[\"EPSG\",1032]],\n" " PARAMETER[\"tx\",1,ID[\"EPSG\",8605]],\n" " PARAMETER[\"ty\",2,ID[\"EPSG\",8606]],\n" " PARAMETER[\"tz\",3,ID[\"EPSG\",8607]],\n" " PARAMETER[\"rotx\",-4,ID[\"EPSG\",8608]],\n" " PARAMETER[\"roty\",-5,ID[\"EPSG\",8609]],\n" " PARAMETER[\"rotz\",-6,ID[\"EPSG\",8610]],\n" " PARAMETER[\"scale\",1.000007,ID[\"EPSG\",8611]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->nameStr(), projcrs->nameStr()); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); ASSERT_TRUE(crs->transformation()->sourceCRS() != nullptr); EXPECT_EQ(crs->transformation()->sourceCRS()->nameStr(), projcrs->baseCRS()->nameStr()); auto params = crs->transformation()->getTOWGS84Parameters(); auto expected = std::vector<double>{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}; ASSERT_EQ(params.size(), expected.size()); for (int i = 0; i < 7; i++) { EXPECT_NEAR(params[i], expected[i], 1e-10); } } // --------------------------------------------------------------------------- TEST(wkt_parse, BOUNDCRS_with_interpolation_as_parameter) { auto wkt = "BOUNDCRS[\n" " SOURCECRS[\n" " VERTCRS[\"unknown\",\n" " VDATUM[\"unknown using [email protected]\"],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]],\n" " TARGETCRS[\n" " GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[\"unknown to WGS84 ellipsoidal height\",\n" " METHOD[\"GravityRelatedHeight to Geographic3D\"],\n" " PARAMETERFILE[\"Geoid (height correction) model " "file\",\"@foo.gtx\",\n" " ID[\"EPSG\",8666]],\n" " PARAMETER[\"EPSG code for Interpolation CRS\",7886]]]"; { auto obj = WKTParser().createFromWKT(wkt); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); EXPECT_TRUE(boundCRS->transformation()->interpolationCRS() == nullptr); EXPECT_EQ(boundCRS->transformation()->parameterValues().size(), 2U); } { auto dbContext = DatabaseContext::create(); // Need a database so that the interpolation CRS EPSG:7886 is resolved auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); EXPECT_TRUE(boundCRS->transformation()->interpolationCRS() != nullptr); EXPECT_EQ(boundCRS->transformation()->parameterValues().size(), 1U); // Check that on export, the interpolation CRS is exported as a // parameter auto exportedWKT = boundCRS->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); EXPECT_TRUE( exportedWKT.find( "PARAMETER[\"EPSG code for Interpolation CRS\",7886,") != std::string::npos) << exportedWKT; } } // --------------------------------------------------------------------------- TEST(wkt_parse, boundcrs_of_verticalcrs_to_geog3Dcrs) { auto wkt = "BOUNDCRS[\n" " SOURCECRS[\n" " VERTCRS[\"my_height\",\n" " VDATUM[\"my_height\"],\n" " CS[vertical,1],\n" " AXIS[\"up\",up,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]],\n" " TARGETCRS[\n" " GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]],\n" " ABRIDGEDTRANSFORMATION[\"my_height height to WGS84 ellipsoidal " "height\",\n" " METHOD[\"GravityRelatedHeight to Geographic3D\"],\n" " PARAMETERFILE[\"Geoid (height correction) model file\"," " \"./tmp/fake.gtx\",\n" " ID[\"EPSG\",8666]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->nameStr(), "my_height"); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4979->nameStr()); } // --------------------------------------------------------------------------- TEST(wkt_parse, geogcs_TOWGS84_3terms) { auto wkt = "GEOGCS[\"my GEOGCRS\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563],\n" " TOWGS84[1,2,3]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->nameStr(), "my GEOGCRS"); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); ASSERT_TRUE(crs->transformation()->sourceCRS() != nullptr); EXPECT_EQ(crs->transformation()->sourceCRS()->nameStr(), "my GEOGCRS"); auto params = crs->transformation()->getTOWGS84Parameters(); auto expected = std::vector<double>{1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0}; ASSERT_EQ(params.size(), expected.size()); for (int i = 0; i < 7; i++) { EXPECT_NEAR(params[i], expected[i], 1e-10); } } // --------------------------------------------------------------------------- TEST(wkt_parse, projcs_TOWGS84_7terms) { auto wkt = "PROJCS[\"my PROJCRS\",\n" " GEOGCS[\"my GEOGCRS\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " TOWGS84[1,2,3,4,5,6,7],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"Latitude\",NORTH],\n" " AXIS[\"Longitude\",EAST]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->nameStr(), "my PROJCRS"); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); ASSERT_TRUE(crs->transformation()->sourceCRS() != nullptr); EXPECT_EQ(crs->transformation()->sourceCRS()->nameStr(), "my GEOGCRS"); auto params = crs->transformation()->getTOWGS84Parameters(); auto expected = std::vector<double>{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0}; ASSERT_EQ(params.size(), expected.size()); for (int i = 0; i < 7; i++) { EXPECT_NEAR(params[i], expected[i], 1e-10); } } // --------------------------------------------------------------------------- TEST(wkt_parse, WKT1_VERT_DATUM_EXTENSION) { auto wkt = "VERT_CS[\"EGM2008 geoid height\",\n" " VERT_DATUM[\"EGM2008 geoid\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"egm08_25.gtx\"],\n" " AUTHORITY[\"EPSG\",\"1027\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Up\",UP],\n" " AUTHORITY[\"EPSG\",\"3855\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->nameStr(), "EGM2008 geoid height"); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4979->nameStr()); ASSERT_TRUE(crs->transformation()->sourceCRS() != nullptr); EXPECT_EQ(crs->transformation()->sourceCRS()->nameStr(), crs->baseCRS()->nameStr()); ASSERT_TRUE(crs->transformation()->targetCRS() != nullptr); EXPECT_EQ(crs->transformation()->targetCRS()->nameStr(), crs->hubCRS()->nameStr()); EXPECT_EQ(crs->transformation()->nameStr(), "EGM2008 geoid height to WGS 84 ellipsoidal height"); EXPECT_EQ(crs->transformation()->method()->nameStr(), "GravityRelatedHeight to Geographic3D"); ASSERT_EQ(crs->transformation()->parameterValues().size(), 1U); { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>( crs->transformation()->parameterValues()[0]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8666); EXPECT_EQ(paramName, "Geoid (height correction) model file"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::FILENAME); EXPECT_EQ(parameterValue->valueFile(), "egm08_25.gtx"); } } // --------------------------------------------------------------------------- TEST(wkt_parse, WKT1_VERT_DATUM_EXTENSION_units_ftUS) { auto wkt = "VERT_CS[\"NAVD88 height (ftUS)\"," " VERT_DATUM[\"North American Vertical Datum 1988\",2005," " EXTENSION[\"PROJ4_GRIDS\",\"foo.gtx\"]," " AUTHORITY[\"EPSG\",\"5103\"]]," " UNIT[\"US survey foot\",0.304800609601219," " AUTHORITY[\"EPSG\",\"9003\"]]," " AXIS[\"Gravity-related height\",UP]," " AUTHORITY[\"EPSG\",\"6360\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->transformation()->nameStr(), "NAVD88 height to WGS 84 ellipsoidal height"); // no (ftUS) auto sourceTransformationCRS = crs->transformation()->sourceCRS(); auto sourceTransformationVertCRS = nn_dynamic_pointer_cast<VerticalCRS>(sourceTransformationCRS); EXPECT_EQ( sourceTransformationVertCRS->coordinateSystem()->axisList()[0]->unit(), UnitOfMeasure::METRE); } // --------------------------------------------------------------------------- TEST(wkt_parse, WKT1_COMPD_CS_VERT_DATUM_EXTENSION) { auto wkt = "COMPD_CS[\"NAD83 + NAVD88 height\",\n" " GEOGCS[\"NAD83\",\n" " DATUM[\"North_American_Datum_1983\",\n" " SPHEROID[\"GRS 1980\",6378137,298.257222101,\n" " AUTHORITY[\"EPSG\",\"7019\"]],\n" " AUTHORITY[\"EPSG\",\"6269\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4269\"]],\n" " VERT_CS[\"NAVD88 height\",\n" " VERT_DATUM[\"North American Vertical Datum 1988\",2005,\n" " EXTENSION[\"PROJ4_GRIDS\",\"@foo.gtx\"],\n" " AUTHORITY[\"EPSG\",\"5103\"]],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Gravity-related height\",UP],\n" " AUTHORITY[\"EPSG\",\"5703\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto boundVertCRS = nn_dynamic_pointer_cast<BoundCRS>(crs->componentReferenceSystems()[1]); ASSERT_TRUE(boundVertCRS != nullptr); EXPECT_EQ(boundVertCRS->transformation()->nameStr(), "NAVD88 height to NAD83 ellipsoidal height"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, WKT1_DATUM_EXTENSION) { auto wkt = "PROJCS[\"unnamed\",\n" " GEOGCS[\"International 1909 (Hayford)\",\n" " DATUM[\"unknown\",\n" " SPHEROID[\"intl\",6378388,297],\n" " EXTENSION[\"PROJ4_GRIDS\",\"nzgd2kgrid0005.gsb\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"New_Zealand_Map_Grid\"],\n" " PARAMETER[\"latitude_of_origin\",-41],\n" " PARAMETER[\"central_meridian\",173],\n" " PARAMETER[\"false_easting\",2510000],\n" " PARAMETER[\"false_northing\",6023150],\n" " UNIT[\"Meter\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->nameStr(), "unnamed"); EXPECT_EQ(crs->hubCRS()->nameStr(), GeographicCRS::EPSG_4326->nameStr()); ASSERT_TRUE(crs->transformation()->sourceCRS() != nullptr); EXPECT_EQ(crs->transformation()->sourceCRS()->nameStr(), "International 1909 (Hayford)"); ASSERT_TRUE(crs->transformation()->targetCRS() != nullptr); EXPECT_EQ(crs->transformation()->targetCRS()->nameStr(), crs->hubCRS()->nameStr()); EXPECT_EQ(crs->transformation()->nameStr(), "International 1909 (Hayford) to WGS84"); EXPECT_EQ(crs->transformation()->method()->nameStr(), "NTv2"); ASSERT_EQ(crs->transformation()->parameterValues().size(), 1U); { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>( crs->transformation()->parameterValues()[0]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_TRUE(opParamvalue->parameter()->getEPSGCode() == 8656); EXPECT_EQ(paramName, "Latitude and longitude difference file"); EXPECT_EQ(parameterValue->type(), ParameterValue::Type::FILENAME); EXPECT_EQ(parameterValue->valueFile(), "nzgd2kgrid0005.gsb"); } } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedGeographicCRS_WKT2) { auto wkt = "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Atlantic pole\",\n" " METHOD[\"Pole rotation\"],\n" " PARAMETER[\"Latitude of rotated pole\",52,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Longitude of rotated pole\",-30,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Axis rotation\",-25,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WMO Atlantic Pole"); EXPECT_EQ(crs->baseCRS()->nameStr(), "WGS 84"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs->baseCRS()) != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "Atlantic pole"); EXPECT_TRUE(nn_dynamic_pointer_cast<EllipsoidalCS>( crs->coordinateSystem()) != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedGeographicCRS_WKT2_2019) { auto wkt = "GEOGCRS[\"WMO Atlantic Pole\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Atlantic pole\",\n" " METHOD[\"Pole rotation\"],\n" " PARAMETER[\"Latitude of rotated pole\",52,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Longitude of rotated pole\",-30,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Axis rotation\",-25,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"longitude\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WMO Atlantic Pole"); EXPECT_EQ(crs->baseCRS()->nameStr(), "WGS 84"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs->baseCRS()) != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "Atlantic pole"); EXPECT_TRUE(nn_dynamic_pointer_cast<EllipsoidalCS>( crs->coordinateSystem()) != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedGeodeticCRS) { auto wkt = "GEODCRS[\"Derived geodetic CRS\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Some conversion\",\n" " METHOD[\"Some method\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Y)\",geocentricY,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(Z)\",geocentricZ,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedGeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Derived geodetic CRS"); EXPECT_EQ(crs->baseCRS()->nameStr(), "WGS 84"); EXPECT_TRUE(nn_dynamic_pointer_cast<GeographicCRS>(crs->baseCRS()) != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "Some conversion"); EXPECT_TRUE(nn_dynamic_pointer_cast<CartesianCS>(crs->coordinateSystem()) != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedGeographicCRS_GDAL_PROJ4_EXSTENSION_hack) { // Note the lack of UNIT[] node auto wkt = "PROJCS[\"unnamed\"," " GEOGCS[\"unknown\"," " DATUM[\"unnamed\"," " SPHEROID[\"Spheroid\",6367470,594.313048347956]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"degree\",0.0174532925199433," " AUTHORITY[\"EPSG\",\"9122\"]]]," " PROJECTION[\"Rotated_pole\"]," " EXTENSION[\"PROJ4\",\"+proj=ob_tran +o_proj=longlat +lon_0=18 " "+o_lon_p=0 +o_lat_p=39.25 +a=6367470 +b=6367470 " "+to_meter=0.0174532925199 +wktext\"]]"; auto obj = WKTParser().setStrict(false).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto obj2 = PROJStringParser().createFromPROJString( "+proj=ob_tran +o_proj=longlat +lon_0=18 " "+o_lon_p=0 +o_lat_p=39.25 +a=6367470 +b=6367470 " "+to_meter=0.0174532925199 +wktext +type=crs"); auto crs2 = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); EXPECT_TRUE( crs->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); { auto op = CoordinateOperationFactory::create()->createOperation( crs->baseCRS(), NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=ob_tran +o_proj=longlat +lon_0=18 +o_lon_p=0 " "+o_lat_p=39.25 +R=6367470 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } { auto op = CoordinateOperationFactory::create()->createOperation( NN_NO_CHECK(crs), crs->baseCRS()); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +inv +proj=ob_tran +o_proj=longlat +lon_0=18 +o_lon_p=0 " "+o_lat_p=39.25 +R=6367470 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"); } } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedProjectedCRS) { auto wkt = "DERIVEDPROJCRS[\"derived projectedCRS\",\n" " BASEPROJCRS[\"WGS 84 / UTM zone 31N\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"UTM zone 31N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "derived projectedCRS"); EXPECT_EQ(crs->baseCRS()->nameStr(), "WGS 84 / UTM zone 31N"); EXPECT_TRUE(nn_dynamic_pointer_cast<ProjectedCRS>(crs->baseCRS()) != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "unnamed"); EXPECT_TRUE(nn_dynamic_pointer_cast<CartesianCS>(crs->coordinateSystem()) != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedProjectedCRS_ordinal) { auto wkt = "DERIVEDPROJCRS[\"derived projectedCRS\",\n" " BASEPROJCRS[\"BASEPROJCRS\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " CS[ordinal,2],\n" " AXIS[\"inline (I)\",northNorthWest,\n" " ORDER[1]],\n" " AXIS[\"crossline (J)\",westSouthWest,\n" " ORDER[2]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(nn_dynamic_pointer_cast<OrdinalCS>(crs->coordinateSystem()) != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, TemporalDatum) { auto wkt = "TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"my calendar\"],\n" " TIMEORIGIN[0000-01-01]]"; auto obj = WKTParser().createFromWKT(wkt); auto tdatum = nn_dynamic_pointer_cast<TemporalDatum>(obj); ASSERT_TRUE(tdatum != nullptr); EXPECT_EQ(tdatum->nameStr(), "Gregorian calendar"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "0000-01-01"); EXPECT_EQ(tdatum->calendar(), "my calendar"); } // --------------------------------------------------------------------------- TEST(wkt_parse, TemporalDatum_no_calendar) { auto wkt = "TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]]"; auto obj = WKTParser().createFromWKT(wkt); auto tdatum = nn_dynamic_pointer_cast<TemporalDatum>(obj); ASSERT_TRUE(tdatum != nullptr); EXPECT_EQ(tdatum->nameStr(), "Gregorian calendar"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "0000-01-01"); EXPECT_EQ(tdatum->calendar(), "proleptic Gregorian"); } // --------------------------------------------------------------------------- TEST(wkt_parse, dateTimeTemporalCRS_WKT2_2015) { auto wkt = "TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<TemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Temporal CRS"); auto tdatum = crs->datum(); EXPECT_EQ(tdatum->nameStr(), "Gregorian calendar"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "0000-01-01"); EXPECT_EQ(tdatum->calendar(), "proleptic Gregorian"); EXPECT_TRUE(nn_dynamic_pointer_cast<DateTimeTemporalCS>( crs->coordinateSystem()) != nullptr); ASSERT_EQ(crs->coordinateSystem()->axisList().size(), 1U); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().type(), UnitOfMeasure::Type::NONE); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().name(), ""); } // --------------------------------------------------------------------------- TEST(wkt_parse, dateTimeTemporalCRS_WKT2_2019) { auto wkt = "TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<TemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Temporal CRS"); auto tdatum = crs->datum(); EXPECT_EQ(tdatum->nameStr(), "Gregorian calendar"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "0000-01-01"); EXPECT_EQ(tdatum->calendar(), "proleptic Gregorian"); EXPECT_TRUE(nn_dynamic_pointer_cast<DateTimeTemporalCS>( crs->coordinateSystem()) != nullptr); ASSERT_EQ(crs->coordinateSystem()->axisList().size(), 1U); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().type(), UnitOfMeasure::Type::NONE); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().name(), ""); } // --------------------------------------------------------------------------- TEST(wkt_parse, temporalCountCRSWithConvFactor_WKT2_2019) { auto wkt = "TIMECRS[\"GPS milliseconds\",\n" " TDATUM[\"GPS time origin\",\n" " TIMEORIGIN[1980-01-01T00:00:00.0Z]],\n" " CS[TemporalCount,1],\n" " AXIS[\"(T)\",future,\n" " TIMEUNIT[\"milliseconds (ms)\",0.001]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<TemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "GPS milliseconds"); auto tdatum = crs->datum(); EXPECT_EQ(tdatum->nameStr(), "GPS time origin"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "1980-01-01T00:00:00.0Z"); EXPECT_EQ(tdatum->calendar(), "proleptic Gregorian"); EXPECT_TRUE(nn_dynamic_pointer_cast<TemporalCountCS>( crs->coordinateSystem()) != nullptr); ASSERT_EQ(crs->coordinateSystem()->axisList().size(), 1U); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().name(), "milliseconds (ms)"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().conversionToSI(), 0.001); } // --------------------------------------------------------------------------- TEST(wkt_parse, temporalCountCRSWithoutConvFactor_WKT2_2019) { auto wkt = "TIMECRS[\"Calendar hours from 1979-12-29\",\n" " TDATUM[\"29 December 1979\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[1979-12-29T00Z]],\n" " CS[TemporalCount,1],\n" " AXIS[\"time\",future,\n" " TIMEUNIT[\"hour\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<TemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Calendar hours from 1979-12-29"); auto tdatum = crs->datum(); EXPECT_EQ(tdatum->nameStr(), "29 December 1979"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "1979-12-29T00Z"); EXPECT_TRUE(nn_dynamic_pointer_cast<TemporalCountCS>( crs->coordinateSystem()) != nullptr); ASSERT_EQ(crs->coordinateSystem()->axisList().size(), 1U); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().name(), "hour"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().conversionToSI(), 0.0); } // --------------------------------------------------------------------------- TEST(wkt_parse, temporalMeasureCRS_WKT2_2015) { auto wkt = "TIMECRS[\"GPS Time\",\n" " TDATUM[\"Time origin\",\n" " TIMEORIGIN[1980-01-01T00:00:00.0Z]],\n" " CS[temporal,1],\n" " AXIS[\"time\",future],\n" " TIMEUNIT[\"day\",86400.0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<TemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "GPS Time"); auto tdatum = crs->datum(); EXPECT_EQ(tdatum->nameStr(), "Time origin"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "1980-01-01T00:00:00.0Z"); EXPECT_TRUE(nn_dynamic_pointer_cast<TemporalMeasureCS>( crs->coordinateSystem()) != nullptr); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); auto axis = cs->axisList()[0]; EXPECT_EQ(axis->nameStr(), "Time"); EXPECT_EQ(axis->unit().name(), "day"); EXPECT_EQ(axis->unit().conversionToSI(), 86400.0); } // --------------------------------------------------------------------------- TEST(wkt_parse, temporalMeasureCRSWithoutConvFactor_WKT2_2019) { auto wkt = "TIMECRS[\"Decimal Years CE\",\n" " TIMEDATUM[\"Common Era\",\n" " TIMEORIGIN[0000]],\n" " CS[TemporalMeasure,1],\n" " AXIS[\"decimal years (a)\",future,\n" " TIMEUNIT[\"year\"]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<TemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Decimal Years CE"); auto tdatum = crs->datum(); EXPECT_EQ(tdatum->nameStr(), "Common Era"); EXPECT_EQ(tdatum->temporalOrigin().toString(), "0000"); EXPECT_TRUE(nn_dynamic_pointer_cast<TemporalMeasureCS>( crs->coordinateSystem()) != nullptr); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); auto axis = cs->axisList()[0]; EXPECT_EQ(axis->nameStr(), "Decimal years"); EXPECT_EQ(axis->unit().name(), "year"); EXPECT_EQ(axis->unit().conversionToSI(), 0.0); } // --------------------------------------------------------------------------- TEST(wkt_parse, EDATUM) { auto wkt = "EDATUM[\"Engineering datum\",\n" " ANCHOR[\"my anchor\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto edatum = nn_dynamic_pointer_cast<EngineeringDatum>(obj); ASSERT_TRUE(edatum != nullptr); EXPECT_EQ(edatum->nameStr(), "Engineering datum"); auto anchor = edatum->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "my anchor"); } // --------------------------------------------------------------------------- TEST(wkt_parse, ENGINEERINGDATUM) { auto wkt = "ENGINEERINGDATUM[\"Engineering datum\"]"; auto obj = WKTParser().createFromWKT(wkt); auto edatum = nn_dynamic_pointer_cast<EngineeringDatum>(obj); ASSERT_TRUE(edatum != nullptr); EXPECT_EQ(edatum->nameStr(), "Engineering datum"); auto anchor = edatum->anchorDefinition(); EXPECT_TRUE(!anchor.has_value()); } // --------------------------------------------------------------------------- TEST(wkt_parse, ENGCRS) { auto wkt = "ENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Engineering CRS"); EXPECT_EQ(crs->datum()->nameStr(), "Engineering datum"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); } // --------------------------------------------------------------------------- TEST(wkt_parse, ENGINEERINGCRS) { auto wkt = "ENGINEERINGCRS[\"Engineering CRS\",\n" " ENGINEERINGDATUM[\"Engineering datum\"],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Engineering CRS"); EXPECT_EQ(crs->datum()->nameStr(), "Engineering datum"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); } // --------------------------------------------------------------------------- TEST(wkt_parse, ENGCRS_unknown_unit) { auto wkt = "ENGCRS[\"Undefined Cartesian SRS with unknown unit\",\n" " EDATUM[\"Unknown engineering datum\"],\n" " CS[Cartesian,2],\n" " AXIS[\"X\",unspecified,\n" " ORDER[1],\n" " LENGTHUNIT[\"unknown\",0]],\n" " AXIS[\"Y\",unspecified,\n" " ORDER[2],\n" " LENGTHUNIT[\"unknown\",0]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Undefined Cartesian SRS with unknown unit"); EXPECT_EQ(crs->datum()->nameStr(), "Unknown engineering datum"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); auto axis0 = cs->axisList()[0]; EXPECT_EQ(axis0->nameStr(), "X"); EXPECT_EQ(axis0->direction(), AxisDirection::UNSPECIFIED); EXPECT_EQ(axis0->unit().name(), "unknown"); EXPECT_EQ(axis0->unit().conversionToSI(), 0.0); auto axis1 = cs->axisList()[1]; EXPECT_EQ(axis1->nameStr(), "Y"); EXPECT_EQ(axis1->direction(), AxisDirection::UNSPECIFIED); EXPECT_EQ(axis1->unit().name(), "unknown"); EXPECT_EQ(axis1->unit().conversionToSI(), 0.0); } // --------------------------------------------------------------------------- TEST(wkt_parse, LOCAL_CS_short) { auto wkt = "LOCAL_CS[\"Engineering CRS\"]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Engineering CRS"); EXPECT_EQ(crs->datum()->nameStr(), "Unknown engineering datum"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); auto expected_wkt = "LOCAL_CS[\"Engineering CRS\",\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), expected_wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, LOCAL_CS_long_one_axis) { auto wkt = "LOCAL_CS[\"Engineering CRS\",\n" " LOCAL_DATUM[\"Engineering datum\",12345],\n" " UNIT[\"meter\",1],\n" " AXIS[\"height\",up]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Engineering CRS"); EXPECT_EQ(crs->datum()->nameStr(), "Engineering datum"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 1U); } // --------------------------------------------------------------------------- TEST(wkt_parse, LOCAL_CS_long_two_axis) { auto wkt = "LOCAL_CS[\"Engineering CRS\",\n" " LOCAL_DATUM[\"Engineering datum\",12345],\n" " UNIT[\"meter\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Engineering CRS"); EXPECT_EQ(crs->datum()->nameStr(), "Engineering datum"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 2U); } // --------------------------------------------------------------------------- TEST(wkt_parse, LOCAL_CS_long_three_axis) { auto wkt = "LOCAL_CS[\"Engineering CRS\",\n" " LOCAL_DATUM[\"Engineering datum\",12345],\n" " UNIT[\"meter\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AXIS[\"Elevation\",UP]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "Engineering CRS"); EXPECT_EQ(crs->datum()->nameStr(), "Engineering datum"); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 3U); } // --------------------------------------------------------------------------- TEST(wkt_parse, PDATUM) { auto wkt = "PDATUM[\"Parametric datum\",\n" " ANCHOR[\"my anchor\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto datum = nn_dynamic_pointer_cast<ParametricDatum>(obj); ASSERT_TRUE(datum != nullptr); EXPECT_EQ(datum->nameStr(), "Parametric datum"); auto anchor = datum->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "my anchor"); } // --------------------------------------------------------------------------- TEST(wkt_parse, PARAMETRICDATUM) { auto wkt = "PARAMETRICDATUM[\"Parametric datum\",\n" " ANCHOR[\"my anchor\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto datum = nn_dynamic_pointer_cast<ParametricDatum>(obj); ASSERT_TRUE(datum != nullptr); EXPECT_EQ(datum->nameStr(), "Parametric datum"); auto anchor = datum->anchorDefinition(); EXPECT_TRUE(anchor.has_value()); EXPECT_EQ(*anchor, "my anchor"); } // --------------------------------------------------------------------------- TEST(wkt_parse, PARAMETRICCRS) { auto wkt = "PARAMETRICCRS[\"WMO standard atmosphere layer 0\"," " PDATUM[\"Mean Sea Level\",ANCHOR[\"1013.25 hPa at 15°C\"]]," " CS[parametric,1]," " AXIS[\"pressure (hPa)\",up]," " PARAMETRICUNIT[\"HectoPascal\",100.0]" " ]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ParametricCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WMO standard atmosphere layer 0"); EXPECT_EQ(crs->datum()->nameStr(), "Mean Sea Level"); auto cs = crs->coordinateSystem(); EXPECT_TRUE(nn_dynamic_pointer_cast<ParametricCS>(cs) != nullptr); ASSERT_EQ(cs->axisList().size(), 1U); auto axis = cs->axisList()[0]; EXPECT_EQ(axis->nameStr(), "Pressure"); EXPECT_EQ(axis->unit().name(), "HectoPascal"); EXPECT_EQ(axis->unit().type(), UnitOfMeasure::Type::PARAMETRIC); EXPECT_EQ(axis->unit().conversionToSI(), 100.0); } // --------------------------------------------------------------------------- TEST(wkt_parse, PARAMETRICCRS_PARAMETRICDATUM) { auto wkt = "PARAMETRICCRS[\"WMO standard atmosphere layer 0\"," " PARAMETRICDATUM[\"Mean Sea Level\"]," " CS[parametric,1]," " AXIS[\"pressure (hPa)\",up]," " PARAMETRICUNIT[\"HectoPascal\",100.0]" " ]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ParametricCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedVerticalCRS) { auto wkt = "VERTCRS[\"Derived vertCRS\",\n" " BASEVERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedVerticalCRS_EPSG_code_for_horizontal_CRS) { auto wkt = "VERTCRS[\"Derived vertCRS\",\n" " BASEVERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\",\n" " ID[\"EPSG\",5101]]],\n" " DERIVINGCONVERSION[\"Conv Vertical Offset and Slope\",\n" " METHOD[\"Vertical Offset and Slope\",\n" " ID[\"EPSG\",1046]],\n" " PARAMETER[\"Ordinate 1 of evaluation point\",40.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8617]],\n" " PARAMETER[\"EPSG code for Horizontal CRS\",4277,\n" " ID[\"EPSG\",1037]]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); // "EPSG code for Horizontal CRS" is removed and set as interpolation CRS EXPECT_EQ(crs->derivingConversion()->parameterValues().size(), 1U); EXPECT_TRUE(crs->derivingConversion()->interpolationCRS() != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedEngineeringCRS) { auto wkt = "ENGCRS[\"Derived EngineeringCRS\",\n" " BASEENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedEngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedParametricCRS) { auto wkt = "PARAMETRICCRS[\"Derived ParametricCRS\",\n" " BASEPARAMCRS[\"Parametric CRS\",\n" " PDATUM[\"Parametric datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedParametricCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, DerivedTemporalCRS) { auto wkt = "TIMECRS[\"Derived TemporalCRS\",\n" " BASETIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1,\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<DerivedTemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); } // --------------------------------------------------------------------------- TEST(wkt_parse, ensemble) { auto wkt = "ENSEMBLE[\"test\",\n" " MEMBER[\"World Geodetic System 1984\",\n" " ID[\"EPSG\",6326]],\n" " MEMBER[\"other datum\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",7030]],\n" " ENSEMBLEACCURACY[100]]"; auto obj = WKTParser().createFromWKT(wkt); auto ensemble = nn_dynamic_pointer_cast<DatumEnsemble>(obj); ASSERT_TRUE(ensemble != nullptr); ASSERT_EQ(ensemble->datums().size(), 2U); auto firstDatum = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(ensemble->datums()[0]); ASSERT_TRUE(firstDatum != nullptr); EXPECT_EQ(firstDatum->nameStr(), "World Geodetic System 1984"); ASSERT_EQ(firstDatum->identifiers().size(), 1U); EXPECT_EQ(firstDatum->identifiers()[0]->code(), "6326"); EXPECT_EQ(*(firstDatum->identifiers()[0]->codeSpace()), "EPSG"); EXPECT_EQ(firstDatum->ellipsoid()->nameStr(), "WGS 84"); EXPECT_EQ(ensemble->positionalAccuracy()->value(), "100"); } // --------------------------------------------------------------------------- TEST(wkt_parse, ensemble_vdatum) { auto wkt = "ENSEMBLE[\"unnamed\",\n" " MEMBER[\"vdatum1\"],\n" " MEMBER[\"vdatum2\"],\n" " ENSEMBLEACCURACY[100]]"; auto obj = WKTParser().createFromWKT(wkt); auto ensemble = nn_dynamic_pointer_cast<DatumEnsemble>(obj); ASSERT_TRUE(ensemble != nullptr); ASSERT_EQ(ensemble->datums().size(), 2U); auto firstDatum = nn_dynamic_pointer_cast<VerticalReferenceFrame>(ensemble->datums()[0]); ASSERT_TRUE(firstDatum != nullptr); EXPECT_EQ(firstDatum->nameStr(), "vdatum1"); EXPECT_EQ(ensemble->positionalAccuracy()->value(), "100"); } // --------------------------------------------------------------------------- TEST(wkt_parse, esri_geogcs_datum_spheroid_name_hardcoded_substitution) { auto wkt = "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"; // Test substitutions of CRS, datum and ellipsoid names from ESRI names // to EPSG names. auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84"); EXPECT_EQ(crs->datum()->nameStr(), "World Geodetic System 1984"); EXPECT_EQ(crs->ellipsoid()->nameStr(), "WGS 84"); } // --------------------------------------------------------------------------- TEST(wkt_parse, esri_geogcs_datum_spheroid_name_from_db_substitution) { auto wkt = "GEOGCS[\"GCS_WGS_1966\",DATUM[\"D_WGS_1966\"," "SPHEROID[\"WGS_1966\",6378145.0,298.25]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"; // Test substitutions of CRS, datum and ellipsoid names from ESRI names // to EPSG names. auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 66"); EXPECT_EQ(crs->datum()->nameStr(), "World Geodetic System 1966"); EXPECT_EQ(crs->ellipsoid()->nameStr(), "WGS_1966"); } // --------------------------------------------------------------------------- TEST(wkt_parse, esri_datum_name_with_prime_meridian) { auto wkt = "GEOGCS[\"GCS_NTF_Paris\",DATUM[\"D_NTF\"," "SPHEROID[\"Clarke_1880_IGN\",6378249.2,293.4660212936265]]," "PRIMEM[\"Paris\",2.337229166666667]," "UNIT[\"Grad\",0.01570796326794897]]"; // D_NTF normally translates to "Nouvelle Triangulation Francaise", // but as we have a non-Greenwich prime meridian, we also test if // "Nouvelle Triangulation Francaise (Paris)" is not a registered datum name auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NTF (Paris)"); EXPECT_EQ(crs->datum()->nameStr(), "Nouvelle Triangulation Francaise (Paris)"); EXPECT_EQ(crs->ellipsoid()->nameStr(), "Clarke 1880 (IGN)"); } // --------------------------------------------------------------------------- static const struct { const char *esriProjectionName; std::vector<std::pair<const char *, double>> esriParams; const char *wkt2ProjectionName; std::vector<std::pair<const char *, double>> wkt2Params; } esriProjDefs[] = { {"Plate_Carree", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Equidistant Cylindrical", { {"Latitude of 1st standard parallel", 0}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Equidistant_Cylindrical", { {"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, }, "Equidistant Cylindrical", { {"Latitude of 1st standard parallel", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Miller_Cylindrical", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Miller Cylindrical", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Mercator", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}}, "Mercator (variant B)", { {"Latitude of 1st standard parallel", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Gauss_Kruger", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}}, "Transverse Mercator", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Transverse_Mercator", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}}, "Transverse Mercator", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Transverse_Mercator_Complex", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}}, "Transverse Mercator", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Albers", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, {"Standard_Parallel_2", 5}, {"Latitude_Of_Origin", 6}}, "Albers Equal Area", { {"Latitude of false origin", 6}, {"Longitude of false origin", 3}, {"Latitude of 1st standard parallel", 4}, {"Latitude of 2nd standard parallel", 5}, {"Easting at false origin", 1}, {"Northing at false origin", 2}, }}, {"Sinusoidal", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Sinusoidal", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Mollweide", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Mollweide", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Eckert_I", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Eckert I", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, // skipping Eckert_II to Eckert_VI {"Gall_Stereographic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Gall Stereographic", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Patterson", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Patterson", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Natural_Earth", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Natural Earth", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Natural_Earth_II", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Natural Earth II", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Compact_Miller", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Compact Miller", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Times", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Times", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Flat_Polar_Quartic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Flat Polar Quartic", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Behrmann", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Lambert Cylindrical Equal Area", { {"Latitude of 1st standard parallel", 30}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Winkel_I", { {"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, }, "Winkel I", { {"Longitude of natural origin", 3}, {"Latitude of 1st standard parallel", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Winkel_II", { {"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, }, "Winkel II", { {"Longitude of natural origin", 3}, {"Latitude of 1st standard parallel", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Lambert_Conformal_Conic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, {"Scale_Factor", 5}, {"Latitude_Of_Origin", 4}}, "Lambert Conic Conformal (1SP)", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 5}, {"False easting", 1}, {"False northing", 2}, }}, {"Lambert_Conformal_Conic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, {"Standard_Parallel_2", 5}, {"Latitude_Of_Origin", 6}}, "Lambert Conic Conformal (2SP)", { {"Latitude of false origin", 6}, {"Longitude of false origin", 3}, {"Latitude of 1st standard parallel", 4}, {"Latitude of 2nd standard parallel", 5}, {"Easting at false origin", 1}, {"Northing at false origin", 2}, }}, // Unusual variant of above with Scale_Factor=1 {"Lambert_Conformal_Conic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, {"Standard_Parallel_2", 5}, {"Scale_Factor", 1.0}, {"Latitude_Of_Origin", 6}}, "Lambert Conic Conformal (2SP)", { {"Latitude of false origin", 6}, {"Longitude of false origin", 3}, {"Latitude of 1st standard parallel", 4}, {"Latitude of 2nd standard parallel", 5}, {"Easting at false origin", 1}, {"Northing at false origin", 2}, }}, {"Polyconic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Latitude_Of_Origin", 4}}, "American Polyconic", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Quartic_Authalic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Quartic Authalic", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Loximuthal", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Central_Parallel", 4}}, "Loximuthal", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Bonne", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}}, "Bonne", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Hotine_Oblique_Mercator_Two_Point_Natural_Origin", {{"False_Easting", 1}, {"False_Northing", 2}, {"Latitude_Of_1st_Point", 3}, {"Latitude_Of_2nd_Point", 4}, {"Scale_Factor", 5}, {"Longitude_Of_1st_Point", 6}, {"Longitude_Of_2nd_Point", 7}, {"Latitude_Of_Center", 8}}, "Hotine Oblique Mercator Two Point Natural Origin", { {"Latitude of projection centre", 8}, {"Latitude of 1st point", 3}, {"Longitude of 1st point", 6}, {"Latitude of 2nd point", 4}, {"Longitude of 2nd point", 7}, {"Scale factor on initial line", 5}, {"Easting at projection centre", 1}, {"Northing at projection centre", 2}, }}, {"Stereographic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}}, "Stereographic", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, // Non standard parameter names longitude_of_center/latitude_of_center // used in https://github.com/OSGeo/PROJ/issues/3210 {"Stereographic", {{"False_Easting", 1}, {"False_Northing", 2}, {"longitude_of_center", 3}, {"Scale_Factor", 4}, {"latitude_of_center", 5}}, "Stereographic", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Stereographic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 90}}, "Polar Stereographic (variant A)", { {"Latitude of natural origin", 90}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Stereographic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", -90}}, "Polar Stereographic (variant A)", { {"Latitude of natural origin", -90}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Equidistant_Conic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, {"Standard_Parallel_2", 5}, {"Latitude_Of_Origin", 6}}, "Equidistant Conic", { {"Latitude of false origin", 6}, {"Longitude of false origin", 3}, {"Latitude of 1st standard parallel", 4}, {"Latitude of 2nd standard parallel", 5}, {"Easting at false origin", 1}, {"Northing at false origin", 2}, }}, {"Cassini", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 1}, {"Latitude_Of_Origin", 4}}, "Cassini-Soldner", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Van_der_Grinten_I", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Van Der Grinten", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Robinson", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Robinson", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Two_Point_Equidistant", {{"False_Easting", 1}, {"False_Northing", 2}, {"Latitude_Of_1st_Point", 3}, {"Latitude_Of_2nd_Point", 4}, {"Longitude_Of_1st_Point", 5}, {"Longitude_Of_2nd_Point", 6}}, "Two Point Equidistant", { {"Latitude of 1st point", 3}, {"Longitude of 1st point", 5}, {"Latitude of 2nd point", 4}, {"Longitude of 2nd point", 6}, {"False easting", 1}, {"False northing", 2}, }}, {"Azimuthal_Equidistant", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Latitude_Of_Origin", 4}}, "Azimuthal Equidistant", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Lambert_Azimuthal_Equal_Area", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Latitude_Of_Origin", 4}}, "Lambert Azimuthal Equal Area", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Cylindrical_Equal_Area", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}}, "Lambert Cylindrical Equal Area", { {"Latitude of 1st standard parallel", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, // Untested: Hotine_Oblique_Mercator_Two_Point_Center {"Hotine_Oblique_Mercator_Azimuth_Natural_Origin", {{"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 3}, {"Azimuth", 4}, {"Longitude_Of_Center", 5}, {"Latitude_Of_Center", 6}}, "Hotine Oblique Mercator (variant A)", { {"Latitude of projection centre", 6}, {"Longitude of projection centre", 5}, {"Azimuth of initial line", 4}, {"Angle from Rectified to Skew Grid", 4}, {"Scale factor on initial line", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Hotine_Oblique_Mercator_Azimuth_Center", {{"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 3}, {"Azimuth", 4}, {"Longitude_Of_Center", 5}, {"Latitude_Of_Center", 6}}, "Hotine Oblique Mercator (variant B)", { {"Latitude of projection centre", 6}, {"Longitude of projection centre", 5}, {"Azimuth of initial line", 4}, {"Angle from Rectified to Skew Grid", 4}, {"Scale factor on initial line", 3}, {"Easting at projection centre", 1}, {"Northing at projection centre", 2}, }}, {"Double_Stereographic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}}, "Oblique Stereographic", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Krovak", {{"False_Easting", 1}, {"False_Northing", 2}, {"Pseudo_Standard_Parallel_1", 3}, {"Scale_Factor", 4}, {"Azimuth", 5}, {"Longitude_Of_Center", 6}, {"Latitude_Of_Center", 7}, {"X_Scale", 1}, {"Y_Scale", 1}, {"XY_Plane_Rotation", 0}}, "Krovak", { {"Latitude of projection centre", 7}, {"Longitude of origin", 6}, {"Co-latitude of cone axis", 5}, {"Latitude of pseudo standard parallel", 3}, {"Scale factor on pseudo standard parallel", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Krovak", {{"False_Easting", 1}, {"False_Northing", 2}, {"Pseudo_Standard_Parallel_1", 3}, {"Scale_Factor", 4}, {"Azimuth", 5}, {"Longitude_Of_Center", 6}, {"Latitude_Of_Center", 7}, {"X_Scale", -1}, {"Y_Scale", 1}, {"XY_Plane_Rotation", 90}}, "Krovak (North Orientated)", { {"Latitude of projection centre", 7}, {"Longitude of origin", 6}, {"Co-latitude of cone axis", 5}, {"Latitude of pseudo standard parallel", 3}, {"Scale factor on pseudo standard parallel", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"New_Zealand_Map_Grid", {{"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Origin", 3}, {"Latitude_Of_Origin", 4}}, "New Zealand Map Grid", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Orthographic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Center", 3}, {"Latitude_Of_Center", 4}}, "Orthographic (Spherical)", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Local", {{"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 1}, {"Azimuth", 0}, {"Longitude_Of_Center", 3}, {"Latitude_Of_Center", 4}}, "Orthographic", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, // Local with unsupported value for Azimuth {"Local", {{"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 1}, {"Azimuth", 123}, {"Longitude_Of_Center", 3}, {"Latitude_Of_Center", 4}}, "Local", { {"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 1}, {"Azimuth", 123}, {"Longitude_Of_Center", 3}, {"Latitude_Of_Center", 4}, }}, {"Winkel_Tripel", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}}, "Winkel Tripel", { {"Longitude of natural origin", 3}, {"Latitude of 1st standard parallel", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Aitoff", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Aitoff", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Craster_Parabolic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Craster Parabolic", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Gnomonic", {{"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Center", 3}, {"Latitude_Of_Center", 4}}, "Gnomonic", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Stereographic_North_Pole", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}}, "Polar Stereographic (variant B)", { {"Latitude of standard parallel", 4}, {"Longitude of origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Stereographic_South_Pole", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", -4}}, "Polar Stereographic (variant B)", { {"Latitude of standard parallel", -4}, {"Longitude of origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Rectified_Skew_Orthomorphic_Natural_Origin", { {"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 3}, {"Azimuth", 4}, {"Longitude_Of_Center", 5}, {"Latitude_Of_Center", 6}, {"XY_Plane_Rotation", 7}, }, "Hotine Oblique Mercator (variant A)", { {"Latitude of projection centre", 6}, {"Longitude of projection centre", 5}, {"Azimuth of initial line", 4}, {"Angle from Rectified to Skew Grid", 7}, {"Scale factor on initial line", 3}, {"False easting", 1}, {"False northing", 2}, }}, // Temptative mapping {"Rectified_Skew_Orthomorphic_Center", { {"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 3}, {"Azimuth", 4}, {"Longitude_Of_Center", 5}, {"Latitude_Of_Center", 6}, {"XY_Plane_Rotation", 7}, }, "Hotine Oblique Mercator (variant B)", { {"Latitude of projection centre", 6}, {"Longitude of projection centre", 5}, {"Azimuth of initial line", 4}, {"Angle from Rectified to Skew Grid", 7}, {"Scale factor on initial line", 3}, {"Easting at projection centre", 1}, {"Northing at projection centre", 2}, }}, {"Goode_Homolosine", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Option", 0.0}}, "Goode Homolosine", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Goode_Homolosine", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Option", 1.0}}, "Interrupted Goode Homolosine", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Goode_Homolosine", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Option", 2.0}}, "Interrupted Goode Homolosine Ocean", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Equidistant_Cylindrical_Ellipsoidal", { {"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, }, "Equidistant Cylindrical", { {"Latitude of 1st standard parallel", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Laborde_Oblique_Mercator", {{"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 3}, {"Azimuth", 4}, {"Longitude_Of_Center", 5}, {"Latitude_Of_Center", 6}}, "Laborde Oblique Mercator", { {"Latitude of projection centre", 6}, {"Longitude of projection centre", 5}, {"Azimuth of initial line", 4}, {"Scale factor on initial line", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Mercator_Variant_A", {{"False_Easting", 1}, {"False_Northing", 2}, {"Scale_Factor", 3}, {"Central_Meridian", 4}}, "Mercator (variant A)", { {"Longitude of natural origin", 4}, {"Scale factor at natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Mercator_Variant_C", {{"False_Easting", 1}, {"False_Northing", 2}, {"Standard_Parallel_1", 3}, {"Central_Meridian", 4}}, "Mercator (variant B)", { {"Latitude of 1st standard parallel", 3}, {"Longitude of natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Transverse_Cylindrical_Equal_Area", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}}, "Transverse Cylindrical Equal Area", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Gnomonic_Ellipsoidal", {{"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Center", 3}, {"Latitude_Of_Center", 4}}, "Gnomonic", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Wagner_IV", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Latitude_Of_Center", 0}}, "Wagner IV", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Wagner_V", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Wagner V", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Wagner_VII", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Wagner VII", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Geostationary_Satellite", { {"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Center", 3}, {"Height", 4}, {"Option", 0.0}, }, "Geostationary Satellite (Sweep Y)", { {"Longitude of natural origin", 3}, {"Satellite Height", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Mercator_Auxiliary_Sphere", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Standard_Parallel_1", 4}, {"Auxiliary_Sphere_Type", 0}}, "Popular Visualisation Pseudo Mercator", { {"Latitude of natural origin", 4}, {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Vertical_Near_Side_Perspective", {{"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Center", 3}, {"Latitude_Of_Center", 4}, {"Height", 5}}, "Vertical Perspective", { {"Latitude of topocentric origin", 4}, {"Longitude of topocentric origin", 3}, {"Viewpoint height", 5}, {"False easting", 1}, {"False northing", 2}, }}, {"Equal_Earth", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}}, "Equal Earth", { {"Longitude of natural origin", 3}, {"False easting", 1}, {"False northing", 2}, }}, {"Peirce_Quincuncial", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}, {"Option", 0}}, "Peirce Quincuncial (Square)", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, {"Peirce_Quincuncial", {{"False_Easting", 1}, {"False_Northing", 2}, {"Central_Meridian", 3}, {"Scale_Factor", 4}, {"Latitude_Of_Origin", 5}, {"Option", 1}}, "Peirce Quincuncial (Diamond)", { {"Latitude of natural origin", 5}, {"Longitude of natural origin", 3}, {"Scale factor at natural origin", 4}, {"False easting", 1}, {"False northing", 2}, }}, { "Unknown_Method", {{"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Origin", 3}, {"Latitude_Of_Origin", 4}}, "Unknown_Method", {{"False_Easting", 1}, {"False_Northing", 2}, {"Longitude_Of_Origin", 3}, {"Latitude_Of_Origin", 4}}, }, }; TEST(wkt_parse, esri_projcs) { for (const auto &projDef : esriProjDefs) { std::string wkt("PROJCS[\"unnamed\",GEOGCS[\"unnamed\"," "DATUM[\"unnamed\",SPHEROID[\"unnamed\"," "6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\""); wkt += projDef.esriProjectionName; wkt += "\"],"; for (const auto &param : projDef.esriParams) { wkt += "PARAMETER[\""; wkt += param.first; wkt += "\","; wkt += toString(param.second); wkt += "],"; } wkt += "UNIT[\"Meter\",1.0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto conv = crs->derivingConversion(); auto method = conv->method(); EXPECT_EQ(method->nameStr(), projDef.wkt2ProjectionName) << wkt; auto values = conv->parameterValues(); EXPECT_EQ(values.size(), projDef.wkt2Params.size()) << wkt; if (values.size() == projDef.wkt2Params.size()) { for (size_t i = 0; i < values.size(); i++) { const auto &opParamvalue = nn_dynamic_pointer_cast<OperationParameterValue>(values[i]); ASSERT_TRUE(opParamvalue); const auto &paramName = opParamvalue->parameter()->nameStr(); const auto &parameterValue = opParamvalue->parameterValue(); EXPECT_EQ(paramName, projDef.wkt2Params[i].first) << wkt; EXPECT_EQ(parameterValue->type(), ParameterValue::Type::MEASURE); auto measure = parameterValue->value(); EXPECT_EQ(measure.value(), projDef.wkt2Params[i].second) << wkt; } } } } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_case_insensitive_names) { auto wkt = "PROJCS[\"WGS_1984_UTM_Zone_31N\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0," "298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\"," "0.0174532925199433]],PROJECTION[\"transverse_mercator\"]," "PARAMETER[\"false_easting\",500000.0]," "PARAMETER[\"false_northing\",0.0]," "PARAMETER[\"central_meridian\",3.0]," "PARAMETER[\"scale_factor\",0.9996]," "PARAMETER[\"latitude_of_origin\",0.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); int zone = 0; bool north = false; EXPECT_TRUE(crs->derivingConversion()->isUTM(zone, north)); EXPECT_EQ(zone, 31); EXPECT_TRUE(north); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_non_expected_param_name) { // We try to be lax on parameter names. auto wkt = "PROJCS[\"WGS_1984_UTM_Zone_31N\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0," "298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\"," "0.0174532925199433]],PROJECTION[\"transverse_mercator\"]," "PARAMETER[\"false_easting\",500000.0]," "PARAMETER[\"false_northing\",0.0]," "PARAMETER[\"longitude_of_center\",3.0]," // should be Central_Meridian "PARAMETER[\"scale_factor\",0.9996]," "PARAMETER[\"latitude_of_origin\",0.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); int zone = 0; bool north = false; EXPECT_TRUE(crs->derivingConversion()->isUTM(zone, north)); EXPECT_EQ(zone, 31); EXPECT_TRUE(north); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_krovak_south_west) { auto wkt = "PROJCS[\"S-JTSK_Krovak\",GEOGCS[\"GCS_S_JTSK\"," "DATUM[\"D_S_JTSK\"," "SPHEROID[\"Bessel_1841\",6377397.155,299.1528128]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Krovak\"],PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Pseudo_Standard_Parallel_1\",78.5]," "PARAMETER[\"Scale_Factor\",0.9999]," "PARAMETER[\"Azimuth\",30.28813975277778]," "PARAMETER[\"Longitude_Of_Center\",24.83333333333333]," "PARAMETER[\"Latitude_Of_Center\",49.5]," "PARAMETER[\"X_Scale\",1.0]," "PARAMETER[\"Y_Scale\",1.0]," "PARAMETER[\"XY_Plane_Rotation\",0.0],UNIT[\"Meter\",1.0]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Krovak"); auto expected_wkt2 = "PROJCRS[\"S-JTSK / Krovak\",\n" " BASEGEODCRS[\"S-JTSK\",\n" " DATUM[\"System of the Unified Trigonometrical Cadastral " "Network\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6156]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Krovak\",\n" " ID[\"EPSG\",9819]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",24.8333333333333,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard " "parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"southing\",south,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"westing\",west,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), expected_wkt2); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_krovak_east_north_non_standard_likely_from_GDAL_wkt1) { auto wkt = "PROJCS[\"S_JTSK_Krovak_East_North\",GEOGCS[\"GCS_S-JTSK\"," "DATUM[\"D_S_JTSK\",SPHEROID[\"Bessel_1841\"," "6377397.155,299.1528128]],PRIMEM[\"Greenwich\",0]," "UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Krovak\"]," "PARAMETER[\"latitude_of_center\",49.5]," "PARAMETER[\"longitude_of_center\",24.83333333333333]," "PARAMETER[\"azimuth\",30.2881397527778]," "PARAMETER[\"pseudo_standard_parallel_1\",78.5]," "PARAMETER[\"scale_factor\",0.9999]," "PARAMETER[\"false_easting\",0]," "PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Krovak (North Orientated)"); auto expected_wkt2 = "PROJCRS[\"S_JTSK_Krovak_East_North\",\n" " BASEGEODCRS[\"GCS_S-JTSK\",\n" " DATUM[\"System of the Unified Trigonometrical Cadastral " "Network\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6156]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Krovak (North Orientated)\",\n" " ID[\"EPSG\",1041]],\n" " PARAMETER[\"Latitude of projection centre\",49.5,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8811]],\n" " PARAMETER[\"Longitude of origin\",24.8333333333333,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8833]],\n" " PARAMETER[\"Co-latitude of cone axis\",30.2881397527778,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",1036]],\n" " PARAMETER[\"Latitude of pseudo standard parallel\",78.5,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433],\n" " ID[\"EPSG\",8818]],\n" " PARAMETER[\"Scale factor on pseudo standard " "parallel\",0.9999,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8819]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; EXPECT_EQ(crs->exportToWKT(WKTFormatter::create().get()), expected_wkt2); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_normalize_unit) { auto wkt = "PROJCS[\"Accra_Ghana_Grid\",GEOGCS[\"GCS_Accra\"," "DATUM[\"D_Accra\",SPHEROID[\"War_Office\",6378300.0,296.0]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Transverse_Mercator\"]," "PARAMETER[\"False_Easting\",900000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",-1.0]," "PARAMETER[\"Scale_Factor\",0.99975]," "PARAMETER[\"Latitude_Of_Origin\",4.666666666666667]," "UNIT[\"Foot_Gold_Coast\",0.3047997101815088]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->unit().name(), "Gold Coast foot"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_ups_north) { // EPSG:32661 auto wkt = "PROJCS[\"UPS_North\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Stereographic\"]," "PARAMETER[\"False_Easting\",2000000.0]," "PARAMETER[\"False_Northing\",2000000.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Scale_Factor\",0.994]," "PARAMETER[\"Latitude_Of_Origin\",90.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / UPS North (N,E)"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->direction(), AxisDirection::SOUTH); // Yes, inconsistency between the name (coming from EPSG) and the fact // that with ESRI CRS, we always output E, N axis order EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->abbreviation(), "E"); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->direction(), AxisDirection::SOUTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->abbreviation(), "N"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_ups_south) { // EPSG:32671 auto wkt = "PROJCS[\"UPS_South\",GEOGCS[\"GCS_WGS_1984\"," "DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Stereographic\"]," "PARAMETER[\"False_Easting\",2000000.0]," "PARAMETER[\"False_Northing\",2000000.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Scale_Factor\",0.994]," "PARAMETER[\"Latitude_Of_Origin\",-90.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / UPS South (N,E)"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->direction(), AxisDirection::NORTH); // Yes, inconsistency between the name (coming from EPSG) and the fact // that with ESRI CRS, we always output E, N axis order EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->abbreviation(), "E"); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->direction(), AxisDirection::NORTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->abbreviation(), "N"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_wgs_1984_ups_north_E_N) { // EPSG:5041 auto wkt = "PROJCS[\"WGS_1984_UPS_North_(E-N)\"," "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Polar_Stereographic_Variant_A\"]," "PARAMETER[\"False_Easting\",2000000.0]," "PARAMETER[\"False_Northing\",2000000.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Scale_Factor\",0.994]," "PARAMETER[\"Latitude_Of_Origin\",90.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / UPS North (E,N)"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->direction(), AxisDirection::SOUTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->abbreviation(), "E"); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->direction(), AxisDirection::SOUTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->abbreviation(), "N"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_wgs_1984_ups_south_E_N) { // EPSG:5042 auto wkt = "PROJCS[\"WGS_1984_UPS_South_(E-N)\"," "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Polar_Stereographic_Variant_A\"]," "PARAMETER[\"False_Easting\",2000000.0]," "PARAMETER[\"False_Northing\",2000000.0]," "PARAMETER[\"Central_Meridian\",0.0]," "PARAMETER[\"Scale_Factor\",0.994]," "PARAMETER[\"Latitude_Of_Origin\",-90.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / UPS South (E,N)"); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->direction(), AxisDirection::NORTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[0]->abbreviation(), "E"); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->direction(), AxisDirection::NORTH); EXPECT_EQ(crs->coordinateSystem()->axisList()[1]->abbreviation(), "N"); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_gauss_kruger) { auto wkt = "PROJCS[\"ETRS_1989_UWPP_2000_PAS_8\",GEOGCS[\"GCS_ETRS_1989\"," "DATUM[\"D_ETRS_1989\"," "SPHEROID[\"GRS_1980\",6378137.0,298.257222101]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Gauss_Kruger\"]," "PARAMETER[\"False_Easting\",8500000.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",24.0]," "PARAMETER[\"Scale_Factor\",0.999923]," "PARAMETER[\"Latitude_Of_Origin\",0.0]," "UNIT[\"Meter\",1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); auto crs2 = AuthorityFactory::create(dbContext, "ESRI") ->createProjectedCRS("102177"); EXPECT_EQ( crs2->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_ESRI, dbContext) .get()), wkt); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_esri_goode_homolosine_without_option_0) { // Not sure if it is really valid to not have PARAMETER["Option",0.0] // but it seems reasonable to check that we understand that as // Goode Homolosine and not Interrupted Goode Homolosine (option 1) auto wkt = "PROJCS[\"unknown\",GEOGCS[\"GCS_unknown\",DATUM[\"D_WGS_1984\"," "SPHEROID[\"WGS_1984\",6378137.0,298.257223563]]," "PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Goode_Homolosine\"]," "PARAMETER[\"False_Easting\",0.0]," "PARAMETER[\"False_Northing\",0.0]," "PARAMETER[\"Central_Meridian\",0.0]," "UNIT[\"Meter\",1.0]]"; auto obj = WKTParser() .attachDatabaseContext(DatabaseContext::create()) .createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Goode Homolosine"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_oracle) { // WKT from mdsys.cs_srs Oracle table auto wkt = "PROJCS[\"RGF93 / Lambert-93\", GEOGCS [ \"RGF93\", " "DATUM [\"Reseau Geodesique Francais 1993 (EPSG ID 6171)\", " "SPHEROID [\"GRS 1980 (EPSG ID 7019)\", 6378137.0, " "298.257222101]], PRIMEM [ \"Greenwich\", 0.000000000 ], " "UNIT [\"Decimal Degree\", 0.0174532925199433]], " "PROJECTION [\"Lambert Conformal Conic\"], " "PARAMETER [\"Latitude_Of_Origin\", 46.5], " "PARAMETER [\"Central_Meridian\", 3.0], " "PARAMETER [\"Standard_Parallel_1\", 49.0], " "PARAMETER [\"Standard_Parallel_2\", 44.0], " "PARAMETER [\"False_Easting\", 700000.0], " "PARAMETER [\"False_Northing\", 6600000.0], " "UNIT [\"Meter\", 1.0]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->datum()->nameStr(), "Reseau Geodesique Francais 1993"); EXPECT_EQ(crs->baseCRS()->datum()->getEPSGCode(), 6171); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Lambert Conic Conformal (2SP)"); auto factoryAll = AuthorityFactory::create(dbContext, std::string()); auto res = crs->identify(factoryAll); ASSERT_GE(res.size(), 1U); EXPECT_EQ(res.front().first->getEPSGCode(), 2154); EXPECT_EQ(res.front().second, 90); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_lcc_1sp_without_1sp_suffix) { // WKT from Trimble auto wkt = "PROJCS[\"TWM-Madison Co LDP\"," "GEOGCS[\"WGS 1984\"," "DATUM[\"WGS 1984\"," "SPHEROID[\"World Geodetic System 1984\"," "6378137,298.257223563]]," "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"Degree\",0.01745329251994," "AUTHORITY[\"EPSG\",\"9102\"]]," "AXIS[\"Long\",EAST],AXIS[\"Lat\",NORTH]]," "PROJECTION[\"Lambert_Conformal_Conic\"]," "PARAMETER[\"False_Easting\",103000.0000035]," "PARAMETER[\"False_Northing\",79000.00007055]," "PARAMETER[\"Latitude_Of_Origin\",38.83333333333]," "PARAMETER[\"Central_Meridian\",-89.93333333333]," "PARAMETER[\"Scale_Factor\",1.000019129]," "UNIT[\"Foot_US\",0.3048006096012,AUTHORITY[\"EPSG\",\"9003\"]]," "AXIS[\"East\",EAST],AXIS[\"North\",NORTH]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Lambert Conic Conformal (1SP)"); } // --------------------------------------------------------------------------- TEST(wkt_parse, wkt1_pseudo_wkt1_gdal_pseudo_wkt1_esri) { // WKT from https://github.com/OSGeo/PROJ/issues/3186 auto wkt = "PROJCS[\"Equidistant_Cylindrical\"," "GEOGCS[\"WGS 84\",DATUM[\"wgs_1984\"," "SPHEROID[\"WGS 84\",6378137,298.257223563," "AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]]," "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," "UNIT[\"degree\",0.0174532925199433," "AUTHORITY[\"EPSG\",\"9102\"]]," "AUTHORITY[\"EPSG\",\"4326\"]]," "PROJECTION[\"Equidistant_Cylindrical\"]," "PARAMETER[\"false_easting\",0]," "PARAMETER[\"false_northing\",0]," "PARAMETER[\"central_meridian\",0]," "PARAMETER[\"standard_parallel_1\",37]," "UNIT[\"Meter\",1,AUTHORITY[\"EPSG\",\"9001\"]]," "AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH]]"; auto dbContext = DatabaseContext::create(); auto obj = WKTParser().attachDatabaseContext(dbContext).createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Equidistant Cylindrical"); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), 1028); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid) { EXPECT_THROW(WKTParser().createFromWKT(""), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("A"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("UNKNOWN[\"foo\"]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("INVALID["), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("INVALID[]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_SPHEROID) { EXPECT_NO_THROW(WKTParser().createFromWKT("SPHEROID[\"x\",1,0.5]")); EXPECT_THROW(WKTParser().createFromWKT("SPHEROID[\"x\"]"), ParsingException); // major axis not number EXPECT_THROW(WKTParser().createFromWKT("SPHEROID[\"x\",\"1\",0.5]"), ParsingException); // major axis not number EXPECT_THROW(WKTParser().createFromWKT("SPHEROID[\"x\",1,\"0.5\"]"), ParsingException); // reverse flatting not number } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DATUM) { EXPECT_NO_THROW( WKTParser().createFromWKT("DATUM[\"x\",SPHEROID[\"x\",1,0.5]]")); EXPECT_THROW(WKTParser().createFromWKT("DATUM[\"x\"]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("DATUM[\"x\",FOO[]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_ENSEMBLE) { EXPECT_THROW(WKTParser().createFromWKT("ENSEMBLE[]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("ENSEMBLE[\"x\"]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT( "ENSEMBLE[\"x\",MEMBER[\"vdatum1\"],MEMBER[\"vdatum2\"]]"), ParsingException); EXPECT_THROW( WKTParser().createFromWKT("ENSEMBLE[\"x\",MEMBER[],MEMBER[\"vdatum2\"]," "ENSEMBLEACCURACY[\"100\"]]"), ParsingException); EXPECT_THROW( WKTParser().createFromWKT("ENSEMBLE[\"x\",MEMBER[\"vdatum1\"],MEMBER[" "\"vdatum2\"],ENSEMBLEACCURACY[]]"), ParsingException); EXPECT_THROW( WKTParser().createFromWKT("ENSEMBLE[\"x\",ENSEMBLEACCURACY[\"100\"]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_GEOGCS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],PRIMEM[\"x\",0],UNIT[" "\"degree\",0.0174532925199433]]")); // missing PRIMEM EXPECT_THROW( WKTParser().createFromWKT("GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0." "5]],UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // missing UNIT EXPECT_THROW( WKTParser().createFromWKT( "GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],PRIMEM[\"x\",0]]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("GEOGCS[\"x\"]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("GEOGCS[\"x\",FOO[]]"), ParsingException); // not enough children for DATUM EXPECT_THROW( WKTParser().createFromWKT("GEOGCS[\"x\",DATUM[\"x\"],PRIMEM[\"x\",0]," "UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // not enough children for AUTHORITY EXPECT_THROW(WKTParser().createFromWKT("GEOGCS[\"x\",DATUM[\"x\",SPHEROID[" "\"x\",1,0.5]],PRIMEM[\"x\",0],UNIT[" "\"degree\",0.0174532925199433]," "AUTHORITY[\"x\"]]"), ParsingException); // not enough children for AUTHORITY, but ignored EXPECT_NO_THROW(WKTParser().setStrict(false).createFromWKT( "GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],PRIMEM[\"x\",0],UNIT[" "\"degree\",0.0174532925199433],AUTHORITY[\"x\"]]")); EXPECT_NO_THROW(WKTParser().createFromWKT( "GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],PRIMEM[\"x\",0],UNIT[" "\"degree\",0.0174532925199433]]")); // PRIMEM not numeric EXPECT_THROW( WKTParser().createFromWKT( "GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0." "5]],PRIMEM[\"x\",\"a\"],UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // not enough children for PRIMEM EXPECT_THROW(WKTParser().createFromWKT("GEOGCS[\"x\",DATUM[\"x\",SPHEROID[" "\"x\",1,0.5]],PRIMEM[\"x\"],UNIT[" "\"degree\",0.0174532925199433]]"), ParsingException); EXPECT_NO_THROW(WKTParser().createFromWKT( "GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],PRIMEM[\"x\",0],UNIT[" "\"degree\",0.0174532925199433],AXIS[\"latitude\"," "NORTH],AXIS[\"longitude\",EAST]]")); // one axis only EXPECT_THROW(WKTParser().createFromWKT( "GEOGCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0." "5]],PRIMEM[\"x\",0],UNIT[\"degree\",0.0174532925199433]," "AXIS[\"latitude\",NORTH]]"), ParsingException); // invalid axis EXPECT_THROW(WKTParser().createFromWKT("GEOGCS[\"x\",DATUM[\"x\",SPHEROID[" "\"x\",1,0.5]],PRIMEM[\"x\",0],UNIT[" "\"degree\",0.0174532925199433]," "AXIS[\"latitude\"," "NORTH],AXIS[\"longitude\"]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_UNIT) { std::string startWKT("GEODCRS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],CS[" "ellipsoidal,2],AXIS[\"latitude\",north],AXIS[" "\"longitude\",east],"); EXPECT_NO_THROW(WKTParser().createFromWKT( startWKT + "UNIT[\"degree\",0.0174532925199433]]")); // not enough children EXPECT_THROW(WKTParser().createFromWKT(startWKT + "UNIT[\"x\"]]]"), ParsingException); // invalid conversion factor EXPECT_THROW( WKTParser().createFromWKT(startWKT + "UNIT[\"x\",\"invalid\"]]]"), ParsingException); // invalid ID EXPECT_THROW( WKTParser().createFromWKT(startWKT + "UNIT[\"x\",1,ID[\"x\"]]]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_GEOCCS) { EXPECT_NO_THROW( WKTParser().createFromWKT("GEOCCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0." "5]],PRIMEM[\"x\",0],UNIT[\"metre\",1]]")); // missing PRIMEM EXPECT_THROW(WKTParser().createFromWKT("GEOCCS[\"x\",DATUM[\"x\",SPHEROID[" "\"x\",1,0.5]],UNIT[\"metre\",1]]"), ParsingException); // missing UNIT EXPECT_THROW( WKTParser().createFromWKT( "GEOCCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],PRIMEM[\"x\",0]]"), ParsingException); // ellipsoidal CS is invalid in a GEOCCS EXPECT_THROW(WKTParser().createFromWKT("GEOCCS[\"x\",DATUM[\"x\",SPHEROID[" "\"x\",1,0.5]],PRIMEM[\"x\",0],UNIT[" "\"degree\",0.0174532925199433]," "AXIS[\"latitude\"," "NORTH],AXIS[\"longitude\",EAST]]"), ParsingException); // ellipsoidal CS is invalid in a GEOCCS EXPECT_THROW(WKTParser().createFromWKT( "GEOCCS[\"WGS 84\",DATUM[\"World Geodetic System 1984\"," "ELLIPSOID[\"WGS 84\",6378274,298.257223564," "LENGTHUNIT[\"metre\",1]]]," "CS[ellipsoidal,2],AXIS[\"geodetic latitude (Lat)\",north," "ANGLEUNIT[\"degree\",0.0174532925199433]]," "AXIS[\"geodetic longitude (Lon)\",east," "ANGLEUNIT[\"degree\",0.0174532925199433]]]"), ParsingException); // 3 axis required EXPECT_THROW(WKTParser().createFromWKT( "GEOCCS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]],PRIMEM[" "\"x\",0],UNIT[\"metre\",1],AXIS[" "\"Geocentric X\",OTHER],AXIS[\"Geocentric Y\",OTHER]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_CS_of_GEODCRS) { std::string startWKT("GEODCRS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]]"); // missing CS EXPECT_THROW(WKTParser().createFromWKT(startWKT + "]"), ParsingException); // CS: not enough children EXPECT_THROW(WKTParser().createFromWKT(startWKT + ",CS[x]]"), ParsingException); // CS: invalid type EXPECT_THROW(WKTParser().createFromWKT(startWKT + ",CS[x,2]]"), ParsingException); // CS: invalid number of axis EXPECT_THROW(WKTParser().createFromWKT(startWKT + ",CS[ellipsoidal,0]]"), ParsingException); // CS: number of axis is not a number EXPECT_THROW( WKTParser().createFromWKT(startWKT + ",CS[ellipsoidal,\"x\"]]"), ParsingException); // CS: invalid CS type EXPECT_THROW(WKTParser().createFromWKT(startWKT + ",CS[invalid,2],AXIS[\"latitude\"," "north],AXIS[\"longitude\",east]]"), ParsingException); // CS: OK EXPECT_NO_THROW(WKTParser().createFromWKT( startWKT + ",CS[ellipsoidal,2],AXIS[\"latitude\",north],AXIS[" "\"longitude\",east],UNIT[\"degree\",0.0174532925199433]]")); // CS: Cartesian with 2 axis unexpected EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",CS[Cartesian,2],AXIS[\"latitude\"," "north],AXIS[\"longitude\",east]," "UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // CS: missing axis EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",CS[ellipsoidal,2],AXIS[\"latitude\",north]," "UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // not enough children in AXIS EXPECT_THROW( WKTParser().createFromWKT( startWKT + ",CS[ellipsoidal,2],AXIS[\"latitude\",north],AXIS[\"longitude\"]," "UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // not enough children in ORDER EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",CS[ellipsoidal,2],AXIS[\"latitude\",north,ORDER[]],AXIS[" "\"longitude\",east]," "UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // invalid value in ORDER EXPECT_THROW( WKTParser().createFromWKT( startWKT + ",CS[ellipsoidal,2],AXIS[\"latitude\",north,ORDER[\"x\"]],AXIS[" "\"longitude\",east],UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // unexpected ORDER value EXPECT_THROW( WKTParser().createFromWKT( startWKT + ",CS[ellipsoidal,2],AXIS[\"latitude\",north,ORDER[2]],AXIS[" "\"longitude\",east],UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // Invalid CS type EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up],\n" " UNIT[\"metre\",1]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_CS_of_GEOGRAPHICCRS) { // A GeographicCRS must have an ellipsoidal CS EXPECT_THROW(WKTParser().createFromWKT( "GEOGRAPHICCRS[\"x\",DATUM[\"x\",SPHEROID[\"x\",1,0.5]]," "CS[Cartesian,3],AXIS[\"(X)\",geocentricX],AXIS[\"(Y)\"," "geocentricY],AXIS[\"(Z)\",geocentricZ]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DYNAMIC) { std::string prefix("GEOGCRS[\"WGS 84 (G1762)\","); std::string suffix( "TRF[\"World Geodetic System 1984 (G1762)\"," "ELLIPSOID[\"WGS 84\",6378137,298.257223563]]," "CS[ellipsoidal,3]," " AXIS[\"(lat)\",north,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"(lon)\",east,ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"ellipsoidal height (h)\",up,LENGTHUNIT[\"metre\",1.0]]" "]"); EXPECT_NO_THROW(WKTParser().createFromWKT( prefix + "DYNAMIC[FRAMEEPOCH[2015]]," + suffix)); EXPECT_THROW(WKTParser().createFromWKT(prefix + "DYNAMIC[]," + suffix), ParsingException); EXPECT_THROW( WKTParser().createFromWKT(prefix + "DYNAMIC[FRAMEEPOCH[]]," + suffix), ParsingException); EXPECT_THROW(WKTParser().createFromWKT( prefix + "DYNAMIC[FRAMEEPOCH[\"invalid\"]]," + suffix), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_PROJCRS) { // missing BASEGEODCRS EXPECT_THROW( WKTParser().createFromWKT("PROJCRS[\"WGS 84 / UTM zone 31N\"]"), ParsingException); std::string startWKT("PROJCRS[\"WGS 84 / UTM zone 31N\",BASEGEOGCRS[\"WGS " "84\",DATUM[\"WGS_1984\",ELLIPSOID[\"WGS " "84\",6378137,298.257223563]],UNIT[\"degree\",0." "0174532925199433]]"); // missing CONVERSION EXPECT_THROW(WKTParser().createFromWKT(startWKT + "]"), ParsingException); // not enough children in CONVERSION EXPECT_THROW(WKTParser().createFromWKT(startWKT + ",CONVERSION[\"x\"]]"), ParsingException); // not enough children in METHOD EXPECT_THROW( WKTParser().createFromWKT(startWKT + ",CONVERSION[\"x\",METHOD[]]]"), ParsingException); // not enough children in PARAMETER EXPECT_THROW( WKTParser().createFromWKT( startWKT + ",CONVERSION[\"x\",METHOD[\"y\"],PARAMETER[\"z\"]]]"), ParsingException); // non numeric value for PARAMETER EXPECT_THROW( WKTParser().createFromWKT( startWKT + ",CONVERSION[\"x\",METHOD[\"y\"],PARAMETER[\"z\",\"foo\"]]]"), ParsingException); // missing CS EXPECT_THROW(WKTParser().createFromWKT(startWKT + ",CONVERSION[\"x\",METHOD[\"y\"]]]"), ParsingException); // CS is not Cartesian EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",CONVERSION[\"x\",METHOD[\"y\"]],CS[" "ellipsoidal,2],AXIS[\"latitude\",north],AXIS[" "\"longitude\",east]]"), ParsingException); // not enough children in MERIDIAN EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",CONVERSION[\"x\",METHOD[\"y\"]],CS[" "Cartesian,2],AXIS[\"easting (X)\",south," "MERIDIAN[90]],AXIS[" "\"northing (Y)\",south]]"), ParsingException); // non numeric angle value for MERIDIAN EXPECT_THROW( WKTParser().createFromWKT( startWKT + ",CONVERSION[\"x\",METHOD[\"y\"]],CS[" "Cartesian,2],AXIS[\"easting (X)\",south," "MERIDIAN[\"x\",UNIT[\"degree\",0.0174532925199433]]],AXIS[" "\"northing (Y)\",south]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_PROJCS) { std::string startWKT( "PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"x\",0],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AXIS[\"latitude\",NORTH],\n" " AXIS[\"longitude\",EAST],\n" " AUTHORITY[\"EPSG\",\"4326\"]]\n"); // missing PROJECTION EXPECT_THROW(WKTParser().createFromWKT(startWKT + "]"), ParsingException); // not enough children in PROJECTION EXPECT_THROW(WKTParser().createFromWKT(startWKT + ",PROJECTION[],UNIT[\"metre\",1]]"), ParsingException); // not enough children in PARAMETER EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",PROJECTION[\"x\"],PARAMETER[\"z\"],UNIT[\"metre\",1]]"), ParsingException); // not enough children in PARAMETER EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",PROJECTION[\"x\"],PARAMETER[\"z\"],UNIT[\"metre\",1]]"), ParsingException); EXPECT_NO_THROW(WKTParser().createFromWKT( startWKT + ",PROJECTION[\"x\"],PARAMETER[\"z\",1],UNIT[\"metre\",1]]")); // missing UNIT EXPECT_THROW(WKTParser().createFromWKT( startWKT + ",PROJECTION[\"x\"],PARAMETER[\"z\",1]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_VERTCRS) { // missing VDATUM EXPECT_THROW(WKTParser().createFromWKT( "VERTCRS[\"foo\",CS[vertical,1],AXIS[\"x\",up]]"), ParsingException); // missing CS EXPECT_THROW(WKTParser().createFromWKT("VERTCRS[\"foo\",VDATUM[\"bar\"]]"), ParsingException); // CS is not of type vertical EXPECT_THROW(WKTParser().createFromWKT("VERTCRS[\"foo\",VDATUM[\"bar\"],CS[" "ellipsoidal,2],AXIS[\"latitude\"," "north],AXIS[" "\"longitude\",east]]"), ParsingException); // verticalCS should have only 1 axis EXPECT_THROW( WKTParser().createFromWKT("VERTCRS[\"foo\",VDATUM[\"bar\"],CS[vertical," "2],AXIS[\"latitude\",north],AXIS[" "\"longitude\",east]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_VERT_CS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "VERT_CS[\"x\",VERT_DATUM[\"y\",2005],UNIT[\"metre\",1]]")); // Missing VERT_DATUM EXPECT_THROW(WKTParser().createFromWKT("VERT_CS[\"x\",UNIT[\"metre\",1]]"), ParsingException); // Missing UNIT EXPECT_THROW( WKTParser().createFromWKT("VERT_CS[\"x\",VERT_DATUM[\"y\",2005]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_COORDINATEOPERATION) { std::string src_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); src_wkt = GeographicCRS::EPSG_4326->exportToWKT(formatter.get()); } std::string dst_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); dst_wkt = GeographicCRS::EPSG_4807->exportToWKT(formatter.get()); } std::string interpolation_wkt; { auto formatter = WKTFormatter::create(); formatter->setOutputId(false); interpolation_wkt = GeographicCRS::EPSG_4979->exportToWKT(formatter.get()); } // Valid { auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[" + dst_wkt + "],\n" " METHOD[\"operationMethodName\"],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"]]"; EXPECT_NO_THROW(WKTParser().createFromWKT(wkt)); } // Missing SOURCECRS { auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " TARGETCRS[" + dst_wkt + "],\n" " METHOD[\"operationMethodName\"],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // Invalid content in SOURCECRS { auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[FOO],\n" " TARGETCRS[" + dst_wkt + "],\n" " METHOD[\"operationMethodName\"],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // Missing TARGETCRS { auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[" + src_wkt + "],\n" " METHOD[\"operationMethodName\"],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // Invalid content in TARGETCRS { auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[FOO],\n" " METHOD[\"operationMethodName\"],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // Missing METHOD { auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[" + dst_wkt + "]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // Invalid METHOD { auto wkt = "COORDINATEOPERATION[\"transformationName\",\n" " SOURCECRS[" + src_wkt + "],\n" " TARGETCRS[" + dst_wkt + "],\n" " METHOD[],\n" " PARAMETERFILE[\"paramName\",\"foo.bin\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_CONCATENATEDOPERATION) { // No STEP EXPECT_THROW(WKTParser().createFromWKT("CONCATENATEDOPERATION[\"name\"]"), ParsingException); auto transf_1 = Transformation::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "transf_1"), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4326), nn_static_pointer_cast<CRS>(GeographicCRS::EPSG_4807), nullptr, PropertyMap().set(IdentifiedObject::NAME_KEY, "operationMethodName"), std::vector<OperationParameterNNPtr>{OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "paramName"))}, std::vector<ParameterValueNNPtr>{ ParameterValue::createFilename("foo.bin")}, std::vector<PositionalAccuracyNNPtr>()); // One single STEP { auto wkt = "CONCATENATEDOPERATION[\"name\",\n" " SOURCECRS[" + transf_1->sourceCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " TARGETCRS[" + transf_1->targetCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " STEP[" + transf_1->exportToWKT(WKTFormatter::create().get()) + "],\n" " ID[\"codeSpace\",\"code\"],\n" " REMARK[\"my remarks\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // empty STEP { auto wkt = "CONCATENATEDOPERATION[\"name\",\n" " SOURCECRS[" + transf_1->sourceCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " TARGETCRS[" + transf_1->targetCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " STEP[],\n" " STEP[],\n" " ID[\"codeSpace\",\"code\"],\n" " REMARK[\"my remarks\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } // Invalid content in STEP { auto wkt = "CONCATENATEDOPERATION[\"name\",\n" " SOURCECRS[" + transf_1->sourceCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " TARGETCRS[" + transf_1->targetCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " STEP[" + transf_1->sourceCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " STEP[" + transf_1->sourceCRS()->exportToWKT(WKTFormatter::create().get()) + "],\n" " ID[\"codeSpace\",\"code\"],\n" " REMARK[\"my remarks\"]]"; EXPECT_THROW(WKTParser().createFromWKT(wkt), ParsingException); } } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_BOUNDCRS) { auto projcrs = ProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my PROJCRS"), GeographicCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "my GEOGCRS"), GeodeticReferenceFrame::EPSG_6326, EllipsoidalCS::createLatitudeLongitude(UnitOfMeasure::DEGREE)), Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); auto valid_wkt = "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" + "TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) + "],\n" " ABRIDGEDTRANSFORMATION[\"foo\",\n" " METHOD[\"bar\"],PARAMETER[\"foo\",1.0]]]"; EXPECT_NO_THROW(WKTParser().createFromWKT(valid_wkt)) << valid_wkt; // Missing SOURCECRS EXPECT_THROW( WKTParser().createFromWKT("BOUNDCRS[TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT( WKTFormatter::create().get()) + "],\n" " ABRIDGEDTRANSFORMATION[\"foo\",\n" " METHOD[\"bar\"]," "PARAMETER[\"foo\",1.0]]]"), ParsingException); // Invalid SOURCECRS EXPECT_THROW( WKTParser().createFromWKT("BOUNDCRS[SOURCECRS[foo], TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT( WKTFormatter::create().get()) + "],\n" " ABRIDGEDTRANSFORMATION[\"foo\",\n" " METHOD[\"bar\"]," "PARAMETER[\"foo\",1.0]]]"), ParsingException); // Missing TARGETCRS EXPECT_THROW(WKTParser().createFromWKT( "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" " ABRIDGEDTRANSFORMATION[\"foo\",\n" " METHOD[\"bar\"]," "PARAMETER[\"foo\",1.0]]]"), ParsingException); // Invalid TARGETCRS EXPECT_THROW(WKTParser().createFromWKT( "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],TARGETCRS[\"foo\"],\n" " ABRIDGEDTRANSFORMATION[\"foo\",\n" " METHOD[\"bar\"]," "PARAMETER[\"foo\",1.0]]]"), ParsingException); // Missing ABRIDGEDTRANSFORMATION EXPECT_THROW(WKTParser().createFromWKT( "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" + "TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT( WKTFormatter::create().get()) + "]]"), ParsingException); // Missing METHOD EXPECT_THROW(WKTParser().createFromWKT( "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" + "TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT( WKTFormatter::create().get()) + "]," "ABRIDGEDTRANSFORMATION[\"foo\"]," "PARAMETER[\"foo\",1.0]]"), ParsingException); // Invalid METHOD EXPECT_THROW(WKTParser().createFromWKT( "BOUNDCRS[SOURCECRS[" + projcrs->exportToWKT(WKTFormatter::create().get()) + "],\n" + "TARGETCRS[" + GeographicCRS::EPSG_4326->exportToWKT( WKTFormatter::create().get()) + "]," "ABRIDGEDTRANSFORMATION[\"foo\",METHOD[]," "PARAMETER[\"foo\",1.0]]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_TOWGS84) { EXPECT_THROW(WKTParser().createFromWKT( "GEOGCS[\"WGS 84\"," " DATUM[\"WGS_1984\"," " SPHEROID[\"WGS 84\",6378137,298.257223563]," " TOWGS84[0]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"degree\",0.0174532925199433]]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT( "GEOGCS[\"WGS 84\"," " DATUM[\"WGS_1984\"," " SPHEROID[\"WGS 84\",6378137,298.257223563]," " TOWGS84[0,0,0,0,0,0,\"foo\"]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"degree\",0.0174532925199433]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DerivedGeographicCRS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]]],\n" " DERIVINGCONVERSION[\"foo\",\n" " METHOD[\"bar\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north],\n" " AXIS[\"longitude\",east],\n" " UNIT[\"degree\",0.0174532925199433]]")); // Missing DERIVINGCONVERSION EXPECT_THROW( WKTParser().createFromWKT( "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"latitude\",north],\n" " AXIS[\"longitude\",east],\n" " UNIT[\"degree\",0.0174532925199433]]"), ParsingException); // Missing CS EXPECT_THROW( WKTParser().createFromWKT( "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]]],\n" " DERIVINGCONVERSION[\"foo\",\n" " METHOD[\"bar\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]]"), ParsingException); // CS should be ellipsoidal given root node is GEOGCRS EXPECT_THROW( WKTParser().createFromWKT( "GEOGCRS[\"WMO Atlantic Pole\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]]],\n" " DERIVINGCONVERSION[\"foo\",\n" " METHOD[\"bar\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[Cartesian,3],\n" " AXIS[\"(X)\",geocentricX],\n" " AXIS[\"(Y)\",geocentricY],\n" " AXIS[\"(Z)\",geocentricZ],\n" " UNIT[\"metre\",1]]"), ParsingException); // CS should have 3 axis EXPECT_THROW( WKTParser().createFromWKT( "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]]],\n" " DERIVINGCONVERSION[\"foo\",\n" " METHOD[\"bar\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(X)\",geocentricX],\n" " AXIS[\"(Y)\",geocentricY],\n" " UNIT[\"metre\",1]]"), ParsingException); // Invalid CS type EXPECT_THROW( WKTParser().createFromWKT( "GEODCRS[\"WMO Atlantic Pole\",\n" " BASEGEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]]],\n" " DERIVINGCONVERSION[\"foo\",\n" " METHOD[\"bar\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up],\n" " UNIT[\"metre\",1]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_TemporalCRS) { EXPECT_NO_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]")); // Missing TDATUM EXPECT_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]"), ParsingException); // Missing CS EXPECT_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]]]"), ParsingException); // CS should be temporal EXPECT_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[Cartesian,2],\n" " AXIS[\"(X)\",geocentricX],\n" " AXIS[\"(Y)\",geocentricY],\n" " UNIT[\"metre\",1]]"), ParsingException); // CS should have 1 axis EXPECT_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[temporal,2],\n" " AXIS[\"time (T)\",future],\n" " AXIS[\"time2 (T)\",future]]"), ParsingException); // CS should have 1 axis EXPECT_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[TemporalDateTime,2],\n" " AXIS[\"time (T)\",future],\n" " AXIS[\"time2 (T)\",future]]"), ParsingException); // CS should have 1 axis EXPECT_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[TemporalCount,2],\n" " AXIS[\"time (T)\",future],\n" " AXIS[\"time2 (T)\",future]]"), ParsingException); // CS should have 1 axis EXPECT_THROW( WKTParser().createFromWKT("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " TIMEORIGIN[0000-01-01]],\n" " CS[TemporalMeasure,2],\n" " AXIS[\"time (T)\",future],\n" " AXIS[\"time2 (T)\",future]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_EngineeingCRS) { EXPECT_NO_THROW( WKTParser().createFromWKT("ENGCRS[\"name\",\n" " EDATUM[\"name\"],\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]")); // Missing EDATUM EXPECT_THROW( WKTParser().createFromWKT("ENGCRS[\"name\",\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]"), ParsingException); // Missing CS EXPECT_THROW(WKTParser().createFromWKT("ENGCRS[\"name\",\n" " EDATUM[\"name\"]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_LOCAL_CS) { EXPECT_THROW( WKTParser().createFromWKT("LOCAL_CS[\"name\",\n" " LOCAL_DATUM[\"name\",1234],\n" " AXIS[\"Geodetic latitude\",NORTH],\n" " AXIS[\"Geodetic longitude\",EAST],\n" " AXIS[\"Ellipsoidal height\",UP]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_ParametricCRS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "PARAMETRICCRS[\"name\",\n" " PDATUM[\"name\"],\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]")); // Missing PDATUM EXPECT_THROW(WKTParser().createFromWKT( "PARAMETRICCRS[\"name\",\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]"), ParsingException); // Missing CS EXPECT_THROW(WKTParser().createFromWKT("PARAMETRICCRS[\"name\",\n" " PDATUM[\"name\"]]"), ParsingException); // Invalid number of axis for CS EXPECT_THROW(WKTParser().createFromWKT( "PARAMETRICCRS[\"name\",\n" " PDATUM[\"name\"],\n" " CS[parametric,2],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]"), ParsingException); // Invalid CS type EXPECT_THROW( WKTParser().createFromWKT("PARAMETRICCRS[\"name\",\n" " PDATUM[\"name\"],\n" " CS[temporal,1],\n" " AXIS[\"time (T)\",future]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DERIVEDPROJCRS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "DERIVEDPROJCRS[\"derived projectedCRS\",\n" " BASEPROJCRS[\"BASEPROJCRS\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1]]")); EXPECT_THROW(WKTParser().createFromWKT( "DERIVEDPROJCRS[\"derived projectedCRS\",\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1]]"), ParsingException); // Missing DERIVINGCONVERSION EXPECT_THROW( WKTParser().createFromWKT( "DERIVEDPROJCRS[\"derived projectedCRS\",\n" " BASEPROJCRS[\"BASEPROJCRS\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " UNIT[\"metre\",1]]"), ParsingException); // Missing CS EXPECT_THROW( WKTParser().createFromWKT( "DERIVEDPROJCRS[\"derived projectedCRS\",\n" " BASEPROJCRS[\"BASEPROJCRS\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DerivedVerticalCRS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "VERTCRS[\"Derived vertCRS\",\n" " BASEVERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up],\n" " UNIT[\"metre\",1]]")); // Missing DERIVINGCONVERSION EXPECT_THROW(WKTParser().createFromWKT( "VERTCRS[\"Derived vertCRS\",\n" " BASEVERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"]],\n" " CS[vertical,1],\n" " AXIS[\"gravity-related height (H)\",up],\n" " UNIT[\"metre\",1]]"), ParsingException); // Missing CS EXPECT_THROW(WKTParser().createFromWKT( "VERTCRS[\"Derived vertCRS\",\n" " BASEVERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]]"), ParsingException); // Wrong CS type EXPECT_THROW(WKTParser().createFromWKT( "VERTCRS[\"Derived vertCRS\",\n" " BASEVERTCRS[\"ODN height\",\n" " VDATUM[\"Ordnance Datum Newlyn\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[parametric,1],\n" " AXIS[\"gravity-related height (H)\",up],\n" " UNIT[\"metre\",1]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DerivedEngineeringCRS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "ENGCRS[\"Derived EngineeringCRS\",\n" " BASEENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " LENGTHUNIT[\"metre\",1]]")); // Missing DERIVINGCONVERSION EXPECT_THROW( WKTParser().createFromWKT("ENGCRS[\"Derived EngineeringCRS\",\n" " BASEENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east],\n" " AXIS[\"(N)\",north],\n" " LENGTHUNIT[\"metre\",1]]"), ParsingException); // Missing CS EXPECT_THROW(WKTParser().createFromWKT( "ENGCRS[\"Derived EngineeringCRS\",\n" " BASEENGCRS[\"Engineering CRS\",\n" " EDATUM[\"Engineering datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DerivedParametricCRS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "PARAMETRICCRS[\"Derived ParametricCRS\",\n" " BASEPARAMCRS[\"Parametric CRS\",\n" " PDATUM[\"Parametric datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]")); // Missing DERIVINGCONVERSION EXPECT_THROW(WKTParser().createFromWKT( "PARAMETRICCRS[\"Derived ParametricCRS\",\n" " BASEPARAMCRS[\"Parametric CRS\",\n" " PDATUM[\"Parametric datum\"]],\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]"), ParsingException); // Missing CS EXPECT_THROW(WKTParser().createFromWKT( "PARAMETRICCRS[\"Derived ParametricCRS\",\n" " BASEPARAMCRS[\"Parametric CRS\",\n" " PDATUM[\"Parametric datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]]"), ParsingException); // Wrong CS type EXPECT_THROW(WKTParser().createFromWKT( "PARAMETRICCRS[\"Derived ParametricCRS\",\n" " BASEPARAMCRS[\"Parametric CRS\",\n" " PDATUM[\"Parametric datum\"]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_DerivedTemporalCRS) { EXPECT_NO_THROW(WKTParser().createFromWKT( "TIMECRS[\"Derived TemporalCRS\",\n" " BASETIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]")); // Missing DERIVINGCONVERSION EXPECT_THROW(WKTParser().createFromWKT( "TIMECRS[\"Derived TemporalCRS\",\n" " BASETIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]"), ParsingException); // Missing CS EXPECT_THROW(WKTParser().createFromWKT( "TIMECRS[\"Derived TemporalCRS\",\n" " BASETIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]]]"), ParsingException); // Wrong CS type EXPECT_THROW(WKTParser().createFromWKT( "TIMECRS[\"Derived TemporalCRS\",\n" " BASETIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]],\n" " DERIVINGCONVERSION[\"unnamed\",\n" " METHOD[\"PROJ unimplemented\"],\n" " PARAMETER[\"foo\",1.0,UNIT[\"metre\",1]]],\n" " CS[parametric,1],\n" " AXIS[\"pressure (hPa)\",up,\n" " PARAMETRICUNIT[\"HectoPascal\",100]]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(wkt_parse, invalid_CoordinateMetadata) { EXPECT_THROW(WKTParser().createFromWKT("COORDINATEMETADATA[]"), ParsingException); EXPECT_THROW(WKTParser().createFromWKT("COORDINATEMETADATA[ELLIPSOID[\"GRS " "1980\",6378137,298.257222101]]"), ParsingException); // Empty epoch EXPECT_THROW( WKTParser().createFromWKT( "COORDINATEMETADATA[\n" " GEOGCRS[\"ITRF2014\",\n" " DYNAMIC[\n" " FRAMEEPOCH[2010]],\n" " DATUM[\"International Terrestrial Reference Frame " "2014\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " USAGE[\n" " SCOPE[\"Geodesy.\"],\n" " AREA[\"World.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",9000]],\n" " EPOCH[]]"), ParsingException); // Invalid epoch EXPECT_THROW( WKTParser().createFromWKT( "COORDINATEMETADATA[\n" " GEOGCRS[\"ITRF2014\",\n" " DYNAMIC[\n" " FRAMEEPOCH[2010]],\n" " DATUM[\"International Terrestrial Reference Frame " "2014\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " USAGE[\n" " SCOPE[\"Geodesy.\"],\n" " AREA[\"World.\"],\n" " BBOX[-90,-180,90,180]],\n" " ID[\"EPSG\",9000]],\n" " EPOCH[invalid]]"), ParsingException); } // --------------------------------------------------------------------------- TEST(io, projstringformatter) { { auto fmt = PROJStringFormatter::create(); fmt->addStep("my_proj"); EXPECT_EQ(fmt->toString(), "+proj=my_proj"); } { auto fmt = PROJStringFormatter::create(); fmt->addStep("my_proj"); fmt->setCurrentStepInverted(true); EXPECT_EQ(fmt->toString(), "+proj=pipeline +step +inv +proj=my_proj"); } { auto fmt = PROJStringFormatter::create(); fmt->addStep("my_proj1"); fmt->addStep("my_proj2"); EXPECT_EQ(fmt->toString(), "+proj=pipeline +step +proj=my_proj1 +step +proj=my_proj2"); } { auto fmt = PROJStringFormatter::create(); fmt->addStep("my_proj1"); fmt->setCurrentStepInverted(true); fmt->addStep("my_proj2"); EXPECT_EQ( fmt->toString(), "+proj=pipeline +step +inv +proj=my_proj1 +step +proj=my_proj2"); } { auto fmt = PROJStringFormatter::create(); fmt->startInversion(); fmt->addStep("my_proj1"); fmt->setCurrentStepInverted(true); fmt->addStep("my_proj2"); fmt->stopInversion(); EXPECT_EQ( fmt->toString(), "+proj=pipeline +step +inv +proj=my_proj2 +step +proj=my_proj1"); } { auto fmt = PROJStringFormatter::create(); fmt->startInversion(); fmt->addStep("my_proj1"); fmt->setCurrentStepInverted(true); fmt->startInversion(); fmt->addStep("my_proj2"); fmt->stopInversion(); fmt->stopInversion(); EXPECT_EQ(fmt->toString(), "+proj=pipeline +step +proj=my_proj2 +step +proj=my_proj1"); } } // --------------------------------------------------------------------------- TEST(io, projstringformatter_helmert_3_param_noop) { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 0); fmt->addParam("y", 0); fmt->addParam("z", 0); EXPECT_EQ(fmt->toString(), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_helmert_7_param_noop) { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 0); fmt->addParam("y", 0); fmt->addParam("z", 0); fmt->addParam("rx", 0); fmt->addParam("ry", 0); fmt->addParam("rz", 0); fmt->addParam("s", 0); fmt->addParam("convention", "position_vector"); EXPECT_EQ(fmt->toString(), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_merge_consecutive_helmert_3_param) { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addStep("helmert"); fmt->addParam("x", -1); fmt->addParam("y", -2); fmt->addParam("z", -3); EXPECT_EQ(fmt->toString(), "+proj=helmert +x=9 +y=18 +z=27"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_merge_consecutive_helmert_3_param_noop) { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addStep("helmert"); fmt->addParam("x", -10); fmt->addParam("y", -20); fmt->addParam("z", -30); EXPECT_EQ(fmt->toString(), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_merge_inverted_helmert_with_opposite_conventions) { { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", 1); fmt->addParam("ry", 2); fmt->addParam("rz", 3); fmt->addParam("s", 4); fmt->addParam("convention", "position_vector"); fmt->addStep("helmert"); fmt->setCurrentStepInverted(true); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", -1); fmt->addParam("ry", -2); fmt->addParam("rz", -3); fmt->addParam("s", 4); fmt->addParam("convention", "coordinate_frame"); EXPECT_EQ(fmt->toString(), "+proj=noop"); } { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->setCurrentStepInverted(true); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", 1); fmt->addParam("ry", 2); fmt->addParam("rz", 3); fmt->addParam("s", 4); fmt->addParam("convention", "coordinate_frame"); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", -1); fmt->addParam("ry", -2); fmt->addParam("rz", -3); fmt->addParam("s", 4); fmt->addParam("convention", "position_vector"); EXPECT_EQ(fmt->toString(), "+proj=noop"); } // Cannot be optimized { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", 1); fmt->addParam("ry", 2); fmt->addParam("rz", 3); fmt->addParam("s", 4); fmt->addParam("convention", "position_vector"); fmt->addStep("helmert"); // fmt->setCurrentStepInverted(true); <== CAUSE fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", -1); fmt->addParam("ry", -2); fmt->addParam("rz", -3); fmt->addParam("s", 4); fmt->addParam("convention", "coordinate_frame"); EXPECT_TRUE(fmt->toString() != "+proj=noop"); } // Cannot be optimized { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", 1); fmt->addParam("ry", 2); fmt->addParam("rz", 3); fmt->addParam("s", 4); fmt->addParam("convention", "position_vector"); fmt->addStep("helmert"); fmt->setCurrentStepInverted(true); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", -1); fmt->addParam("ry", -2); fmt->addParam("rz", -3); fmt->addParam("s", 4); fmt->addParam("convention", "position_vector"); // <== CAUSE EXPECT_TRUE(fmt->toString() != "+proj=noop"); } // Cannot be optimized { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", 1); fmt->addParam("ry", 2); fmt->addParam("rz", 3); fmt->addParam("s", 4); fmt->addParam("convention", "position_vector"); fmt->addStep("helmert"); fmt->setCurrentStepInverted(true); fmt->addParam("x", -10); // <== CAUSE fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", -1); fmt->addParam("ry", -2); fmt->addParam("rz", -3); fmt->addParam("s", 4); fmt->addParam("convention", "coordinate_frame"); EXPECT_TRUE(fmt->toString() != "+proj=noop"); } // Cannot be optimized { auto fmt = PROJStringFormatter::create(); fmt->addStep("helmert"); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", 1); fmt->addParam("ry", 3); fmt->addParam("rz", 2); fmt->addParam("s", 4); fmt->addParam("convention", "position_vector"); fmt->addStep("helmert"); fmt->setCurrentStepInverted(true); fmt->addParam("x", 10); fmt->addParam("y", 20); fmt->addParam("z", 30); fmt->addParam("rx", 1); // <== CAUSE fmt->addParam("ry", -2); fmt->addParam("rz", -3); fmt->addParam("s", 4); fmt->addParam("convention", "coordinate_frame"); EXPECT_TRUE(fmt->toString() != "+proj=noop"); } } // --------------------------------------------------------------------------- TEST(io, projstringformatter_cart_grs80_wgs84) { auto fmt = PROJStringFormatter::create(); fmt->addStep("cart"); fmt->addParam("ellps", "WGS84"); fmt->addStep("cart"); fmt->setCurrentStepInverted(true); fmt->addParam("ellps", "GRS80"); EXPECT_EQ(fmt->toString(), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_axisswap_unitconvert_axisswap) { auto fmt = PROJStringFormatter::create(); fmt->addStep("axisswap"); fmt->addParam("order", "2,1"); fmt->addStep("unitconvert"); fmt->addParam("xy_in", "rad"); fmt->addParam("xy_out", "deg"); fmt->addStep("axisswap"); fmt->addParam("order", "2,1"); EXPECT_EQ(fmt->toString(), "+proj=unitconvert +xy_in=rad +xy_out=deg"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_axisswap_one_minus_two_inv) { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline +step +inv +proj=axisswap +order=1,-2"); EXPECT_EQ(fmt->toString(), "+proj=axisswap +order=1,-2"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_axisswap_two_one_followed_two_minus_one) { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString("+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=axisswap +order=2,-1"); EXPECT_EQ(fmt->toString(), "+proj=axisswap +order=1,-2"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_axisswap_minus_two_one_followed_two_one) { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString("+proj=pipeline " "+step +proj=axisswap +order=-2,1 " "+step +proj=axisswap +order=2,1"); EXPECT_EQ(fmt->toString(), "+proj=axisswap +order=1,-2"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_axisswap_two_minus_one_followed_minus_two_one) { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString("+proj=pipeline " "+step +proj=axisswap +order=2,-1 " "+step +proj=axisswap +order=-2,1"); EXPECT_EQ(fmt->toString(), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_axisswap_two_minus_one_followed_one_minus_two) { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString("+proj=pipeline " "+step +proj=axisswap +order=2,-1 " "+step +proj=axisswap +order=1,-2"); EXPECT_EQ(fmt->toString(), "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(io, projstringformatter_unitconvert) { // +step +proj=unitconvert +xy_in=X1 +xy_out=X2 // +step +proj=unitconvert +xy_in=X2 +z_in=Z1 +xy_out=X1 +z_out=Z2 // ==> // +step +proj=unitconvert +z_in=Z1 +z_out=Z2 { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=ft"); EXPECT_EQ(fmt->toString(), "+proj=unitconvert +z_in=m +z_out=ft"); } // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2 // +step +proj=unitconvert +z_in=Z2 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 // +z_out=Z3 { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=ft " "+step +proj=unitconvert +z_in=ft +z_out=us-ft"); EXPECT_EQ( fmt->toString(), "+proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=us-ft"); } // +step +proj=unitconvert +z_in=Z1 +z_out=Z2 // +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X2 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 // +z_out=Z3 { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString("+proj=pipeline " "+step +proj=unitconvert +z_in=ft +z_out=m " "+step +proj=unitconvert +xy_in=deg +z_in=m " "+xy_out=rad +z_out=us-ft "); EXPECT_EQ( fmt->toString(), "+proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=us-ft"); } // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2 // +step +proj=unitconvert +xy_in=X2 +xy_out=X3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3 // +z_out=Z2 { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=ft " "+step +proj=unitconvert +xy_in=rad +xy_out=grad"); EXPECT_EQ( fmt->toString(), "+proj=unitconvert +xy_in=deg +z_in=m +xy_out=grad +z_out=ft"); } // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2 // +step +proj=unitconvert +xy_in=X2 +z_in=Z3 +xy_out=X3 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3 +z_out=Z2 { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad " "+z_out=us-ft " "+step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=grad +z_out=m"); EXPECT_EQ( fmt->toString(), "+proj=unitconvert +xy_in=deg +z_in=ft +xy_out=grad +z_out=us-ft"); } // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z1 // +step +proj=unitconvert +xy_in=X2 +z_in=Z2 +xy_out=X3 +z_out=Z3 // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X3 +z_out=Z3 { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad " "+z_out=m " "+step +proj=unitconvert +xy_in=rad +z_in=ft +xy_out=grad " "+z_out=us-ft"); EXPECT_EQ( fmt->toString(), "+proj=unitconvert +xy_in=deg +z_in=ft +xy_out=grad +z_out=us-ft"); } } // --------------------------------------------------------------------------- TEST(io, projstringformatter_unmodified) { const char *const strs[] = {"+proj=pipeline " "+step +proj=axisswap +order=2,-1 " "+step +proj=axisswap +order=2,1", "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=axisswap +order=-2,1", "+proj=pipeline " "+step +inv +proj=axisswap +order=-2,1 " "+step +proj=axisswap +order=2,1"}; for (const char *str : strs) { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString(str); EXPECT_EQ(fmt->toString(), str); } } // --------------------------------------------------------------------------- TEST(io, projstringformatter_optim_hgridshift_vgridshift_hgridshift_inv) { // Nominal case { auto fmt = PROJStringFormatter::create(); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo"); fmt->addStep("vgridshift"); fmt->addParam("grids", "bar"); fmt->startInversion(); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo"); fmt->stopInversion(); EXPECT_EQ(fmt->toString(), "+proj=pipeline " "+step +proj=push +v_1 +v_2 " "+step +proj=hgridshift +grids=foo +omit_inv " "+step +proj=vgridshift +grids=bar " "+step +inv +proj=hgridshift +grids=foo +omit_fwd " "+step +proj=pop +v_1 +v_2"); } // Test omit_fwd->omit_inv when inversing the pipeline { auto fmt = PROJStringFormatter::create(); fmt->startInversion(); fmt->ingestPROJString("+proj=hgridshift +grids=foo +omit_fwd"); fmt->stopInversion(); EXPECT_EQ(fmt->toString(), "+proj=pipeline " "+step +inv +proj=hgridshift +grids=foo +omit_inv"); } // Test omit_inv->omit_fwd when inversing the pipeline { auto fmt = PROJStringFormatter::create(); fmt->startInversion(); fmt->ingestPROJString("+proj=hgridshift +grids=foo +omit_inv"); fmt->stopInversion(); EXPECT_EQ(fmt->toString(), "+proj=pipeline " "+step +inv +proj=hgridshift +grids=foo +omit_fwd"); } // Variant with first hgridshift inverted, and second forward { auto fmt = PROJStringFormatter::create(); fmt->startInversion(); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo"); fmt->stopInversion(); fmt->addStep("vgridshift"); fmt->addParam("grids", "bar"); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo"); EXPECT_EQ(fmt->toString(), "+proj=pipeline " "+step +proj=push +v_1 +v_2 " "+step +inv +proj=hgridshift +grids=foo +omit_inv " "+step +proj=vgridshift +grids=bar " "+step +proj=hgridshift +grids=foo +omit_fwd " "+step +proj=pop +v_1 +v_2"); } // Do not apply ! not same grid name { auto fmt = PROJStringFormatter::create(); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo"); fmt->addStep("vgridshift"); fmt->addParam("grids", "bar"); fmt->startInversion(); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo2"); fmt->stopInversion(); EXPECT_EQ(fmt->toString(), "+proj=pipeline " "+step +proj=hgridshift +grids=foo " "+step +proj=vgridshift +grids=bar " "+step +inv +proj=hgridshift +grids=foo2"); } // Do not apply ! missing inversion { auto fmt = PROJStringFormatter::create(); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo"); fmt->addStep("vgridshift"); fmt->addParam("grids", "bar"); fmt->addStep("hgridshift"); fmt->addParam("grids", "foo"); EXPECT_EQ(fmt->toString(), "+proj=pipeline " "+step +proj=hgridshift +grids=foo " "+step +proj=vgridshift +grids=bar " "+step +proj=hgridshift +grids=foo"); } } // --------------------------------------------------------------------------- TEST(io, projstringformatter_optim_as_uc_vgridshift_uc_as_push_as_uc) { // Nominal case { auto fmt = PROJStringFormatter::create(); fmt->addStep("axisswap"); fmt->addParam("order", "2,1"); fmt->addStep("unitconvert"); fmt->addParam("xy_in", "deg"); fmt->addParam("xy_out", "rad"); fmt->addStep("vgridshift"); fmt->addParam("grids", "foo"); fmt->addStep("unitconvert"); fmt->addParam("xy_in", "rad"); fmt->addParam("xy_out", "deg"); fmt->addStep("axisswap"); fmt->addParam("order", "2,1"); fmt->addStep("push"); fmt->addParam("v_1"); fmt->addParam("v_2"); fmt->addStep("axisswap"); fmt->addParam("order", "2,1"); fmt->addStep("unitconvert"); fmt->addParam("xy_in", "deg"); fmt->addParam("xy_out", "rad"); EXPECT_EQ(fmt->toString(), "+proj=pipeline " "+step +proj=push +v_1 +v_2 " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=foo"); } } // --------------------------------------------------------------------------- TEST(io, projstringformatter_krovak_to_krovak_east_north) { // Working case { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +inv +proj=krovak +axis=swu +lat_0=49.5 " "+lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+step +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel"); EXPECT_EQ(fmt->toString(), "+proj=axisswap +order=-2,-1"); } // Missing parameter { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +inv +proj=krovak +axis=swu +lat_0=49.5 " "+lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+step +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 "); // Not equal EXPECT_NE(fmt->toString(), "+proj=axisswap +order=-2,-1"); } // Different parameter values { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +inv +proj=krovak +axis=swu +lat_0=49.5 " "+lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+step +proj=krovak +lat_0=FOO +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel"); // Not equal EXPECT_NE(fmt->toString(), "+proj=axisswap +order=-2,-1"); } } // --------------------------------------------------------------------------- TEST(io, projstringformatter_krovak_east_north_to_krovak) { // Working case { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +inv +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+step +proj=krovak +axis=swu +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel"); EXPECT_EQ(fmt->toString(), "+proj=axisswap +order=-2,-1"); } // Missing parameter { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +inv +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+step +proj=krovak +axis=swu +lat_0=FOO +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0"); // Not equal EXPECT_NE(fmt->toString(), "+proj=axisswap +order=-2,-1"); } // Different parameter values { auto fmt = PROJStringFormatter::create(); fmt->ingestPROJString( "+proj=pipeline " "+step +inv +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel " "+step +proj=krovak +axis=swu +lat_0=FOO +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel"); // Not equal EXPECT_NE(fmt->toString(), "+proj=axisswap +order=-2,-1"); } } // --------------------------------------------------------------------------- TEST(io, projparse_longlat) { auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; { auto obj = PROJStringParser().createFromPROJString("+proj=longlat +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), expected); } { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), expected); } } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_datum_NAD83) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +datum=NAD83 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEODCRS[\"unknown\",\n" " DATUM[\"North American Datum 1983\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6269]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_datum_NAD27) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +datum=NAD27 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEODCRS[\"unknown\",\n" " DATUM[\"North American Datum 1927\",\n" " ELLIPSOID[\"Clarke 1866\",6378206.4,294.978698213898,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6267]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_datum_other) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +datum=carthage +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); crs->exportToWKT(f.get()); EXPECT_EQ(f->toString(), "GEODCRS[\"unknown\",\n" " DATUM[\"Carthage\",\n" " ELLIPSOID[\"Clarke 1880 (IGN)\",6378249.2,293.4660213,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6223]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_ellps_WGS84) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"Unknown based on WGS 84 ellipsoid\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_ellps_GRS80) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"Unknown based on GRS 1980 ellipsoid\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_b) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=2 +b=1.5 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"unknown\",\n" " ELLIPSOID[\"unknown\",2,4,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Reference meridian\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); EXPECT_EQ(crs->ellipsoid()->celestialBody(), "Non-Earth body"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_rf_WGS84) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=6378137 +rf=298.257223563 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"Unknown based on WGS 84 ellipsoid\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); EXPECT_EQ(crs->ellipsoid()->celestialBody(), Ellipsoid::EARTH); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_rf) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=2 +rf=4 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"unknown\",\n" " ELLIPSOID[\"unknown\",2,4,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Reference meridian\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_f_zero) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=2 +f=0 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"unknown\",\n" " ELLIPSOID[\"unknown\",2,0,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Reference meridian\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_f_non_zero) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=2 +f=0.5 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis().getSIValue(), 2); auto rf = crs->ellipsoid()->computedInverseFlattening(); EXPECT_EQ(rf, 2) << rf; } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_e) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=2 +e=0.5 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis().getSIValue(), 2); auto rf = crs->ellipsoid()->computedInverseFlattening(); EXPECT_NEAR(rf, 7.46410161513775, 1e-14) << rf; } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_es) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=2 +es=0.5 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis().getSIValue(), 2); auto rf = crs->ellipsoid()->computedInverseFlattening(); EXPECT_NEAR(rf, 3.4142135623730958, 1e-14) << rf; } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_R) { auto obj = PROJStringParser().createFromPROJString("+proj=longlat +R=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->ellipsoid()->isSphere()); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis().getSIValue(), 2); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a) { auto obj = PROJStringParser().createFromPROJString("+proj=longlat +a=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->ellipsoid()->isSphere()); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis().getSIValue(), 2); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_a_override_ellps) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +a=2 +ellps=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(!crs->ellipsoid()->isSphere()); EXPECT_EQ(crs->ellipsoid()->semiMajorAxis().getSIValue(), 2); EXPECT_EQ(crs->ellipsoid()->computedInverseFlattening(), 298.25722356300003) << crs->ellipsoid()->computedInverseFlattening(); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_pm_paris) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +pm=paris +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"Unknown based on WGS 84 ellipsoid\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Paris\",2.5969213,\n" " ANGLEUNIT[\"grad\",0.015707963267949]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_pm_ferro) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=bessel +pm=ferro +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"Unknown based on Bessel 1841 ellipsoid\",\n" " ELLIPSOID[\"Bessel 1841\",6377397.155,299.1528128,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Ferro\",-17.6666666666667,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_pm_numeric) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +pm=2.5 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "GEODCRS[\"unknown\",\n" " DATUM[\"Unknown based on WGS 84 ellipsoid\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"unknown\",2.5,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"longitude\",east,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"latitude\",north,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_pm_overriding_datum) { // It is arguable that we allow the prime meridian of a datum defined by // its name to be overridden, but this is found at least in a regression // test // of GDAL. So let's keep the ellipsoid part of the datum in that case and // use the specified prime meridian. auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +datum=WGS84 +pm=ferro +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->datum()->nameStr(), "Unknown based on WGS 84 ellipsoid"); EXPECT_EQ(crs->datum()->primeMeridian()->nameStr(), "Ferro"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_complex) { std::string input = "+step +proj=longlat +ellps=clrk80ign " "+pm=paris +step +proj=unitconvert +xy_in=rad +xy_out=grad +step " "+proj=axisswap +order=2,1"; auto obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline " + input); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad " + input); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_towgs84_3_terms) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +towgs84=1.2,2,3 +type=crs"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Geocentric translations") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"X-axis translation\",1.2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Y-axis translation\",2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Z-axis translation\",3") != std::string::npos) << wkt; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=longlat +ellps=GRS80 +towgs84=1.2,2,3,0,0,0,0 +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_towgs84_7_terms) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +towgs84=1.2,2,3,4,5,6,7 +type=crs"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Position Vector transformation") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"X-axis translation\",1.2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Y-axis translation\",2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Z-axis translation\",3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Scale difference\",1.000007") != std::string::npos) << wkt; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=longlat +ellps=GRS80 +towgs84=1.2,2,3,4,5,6,7 +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_nadgrids) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +nadgrids=foo.gsb +type=crs"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"NTv2\"") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETERFILE[\"Latitude and longitude difference " "file\",\"foo.gsb\"]") != std::string::npos) << wkt; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=longlat +ellps=GRS80 +nadgrids=foo.gsb +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_nadgrids_towgs84_ignored) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +towgs84=1,2,3 +nadgrids=foo.gsb " "+type=crs"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(dynamic_cast<GeographicCRS *>(crs->baseCRS().get()) != nullptr); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_geoidgrids) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +geoidgrids=foo.gtx +type=crs"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("ABRIDGEDTRANSFORMATION[\"unknown to WGS 84 " "ellipsoidal height\"") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETERFILE[\"Geoid (height correction) model " "file\",\"foo.gtx\"]") != std::string::npos) << wkt; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=longlat +ellps=GRS80 +geoidgrids=foo.gtx +geoid_crs=WGS84 " "+vunits=m +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_geoidgrids_vunits) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +geoidgrids=foo.gtx +vunits=ft +type=crs"); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("AXIS[\"gravity-related height " "(H)\",up,LENGTHUNIT[\"foot\",0.3048]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_vunits) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +vunits=ft +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("AXIS[\"ellipsoidal height " "(h)\",up,ORDER[3],LENGTHUNIT[\"foot\",0.3048]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_vunits) { auto obj = PROJStringParser().createFromPROJString("+vunits=ft +type=crs"); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+vunits=ft +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_vto_meter) { auto obj = PROJStringParser().createFromPROJString("+vto_meter=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+vto_meter=2 +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_axis_enu) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +axis=enu +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("AXIS[\"longitude\",east,ORDER[1]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("AXIS[\"latitude\",north,ORDER[2]") != std::string::npos) << wkt; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_axis_neu) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +axis=neu +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("AXIS[\"latitude\",north,ORDER[1]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("AXIS[\"longitude\",east,ORDER[2]") != std::string::npos) << wkt; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=noop"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_axis_swu) { auto obj = PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 +axis=swu +type=crs"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("AXIS[\"latitude\",south,ORDER[1]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("AXIS[\"longitude\",west,ORDER[2]") != std::string::npos) << wkt; auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=axisswap +order=-2,-1"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_unitconvert_deg) { auto obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=longlat +ellps=GRS80 +step " "+proj=unitconvert +xy_in=rad +xy_out=deg"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=axisswap +order=2,1"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_unitconvert_grad) { auto obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=longlat +ellps=GRS80 +step " "+proj=unitconvert +xy_in=rad +xy_out=grad"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step " "+proj=unitconvert +xy_in=rad +xy_out=grad"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_unitconvert_rad) { auto obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=longlat +ellps=GRS80 +step " "+proj=unitconvert +xy_in=rad +xy_out=rad"); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_axisswap) { for (auto order1 : {"1", "-1", "2", "-2"}) { for (auto order2 : {"1", "-1", "2", "-2"}) { if (std::abs(atoi(order1) * atoi(order2)) == 2 && !(atoi(order1) == 1 && atoi(order2) == 2)) { auto str = "+type=crs +proj=pipeline +step +proj=longlat +ellps=GRS80 " "+step +proj=axisswap +order=" + std::string(order1) + "," + order2; auto obj = PROJStringParser().createFromPROJString(str); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), (atoi(order1) == 2 && atoi(order2) == 1) ? "+proj=noop" : (atoi(order1) == 2 && atoi(order2) == -1) ? "+proj=axisswap +order=1,-2" : "+proj=pipeline +step +proj=axisswap " "+order=2,1 " "+step +proj=axisswap +order=" + std::string(order1) + "," + order2); } } } } // --------------------------------------------------------------------------- TEST(io, projparse_tmerc) { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +x_0=1 +lat_0=1 +k_0=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "PROJCRS[\"unknown\",\n" " BASEGEODCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",2,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",1,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]"; EXPECT_EQ(f->toString(), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_tmerc_south_oriented) { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +axis=wsu +x_0=1 +lat_0=1 +k_0=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); crs->exportToWKT(f.get()); auto expected = "PROJCRS[\"unknown\",\n" " BASEGEODCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Transverse Mercator (South Orientated)\",\n" " ID[\"EPSG\",9808]],\n" " PARAMETER[\"Latitude of natural origin\",1,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",2,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",1,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"westing\",west,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1]],\n" " AXIS[\"southing\",south,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1]]]"; EXPECT_EQ(f->toString(), expected); obj = PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=tmerc +x_0=1 +lat_0=1 +k_0=2 " "+step " "+proj=axisswap +order=-1,-2"); crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Transverse Mercator (South Orientated)"); } // --------------------------------------------------------------------------- TEST(io, projparse_lcc_as_lcc1sp) { auto obj = PROJStringParser().createFromPROJString( "+proj=lcc +lat_0=45 +lat_1=45 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("Lambert Conic Conformal (1SP)") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_lcc_as_lcc1sp_variant_b) { auto obj = PROJStringParser().createFromPROJString( "+proj=lcc +lat_0=45 +lat_1=46 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("Lambert Conic Conformal (1SP variant B)") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_lcc_as_lcc2sp) { auto obj = PROJStringParser().createFromPROJString( "+proj=lcc +lat_0=45 +lat_1=46 +lat_2=44 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("Lambert Conic Conformal (2SP)") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_lcc_as_lcc2sp_michigan) { auto obj = PROJStringParser().createFromPROJString( "+proj=lcc +lat_0=45 +lat_1=46 +lat_2=44 +k_0=1.02 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("Lambert Conic Conformal (2SP Michigan)") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_aeqd_guam) { auto obj = PROJStringParser().createFromPROJString("+proj=aeqd +guam +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("Guam Projection") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_cea_spherical) { const std::string input( "+proj=cea +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +R=6371228 +units=m " "+no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); auto crs2 = ProjectedCRS::create( PropertyMap(), crs->baseCRS(), Conversion::createLambertCylindricalEqualArea( PropertyMap(), Angle(0), Angle(0), Length(0), Length(0)), crs->coordinateSystem()); EXPECT_EQ(crs2->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA); EXPECT_TRUE( crs->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs2->isEquivalentTo(crs.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(io, projparse_cea_spherical_on_ellipsoid) { std::string input("+proj=cea +R_A +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 " "+ellps=WGS84 +units=m +no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_cea_ellipsoidal) { auto obj = PROJStringParser().createFromPROJString( "+proj=cea +ellps=GRS80 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find( "METHOD[\"Lambert Cylindrical Equal Area\",ID[\"EPSG\",9835]]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_cea_ellipsoidal_with_k_0) { auto obj = PROJStringParser().createFromPROJString( "+proj=cea +ellps=GRS80 +k_0=0.99 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find("PARAMETER[\"Latitude of 1st standard parallel\",8.1365") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_merc_spherical_on_ellipsoid) { std::string input("+proj=merc +R_C +lat_0=1 +lon_0=2 +x_0=3 +y_0=4 " "+ellps=WGS84 +units=m +no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_MERCATOR_SPHERICAL); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_geos_sweep_x) { auto obj = PROJStringParser().createFromPROJString( "+proj=geos +sweep=x +h=1 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("Geostationary Satellite (Sweep X)") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_geos_sweep_y) { auto obj = PROJStringParser().createFromPROJString("+proj=geos +h=1 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("Geostationary Satellite (Sweep Y)") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_omerc_nouoff) { auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +no_uoff +alpha=2 +gamma=3 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Hotine Oblique Mercator (variant " "A)\",ID[\"EPSG\",9812]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Azimuth of initial line\",2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Angle from Rectified to Skew Grid\",3") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_omerc_tpno) { auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +lat_1=1 +lat_2=2 +lon_1=3 +lon_2=4 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find( "METHOD[\"Hotine Oblique Mercator Two Point Natural Origin\"]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_omerc_variant_b) { auto obj = PROJStringParser().createFromPROJString( "+proj=omerc +alpha=2 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Hotine Oblique Mercator (variant " "B)\",ID[\"EPSG\",9815]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Angle from Rectified to Skew Grid\",2") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_somerc) { auto obj = PROJStringParser().createFromPROJString( "+proj=somerc +lat_0=1 +lon_0=2 +k_0=3 +x_0=4 +y_0=5 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Hotine Oblique Mercator (variant " "B)\",ID[\"EPSG\",9815]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Latitude of projection centre\",1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Longitude of projection centre\",2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Scale factor on initial line\",3") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Azimuth of initial line\",90") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Angle from Rectified to Skew Grid\",90") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Easting at projection centre\",4") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Northing at projection centre\",5") != std::string::npos) << wkt; auto wkt1 = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(wkt1.find("EXTENSION") == std::string::npos) << wkt1; } // --------------------------------------------------------------------------- TEST(io, projparse_krovak) { auto obj = PROJStringParser().createFromPROJString("+proj=krovak +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find("METHOD[\"Krovak (North Orientated)\",ID[\"EPSG\",1041]]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_krovak_axis_swu) { auto obj = PROJStringParser().createFromPROJString( "+proj=krovak +axis=swu +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Krovak\",ID[\"EPSG\",9819]]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_krovak_czech) { auto obj = PROJStringParser().createFromPROJString( "+proj=krovak +czech +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=krovak +czech +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 " "+ellps=bessel +units=m +no_defs +type=crs"); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Krovak\",ID[\"EPSG\",9819]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find(",AXIS[\"westing\",west,ORDER[1]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find(",AXIS[\"southing\",south,ORDER[2]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_krovak_modified) { auto obj = PROJStringParser().createFromPROJString("+proj=mod_krovak +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Krovak Modified (North " "Orientated)\",ID[\"EPSG\",1043]]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_krovak_modified_axis_swu) { auto obj = PROJStringParser().createFromPROJString( "+proj=mod_krovak +axis=swu +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Krovak Modified\",ID[\"EPSG\",1042]]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_krovak_modified_czech) { auto obj = PROJStringParser().createFromPROJString( "+proj=mod_krovak +czech +x_0=5000000 +y_0=5000000 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=mod_krovak +czech +lat_0=49.5 +lon_0=24.8333333333333 " "+alpha=30.2881397527778 +k=0.9999 +x_0=5000000 +y_0=5000000 " "+ellps=bessel +units=m +no_defs +type=crs"); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Krovak Modified\",ID[\"EPSG\",1042]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find(",AXIS[\"westing\",west,ORDER[1]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find(",AXIS[\"southing\",south,ORDER[2]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_etmerc) { auto obj = PROJStringParser().createFromPROJString("+proj=etmerc +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto wkt2 = crs->exportToWKT( &WKTFormatter::create()->simulCurNodeHasId().setMultiLine(false)); EXPECT_TRUE( wkt2.find("METHOD[\"Transverse Mercator\",ID[\"EPSG\",9807]]") != std::string::npos) << wkt2; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=tmerc +lat_0=0 +lon_0=0 +k=1 +x_0=0 +y_0=0 " "+datum=WGS84 +units=m +no_defs +type=crs"); auto wkt1 = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(wkt1.find("EXTENSION[\"PROJ4\"") == std::string::npos) << wkt1; } // --------------------------------------------------------------------------- TEST(io, projparse_tmerc_approx) { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +approx +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto wkt2 = crs->exportToWKT( &WKTFormatter::create()->simulCurNodeHasId().setMultiLine(false)); EXPECT_TRUE( wkt2.find("METHOD[\"Transverse Mercator\",ID[\"EPSG\",9807]]") != std::string::npos) << wkt2; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=tmerc +approx +lat_0=0 +lon_0=0 +k=1 +x_0=0 +y_0=0 " "+datum=WGS84 +units=m +no_defs +type=crs"); auto wkt1 = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()); EXPECT_TRUE(wkt1.find("EXTENSION[\"PROJ4\",\"+proj=tmerc +approx +lat_0=0 " "+lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m " "+no_defs\"]") != std::string::npos) << wkt1; } // --------------------------------------------------------------------------- TEST(io, projparse_merc_variant_B) { auto obj = PROJStringParser().createFromPROJString( "+proj=merc +lat_ts=1 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find("METHOD[\"Mercator (variant B)\",ID[\"EPSG\",9805]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Latitude of 1st standard parallel\",1") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_merc_google_mercator) { auto projString = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 " "+k=1 +units=m +nadgrids=@null +no_defs +type=crs"; auto obj = PROJStringParser().createFromPROJString(projString); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Popular Visualisation Pseudo " "Mercator\",ID[\"EPSG\",1024]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("DATUM[\"World Geodetic System 1984\"") != std::string::npos) << wkt; EXPECT_EQ( replaceAll(crs->exportToPROJString(PROJStringFormatter::create().get()), " +wktext", ""), projString); } // --------------------------------------------------------------------------- TEST(io, projparse_merc_google_mercator_non_metre_unit) { auto projString = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 " "+k=1 +units=ft +nadgrids=@null +no_defs +type=crs"; auto obj = PROJStringParser().createFromPROJString(projString); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / Pseudo-Mercator (unit ft)"); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), "Popular Visualisation Pseudo Mercator"); EXPECT_EQ( replaceAll(crs->exportToPROJString(PROJStringFormatter::create().get()), " +wktext", ""), projString); auto wkt = crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()); auto expected_wkt = "PROJCRS[\"WGS 84 / Pseudo-Mercator (unit ft)\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " ID[\"EPSG\",4326]],\n" " CONVERSION[\"unnamed\",\n" " METHOD[\"Popular Visualisation Pseudo Mercator\",\n" " ID[\"EPSG\",1024]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"False easting\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"foot\",0.3048,\n" " ID[\"EPSG\",9002]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"foot\",0.3048,\n" " ID[\"EPSG\",9002]]]]"; EXPECT_EQ(wkt, expected_wkt); auto objFromWkt = WKTParser().createFromWKT(wkt); auto crsFromWkt = nn_dynamic_pointer_cast<ProjectedCRS>(objFromWkt); ASSERT_TRUE(crsFromWkt != nullptr); EXPECT_TRUE(crs->isEquivalentTo(crsFromWkt.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(io, projparse_merc_not_quite_google_mercator) { auto projString = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=10 +x_0=0 +y_0=0 " "+k=1 +units=m +nadgrids=@null +no_defs +type=crs"; auto obj = PROJStringParser().createFromPROJString(projString); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Popular Visualisation Pseudo " "Mercator\",ID[\"EPSG\",1024]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("DATUM[\"unknown using nadgrids=@null\",") != std::string::npos) << wkt; EXPECT_EQ( replaceAll(crs->exportToPROJString(PROJStringFormatter::create().get()), " +wktext", ""), projString); } // --------------------------------------------------------------------------- TEST(io, projparse_merc_stere_polar_variant_B) { auto obj = PROJStringParser().createFromPROJString( "+proj=stere +lat_0=90 +lat_ts=70 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find( "METHOD[\"Polar Stereographic (variant B)\",ID[\"EPSG\",9829]]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_merc_stere_polar_variant_A) { auto obj = PROJStringParser().createFromPROJString( "+proj=stere +lat_0=-90 +k=0.994 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find( "METHOD[\"Polar Stereographic (variant A)\",ID[\"EPSG\",9810]]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_merc_stere_polar_k_and_lat_ts) { auto obj = PROJStringParser().createFromPROJString( "+proj=stere +lat_0=90 +lat_ts=90 +k=1 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto wkt = crs->exportToWKT( &(WKTFormatter::create()->simulCurNodeHasId().setMultiLine(false))); EXPECT_TRUE( wkt.find( "METHOD[\"Polar Stereographic (variant B)\",ID[\"EPSG\",9829]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Latitude of standard parallel\",90") != std::string::npos) << wkt; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=stere +lat_0=90 +lat_ts=90 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 " "+units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_merc_stere_polar_k_and_lat_ts_incompatible) { EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=stere +lat_0=90 +lat_ts=70 +k=0.994 +type=crs"), ParsingException); } // --------------------------------------------------------------------------- TEST(io, projparse_merc_stere) { auto obj = PROJStringParser().createFromPROJString( "+proj=stere +lat_0=30 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("METHOD[\"Stereographic\"]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_utm) { auto obj = PROJStringParser().createFromPROJString("+proj=utm +zone=1 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("CONVERSION[\"UTM zone 1N\",METHOD[\"Transverse " "Mercator\",ID[\"EPSG\",9807]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Longitude of natural origin\",-177,") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"False northing\",0,") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_utm_south) { auto obj = PROJStringParser().createFromPROJString( "+proj=utm +zone=1 +south +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("CONVERSION[\"UTM zone 1S\",METHOD[\"Transverse " "Mercator\",ID[\"EPSG\",9807]]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"Longitude of natural origin\",-177,") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("\"False northing\",10000000,") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_laea_north_pole) { auto obj = PROJStringParser().createFromPROJString( "+proj=laea +lat_0=90 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("AXIS[\"(E)\",south") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("AXIS[\"(N)\",south") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_laea_south_pole) { auto obj = PROJStringParser().createFromPROJString( "+proj=laea +lat_0=-90 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("AXIS[\"(E)\",north") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("AXIS[\"(N)\",north") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_laea_spherical) { auto obj = PROJStringParser().createFromPROJString( "+proj=laea +R=6371228 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL); auto crs2 = ProjectedCRS::create( PropertyMap(), crs->baseCRS(), Conversion::createLambertAzimuthalEqualArea( PropertyMap(), Angle(0), Angle(0), Length(0), Length(0)), crs->coordinateSystem()); EXPECT_EQ(crs2->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA); EXPECT_TRUE( crs->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs2->isEquivalentTo(crs.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(io, projparse_laea_ellipsoidal) { auto obj = PROJStringParser().createFromPROJString( "+proj=laea +ellps=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA); } // --------------------------------------------------------------------------- TEST(io, projparse_laea_spherical_on_ellipsoid) { std::string input("+proj=laea +R_A +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+ellps=WGS84 +units=m +no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_eqc_spherical) { auto obj = PROJStringParser().createFromPROJString( "+proj=eqc +R=6371228 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL); auto crs2 = ProjectedCRS::create( PropertyMap(), crs->baseCRS(), Conversion::createEquidistantCylindrical( PropertyMap(), Angle(0), Angle(0), Length(0), Length(0)), crs->coordinateSystem()); EXPECT_EQ(crs2->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL); EXPECT_TRUE( crs->isEquivalentTo(crs2.get(), IComparable::Criterion::EQUIVALENT)); EXPECT_TRUE( crs2->isEquivalentTo(crs.get(), IComparable::Criterion::EQUIVALENT)); } // --------------------------------------------------------------------------- TEST(io, projparse_eqc_ellipsoidal) { auto obj = PROJStringParser().createFromPROJString( "+proj=eqc +ellps=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL); } // --------------------------------------------------------------------------- TEST(io, projparse_non_earth_ellipsoid) { std::string input("+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +R=1 +units=m " "+no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_ortho_ellipsoidal) { std::string input("+proj=ortho +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+ellps=WGS84 +units=m +no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->getEPSGCode(), EPSG_CODE_METHOD_ORTHOGRAPHIC); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_ortho_spherical_on_ellipsoid) { std::string input("+proj=ortho +f=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+ellps=WGS84 +units=m +no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->method()->nameStr(), PROJ_WKT2_NAME_ORTHOGRAPHIC_SPHERICAL); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_ortho_spherical_on_sphere) { std::string input("+proj=ortho +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 " "+R=6378137 +units=m +no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_peirce_q_square) { std::string input("+proj=peirce_q +shape=square +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=peirce_q +shape=square +lat_0=90 +lon_0=0 +k_0=1 +x_0=0 +y_0=0 " "+datum=WGS84 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_peirce_q_diamond) { std::string input("+proj=peirce_q +shape=diamond +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=peirce_q +shape=diamond +lat_0=90 +lon_0=0 +k_0=1 +x_0=0 +y_0=0 " "+datum=WGS84 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_peirce_q_horizontal) { std::string input("+proj=peirce_q +shape=horizontal +datum=WGS84 +units=m " "+no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_peirce_q_invalid_lat_0) { std::string input("+proj=peirce_q +lat_0=0 +shape=square +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_THROW( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), FormattingException); } // --------------------------------------------------------------------------- TEST(io, projparse_peirce_q_invalid_k_0) { std::string input("+proj=peirce_q +k_0=0.5 +shape=square +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_THROW( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), FormattingException); } // --------------------------------------------------------------------------- TEST(io, projparse_axisswap_unitconvert_longlat_proj) { std::string input = "+type=crs +proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=grad +xy_out=rad +step +inv +proj=longlat " "+ellps=clrk80ign +pm=paris +step +proj=lcc +lat_1=49.5 " "+lat_0=49.5 +lon_0=0 +k_0=0.999877341 +x_0=600000 +y_0=200000 " "+ellps=clrk80ign +pm=paris"; auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=lcc " "+lat_1=49.5 +lat_0=49.5 +lon_0=0 +k_0=0.999877341 +x_0=600000 " "+y_0=200000 +ellps=clrk80ign +pm=paris"); } // --------------------------------------------------------------------------- TEST(io, projparse_axisswap_unitconvert_proj_axisswap) { std::string input = "+type=crs +proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=igh " "+lon_0=0 +x_0=0 +y_0=0 +ellps=GRS80 +step +proj=axisswap +order=2,1"; auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=igh " "+lon_0=0 +x_0=0 +y_0=0 +ellps=GRS80 +step +proj=axisswap " "+order=2,1"); } // --------------------------------------------------------------------------- TEST(io, projparse_axisswap_unitconvert_proj_unitconvert) { std::string input = "+type=crs +proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=igh " "+lon_0=0 +x_0=0 +y_0=0 +ellps=GRS80 +step +proj=unitconvert +xy_in=m " "+xy_out=ft"; auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=igh " "+lon_0=0 +x_0=0 +y_0=0 +ellps=GRS80 +step +proj=unitconvert " "+xy_in=m +xy_out=ft"); } // --------------------------------------------------------------------------- TEST(io, projparse_axisswap_unitconvert_proj_unitconvert_numeric_axisswap) { std::string input = "+type=crs +proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=igh " "+lon_0=0 +x_0=0 +y_0=0 +ellps=GRS80 +step +proj=unitconvert +xy_in=m " "+xy_out=2.5 +step +proj=axisswap +order=-2,-1"; auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=igh " "+lon_0=0 +x_0=0 +y_0=0 +ellps=GRS80 +step +proj=unitconvert " "+xy_in=m +xy_out=2.5 +step +proj=axisswap " "+order=-2,-1"); } // --------------------------------------------------------------------------- TEST(io, projparse_projected_units) { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +x_0=0.304800609601219 +units=us-ft +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("PARAMETER[\"False easting\",1,LENGTHUNIT[\"US survey " "foot\",0.304800609601219]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("AXIS[\"(E)\",east,ORDER[1],LENGTHUNIT[\"US survey " "foot\",0.304800609601219]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_projected_to_meter_known) { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +to_meter=0.304800609601219 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE(wkt.find("PARAMETER[\"False easting\",0,LENGTHUNIT[\"US survey " "foot\",0.304800609601219]") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("AXIS[\"(E)\",east,ORDER[1],LENGTHUNIT[\"US survey " "foot\",0.304800609601219]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_projected_to_meter_unknown) { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +to_meter=0.1234 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find( "PARAMETER[\"False easting\",0,LENGTHUNIT[\"unknown\",0.1234]") != std::string::npos) << wkt; EXPECT_TRUE( wkt.find("AXIS[\"(E)\",east,ORDER[1],LENGTHUNIT[\"unknown\",0.1234]") != std::string::npos) << wkt; } // --------------------------------------------------------------------------- TEST(io, projparse_projected_vunits) { auto obj = PROJStringParser().createFromPROJString( "+proj=tmerc +vunits=ft +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto cs = crs->coordinateSystem(); ASSERT_EQ(cs->axisList().size(), 3U); EXPECT_EQ(cs->axisList()[2]->unit().name(), "foot"); } // --------------------------------------------------------------------------- TEST(io, projparse_projected_unknown) { auto obj = PROJStringParser().createFromPROJString( "+proj=mbt_s +unused_flag +lat_0=45 +lon_0=0 +k=1 +x_0=10 +y_0=0 " "+datum=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); { WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find("CONVERSION[\"unknown\",METHOD[\"PROJ mbt_s\"]," "PARAMETER[\"lat_0\",45,ANGLEUNIT[" "\"degree\",0.0174532925199433]],PARAMETER[\"lon_0\"," "0,ANGLEUNIT[\"degree\",0.0174532925199433]]," "PARAMETER[\"k\",1,SCALEUNIT[\"unity\",1]],PARAMETER[" "\"x_0\",10,LENGTHUNIT[\"metre\",1]],PARAMETER[\"y_0\"," "0,LENGTHUNIT[\"metre\",1]]]") != std::string::npos) << wkt; } std::string expected_wkt1 = "PROJCS[\"unknown\",GEOGCS[\"unknown\",DATUM[\"WGS_1984\",SPHEROID[" "\"WGS " "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[" "\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\"," "\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\"," "\"9122\"]]]," "PROJECTION[\"custom_proj4\"],UNIT[\"metre\",1,AUTHORITY[\"EPSG\"," "\"9001\"]],AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH],EXTENSION[" "\"PROJ4\",\"+proj=mbt_s +lat_0=45 " "+lon_0=0 +k=1 +x_0=10 +y_0=0 +datum=WGS84\"]]"; { WKTFormatterNNPtr f( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL)); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_EQ(wkt, expected_wkt1); } EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=mbt_s +lat_0=45 +lon_0=0 +k=1 +x_0=10 " "+y_0=0 +datum=WGS84 +type=crs"); { auto obj2 = WKTParser().createFromWKT(expected_wkt1); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs2->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find("CONVERSION[\"unknown\",METHOD[\"PROJ mbt_s\"]," "PARAMETER[\"lat_0\",45,ANGLEUNIT[" "\"degree\",0.0174532925199433]],PARAMETER[\"lon_0\"," "0,ANGLEUNIT[\"degree\",0.0174532925199433]]," "PARAMETER[\"k\",1,SCALEUNIT[\"unity\",1]],PARAMETER[" "\"x_0\",10,LENGTHUNIT[\"metre\",1]],PARAMETER[\"y_0\"," "0,LENGTHUNIT[\"metre\",1]]]") != std::string::npos) << wkt; } } // --------------------------------------------------------------------------- TEST(io, projparse_geocent) { auto obj = PROJStringParser().createFromPROJString( "+proj=geocent +ellps=WGS84 +type=crs"); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_EQ(wkt, "GEODCRS[\"unknown\",DATUM[\"Unknown based on WGS 84 " "ellipsoid\",ELLIPSOID[\"WGS " "84\",6378137,298.257223563,LENGTHUNIT[\"metre\",1]]]," "PRIMEM[\"Greenwich\",0,ANGLEUNIT[\"degree\",0." "0174532925199433]],CS[Cartesian,3],AXIS[\"(X)\"," "geocentricX,ORDER[1],LENGTHUNIT[\"metre\",1]],AXIS[\"(Y)\"," "geocentricY,ORDER[2],LENGTHUNIT[\"metre\",1]],AXIS[\"(Z)\"," "geocentricZ,ORDER[3],LENGTHUNIT[\"metre\",1]]]"); } // --------------------------------------------------------------------------- TEST(io, projparse_geocent_towgs84) { auto obj = PROJStringParser().createFromPROJString( "+proj=geocent +ellps=WGS84 +towgs84=1,2,3 +type=crs"); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); WKTFormatterNNPtr f(WKTFormatter::create()); f->simulCurNodeHasId(); f->setMultiLine(false); crs->exportToWKT(f.get()); auto wkt = f->toString(); EXPECT_TRUE( wkt.find("METHOD[\"Geocentric translations (geocentric domain)") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"X-axis translation\",1") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Y-axis translation\",2") != std::string::npos) << wkt; EXPECT_TRUE(wkt.find("PARAMETER[\"Z-axis translation\",3") != std::string::npos) << wkt; EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=geocent +ellps=WGS84 +towgs84=1,2,3,0,0,0,0 +units=m +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_cart_unit) { std::string input( "+proj=pipeline +step +proj=cart +ellps=WGS84 +step " "+proj=unitconvert +xy_in=m +z_in=m +xy_out=km +z_out=km"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=m +z_in=m +xy_out=km +z_out=km"); } // --------------------------------------------------------------------------- TEST(io, projparse_cart_unit_numeric) { std::string input( "+proj=pipeline +step +proj=cart +ellps=WGS84 +step " "+proj=unitconvert +xy_in=m +z_in=m +xy_out=500 +z_out=500"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); EXPECT_EQ( op->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline " "+step +proj=axisswap +order=2,1 " "+step +proj=unitconvert +xy_in=deg +z_in=m +xy_out=rad +z_out=m " "+step +proj=cart +ellps=WGS84 " "+step +proj=unitconvert +xy_in=m +z_in=m +xy_out=500 +z_out=500"); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_wktext) { std::string input("+proj=longlat +foo +wktext +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=longlat +datum=WGS84 +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_geocent_wktext) { std::string input("+proj=geocent +foo +wktext +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=geocent +datum=WGS84 +units=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_geoc) { std::string input("+proj=longlat +geoc +datum=WGS84 +no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->isSphericalPlanetocentric()); #if 1 EXPECT_THROW( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), FormattingException); #else EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), input); #endif } // --------------------------------------------------------------------------- TEST(io, projparse_topocentric) { auto obj = PROJStringParser().createFromPROJString( "+proj=topocentric +datum=WGS84 +X_0=-3982059.42 +Y_0=3331314.88 " "+Z_0=3692463.58 +no_defs +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); auto expected = "PROJCRS[\"unknown\",\n" " BASEGEODCRS[\"unknown\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6326]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"unknown\",\n" " METHOD[\"Geocentric/topocentric conversions\",\n" " ID[\"EPSG\",9836]],\n" " PARAMETER[\"Geocentric X of topocentric " "origin\",-3982059.42,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8837]],\n" " PARAMETER[\"Geocentric Y of topocentric origin\",3331314.88,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8838]],\n" " PARAMETER[\"Geocentric Z of topocentric origin\",3692463.58,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8839]]],\n" " CS[Cartesian,3],\n" " AXIS[\"topocentric East (U)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"topocentric North (V)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"topocentric Up (W)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]]]"; EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), expected); } // --------------------------------------------------------------------------- TEST(io, projparse_projected_wktext) { std::string input("+proj=merc +foo +wktext +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_ob_tran_longlat) { for (const char *o_proj : {"longlat", "lonlat", "latlong", "latlon"}) { std::string input( "+type=crs +proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=ob_tran " "+o_proj="); input += o_proj; input += " +o_lat_p=52 +o_lon_p=-30 +lon_0=-25 +ellps=WGS84 " "+step +proj=axisswap +order=2,1"; auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto op = CoordinateOperationFactory::create()->createOperation( GeographicCRS::EPSG_4326, NN_NO_CHECK(crs)); ASSERT_TRUE(op != nullptr); std::string expected( "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=ob_tran " "+o_proj="); expected += o_proj; expected += " +o_lat_p=52 +o_lon_p=-30 +lon_0=-25 " "+ellps=WGS84 +step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"; EXPECT_EQ(op->exportToPROJString(PROJStringFormatter::create().get()), expected); } } // --------------------------------------------------------------------------- TEST(io, projparse_ob_tran_rhealpix) { std::string input( "+proj=ob_tran +o_proj=rhealpix +o_lat_p=90 +o_lon_p=-180 +lon_0=180 " "+north_square=1 +south_square=0 +ellps=WGS84 +type=crs"); auto obj = PROJStringParser().createFromPROJString(input); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), input); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_title) { std::string projString("+title=Ile d'Amsterdam 1963 +proj=longlat " "+towgs84=109.7530,-528.1330,-362.2440 " "+a=6378388.0000 +rf=297.0000000000000 +units=m " "+no_defs +type=crs"); auto obj = PROJStringParser().createFromPROJString(projString); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto baseCRS = nn_dynamic_pointer_cast<GeographicCRS>(crs->baseCRS()); ASSERT_TRUE(baseCRS != nullptr); EXPECT_EQ(baseCRS->nameStr(), "Ile d'Amsterdam 1963"); EXPECT_EQ(baseCRS->datum()->nameStr(), "Ile d'Amsterdam 1963"); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=longlat +ellps=intl +towgs84=109.753,-528.133,-362.244,0,0,0,0 " "+no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_projected_title) { std::string projString( "+title=Amsterdam 1963 +proj=tmerc " "+towgs84=109.7530,-528.1330,-362.2440 +a=6378388.0000 " "+rf=297.0000000000000 +lat_0=0.000000000 +lon_0=75.000000000 " "+k_0=0.99960000 +x_0=500000.000 +y_0=10000000.000 +units=m +no_defs " "+type=crs"); auto obj = PROJStringParser().createFromPROJString(projString); auto crs = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(crs != nullptr); auto baseCRS = nn_dynamic_pointer_cast<ProjectedCRS>(crs->baseCRS()); ASSERT_TRUE(baseCRS != nullptr); EXPECT_EQ(baseCRS->nameStr(), "Amsterdam 1963"); EXPECT_EQ(baseCRS->baseCRS()->nameStr(), "unknown"); EXPECT_EQ( crs->exportToPROJString( PROJStringFormatter::create(PROJStringFormatter::Convention::PROJ_4) .get()), "+proj=utm +zone=43 +south +ellps=intl " "+towgs84=109.753,-528.133,-362.244,0,0,0,0 +units=m +no_defs " "+type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_init) { auto dbContext = DatabaseContext::create(); // Not allowed in non-compatibillity mode EXPECT_THROW( PROJStringParser().createFromPROJString("init=epsg:4326 +type=crs"), ParsingException); { // EPSG:4326 is normally latitude-longitude order with degree, // but in compatibillity mode it will be long-lat auto obj = createFromUserInput("init=epsg:4326", dbContext, true); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->coordinateSystem()->isEquivalentTo( EllipsoidalCS::createLongitudeLatitude(UnitOfMeasure::DEGREE) .get())); } { // Test that +no_defs +type=crs have no effect auto obj = createFromUserInput( "+init=epsg:4326 +no_defs +type=crs +wktext", dbContext, true); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto wkt = crs->exportToWKT(WKTFormatter::create().get()); EXPECT_TRUE(wkt.find("GEODCRS[\"WGS 84\"") == 0) << wkt; } { // EPSG:3040 is normally northing-easting order, but in compatibillity // mode it will be easting-northing auto obj = createFromUserInput("init=epsg:3040 +type=crs", dbContext, true); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_TRUE(crs->coordinateSystem()->isEquivalentTo( CartesianCS::createEastingNorthing(UnitOfMeasure::METRE).get())); } { auto obj = PROJStringParser().createFromPROJString("init=ITRF2000:ITRF2005"); auto co = nn_dynamic_pointer_cast<CoordinateOperation>(obj); ASSERT_TRUE(co != nullptr); EXPECT_EQ(co->exportToPROJString(PROJStringFormatter::create().get()), "+proj=helmert +x=-0.0001 +y=0.0008 +z=0.0058 +s=-0.0004 " "+dx=0.0002 +dy=-0.0001 +dz=0.0018 +ds=-0.00008 " "+t_epoch=2000.0 +convention=position_vector"); } { auto obj = createFromUserInput("+title=mytitle +init=epsg:4326 +over", dbContext, true); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "mytitle"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=longlat +datum=WGS84 +over +no_defs +type=crs"); } { auto obj = createFromUserInput( "proj=pipeline step init=epsg:4326 step proj=longlat ellps=WGS84", dbContext, true); auto co = nn_dynamic_pointer_cast<CoordinateOperation>(obj); ASSERT_TRUE(co != nullptr); EXPECT_EQ(co->exportToPROJString(PROJStringFormatter::create().get()), "+proj=pipeline +step +init=epsg:4326 +step +proj=longlat " "+ellps=WGS84"); } } // --------------------------------------------------------------------------- TEST(io, projparse_errors) { EXPECT_THROW(PROJStringParser().createFromPROJString(""), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString("foo"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString("inv"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString("step"), ParsingException); EXPECT_THROW( PROJStringParser().createFromPROJString("proj=unknown +type=crs"), ParsingException); EXPECT_THROW( PROJStringParser().createFromPROJString( "proj=pipeline step proj=unitconvert step proj=longlat a=invalid"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "proj=pipeline step proj=pipeline"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "proj=pipeline step init=epsg:4326 init=epsg:4326"), ParsingException); EXPECT_THROW( PROJStringParser().createFromPROJString("proj=\tinit= +type=crs"), ParsingException); } // --------------------------------------------------------------------------- TEST(io, projparse_longlat_errors) { EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +datum=unknown +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +ellps=unknown +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +a=invalid +b=1 +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +a=1 +b=invalid +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +a=invalid +rf=1 +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +a=1 +rf=invalid +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +a=1 +f=invalid +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +R=invalid +type=crs"), ParsingException); EXPECT_THROW( PROJStringParser().createFromPROJString("+proj=longlat +b=1 +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +rf=1 +type=crs"), ParsingException); EXPECT_THROW( PROJStringParser().createFromPROJString("+proj=longlat +f=0 +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +pm=unknown +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +ellps=GRS80 " "+towgs84=1.2,2,3,4,5,6,invalid +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=longlat +axis=foo +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=pipeline +step +proj=longlat +ellps=GRS80 +step " "+proj=unitconvert +xy_in=rad +xy_out=foo"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=pipeline +step +proj=longlat +ellps=GRS80 +step " "+proj=axisswap"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=pipeline +step +proj=longlat +ellps=GRS80 +step " "+proj=axisswap +order=0,0"), ParsingException); // We just want to check that we don't loop forever PROJStringParser().createFromPROJString( "+=x;proj=pipeline step proj=push +type=crs"); } // --------------------------------------------------------------------------- TEST(io, projparse_projected_errors) { EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=tmerc +units=foo +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=tmerc +x_0=foo +type=crs"), ParsingException); EXPECT_THROW(PROJStringParser().createFromPROJString( "+proj=tmerc +lat_0=foo +type=crs"), ParsingException); // Inconsistent pm values between geogCRS and projectedCRS EXPECT_THROW( PROJStringParser().createFromPROJString( "+type=crs +proj=pipeline +step +proj=longlat +ellps=WGS84 " "+step +proj=tmerc +ellps=WGS84 +lat_0=0 +pm=paris"), ParsingException); } // --------------------------------------------------------------------------- TEST(io, createFromUserInput) { auto dbContext = DatabaseContext::create(); EXPECT_THROW(createFromUserInput("foo", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("GEOGCRS", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("+proj=unhandled +type=crs", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("EPSG:4326", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("ESRI:103668+EPSG:5703", nullptr), ParsingException); EXPECT_THROW( createFromUserInput("urn:ogc:def:unhandled:EPSG::4326", dbContext), ParsingException); EXPECT_THROW(createFromUserInput("urn:ogc:def:crs:non_existing_auth::4326", dbContext), NoSuchAuthorityCodeException); EXPECT_THROW(createFromUserInput( "urn:ogc:def:crs,crs:EPSG::2393,unhandled_type:EPSG::5717", dbContext), ParsingException); EXPECT_THROW(createFromUserInput( "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::unexisting_code", dbContext), NoSuchAuthorityCodeException); EXPECT_THROW( createFromUserInput( "urn:ogc:def:crs,crs:EPSG::2393::extra_element,crs:EPSG::EPSG", dbContext), ParsingException); EXPECT_THROW(createFromUserInput("urn:ogc:def:coordinateOperation," "coordinateOperation:EPSG::3895," "unhandled_type:EPSG::1618", dbContext), ParsingException); EXPECT_THROW( createFromUserInput("urn:ogc:def:coordinateOperation," "coordinateOperation:EPSG::3895," "coordinateOperation:EPSG::unexisting_code", dbContext), NoSuchAuthorityCodeException); EXPECT_THROW( createFromUserInput("urn:ogc:def:coordinateOperation," "coordinateOperation:EPSG::3895::extra_element," "coordinateOperation:EPSG::1618", dbContext), ParsingException); EXPECT_NO_THROW(createFromUserInput("+proj=longlat", nullptr)); EXPECT_NO_THROW(createFromUserInput("EPSG:4326", dbContext)); EXPECT_NO_THROW(createFromUserInput("epsg:4326", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:crs:EPSG::4326", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:crs:EPSG:10:4326", dbContext)); EXPECT_THROW(createFromUserInput("urn:ogc:def:crs:EPSG::4326", nullptr), ParsingException); EXPECT_NO_THROW(createFromUserInput( "urn:ogc:def:coordinateOperation:EPSG::1671", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:datum:EPSG::6326", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:ensemble:EPSG::6326", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:meridian:EPSG::8901", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:ellipsoid:EPSG::7030", dbContext)); EXPECT_NO_THROW(createFromUserInput("IAU:1000", dbContext)); EXPECT_NO_THROW(createFromUserInput("IAU_2015:1000", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:crs:IAU::1000", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:crs:IAU_2015::1000", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:ogc:def:crs:IAU:2015:1000", dbContext)); EXPECT_THROW(createFromUserInput("urn:ogc:def:crs:IAU_2015::xxxx", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("urn:ogc:def:crs:IAU:xxxx:1000", nullptr), ParsingException); // Found as srsName in some GMLs... EXPECT_NO_THROW( createFromUserInput("URN:OGC:DEF:CRS:OGC:1.3:CRS84", dbContext)); // Legacy formulations EXPECT_NO_THROW( createFromUserInput("urn:x-ogc:def:crs:EPSG::4326", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:opengis:def:crs:EPSG::4326", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:opengis:crs:EPSG::4326", dbContext)); EXPECT_NO_THROW( createFromUserInput("urn:x-ogc:def:crs:EPSG:4326", dbContext)); EXPECT_THROW(createFromUserInput("urn:opengis:crs:EPSG::4326", nullptr), ParsingException); EXPECT_THROW( createFromUserInput("urn:opengis:unhandled:EPSG::4326", dbContext), ParsingException); { auto obj = createFromUserInput("EPSG:2393+5717", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "KKJ / Finland Uniform Coordinate System + N60 height"); } { auto obj = createFromUserInput("EPSG:2393+EPSG:5717", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "KKJ / Finland Uniform Coordinate System + N60 height"); } { auto obj = createFromUserInput("ESRI:103668+EPSG:5703", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAD_1983_HARN_Adj_MN_Ramsey_Meters + NAVD88 height"); } EXPECT_THROW(createFromUserInput("ESRI:42+EPSG:5703", dbContext), NoSuchAuthorityCodeException); EXPECT_THROW(createFromUserInput("ESRI:103668+EPSG:999999", dbContext), NoSuchAuthorityCodeException); { auto obj = createFromUserInput( "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "KKJ / Finland Uniform Coordinate System + N60 height"); } { auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::4979," "cs:PROJ::ENh," "coordinateOperation:EPSG::16031", dbContext); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 (3D) / UTM zone 31N"); EXPECT_EQ(crs->baseCRS()->getEPSGCode(), 4979); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ(crs->derivingConversion()->getEPSGCode(), 16031); } // We accept non-conformant EPSG:4326+4326 { auto obj = createFromUserInput("EPSG:4326+4326", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84"); EXPECT_EQ(crs->getEPSGCode(), 4979); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); const auto wkt = "COMPD_CS[\"WGS 84 + WGS 84\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]]]"; EXPECT_EQ( crs->exportToWKT(WKTFormatter::create( WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()), wkt); } // Non consistent EXPECT_THROW(createFromUserInput("EPSG:4326+4258", dbContext), InvalidCompoundCRSException); // We accept non-conformant EPSG:32631+4326 { auto obj = createFromUserInput("EPSG:32631+4326", dbContext); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 / UTM zone 31N"); EXPECT_EQ(crs->baseCRS()->getEPSGCode(), 4979); EXPECT_EQ(crs->baseCRS()->coordinateSystem()->axisList().size(), 3U); EXPECT_EQ(crs->coordinateSystem()->axisList().size(), 3U); const auto wkt = "COMPD_CS[\"WGS 84 / UTM zone 31N + WGS 84\",\n" " PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH],\n" " AUTHORITY[\"EPSG\",\"32631\"]],\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\n" " AUTHORITY[\"EPSG\",\"7030\"]],\n" " AUTHORITY[\"EPSG\",\"6326\"]],\n" " PRIMEM[\"Greenwich\",0,\n" " AUTHORITY[\"EPSG\",\"8901\"]],\n" " UNIT[\"degree\",0.0174532925199433,\n" " AUTHORITY[\"EPSG\",\"9122\"]],\n" " AUTHORITY[\"EPSG\",\"4326\"]]]"; EXPECT_EQ( crs->exportToWKT(WKTFormatter::create( WKTFormatter::Convention::WKT1_GDAL, dbContext) .get()), wkt); } EXPECT_THROW(createFromUserInput( "urn:ogc:def:crs,crs:EPSG::4979," "cs:PROJ::ENh," "coordinateOperation:EPSG::1024", // not a conversion dbContext), ParsingException); EXPECT_THROW(createFromUserInput("urn:ogc:def:crs,crs:," "cs:PROJ::ENh," "coordinateOperation:EPSG::16031", dbContext), ParsingException); EXPECT_THROW(createFromUserInput("urn:ogc:def:crs,crs:EPSG::4979," "cs:," "coordinateOperation:EPSG::16031", dbContext), ParsingException); EXPECT_THROW(createFromUserInput("urn:ogc:def:crs,crs:EPSG::4979," "cs:PROJ::ENh," "coordinateOperation:", dbContext), ParsingException); { // Completely nonsensical from a geodesic point of view... auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::4978," "cs:EPSG::6500," "coordinateOperation:EPSG::16031", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedGeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->getEPSGCode(), 4978); EXPECT_EQ(crs->coordinateSystem()->getEPSGCode(), 6500); EXPECT_EQ(crs->derivingConversion()->getEPSGCode(), 16031); } { // Completely nonsensical from a geodesic point of view... auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::4979," "cs:EPSG::6423," "coordinateOperation:EPSG::16031", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->getEPSGCode(), 4979); EXPECT_EQ(crs->coordinateSystem()->getEPSGCode(), 6423); EXPECT_EQ(crs->derivingConversion()->getEPSGCode(), 16031); } { // Completely nonsensical from a geodesic point of view... auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::32631," "cs:EPSG::4400," "coordinateOperation:EPSG::16031", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->baseCRS()->getEPSGCode(), 32631); EXPECT_EQ(crs->coordinateSystem()->getEPSGCode(), 4400); EXPECT_EQ(crs->derivingConversion()->getEPSGCode(), 16031); } { // DerivedVerticalCRS based on "NAVD88 height", using a foot UP axis, // and EPSG:7813 "Vertical Axis Unit Conversion" conversion auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::5703," "cs:EPSG::1030," "coordinateOperation:EPSG::7813", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 height (ft)"); EXPECT_EQ(crs->baseCRS()->getEPSGCode(), 5703); EXPECT_EQ(crs->coordinateSystem()->getEPSGCode(), 1030); EXPECT_EQ(crs->derivingConversion()->getEPSGCode(), 7813); } { // DerivedVerticalCRS based on "NAVD88 height", using a ftUS UP axis, // and EPSG:7813 "Vertical Axis Unit Conversion" conversion auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::5703," "cs:EPSG::6497," "coordinateOperation:EPSG::7813", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 height (ftUS)"); } { // DerivedVerticalCRS based on "NAVD88 height (ftUS)", using a metre UP // axis, and EPSG:7813 "Vertical Axis Unit Conversion" conversion auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::6360," "cs:EPSG::6499," "coordinateOperation:EPSG::7813", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 height"); } { // DerivedVerticalCRS based on "NAVD88 height", using a metre DOWN axis, // and EPSG:7812 "Height / Depth reversal" conversion auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::5703," "cs:EPSG::6498," "coordinateOperation:EPSG::7812", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 depth"); } { // DerivedVerticalCRS based on "NAVD88 height (ftUS)", using a ftUS DOWN // axis, and EPSG:7812 "Height / Depth reversal" conversion auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::6360," "cs:EPSG::1043," "coordinateOperation:EPSG::7812", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 depth (ftUS)"); } { // DerivedVerticalCRS based on "NAVD88 depth (ftUS)", using a ftUS UP // axis, and EPSG:7812 "Height / Depth reversal" conversion auto obj = createFromUserInput("urn:ogc:def:crs,crs:EPSG::6358," "cs:EPSG::6497," "coordinateOperation:EPSG::7812", dbContext); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NAVD88 height (ftUS)"); } { auto obj = createFromUserInput("urn:ogc:def:coordinateOperation," "coordinateOperation:EPSG::3895," "coordinateOperation:EPSG::1618", dbContext); auto concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(obj); ASSERT_TRUE(concat != nullptr); EXPECT_EQ(concat->nameStr(), "MGI (Ferro) to MGI (1) + MGI to WGS 84 (3)"); } EXPECT_NO_THROW(createFromUserInput( " \n\t\rGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"latitude\",north,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"longitude\",east,\n" " UNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height\",up,\n" " UNIT[\"metre\",1]],\n" " ID[\"EPSG\",4979]]", nullptr)); // Search names in the database EXPECT_THROW(createFromUserInput("foobar", dbContext), ParsingException); { // Official name auto obj = createFromUserInput("WGS 84", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); EXPECT_TRUE(crs != nullptr); } { // PROJ alias auto obj = createFromUserInput("WGS84", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); EXPECT_TRUE(crs != nullptr); } EXPECT_NO_THROW(createFromUserInput("UTM zone 31N", dbContext)); EXPECT_THROW(createFromUserInput("UTM zone 31", dbContext), ParsingException); EXPECT_NO_THROW(createFromUserInput("WGS84 UTM zone 31N", dbContext)); EXPECT_NO_THROW(createFromUserInput("ID74", dbContext)); { // Approximate match of a vertical CRS auto obj = createFromUserInput("NGF IGN69 height", dbContext); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); EXPECT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "NGF-IGN69 height"); } { // Exact match on each piece of the compound CRS auto obj = createFromUserInput("WGS 84 + EGM96 height", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 + EGM96 height"); } { // Approximate match on each piece of the compound CRS auto obj = createFromUserInput("WGS84 + NAVD88 height", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 + NAVD88 height"); } { // Exact match of a CompoundCRS object auto obj = createFromUserInput( "WGS 84 / World Mercator + EGM2008 height", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->identifiers().size(), 1U); } EXPECT_THROW(createFromUserInput("WGS 84 + foobar", dbContext), ParsingException); EXPECT_THROW(createFromUserInput("foobar + EGM96 height", dbContext), ParsingException); { auto obj = createFromUserInput("World Geodetic System 1984 ensemble", dbContext); auto ensemble = nn_dynamic_pointer_cast<DatumEnsemble>(obj); ASSERT_TRUE(ensemble != nullptr); EXPECT_EQ(ensemble->identifiers().size(), 1U); } // Check that "foo" doesn't match with "Amersfoort" EXPECT_THROW(createFromUserInput("foo", dbContext), ParsingException); // Check that "omerc" doesn't match with "WGS 84 / Pseudo-Mercator" EXPECT_THROW(createFromUserInput("omerc", dbContext), ParsingException); // Missing space, dash: OK EXPECT_NO_THROW(createFromUserInput("WGS84 PseudoMercator", dbContext)); // Invalid CoordinateMetadata EXPECT_THROW(createFromUserInput("@", dbContext), ParsingException); // Invalid CoordinateMetadata EXPECT_THROW(createFromUserInput("ITRF2014@", dbContext), ParsingException); // Invalid CoordinateMetadata EXPECT_THROW(createFromUserInput("ITRF2014@foo", dbContext), ParsingException); // Invalid CoordinateMetadata EXPECT_THROW(createFromUserInput("foo@2025", dbContext), ParsingException); // Invalid CoordinateMetadata EXPECT_THROW(createFromUserInput("@2025", dbContext), ParsingException); // Invalid CoordinateMetadata: static CRS not allowed EXPECT_THROW(createFromUserInput("RGF93@2025", dbContext), ParsingException); { auto obj = createFromUserInput("[email protected]", dbContext); auto coordinateMetadata = nn_dynamic_pointer_cast<CoordinateMetadata>(obj); ASSERT_TRUE(coordinateMetadata != nullptr); EXPECT_EQ(coordinateMetadata->coordinateEpochAsDecimalYear(), 2025.1); } { // Allow spaces before and after @ auto obj = createFromUserInput("ITRF2014 @ 2025.1", dbContext); auto coordinateMetadata = nn_dynamic_pointer_cast<CoordinateMetadata>(obj); ASSERT_TRUE(coordinateMetadata != nullptr); EXPECT_EQ(coordinateMetadata->coordinateEpochAsDecimalYear(), 2025.1); } { auto obj = createFromUserInput("EPSG:9000 @ 2025.1", dbContext); auto coordinateMetadata = nn_dynamic_pointer_cast<CoordinateMetadata>(obj); ASSERT_TRUE(coordinateMetadata != nullptr); EXPECT_EQ(coordinateMetadata->coordinateEpochAsDecimalYear(), 2025.1); } } // --------------------------------------------------------------------------- TEST(io, createFromUserInput_ogc_crs_url) { auto dbContext = DatabaseContext::create(); { auto obj = createFromUserInput( "http://www.opengis.net/def/crs/EPSG/0/4326", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); } { auto obj = createFromUserInput( "http://www.opengis.net/def/crs/IAU/2015/49900", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); } { // Not sure if this is intended to be valid (version=0), but let's // imitate the logic of EPSG, this will use the latest version of IAU // (if/when there will be several of them) auto obj = createFromUserInput( "http://www.opengis.net/def/crs/IAU/0/49900", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); } EXPECT_THROW( createFromUserInput("http://www.opengis.net/def/crs", dbContext), ParsingException); EXPECT_THROW( createFromUserInput("http://www.opengis.net/def/crs/EPSG/0", dbContext), ParsingException); EXPECT_THROW(createFromUserInput( "http://www.opengis.net/def/crs/EPSG/0/XXXX", dbContext), NoSuchAuthorityCodeException); EXPECT_THROW( createFromUserInput("http://www.opengis.net/def/crs/IAU/2015/invalid", dbContext), NoSuchAuthorityCodeException); { auto obj = createFromUserInput( "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/" "def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/3855", dbContext); auto crs = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->nameStr(), "WGS 84 + EGM2008 height"); } // No part EXPECT_THROW(createFromUserInput("http://www.opengis.net/def/crs-compound?", dbContext), ParsingException); // Just one part EXPECT_THROW( createFromUserInput("http://www.opengis.net/def/crs-compound?1=http://" "www.opengis.net/def/crs/EPSG/0/4326", dbContext), InvalidCompoundCRSException); // Invalid compound CRS EXPECT_THROW( createFromUserInput( "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/" "def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/4326", dbContext), InvalidCompoundCRSException); // Missing 2= EXPECT_THROW( createFromUserInput( "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/" "def/crs/EPSG/0/4326&3=http://www.opengis.net/def/crs/EPSG/0/3855", dbContext), ParsingException); // Invalid query parameter EXPECT_THROW( createFromUserInput("http://www.opengis.net/def/crs-compound?1=http://" "www.opengis.net/def/crs/EPSG/0/4326&bla", dbContext), ParsingException); // Invalid query parameter EXPECT_THROW( createFromUserInput("http://www.opengis.net/def/crs-compound?1=http://" "www.opengis.net/def/crs/EPSG/0/4326&two=http://" "www.opengis.net/def/crs/EPSG/0/3855", dbContext), ParsingException); } // --------------------------------------------------------------------------- TEST(io, createFromUserInput_OGC_AUTO) { // UTM north { auto obj = createFromUserInput("AUTO:42001,-117,33", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "UTM zone 11N"); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs +type=crs"); } // UTM south { auto obj = createFromUserInput("AUTO:42001,-117,-33", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "UTM zone 11S"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=11 +south +datum=WGS84 +units=m +no_defs " "+type=crs"); } // Explicit unit: metre { auto obj = createFromUserInput("AUTO:42001,9001,-117,33", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "UTM zone 11N"); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs +type=crs"); } // Explicit unit: foot { auto obj = createFromUserInput("AUTO:42001,9002,-117,33", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "UTM zone 11N"); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=11 +datum=WGS84 +units=ft +no_defs +type=crs"); } // Explicit unit: US survery foot { auto obj = createFromUserInput("AUTO:42001,9003,-117,33", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "UTM zone 11N"); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=11 +datum=WGS84 +units=us-ft +no_defs +type=crs"); } // Explicit unit: invalid EXPECT_THROW(createFromUserInput("AUTO:42001,0,-117,33", nullptr), ParsingException); // Invalid longitude EXPECT_THROW(createFromUserInput("AUTO:42001,-180.01,33", nullptr), ParsingException); EXPECT_NO_THROW(createFromUserInput("AUTO:42001,-180,33", nullptr)); EXPECT_THROW(createFromUserInput("AUTO:42001,180,33", nullptr), ParsingException); EXPECT_NO_THROW(createFromUserInput("AUTO:42001,179.999,33", nullptr)); // Too short EXPECT_THROW(createFromUserInput("AUTO:42001", nullptr), ParsingException); // TMerc / north { auto obj = createFromUserInput("AUTO:42002,1,2", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "Transverse Mercator"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=tmerc +lat_0=0 +lon_0=1 +k=0.9996 +x_0=500000 +y_0=0 " "+datum=WGS84 +units=m +no_defs +type=crs"); } // TMerc / south { auto obj = createFromUserInput("AUTO:42002,1,-2", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->derivingConversion()->nameStr(), "Transverse Mercator"); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=tmerc +lat_0=0 +lon_0=1 +k=0.9996 +x_0=500000 " "+y_0=10000000 +datum=WGS84 +units=m +no_defs +type=crs"); } // Orthographic { auto obj = createFromUserInput("AUTO:42003,1,2", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=ortho +lat_0=2 +lon_0=1 +x_0=0 +y_0=0 +datum=WGS84 " "+units=m +no_defs +type=crs"); } // Equirectangular { auto obj = createFromUserInput("AUTO:42004,1,0", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=1 +x_0=0 +y_0=0 " "+datum=WGS84 +units=m +no_defs +type=crs"); } // Mollweide { auto obj = createFromUserInput("AUTO:42005,1", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=moll +lon_0=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m " "+no_defs +type=crs"); } // Mollweide with explicit unit { auto obj = createFromUserInput("AUTO:42005,9001,1", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=moll +lon_0=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m " "+no_defs +type=crs"); } // Invalid method id EXPECT_THROW(createFromUserInput("AUTO:42999,1,0", nullptr), ParsingException); // As urn:ogc:def:crs:OGC::AUTOxxxx:.... { auto obj = createFromUserInput("urn:ogc:def:crs:OGC::AUTO42001:-117:33", nullptr); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs +type=crs"); } } // --------------------------------------------------------------------------- TEST(io, createFromUserInput_hack_EPSG_102100) { auto dbContext = DatabaseContext::create(); auto obj = createFromUserInput("EPSG:102100", dbContext); auto crs = nn_dynamic_pointer_cast<CRS>(obj); ASSERT_TRUE(crs != nullptr); const auto &ids = crs->identifiers(); ASSERT_EQ(ids.size(), 1U); // we do not lie on the real authority EXPECT_EQ(*ids[0]->codeSpace(), "ESRI"); EXPECT_EQ(ids[0]->code(), "102100"); } // --------------------------------------------------------------------------- TEST(io, guessDialect) { EXPECT_EQ(WKTParser().guessDialect("LOCAL_CS[\"foo\"]"), WKTParser::WKTGuessedDialect::WKT1_GDAL); EXPECT_EQ(WKTParser().guessDialect( "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_" "1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"), WKTParser::WKTGuessedDialect::WKT1_ESRI); EXPECT_EQ(WKTParser().guessDialect( "GEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north],\n" " AXIS[\"geodetic longitude (Lon)\",east],\n" " UNIT[\"degree\",0.0174532925199433]]"), WKTParser::WKTGuessedDialect::WKT2_2019); EXPECT_EQ( WKTParser().guessDialect("TIMECRS[\"Temporal CRS\",\n" " TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]],\n" " CS[TemporalDateTime,1],\n" " AXIS[\"time (T)\",future]]"), WKTParser::WKTGuessedDialect::WKT2_2019); EXPECT_EQ(WKTParser().guessDialect( "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north],\n" " AXIS[\"geodetic longitude (Lon)\",east],\n" " UNIT[\"degree\",0.0174532925199433]]"), WKTParser::WKTGuessedDialect::WKT2_2015); EXPECT_EQ(WKTParser().guessDialect("foo"), WKTParser::WKTGuessedDialect::NOT_WKT); EXPECT_EQ(WKTParser().guessDialect("ID74"), WKTParser::WKTGuessedDialect::NOT_WKT); } // --------------------------------------------------------------------------- // GDAL MITAB driver requires on rather excessive precision on parameter // values to implement a nasty trick... TEST(wkt_export, precision) { auto wkt = "PROJCS[\"RGF93 / Lambert-93\",\n" " GEOGCS[\"RGF93\",\n" " DATUM[\"Reseau_Geodesique_Francais_1993\",\n" " SPHEROID[\"GRS 80\",6378137,298.257222101],\n" " AUTHORITY[\"EPSG\",\"6171\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Lambert_Conformal_Conic_2SP\"],\n" " PARAMETER[\"standard_parallel_1\",49.00000000001],\n" " PARAMETER[\"standard_parallel_2\",44],\n" " PARAMETER[\"latitude_of_origin\",46.5],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"false_easting\",700000],\n" " PARAMETER[\"false_northing\",6600000],\n" " UNIT[\"Meter\",1],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), wkt); } // --------------------------------------------------------------------------- // Avoid division by zero TEST(wkt_export, invalid_linear_unit) { auto wkt = "PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"foo\",0]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- // Avoid division by zero TEST(wkt_export, invalid_angular_unit) { auto wkt = "PROJCS[\"WGS 84 / UTM zone 31N\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"foo\",0]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",0],\n" " PARAMETER[\"central_meridian\",3],\n" " PARAMETER[\"scale_factor\",0.9996],\n" " PARAMETER[\"false_easting\",500000],\n" " PARAMETER[\"false_northing\",0],\n" " UNIT[\"meter\",1]]"; auto obj = WKTParser().createFromWKT(wkt); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_THROW( crs->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()), FormattingException); } // --------------------------------------------------------------------------- TEST(json_import, ellipsoid_flattened_sphere) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7030\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto ellps = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellps != nullptr); EXPECT_EQ(ellps->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, ellipsoid_major_minor_custom_unit) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"foo\",\n" " \"semi_major_axis\": 6378137,\n" " \"semi_minor_axis\": {\n" " \"value\": 6370000,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"my_unit\",\n" " \"conversion_factor\": 2\n" " }\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto ellps = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellps != nullptr); EXPECT_EQ(ellps->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, ellipsoid_sphere) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"Sphere\",\n" " \"radius\": 6371000,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7035\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto ellps = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellps != nullptr); EXPECT_EQ(ellps->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, ellipsoid_errors) { EXPECT_THROW(createFromUserInput("{", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("{}", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("{ \"type\": \"Ellipsoid\" }", nullptr), ParsingException); EXPECT_THROW(createFromUserInput( "{ \"type\": \"Ellipsoid\", \"name\": \"foo\" }", nullptr), ParsingException); EXPECT_THROW( createFromUserInput( "{ \"type\": \"Ellipsoid\", \"name\": \"foo\", \"radius\": null }", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("{ \"type\": \"Ellipsoid\", \"name\": " "\"foo\", \"semi_major_axis\": 1 }", nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, axis_with_meridian) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Axis\",\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"south\",\n" " \"meridian\": {\n" " \"longitude\": 180\n" " },\n" " \"unit\": \"metre\"\n" "}"; auto obj = createFromUserInput(json, nullptr); auto axis = nn_dynamic_pointer_cast<CoordinateSystemAxis>(obj); ASSERT_TRUE(axis != nullptr); EXPECT_EQ(axis->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, axis_with_meridian_with_unit) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Axis\",\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"south\",\n" " \"meridian\": {\n" " \"longitude\": {\n" " \"value\": 200,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"grad\",\n" " \"conversion_factor\": 0.0157079632679489\n" " }\n" " }\n" " },\n" " \"unit\": \"metre\"\n" "}"; auto obj = createFromUserInput(json, nullptr); auto axis = nn_dynamic_pointer_cast<CoordinateSystemAxis>(obj); ASSERT_TRUE(axis != nullptr); EXPECT_EQ(axis->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, axis_with_minimum_value_maximum_value_range_meaning) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Axis\",\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\",\n" " \"minimum_value\": 0,\n" " \"maximum_value\": 360,\n" " \"range_meaning\": \"wraparound\"\n" "}"; auto obj = createFromUserInput(json, nullptr); auto axis = nn_dynamic_pointer_cast<CoordinateSystemAxis>(obj); ASSERT_TRUE(axis != nullptr); EXPECT_EQ(axis->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, axis_with_invalid_minimum_value) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Axis\",\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\",\n" " \"minimum_value\": \"invalid\"\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, axis_with_invalid_maximum_value) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Axis\",\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\",\n" " \"maximum_value\": \"invalid\"\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, axis_with_invalid_range_meaning_str) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Axis\",\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\",\n" " \"range_meaning\": \"invalid\"\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, axis_with_invalid_range_meaning_number) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Axis\",\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\",\n" " \"range_meaning\": 1\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, prime_meridian) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"PrimeMeridian\",\n" " \"name\": \"Paris\",\n" " \"longitude\": {\n" " \"value\": 2.5969213,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"grad\",\n" " \"conversion_factor\": 0.0157079632679489\n" " }\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto pm = nn_dynamic_pointer_cast<PrimeMeridian>(obj); ASSERT_TRUE(pm != nullptr); EXPECT_EQ(pm->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, prime_meridian_errors) { EXPECT_THROW(createFromUserInput("{ \"type\": \"PrimeMeridian\", \"name\": " "\"foo\" }", nullptr), ParsingException); EXPECT_THROW(createFromUserInput("{ \"type\": \"PrimeMeridian\", \"name\": " "\"foo\", \"longitude\": null }", nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, geodetic_reference_frame_with_implicit_prime_meridian) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto grf = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(grf != nullptr); EXPECT_EQ(grf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geodetic_reference_frame_with_explicit_prime_meridian) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Nouvelle Triangulation Francaise (Paris)\",\n" " \"ellipsoid\": {\n" " \"name\": \"Clarke 1880 (IGN)\",\n" " \"semi_major_axis\": 6378249.2,\n" " \"semi_minor_axis\": 6356515\n" " },\n" " \"prime_meridian\": {\n" " \"name\": \"Paris\",\n" " \"longitude\": {\n" " \"value\": 2.5969213,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"grad\",\n" " \"conversion_factor\": 0.0157079632679489\n" " }\n" " }\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto grf = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(grf != nullptr); EXPECT_EQ(grf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geodetic_reference_frame_with_anchor_epoch) { // Use dummy anchor_epoch = 0 to avoid fp issues on some architectures // (cf https://github.com/OSGeo/PROJ/issues/3632) auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"my_name\",\n" " \"anchor_epoch\": 0,\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto grf = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(grf != nullptr); EXPECT_EQ(grf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geodetic_reference_frame_with_invalid_anchor_epoch) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"my_name\",\n" " \"anchor_epoch\": \"invalid\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, dynamic_geodetic_reference_frame_with_implicit_prime_meridian) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DynamicGeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"frame_reference_epoch\": 1,\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto dgrf = nn_dynamic_pointer_cast<DynamicGeodeticReferenceFrame>(obj); ASSERT_TRUE(dgrf != nullptr); EXPECT_EQ(dgrf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_extent) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"vertical_extent\": {\n" " \"minimum\": -1000,\n" " \"maximum\": 0\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gdrf = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(gdrf != nullptr); EXPECT_EQ(gdrf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_extent_with_unit) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"vertical_extent\": {\n" " \"minimum\": -1000,\n" " \"maximum\": 0,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"my_metre\",\n" " \"conversion_factor\": 1\n" " }\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gdrf = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(gdrf != nullptr); EXPECT_EQ(gdrf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, temporal_extent) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"temporal_extent\": {\n" " \"start\": \"my start\",\n" " \"end\": \"my end\"\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gdrf = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(gdrf != nullptr); EXPECT_EQ(gdrf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geodetic_reference_frame_errors) { EXPECT_THROW( createFromUserInput( "{ \"type\": \"GeodeticReferenceFrame\", \"name\": \"foo\" }", nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, dynamic_vertical_reference_frame) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DynamicVerticalReferenceFrame\",\n" " \"name\": \"bar\",\n" " \"frame_reference_epoch\": 1\n" "}"; auto obj = createFromUserInput(json, nullptr); auto dvrf = nn_dynamic_pointer_cast<DynamicVerticalReferenceFrame>(obj); ASSERT_TRUE(dvrf != nullptr); EXPECT_EQ(dvrf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, several_usages) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"usages\": [\n" " {\n" " \"area\": \"World\",\n" " \"bbox\": {\n" " \"south_latitude\": -90,\n" " \"west_longitude\": -180,\n" " \"north_latitude\": 90,\n" " \"east_longitude\": 180\n" " }\n" " },\n" " {\n" " \"scope\": \"my_scope\",\n" " \"area\": \"my_area\"\n" " }\n" " ]\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gdr = nn_dynamic_pointer_cast<GeodeticReferenceFrame>(obj); ASSERT_TRUE(gdr != nullptr); EXPECT_EQ(gdr->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geographic_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"area\": \"World\",\n" " \"bbox\": {\n" " \"south_latitude\": -90,\n" " \"west_longitude\": -180,\n" " \"north_latitude\": 90,\n" " \"east_longitude\": 180\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4326\n" " },\n" " \"remarks\": \"my_remarks\"\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(gcrs != nullptr); EXPECT_EQ(gcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geographic_crs_with_deformation_models) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"test\",\n" " \"datum\": {\n" " \"type\": \"DynamicGeodeticReferenceFrame\",\n" " \"name\": \"test\",\n" " \"frame_reference_epoch\": 2005,\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"deformation_models\": [\n" " {\n" " \"name\": \"my_model\"\n" " }\n" " ]\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(gcrs != nullptr); EXPECT_EQ(gcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, spherical_planetocentric) { const auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticCRS\",\n" " \"name\": \"Mercury (2015) / Ocentric\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Mercury (2015)\",\n" " \"anchor\": \"Hun Kal: 20.0\",\n" " \"ellipsoid\": {\n" " \"name\": \"Mercury (2015)\",\n" " \"semi_major_axis\": 2440530,\n" " \"inverse_flattening\": 1075.12334801762\n" " },\n" " \"prime_meridian\": {\n" " \"name\": \"Reference Meridian\",\n" " \"longitude\": 0\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"spherical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Planetocentric latitude\",\n" " \"abbreviation\": \"U\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Planetocentric longitude\",\n" " \"abbreviation\": \"V\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"IAU\",\n" " \"code\": 19902\n" " },\n" " \"remarks\": \"Source of IAU Coordinate systems: " "doi://10.1007/s10569-017-9805-5\"\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gcrs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(gcrs != nullptr); EXPECT_TRUE(gcrs->isSphericalPlanetocentric()); EXPECT_EQ(gcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geographic_crs_errors) { EXPECT_THROW( createFromUserInput( "{ \"type\": \"GeographicCRS\", \"name\": \"foo\" }", nullptr), ParsingException); EXPECT_THROW( createFromUserInput("{\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " }\n" "}", nullptr), ParsingException); EXPECT_THROW( createFromUserInput("{\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}", nullptr), ParsingException); } // --------------------------------------------------------------------------- TEST(json_import, geocentric_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeodeticCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geocentric X\",\n" " \"abbreviation\": \"X\",\n" " \"direction\": \"geocentricX\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Geocentric Y\",\n" " \"abbreviation\": \"Y\",\n" " \"direction\": \"geocentricY\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Geocentric Z\",\n" " \"abbreviation\": \"Z\",\n" " \"direction\": \"geocentricZ\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto gdcrs = nn_dynamic_pointer_cast<GeodeticCRS>(obj); ASSERT_TRUE(gdcrs != nullptr); EXPECT_EQ(gdcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, projected_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"ProjectedCRS\",\n" " \"name\": \"WGS 84 / UTM zone 31N\",\n" " \"base_crs\": {\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4326\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"UTM zone 31N\",\n" " \"method\": {\n" " \"name\": \"Transverse Mercator\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9807\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude of natural origin\",\n" " \"value\": 0,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8801\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude of natural origin\",\n" " \"value\": 3,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8802\n" " }\n" " },\n" " {\n" " \"name\": \"Scale factor at natural origin\",\n" " \"value\": 0.9996,\n" " \"unit\": \"unity\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8805\n" " }\n" " },\n" " {\n" " \"name\": \"False easting\",\n" " \"value\": 500000,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8806\n" " }\n" " },\n" " {\n" " \"name\": \"False northing\",\n" " \"value\": 0,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8807\n" " }\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto pcrs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(pcrs != nullptr); EXPECT_EQ(pcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, projected_crs_with_geocentric_base) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"ProjectedCRS\",\n" " \"name\": \"EPSG topocentric example B\",\n" " \"base_crs\": {\n" " \"name\": \"WGS 84\",\n" " \"datum_ensemble\": {\n" " \"name\": \"World Geodetic System 1984 ensemble\",\n" " \"members\": [\n" " {\n" " \"name\": \"World Geodetic System 1984 (Transit)\"\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G730)\"\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G873)\"\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1150)\"\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1674)\"\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1762)\"\n" " }\n" " ],\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"accuracy\": \"2.0\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geocentric X\",\n" " \"abbreviation\": \"X\",\n" " \"direction\": \"geocentricX\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Geocentric Y\",\n" " \"abbreviation\": \"Y\",\n" " \"direction\": \"geocentricY\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Geocentric Z\",\n" " \"abbreviation\": \"Z\",\n" " \"direction\": \"geocentricZ\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4978\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"EPSG topocentric example B\",\n" " \"method\": {\n" " \"name\": \"Geocentric/topocentric conversions\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9836\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Geocentric X of topocentric origin\",\n" " \"value\": 3771793.97,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8837\n" " }\n" " },\n" " {\n" " \"name\": \"Geocentric Y of topocentric origin\",\n" " \"value\": 140253.34,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8838\n" " }\n" " },\n" " {\n" " \"name\": \"Geocentric Z of topocentric origin\",\n" " \"value\": 5124304.35,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8839\n" " }\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Topocentric East\",\n" " \"abbreviation\": \"U\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Topocentric North\",\n" " \"abbreviation\": \"V\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Topocentric height\",\n" " \"abbreviation\": \"W\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"scope\": \"Example only (fictitious).\",\n" " \"area\": \"Description of the extent of the CRS.\",\n" " \"bbox\": {\n" " \"south_latitude\": -90,\n" " \"west_longitude\": -180,\n" " \"north_latitude\": 90,\n" " \"east_longitude\": 180\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 5820\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto pcrs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(pcrs != nullptr); EXPECT_TRUE(pcrs->baseCRS()->isGeocentric()); EXPECT_EQ(pcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, compound_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"CompoundCRS\",\n" " \"name\": \"WGS 84 + EGM2008 height\",\n" " \"components\": [\n" " {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4326\n" " }\n" " },\n" " {\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"EGM2008 height\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"EGM2008 geoid\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 3855\n" " }\n" " }\n" " ]\n" "}"; auto obj = createFromUserInput(json, nullptr); auto compoundCRS = nn_dynamic_pointer_cast<CompoundCRS>(obj); ASSERT_TRUE(compoundCRS != nullptr); EXPECT_EQ( compoundCRS->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, bound_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"BoundCRS\",\n" " \"source_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"unknown\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Unknown based on GRS80 ellipsoid\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7019\n" " }\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" " },\n" " \"target_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4326\n" " }\n" " },\n" " \"transformation\": {\n" " \"name\": \"unknown to WGS84\",\n" " \"method\": {\n" " \"name\": \"NTv2\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9615\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude and longitude difference file\",\n" " \"value\": \"@foo\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8656\n" " }\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ( boundCRS->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, bound_crs_with_name_and_usage) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"BoundCRS\",\n" " \"name\": \"my bound crs\",\n" " \"source_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"unknown\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Unknown based on GRS80 ellipsoid\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7019\n" " }\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" " },\n" " \"target_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4326\n" " }\n" " },\n" " \"transformation\": {\n" " \"name\": \"unknown to WGS84\",\n" " \"method\": {\n" " \"name\": \"NTv2\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9615\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude and longitude difference file\",\n" " \"value\": \"@foo\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8656\n" " }\n" " }\n" " ]\n" " },\n" " \"scope\": \"Example only (fictitious).\",\n" " \"area\": \"Description of the extent of the CRS.\",\n" " \"bbox\": {\n" " \"south_latitude\": -90,\n" " \"west_longitude\": -180,\n" " \"north_latitude\": 90,\n" " \"east_longitude\": 180\n" " },\n" " \"id\": {\n" " \"authority\": \"foo\",\n" " \"code\": 1234\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ( boundCRS->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, bound_crs_with_source_crs_in_transformation) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"BoundCRS\",\n" " \"source_crs\": {\n" " \"type\": \"DerivedGeographicCRS\",\n" " \"name\": \"CH1903+ with height offset\",\n" " \"base_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"CH1903+\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"CH1903+\",\n" " \"ellipsoid\": {\n" " \"name\": \"Bessel 1841\",\n" " \"semi_major_axis\": 6377397.155,\n" " \"inverse_flattening\": 299.1528128\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"Ellipsoidal to gravity related height\",\n" " \"method\": {\n" " \"name\": \"Geographic3D offsets\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9660\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude offset\",\n" " \"value\": 0,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8601\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude offset\",\n" " \"value\": 0,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8602\n" " }\n" " },\n" " {\n" " \"name\": \"Vertical Offset\",\n" " \"value\": 10,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8603\n" " }\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"target_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum_ensemble\": {\n" " \"name\": \"World Geodetic System 1984 ensemble\",\n" " \"members\": [\n" " {\n" " \"name\": \"World Geodetic System 1984 (Transit)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1166\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G730)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1152\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G873)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1153\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1150)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1154\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1674)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1155\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G1762)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1156\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G2139)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1309\n" " }\n" " }\n" " ],\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"accuracy\": \"2.0\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4979\n" " }\n" " },\n" " \"transformation\": {\n" " \"name\": \"CH1903+ to WGS 84 (1)\",\n" " \"source_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"CH1903+\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"CH1903+\",\n" " \"ellipsoid\": {\n" " \"name\": \"Bessel 1841\",\n" " \"semi_major_axis\": 6377397.155,\n" " \"inverse_flattening\": 299.1528128\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"method\": {\n" " \"name\": \"Geocentric translations (geog2D domain)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9603\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"X-axis translation\",\n" " \"value\": 674.374,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8605\n" " }\n" " },\n" " {\n" " \"name\": \"Y-axis translation\",\n" " \"value\": 15.056,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8606\n" " }\n" " },\n" " {\n" " \"name\": \"Z-axis translation\",\n" " \"value\": 405.346,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8607\n" " }\n" " }\n" " ],\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1676\n" " }\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto boundCRS = nn_dynamic_pointer_cast<BoundCRS>(obj); ASSERT_TRUE(boundCRS != nullptr); EXPECT_EQ( boundCRS->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, transformation) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Transformation\",\n" " \"name\": \"GDA94 to GDA2020 (1)\",\n" " \"source_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"GDA94\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Geocentric Datum of Australia 1994\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" " },\n" " \"target_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"GDA2020\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Geocentric Datum of Australia 2020\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" " },\n" " \"method\": {\n" " \"name\": \"Coordinate Frame rotation (geog2D domain)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9607\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"X-axis translation\",\n" " \"value\": 61.55,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"millimetre\",\n" " \"conversion_factor\": 0.001\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8605\n" " }\n" " },\n" " {\n" " \"name\": \"Y-axis translation\",\n" " \"value\": -10.87,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"millimetre\",\n" " \"conversion_factor\": 0.001\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8606\n" " }\n" " },\n" " {\n" " \"name\": \"Z-axis translation\",\n" " \"value\": -40.19,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"millimetre\",\n" " \"conversion_factor\": 0.001\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8607\n" " }\n" " },\n" " {\n" " \"name\": \"X-axis rotation\",\n" " \"value\": -39.4924,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"milliarc-second\",\n" " \"conversion_factor\": 4.84813681109536e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8608\n" " }\n" " },\n" " {\n" " \"name\": \"Y-axis rotation\",\n" " \"value\": -32.7221,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"milliarc-second\",\n" " \"conversion_factor\": 4.84813681109536e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8609\n" " }\n" " },\n" " {\n" " \"name\": \"Z-axis rotation\",\n" " \"value\": -32.8979,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"milliarc-second\",\n" " \"conversion_factor\": 4.84813681109536e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8610\n" " }\n" " },\n" " {\n" " \"name\": \"Scale difference\",\n" " \"value\": -9.994,\n" " \"unit\": {\n" " \"type\": \"ScaleUnit\",\n" " \"name\": \"parts per billion\",\n" " \"conversion_factor\": 1e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8611\n" " }\n" " }\n" " ],\n" " \"accuracy\": \"0.01\",\n" " \"scope\": \"scope\",\n" " \"area\": \"Australia - GDA\",\n" " \"bbox\": {\n" " \"south_latitude\": -60.56,\n" " \"west_longitude\": 93.41,\n" " \"north_latitude\": -8.47,\n" " \"east_longitude\": 173.35\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8048\n" " },\n" " \"remarks\": \"foo\"\n" "}"; auto obj = createFromUserInput(json, nullptr); auto transf = nn_dynamic_pointer_cast<Transformation>(obj); ASSERT_TRUE(transf != nullptr); EXPECT_EQ( transf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, concatenated_operation) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"ConcatenatedOperation\",\n" " \"name\": \"Inverse of Vicgrid + GDA94 to GDA2020 (1)\",\n" " \"source_crs\": {\n" " \"type\": \"ProjectedCRS\",\n" " \"name\": \"GDA94 / Vicgrid\",\n" " \"base_crs\": {\n" " \"name\": \"GDA94\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Geocentric Datum of Australia 1994\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4283\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"Vicgrid\",\n" " \"method\": {\n" " \"name\": \"Lambert Conic Conformal (2SP)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9802\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude of false origin\",\n" " \"value\": -37,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8821\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude of false origin\",\n" " \"value\": 145,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8822\n" " }\n" " },\n" " {\n" " \"name\": \"Latitude of 1st standard parallel\",\n" " \"value\": -36,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8823\n" " }\n" " },\n" " {\n" " \"name\": \"Latitude of 2nd standard parallel\",\n" " \"value\": -38,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8824\n" " }\n" " },\n" " {\n" " \"name\": \"Easting at false origin\",\n" " \"value\": 2500000,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8826\n" " }\n" " },\n" " {\n" " \"name\": \"Northing at false origin\",\n" " \"value\": 2500000,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8827\n" " }\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 3111\n" " }\n" " },\n" " \"target_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"GDA2020\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Geocentric Datum of Australia 2020\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7844\n" " }\n" " },\n" " \"steps\": [\n" " {\n" " \"type\": \"Conversion\",\n" " \"name\": \"Inverse of Vicgrid\",\n" " \"method\": {\n" " \"name\": \"Inverse of Lambert Conic Conformal (2SP)\",\n" " \"id\": {\n" " \"authority\": \"INVERSE(EPSG)\",\n" " \"code\": 9802\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude of false origin\",\n" " \"value\": -37,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8821\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude of false origin\",\n" " \"value\": 145,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8822\n" " }\n" " },\n" " {\n" " \"name\": \"Latitude of 1st standard parallel\",\n" " \"value\": -36,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8823\n" " }\n" " },\n" " {\n" " \"name\": \"Latitude of 2nd standard parallel\",\n" " \"value\": -38,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8824\n" " }\n" " },\n" " {\n" " \"name\": \"Easting at false origin\",\n" " \"value\": 2500000,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8826\n" " }\n" " },\n" " {\n" " \"name\": \"Northing at false origin\",\n" " \"value\": 2500000,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8827\n" " }\n" " }\n" " ],\n" " \"id\": {\n" " \"authority\": \"INVERSE(EPSG)\",\n" " \"code\": 17361\n" " }\n" " },\n" " {\n" " \"type\": \"Transformation\",\n" " \"name\": \"GDA94 to GDA2020 (1)\",\n" " \"source_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"GDA94\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Geocentric Datum of Australia 1994\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4283\n" " }\n" " },\n" " \"target_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"GDA2020\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"Geocentric Datum of Australia 2020\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7844\n" " }\n" " },\n" " \"method\": {\n" " \"name\": \"Coordinate Frame rotation (geog2D domain)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9607\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"X-axis translation\",\n" " \"value\": 61.55,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"millimetre\",\n" " \"conversion_factor\": 0.001\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8605\n" " }\n" " },\n" " {\n" " \"name\": \"Y-axis translation\",\n" " \"value\": -10.87,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"millimetre\",\n" " \"conversion_factor\": 0.001\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8606\n" " }\n" " },\n" " {\n" " \"name\": \"Z-axis translation\",\n" " \"value\": -40.19,\n" " \"unit\": {\n" " \"type\": \"LinearUnit\",\n" " \"name\": \"millimetre\",\n" " \"conversion_factor\": 0.001\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8607\n" " }\n" " },\n" " {\n" " \"name\": \"X-axis rotation\",\n" " \"value\": -39.4924,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"milliarc-second\",\n" " \"conversion_factor\": 4.84813681109536e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8608\n" " }\n" " },\n" " {\n" " \"name\": \"Y-axis rotation\",\n" " \"value\": -32.7221,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"milliarc-second\",\n" " \"conversion_factor\": 4.84813681109536e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8609\n" " }\n" " },\n" " {\n" " \"name\": \"Z-axis rotation\",\n" " \"value\": -32.8979,\n" " \"unit\": {\n" " \"type\": \"AngularUnit\",\n" " \"name\": \"milliarc-second\",\n" " \"conversion_factor\": 4.84813681109536e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8610\n" " }\n" " },\n" " {\n" " \"name\": \"Scale difference\",\n" " \"value\": -9.994,\n" " \"unit\": {\n" " \"type\": \"ScaleUnit\",\n" " \"name\": \"parts per billion\",\n" " \"conversion_factor\": 1e-09\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8611\n" " }\n" " }\n" " ],\n" " \"accuracy\": \"0.01\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8048\n" " },\n" " \"remarks\": \"remarks\"\n" " }\n" " ],\n" " \"accuracy\": \"0.02\",\n" " \"area\": \"Australia - GDA\",\n" " \"bbox\": {\n" " \"south_latitude\": -60.56,\n" " \"west_longitude\": 93.41,\n" " \"north_latitude\": -8.47,\n" " \"east_longitude\": 173.35\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto concat = nn_dynamic_pointer_cast<ConcatenatedOperation>(obj); ASSERT_TRUE(concat != nullptr); EXPECT_EQ( concat->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, geographic_crs_with_datum_ensemble) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum_ensemble\": {\n" " \"name\": \"WGS 84 ensemble\",\n" " \"members\": [\n" " {\n" " \"name\": \"World Geodetic System 1984 (Transit)\"\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G730)\"\n" " },\n" " {\n" " \"name\": \"Some unknown ensemble with unknown id\",\n" " \"id\": {\n" " \"authority\": \"UNKNOWN\",\n" " \"code\": 1234\n" " }\n" " }\n" " ],\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " },\n" " \"accuracy\": \"2\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" "}"; auto expected_json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum_ensemble\": {\n" " \"name\": \"WGS 84 ensemble\",\n" " \"members\": [\n" " {\n" " \"name\": \"World Geodetic System 1984 (Transit)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1166\n" " }\n" " },\n" " {\n" " \"name\": \"World Geodetic System 1984 (G730)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1152\n" " }\n" " },\n" " {\n" " \"name\": \"Some unknown ensemble with unknown id\",\n" " \"id\": {\n" " \"authority\": \"UNKNOWN\",\n" " \"code\": 1234\n" " }\n" " }\n" " ],\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7030\n" " }\n" " },\n" " \"accuracy\": \"2\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" "}"; { // No database auto obj = createFromUserInput(json, nullptr); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(gcrs != nullptr); EXPECT_EQ( gcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } { auto obj = createFromUserInput(json, DatabaseContext::create()); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(gcrs != nullptr); EXPECT_EQ( gcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), expected_json); } { auto obj = createFromUserInput(expected_json, DatabaseContext::create()); auto gcrs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(gcrs != nullptr); EXPECT_EQ( gcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), expected_json); } } // --------------------------------------------------------------------------- TEST(json_import, datum_ensemble_without_ellipsoid) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DatumEnsemble\",\n" " \"name\": \"ensemble\",\n" " \"members\": [\n" " {\n" " \"name\": \"member1\"\n" " },\n" " {\n" " \"name\": \"member2\"\n" " }\n" " ],\n" " \"accuracy\": \"2\"\n" "}"; // No database auto obj = createFromUserInput(json, nullptr); auto ensemble = nn_dynamic_pointer_cast<DatumEnsemble>(obj); ASSERT_TRUE(ensemble != nullptr); EXPECT_EQ( ensemble->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"EGM2008 height\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"EGM2008 geoid\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); auto datum = crs->datum(); auto datum_json = datum->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))); auto datum_obj = createFromUserInput(datum_json, nullptr); auto datum_got = nn_dynamic_pointer_cast<VerticalReferenceFrame>(datum_obj); ASSERT_TRUE(datum_got != nullptr); } // --------------------------------------------------------------------------- TEST(json_import, vertical_crs_with_datum_ensemble) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"foo\",\n" " \"datum_ensemble\": {\n" " \"name\": \"ensemble\",\n" " \"members\": [\n" " {\n" " \"name\": \"member1\"\n" " },\n" " {\n" " \"name\": \"member2\"\n" " }\n" " ],\n" " \"accuracy\": \"2\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; // No database auto obj = createFromUserInput(json, nullptr); auto vcrs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(vcrs != nullptr); EXPECT_EQ(vcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_crs_with_geoid_model) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"CGVD2013\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"Canadian Geodetic Vertical Datum of 2013\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"geoid_model\": {\n" " \"name\": \"CGG2013\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 6648\n" " }\n" " }\n" "}"; // No database auto obj = createFromUserInput(json, nullptr); auto vcrs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(vcrs != nullptr); EXPECT_EQ(vcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_crs_with_geoid_models) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"CGVD2013\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"Canadian Geodetic Vertical Datum of 2013\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"geoid_models\": [\n" " {\n" " \"name\": \"CGG2013\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 6648\n" " }\n" " },\n" " {\n" " \"name\": \"other\"\n" " }\n" " ]\n" "}"; // No database auto obj = createFromUserInput(json, nullptr); auto vcrs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(vcrs != nullptr); EXPECT_EQ(vcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_crs_with_deformation_models) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"test\",\n" " \"datum\": {\n" " \"type\": \"DynamicVerticalReferenceFrame\",\n" " \"name\": \"test\",\n" " \"frame_reference_epoch\": 2005\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"deformation_models\": [\n" " {\n" " \"name\": \"my_model\"\n" " }\n" " ]\n" "}"; // No database auto obj = createFromUserInput(json, nullptr); auto vcrs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(vcrs != nullptr); EXPECT_EQ(vcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_crs_with_geoid_model_and_interpolation_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"foo\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"bar\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"geoid_model\": {\n" " \"name\": \"baz\",\n" " \"interpolation_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"NAD83(2011)\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"NAD83 (National Spatial Reference System " "2011)\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 6319\n" " }\n" " }\n" " }\n" "}"; // No database auto obj = createFromUserInput(json, nullptr); auto vcrs = nn_dynamic_pointer_cast<VerticalCRS>(obj); ASSERT_TRUE(vcrs != nullptr); EXPECT_EQ(vcrs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, vertical_reference_frame_with_anchor_epoch) { // Use dummy anchor_epoch = 0 to avoid fp issues on some architectures // (cf https://github.com/OSGeo/PROJ/issues/3632) auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"my_name\",\n" " \"anchor\": \"my_anchor_definition\",\n" " \"anchor_epoch\": 0\n" "}"; auto obj = createFromUserInput(json, nullptr); auto vrf = nn_dynamic_pointer_cast<VerticalReferenceFrame>(obj); ASSERT_TRUE(vrf != nullptr); EXPECT_EQ(vrf->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, parametric_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"ParametricCRS\",\n" " \"name\": \"WMO standard atmosphere layer 0\",\n" " \"datum\": {\n" " \"name\": \"Mean Sea Level\",\n" " \"anchor\": \"1013.25 hPa at 15°C\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"parametric\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Pressure\",\n" " \"abbreviation\": \"hPa\",\n" " \"direction\": \"up\",\n" " \"unit\": {\n" " \"type\": \"ParametricUnit\",\n" " \"name\": \"HectoPascal\",\n" " \"conversion_factor\": 100\n" " }\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<ParametricCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); auto datum = crs->datum(); auto datum_json = datum->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))); auto datum_obj = createFromUserInput(datum_json, nullptr); auto datum_got = nn_dynamic_pointer_cast<ParametricDatum>(datum_obj); ASSERT_TRUE(datum_got != nullptr); } // --------------------------------------------------------------------------- TEST(json_import, engineering_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"EngineeringCRS\",\n" " \"name\": \"Engineering CRS\",\n" " \"datum\": {\n" " \"name\": \"Engineering datum\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); auto datum = crs->datum(); auto datum_json = datum->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))); auto datum_obj = createFromUserInput(datum_json, nullptr); auto datum_got = nn_dynamic_pointer_cast<EngineeringDatum>(datum_obj); ASSERT_TRUE(datum_got != nullptr); } // --------------------------------------------------------------------------- TEST(json_import, engineering_crs_affine_CS) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"EngineeringCRS\",\n" " \"name\": \"myEngCRS\",\n" " \"datum\": {\n" " \"name\": \"myEngDatum\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"affine\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<EngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, temporal_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"TemporalCRS\",\n" " \"name\": \"Temporal CRS\",\n" " \"datum\": {\n" " \"name\": \"Gregorian calendar\",\n" " \"calendar\": \"proleptic Gregorian\",\n" " \"time_origin\": \"0000-01-01\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"TemporalDateTime\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Time\",\n" " \"abbreviation\": \"T\",\n" " \"direction\": \"future\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<TemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); auto datum = crs->datum(); auto datum_json = datum->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))); auto datum_obj = createFromUserInput(datum_json, nullptr); auto datum_got = nn_dynamic_pointer_cast<TemporalDatum>(datum_obj); ASSERT_TRUE(datum_got != nullptr); } // --------------------------------------------------------------------------- TEST(json_import, derived_geodetic_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedGeodeticCRS\",\n" " \"name\": \"Derived geodetic CRS\",\n" " \"base_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"Some conversion\",\n" " \"method\": {\n" " \"name\": \"Some method\"\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"foo\",\n" " \"value\": 1,\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geocentric X\",\n" " \"abbreviation\": \"X\",\n" " \"direction\": \"geocentricX\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Geocentric Y\",\n" " \"abbreviation\": \"Y\",\n" " \"direction\": \"geocentricY\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Geocentric Z\",\n" " \"abbreviation\": \"Z\",\n" " \"direction\": \"geocentricZ\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<DerivedGeodeticCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, derived_geographic_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedGeographicCRS\",\n" " \"name\": \"WMO Atlantic Pole\",\n" " \"base_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"Atlantic pole\",\n" " \"method\": {\n" " \"name\": \"Pole rotation\"\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude of rotated pole\",\n" " \"value\": 52,\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude of rotated pole\",\n" " \"value\": -30,\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Axis rotation\",\n" " \"value\": -25,\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<DerivedGeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, derived_projected_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedProjectedCRS\",\n" " \"name\": \"derived projectedCRS\",\n" " \"base_crs\": {\n" " \"type\": \"ProjectedCRS\",\n" " \"name\": \"WGS 84 / UTM zone 31N\",\n" " \"base_crs\": {\n" " \"name\": \"WGS 84\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"World Geodetic System 1984\",\n" " \"ellipsoid\": {\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Latitude\",\n" " \"abbreviation\": \"lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Longitude\",\n" " \"abbreviation\": \"lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"UTM zone 31N\",\n" " \"method\": {\n" " \"name\": \"Transverse Mercator\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9807\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Latitude of natural origin\",\n" " \"value\": 0,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8801\n" " }\n" " },\n" " {\n" " \"name\": \"Longitude of natural origin\",\n" " \"value\": 3,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8802\n" " }\n" " },\n" " {\n" " \"name\": \"Scale factor at natural origin\",\n" " \"value\": 0.9996,\n" " \"unit\": \"unity\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8805\n" " }\n" " },\n" " {\n" " \"name\": \"False easting\",\n" " \"value\": 500000,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8806\n" " }\n" " },\n" " {\n" " \"name\": \"False northing\",\n" " \"value\": 0,\n" " \"unit\": \"metre\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8807\n" " }\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"unnamed\",\n" " \"method\": {\n" " \"name\": \"PROJ unimplemented\"\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"foo\",\n" " \"value\": 1,\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<DerivedProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, derived_vertical_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedVerticalCRS\",\n" " \"name\": \"Derived vertCRS\",\n" " \"base_crs\": {\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"ODN height\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"Ordnance Datum Newlyn\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"unnamed\",\n" " \"method\": {\n" " \"name\": \"PROJ unimplemented\"\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"foo\",\n" " \"value\": 1,\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, derived_vertical_crs_EPSG_code_for_horizontal_CRS) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedVerticalCRS\",\n" " \"name\": \"Derived vertCRS\",\n" " \"base_crs\": {\n" " \"type\": \"VerticalCRS\",\n" " \"name\": \"ODN height\",\n" " \"datum\": {\n" " \"type\": \"VerticalReferenceFrame\",\n" " \"name\": \"Ordnance Datum Newlyn\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 5101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"Conv Vertical Offset and Slope\",\n" " \"method\": {\n" " \"name\": \"Vertical Offset and Slope\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1046\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Ordinate 1 of evaluation point\",\n" " \"value\": 40.5,\n" " \"unit\": \"degree\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8617\n" " }\n" " },\n" " {\n" " \"name\": \"EPSG code for Horizontal CRS\",\n" " \"value\": 4277,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1037\n" " }\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"vertical\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Gravity-related height\",\n" " \"abbreviation\": \"H\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, DatabaseContext::create()); auto crs = nn_dynamic_pointer_cast<DerivedVerticalCRS>(obj); ASSERT_TRUE(crs != nullptr); // "EPSG code for Horizontal CRS" is removed and set as interpolation CRS EXPECT_EQ(crs->derivingConversion()->parameterValues().size(), 1U); EXPECT_TRUE(crs->derivingConversion()->interpolationCRS() != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, derived_engineering_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedEngineeringCRS\",\n" " \"name\": \"Derived EngineeringCRS\",\n" " \"base_crs\": {\n" " \"type\": \"EngineeringCRS\",\n" " \"name\": \"Engineering CRS\",\n" " \"datum\": {\n" " \"name\": \"Engineering datum\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"unnamed\",\n" " \"method\": {\n" " \"name\": \"PROJ unimplemented\"\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"foo\",\n" " \"value\": 1,\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"Cartesian\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Easting\",\n" " \"abbreviation\": \"E\",\n" " \"direction\": \"east\",\n" " \"unit\": \"metre\"\n" " },\n" " {\n" " \"name\": \"Northing\",\n" " \"abbreviation\": \"N\",\n" " \"direction\": \"north\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<DerivedEngineeringCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, derived_parametric_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedParametricCRS\",\n" " \"name\": \"Derived ParametricCRS\",\n" " \"base_crs\": {\n" " \"type\": \"ParametricCRS\",\n" " \"name\": \"Parametric CRS\",\n" " \"datum\": {\n" " \"name\": \"Parametric datum\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"parametric\",\n" " \"axis\": [\n" " {\n" " \"name\": \"unknown parametric\",\n" " \"abbreviation\": \"\",\n" " \"direction\": \"unspecified\",\n" " \"unit\": {\n" " \"type\": \"ParametricUnit\",\n" " \"name\": \"unknown\",\n" " \"conversion_factor\": 1\n" " }\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"unnamed\",\n" " \"method\": {\n" " \"name\": \"PROJ unimplemented\"\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"foo\",\n" " \"value\": 1,\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"parametric\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Pressure\",\n" " \"abbreviation\": \"hPa\",\n" " \"direction\": \"up\",\n" " \"unit\": {\n" " \"type\": \"ParametricUnit\",\n" " \"name\": \"HectoPascal\",\n" " \"conversion_factor\": 100\n" " }\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<DerivedParametricCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, derived_temporal_crs) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"DerivedTemporalCRS\",\n" " \"name\": \"Derived TemporalCRS\",\n" " \"base_crs\": {\n" " \"type\": \"TemporalCRS\",\n" " \"name\": \"Temporal CRS\",\n" " \"datum\": {\n" " \"name\": \"Gregorian calendar\",\n" " \"calendar\": \"proleptic Gregorian\",\n" " \"time_origin\": \"0000-01-01\"\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"TemporalDateTime\",\n" " \"axis\": [\n" " {\n" " \"name\": \"unknown temporal\",\n" " \"abbreviation\": \"\",\n" " \"direction\": \"future\",\n" " \"unit\": {\n" " \"type\": \"TimeUnit\",\n" " \"name\": \"unknown\",\n" " \"conversion_factor\": 1\n" " }\n" " }\n" " ]\n" " }\n" " },\n" " \"conversion\": {\n" " \"name\": \"unnamed\",\n" " \"method\": {\n" " \"name\": \"PROJ unimplemented\"\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"foo\",\n" " \"value\": 1,\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"TemporalDateTime\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Time\",\n" " \"abbreviation\": \"T\",\n" " \"direction\": \"future\"\n" " }\n" " ]\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto crs = nn_dynamic_pointer_cast<DerivedTemporalCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, id) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 6326,\n" " \"version\": 1,\n" " \"authority_citation\": \"my citation\",\n" " \"uri\": \"my uri\"\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto ellps = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellps != nullptr); EXPECT_EQ(ellps->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, id_code_string_version_string) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": \"abc\",\n" " \"version\": \"def\",\n" " \"authority_citation\": \"my citation\",\n" " \"uri\": \"my uri\"\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto ellps = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellps != nullptr); EXPECT_EQ(ellps->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, id_code_string_version_double) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": \"abc\",\n" " \"version\": 9.8,\n" " \"authority_citation\": \"my citation\",\n" " \"uri\": \"my uri\"\n" " }\n" "}"; auto obj = createFromUserInput(json, nullptr); auto ellps = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellps != nullptr); EXPECT_EQ(ellps->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, multiple_ids) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"ids\": [\n" " {\n" " \"authority\": \"EPSG\",\n" " \"code\": 4326\n" " },\n" " {\n" " \"authority\": \"FOO\",\n" " \"code\": \"BAR\"\n" " }\n" " ]\n" "}"; auto obj = createFromUserInput(json, nullptr); auto ellps = nn_dynamic_pointer_cast<Ellipsoid>(obj); ASSERT_TRUE(ellps != nullptr); EXPECT_EQ(ellps->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_export, coordinate_system_id) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"CoordinateSystem\",\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ],\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 6422\n" " }\n" "}"; auto dbContext = DatabaseContext::create(); auto obj = createFromUserInput("EPSG:4326", dbContext); auto crs = nn_dynamic_pointer_cast<GeographicCRS>(obj); ASSERT_TRUE(crs != nullptr); auto cs = crs->coordinateSystem(); ASSERT_TRUE(cs != nullptr); EXPECT_EQ(cs->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); } // --------------------------------------------------------------------------- TEST(json_import, invalid_CoordinateMetadata) { { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"CoordinateMetadata\"\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"CoordinateMetadata\",\n" " \"crs\": \"not quite a CRS...\"\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } { auto json = "{\n" " \"$schema\": " "\"https://proj.org/schemas/v0.6/projjson.schema.json\",\n" " \"type\": \"CoordinateMetadata\",\n" " \"crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"ITRF2014\",\n" " \"datum\": {\n" " \"type\": \"DynamicGeodeticReferenceFrame\",\n" " \"name\": \"International Terrestrial Reference " "Frame 2014\",\n" " \"frame_reference_epoch\": 2010,\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 9000\n" " }\n" " },\n" " \"coordinateEpoch\": \"this should be a number\"\n" "}"; EXPECT_THROW(createFromUserInput(json, nullptr), ParsingException); } } // --------------------------------------------------------------------------- TEST(io, EXTENSION_PROJ4) { // Check that the PROJ string is preserved in the remarks auto obj = PROJStringParser().createFromPROJString( "+proj=utm +datum=NAD27 +zone=11 +over +type=crs"); auto crs = nn_dynamic_pointer_cast<ProjectedCRS>(obj); ASSERT_TRUE(crs != nullptr); EXPECT_EQ(crs->remarks(), "PROJ CRS string: +proj=utm +datum=NAD27 +zone=11 +over"); // Chat that the PROJ string is detected when ingesting a WKT2 with // a REMARKS node that contains it auto wkt2 = crs->exportToWKT(WKTFormatter::create().get()); auto obj2 = WKTParser().createFromWKT(wkt2); auto crs2 = nn_dynamic_pointer_cast<ProjectedCRS>(obj2); ASSERT_TRUE(crs2 != nullptr); EXPECT_EQ(crs2->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +datum=NAD27 +zone=11 +over +type=crs"); // Chat that the PROJ string is detected when ingesting a WKT2 with // a REMARKS node that contains it (in the middle of the remarks) auto wkt3 = "PROJCRS[\"unknown\",\n" " BASEGEOGCRS[\"unknown\",\n" " DATUM[\"North American Datum 1927\",\n" " ELLIPSOID[\"Clarke 1866\",6378206.4,294.978698213898,\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",6267]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8901]]],\n" " CONVERSION[\"UTM zone 11N\",\n" " METHOD[\"Transverse Mercator\",\n" " ID[\"EPSG\",9807]],\n" " PARAMETER[\"Latitude of natural origin\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8801]],\n" " PARAMETER[\"Longitude of natural origin\",-117,\n" " ANGLEUNIT[\"degree\",0.0174532925199433],\n" " ID[\"EPSG\",8802]],\n" " PARAMETER[\"Scale factor at natural origin\",0.9996,\n" " SCALEUNIT[\"unity\",1],\n" " ID[\"EPSG\",8805]],\n" " PARAMETER[\"False easting\",500000,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8806]],\n" " PARAMETER[\"False northing\",0,\n" " LENGTHUNIT[\"metre\",1],\n" " ID[\"EPSG\",8807]],\n" " ID[\"EPSG\",16011]],\n" " CS[Cartesian,2],\n" " AXIS[\"(E)\",east,\n" " ORDER[1],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " AXIS[\"(N)\",north,\n" " ORDER[2],\n" " LENGTHUNIT[\"metre\",1,\n" " ID[\"EPSG\",9001]]],\n" " REMARK[\"Prefix. PROJ CRS string: +proj=utm +datum=NAD27 +zone=11 " "+over. Suffix\"]]"; auto obj3 = WKTParser().createFromWKT(wkt3); auto crs3 = nn_dynamic_pointer_cast<ProjectedCRS>(obj3); ASSERT_TRUE(crs3 != nullptr); EXPECT_EQ(crs3->remarks(), "Prefix. PROJ CRS string: +proj=utm " "+datum=NAD27 +zone=11 +over. Suffix"); EXPECT_EQ(crs3->exportToPROJString(PROJStringFormatter::create().get()), "+proj=utm +datum=NAD27 +zone=11 +over +type=crs"); } // --------------------------------------------------------------------------- TEST(wkt_parse, PointMotionOperation) { auto wkt = "POINTMOTIONOPERATION[\"Canada velocity grid v7\",\n" " SOURCECRS[\n" " GEOGCRS[\"NAD83(CSRS)v7\",\n" " DATUM[\"North American Datum of 1983 (CSRS) version 7\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " CS[ellipsoidal,3],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"ellipsoidal height (h)\",up,\n" " ORDER[3],\n" " LENGTHUNIT[\"metre\",1]],\n" " ID[\"EPSG\",8254]]],\n" " METHOD[\"Point motion by grid (Canada NTv2_Vel)\",\n" " ID[\"EPSG\",1070]],\n" " PARAMETERFILE[\"Point motion velocity grid file\",\"foo.tif\"],\n" " OPERATIONACCURACY[0.01],\n" " USAGE[\n" " SCOPE[\"scope\"],\n" " AREA[\"area\"],\n" " BBOX[38.21,-141.01,86.46,-40.73]],\n" " ID[\"DERIVED_FROM(EPSG)\",9483],\n" " REMARK[\"remark.\"]]"; auto obj = WKTParser().createFromWKT(wkt); auto pmo = nn_dynamic_pointer_cast<PointMotionOperation>(obj); ASSERT_TRUE(pmo != nullptr); EXPECT_EQ( pmo->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019).get()), wkt); } // --------------------------------------------------------------------------- TEST(json_import, PointMotionOperation) { auto json = "{\n" " \"$schema\": \"foo\",\n" " \"type\": \"PointMotionOperation\",\n" " \"name\": \"Canada velocity grid v7\",\n" " \"source_crs\": {\n" " \"type\": \"GeographicCRS\",\n" " \"name\": \"NAD83(CSRS)v7\",\n" " \"datum\": {\n" " \"type\": \"GeodeticReferenceFrame\",\n" " \"name\": \"North American Datum of 1983 (CSRS) version 7\",\n" " \"ellipsoid\": {\n" " \"name\": \"GRS 1980\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257222101\n" " }\n" " },\n" " \"coordinate_system\": {\n" " \"subtype\": \"ellipsoidal\",\n" " \"axis\": [\n" " {\n" " \"name\": \"Geodetic latitude\",\n" " \"abbreviation\": \"Lat\",\n" " \"direction\": \"north\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Geodetic longitude\",\n" " \"abbreviation\": \"Lon\",\n" " \"direction\": \"east\",\n" " \"unit\": \"degree\"\n" " },\n" " {\n" " \"name\": \"Ellipsoidal height\",\n" " \"abbreviation\": \"h\",\n" " \"direction\": \"up\",\n" " \"unit\": \"metre\"\n" " }\n" " ]\n" " },\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 8254\n" " }\n" " },\n" " \"method\": {\n" " \"name\": \"Point motion by grid (Canada NTv2_Vel)\",\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 1070\n" " }\n" " },\n" " \"parameters\": [\n" " {\n" " \"name\": \"Point motion velocity grid file\",\n" " \"value\": \"foo.tif\"\n" " }\n" " ],\n" " \"accuracy\": \"0.01\",\n" " \"scope\": \"scope\",\n" " \"area\": \"area\",\n" " \"bbox\": {\n" " \"south_latitude\": 38.21,\n" " \"west_longitude\": -141.01,\n" " \"north_latitude\": 86.46,\n" " \"east_longitude\": -40.73\n" " },\n" " \"id\": {\n" " \"authority\": \"DERIVED_FROM(EPSG)\",\n" " \"code\": 9483\n" " },\n" " \"remarks\": \"remark.\"\n" "}"; auto obj = createFromUserInput(json, nullptr); auto pmo = nn_dynamic_pointer_cast<PointMotionOperation>(obj); ASSERT_TRUE(pmo != nullptr); EXPECT_EQ(pmo->exportToJSON(&(JSONFormatter::create()->setSchema("foo"))), json); }
cpp
PROJ
data/projects/PROJ/test/unit/test_tinshift.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test TIN shift * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2020, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #define PROJ_COMPILATION #define TINSHIFT_NAMESPACE TestTINShift #include "transformations/tinshift.hpp" using namespace TINSHIFT_NAMESPACE; namespace { static json getMinValidContent() { json j; j["file_type"] = "triangulation_file"; j["format_version"] = "1.0"; j["input_crs"] = "EPSG:2393"; j["output_crs"] = "EPSG:3067"; j["transformed_components"] = {"horizontal"}; j["vertices_columns"] = {"source_x", "source_y", "target_x", "target_y"}; j["triangles_columns"] = {"idx_vertex1", "idx_vertex2", "idx_vertex3"}; j["vertices"] = {{0, 0, 101, 101}, {0, 1, 100, 101}, {1, 1, 100, 100}}; j["triangles"] = {{0, 1, 2}}; return j; } // --------------------------------------------------------------------------- TEST(tinshift, basic) { EXPECT_THROW(TINShiftFile::parse("foo"), ParsingException); EXPECT_THROW(TINShiftFile::parse("null"), ParsingException); EXPECT_THROW(TINShiftFile::parse("{}"), ParsingException); const auto jMinValid(getMinValidContent()); { auto f = TINShiftFile::parse(jMinValid.dump()); EXPECT_EQ(f->fileType(), "triangulation_file"); EXPECT_EQ(f->formatVersion(), "1.0"); EXPECT_EQ(f->inputCRS(), "EPSG:2393"); EXPECT_EQ(f->outputCRS(), "EPSG:3067"); EXPECT_EQ(f->fallbackStrategy(), FALLBACK_NONE); auto eval = Evaluator(std::move(f)); double x_out = 0; double y_out = 0; double z_out = 0; EXPECT_FALSE(eval.forward(-0.1, 0.0, 1000.0, x_out, y_out, z_out)); EXPECT_TRUE(eval.forward(0.0, 0.0, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 101.0); EXPECT_EQ(y_out, 101.0); EXPECT_EQ(z_out, 1000.0); EXPECT_TRUE(eval.forward(0.0, 1.0, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 100.0); EXPECT_EQ(y_out, 101.0); EXPECT_EQ(z_out, 1000.0); EXPECT_TRUE(eval.forward(1.0, 1.0, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 100.0); EXPECT_EQ(y_out, 100.0); EXPECT_EQ(z_out, 1000.0); EXPECT_TRUE(eval.forward(0.0, 0.5, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 100.5); EXPECT_EQ(y_out, 101.0); EXPECT_EQ(z_out, 1000.0); EXPECT_TRUE(eval.forward(0.5, 0.5, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 100.5); EXPECT_EQ(y_out, 100.5); EXPECT_EQ(z_out, 1000.0); EXPECT_TRUE(eval.forward(0.5, 0.75, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 100.25); EXPECT_EQ(y_out, 100.5); EXPECT_EQ(z_out, 1000.0); EXPECT_TRUE(eval.inverse(100.25, 100.5, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.5); EXPECT_EQ(y_out, 0.75); EXPECT_EQ(z_out, 1000.0); } // Vertical only, through source_z / target_z { auto j(jMinValid); j["transformed_components"] = {"vertical"}; j["vertices_columns"] = {"source_x", "source_y", "source_z", "target_z"}; j["triangles_columns"] = {"idx_vertex1", "idx_vertex2", "idx_vertex3"}; j["vertices"] = { {0, 0, 10.5, 10.6}, {0, 1, 15.0, 15.2}, {1, 1, 17.5, 18.0}}; j["triangles"] = {{0, 1, 2}}; auto f = TINShiftFile::parse(j.dump()); auto eval = Evaluator(std::move(f)); double x_out = 0; double y_out = 0; double z_out = 0; EXPECT_TRUE(eval.forward(0.0, 0.0, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.0); EXPECT_EQ(y_out, 0.0); EXPECT_EQ(z_out, 1000.1); EXPECT_TRUE(eval.forward(0.5, 0.75, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.5); EXPECT_EQ(y_out, 0.75); EXPECT_EQ(z_out, 1000.325); EXPECT_TRUE(eval.inverse(0.5, 0.75, 1000.325, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.5); EXPECT_EQ(y_out, 0.75); EXPECT_EQ(z_out, 1000.0); } // Vertical only, through offset_z { auto j(jMinValid); j["transformed_components"] = {"vertical"}; j["vertices_columns"] = {"source_x", "source_y", "offset_z"}; j["triangles_columns"] = {"idx_vertex1", "idx_vertex2", "idx_vertex3"}; j["vertices"] = {{0, 0, 0.1}, {0, 1, 0.2}, {1, 1, 0.5}}; j["triangles"] = {{0, 1, 2}}; auto f = TINShiftFile::parse(j.dump()); auto eval = Evaluator(std::move(f)); double x_out = 0; double y_out = 0; double z_out = 0; EXPECT_TRUE(eval.forward(0.0, 0.0, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.0); EXPECT_EQ(y_out, 0.0); EXPECT_EQ(z_out, 1000.1); EXPECT_TRUE(eval.forward(0.5, 0.75, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.5); EXPECT_EQ(y_out, 0.75); EXPECT_EQ(z_out, 1000.325); EXPECT_TRUE(eval.inverse(0.5, 0.75, 1000.325, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.5); EXPECT_EQ(y_out, 0.75); EXPECT_EQ(z_out, 1000.0); } // Horizontal + vertical { auto j(jMinValid); j["transformed_components"] = {"horizontal", "vertical"}; j["vertices_columns"] = {"source_x", "source_y", "target_x", "target_y", "offset_z"}; j["triangles_columns"] = {"idx_vertex1", "idx_vertex2", "idx_vertex3"}; j["vertices"] = {{0, 0, 101, 101, 0.1}, {0, 1, 100, 101, 0.2}, {1, 1, 100, 100, 0.5}}; j["triangles"] = {{0, 1, 2}}; auto f = TINShiftFile::parse(j.dump()); auto eval = Evaluator(std::move(f)); double x_out = 0; double y_out = 0; double z_out = 0; EXPECT_TRUE(eval.forward(0.0, 0.0, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 101.0); EXPECT_EQ(y_out, 101.0); EXPECT_EQ(z_out, 1000.1); EXPECT_TRUE(eval.forward(0.5, 0.75, 1000.0, x_out, y_out, z_out)); EXPECT_EQ(x_out, 100.25); EXPECT_EQ(y_out, 100.5); EXPECT_EQ(z_out, 1000.325); EXPECT_TRUE(eval.inverse(100.25, 100.5, 1000.325, x_out, y_out, z_out)); EXPECT_EQ(x_out, 0.5); EXPECT_EQ(y_out, 0.75); EXPECT_EQ(z_out, 1000.0); } // invalid fallback_strategy field with 1.0 version { auto j(jMinValid); j["fallback_strategy"] = "none"; EXPECT_THROW(TINShiftFile::parse(j.dump()), ParsingException); } // invalid fallback_strategy field with 1.1 version { auto j(jMinValid); j["format_version"] = "1.1"; j["fallback_strategy"] = "invalid"; EXPECT_THROW(TINShiftFile::parse(j.dump()), ParsingException); } // fail with no triangles and fallback nearest_side { auto j(jMinValid); j["format_version"] = "1.1"; j["fallback_strategy"] = "nearest_side"; j["triangles"] = json::array(); // empty auto f = TINShiftFile::parse(j.dump()); auto eval = Evaluator(std::move(f)); double x_out = 0; double y_out = 0; double z_out = 0; EXPECT_FALSE(eval.forward(1.0, 1.0, 1.0, x_out, y_out, z_out)); } // fail with only degenerate triangles (one size is zero length) and // fallback nearest_side { auto j(jMinValid); j["format_version"] = "1.1"; j["fallback_strategy"] = "nearest_side"; j["vertices"] = {{0, 0, 101, 101}, {0, 1, 100, 101}, {0, 1, 100, 100}}; auto f = TINShiftFile::parse(j.dump()); auto eval = Evaluator(std::move(f)); double x_out = 0; double y_out = 0; double z_out = 0; EXPECT_FALSE(eval.forward(1.0, 1.0, 1.0, x_out, y_out, z_out)); } // fail with only degenerate triangles (two angles are 0°) and fallback // nearest_side { auto j(jMinValid); j["format_version"] = "1.1"; j["fallback_strategy"] = "nearest_side"; j["vertices"] = { {0, 0, 101, 101}, {0, 0.5, 100, 101}, {0, 1, 100, 100}}; auto f = TINShiftFile::parse(j.dump()); auto eval = Evaluator(std::move(f)); double x_out = 0; double y_out = 0; double z_out = 0; EXPECT_FALSE(eval.forward(1.0, 1.0, 1.0, x_out, y_out, z_out)); } } } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_c_api.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include <cstdio> #include <limits> #include <math.h> #include "proj.h" #include "proj_constants.h" #include "proj_experimental.h" #include "proj/common.hpp" #include "proj/coordinateoperation.hpp" #include "proj/coordinatesystem.hpp" #include "proj/crs.hpp" #include "proj/datum.hpp" #include "proj/io.hpp" #include "proj/metadata.hpp" #include "proj/util.hpp" #include <sqlite3.h> #if !defined(_WIN32) #include <sys/resource.h> #endif #ifndef __MINGW32__ #include <thread> #endif using namespace osgeo::proj::common; using namespace osgeo::proj::crs; using namespace osgeo::proj::cs; using namespace osgeo::proj::datum; using namespace osgeo::proj::io; using namespace osgeo::proj::metadata; using namespace osgeo::proj::operation; using namespace osgeo::proj::util; namespace { class CApi : public ::testing::Test { static void DummyLogFunction(void *, int, const char *) {} protected: void SetUp() override { m_ctxt = proj_context_create(); proj_log_func(m_ctxt, nullptr, DummyLogFunction); } void TearDown() override { if (m_ctxt) proj_context_destroy(m_ctxt); } static BoundCRSNNPtr createBoundCRS() { return BoundCRS::create( GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326, Transformation::create( PropertyMap(), GeographicCRS::EPSG_4807, GeographicCRS::EPSG_4326, nullptr, PropertyMap(), {OperationParameter::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "foo"))}, {ParameterValue::create( Measure(1.0, UnitOfMeasure::SCALE_UNITY))}, {})); } static ProjectedCRSNNPtr createProjectedCRS() { PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 32631) .set(IdentifiedObject::NAME_KEY, "WGS 84 / UTM zone 31N"); return ProjectedCRS::create( propertiesCRS, GeographicCRS::EPSG_4326, Conversion::createUTM(PropertyMap(), 31, true), CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } static DerivedProjectedCRSNNPtr createDerivedProjectedCRS() { auto derivingConversion = Conversion::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), PropertyMap().set(IdentifiedObject::NAME_KEY, "PROJ unimplemented"), std::vector<OperationParameterNNPtr>{}, std::vector<ParameterValueNNPtr>{}); return DerivedProjectedCRS::create( PropertyMap().set(IdentifiedObject::NAME_KEY, "derived projectedCRS"), createProjectedCRS(), derivingConversion, CartesianCS::createEastingNorthing(UnitOfMeasure::METRE)); } static VerticalCRSNNPtr createVerticalCRS() { PropertyMap propertiesVDatum; propertiesVDatum.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5101) .set(IdentifiedObject::NAME_KEY, "Ordnance Datum Newlyn"); auto vdatum = VerticalReferenceFrame::create(propertiesVDatum); PropertyMap propertiesCRS; propertiesCRS.set(Identifier::CODESPACE_KEY, "EPSG") .set(Identifier::CODE_KEY, 5701) .set(IdentifiedObject::NAME_KEY, "ODN height"); return VerticalCRS::create( propertiesCRS, vdatum, VerticalCS::createGravityRelatedHeight(UnitOfMeasure::METRE)); } static CompoundCRSNNPtr createCompoundCRS() { PropertyMap properties; properties.set(Identifier::CODESPACE_KEY, "codespace") .set(Identifier::CODE_KEY, "code") .set(IdentifiedObject::NAME_KEY, "horizontal + vertical"); return CompoundCRS::create( properties, std::vector<CRSNNPtr>{createProjectedCRS(), createVerticalCRS()}); } PJ_CONTEXT *m_ctxt = nullptr; struct ObjectKeeper { PJ *m_obj = nullptr; explicit ObjectKeeper(PJ *obj) : m_obj(obj) {} ~ObjectKeeper() { proj_destroy(m_obj); } void clear() { proj_destroy(m_obj); m_obj = nullptr; } ObjectKeeper(const ObjectKeeper &) = delete; ObjectKeeper &operator=(const ObjectKeeper &) = delete; }; struct PjContextKeeper { PJ_CONTEXT *m_ctxt = nullptr; explicit PjContextKeeper(PJ_CONTEXT *ctxt) : m_ctxt(ctxt) {} ~PjContextKeeper() { proj_context_destroy(m_ctxt); } PjContextKeeper(const PjContextKeeper &) = delete; PjContextKeeper &operator=(const PjContextKeeper &) = delete; }; struct ContextKeeper { PJ_OPERATION_FACTORY_CONTEXT *m_op_ctxt = nullptr; explicit ContextKeeper(PJ_OPERATION_FACTORY_CONTEXT *op_ctxt) : m_op_ctxt(op_ctxt) {} ~ContextKeeper() { proj_operation_factory_context_destroy(m_op_ctxt); } ContextKeeper(const ContextKeeper &) = delete; ContextKeeper &operator=(const ContextKeeper &) = delete; }; struct ObjListKeeper { PJ_OBJ_LIST *m_res = nullptr; explicit ObjListKeeper(PJ_OBJ_LIST *res) : m_res(res) {} ~ObjListKeeper() { proj_list_destroy(m_res); } ObjListKeeper(const ObjListKeeper &) = delete; ObjListKeeper &operator=(const ObjListKeeper &) = delete; }; }; // --------------------------------------------------------------------------- TEST_F(CApi, proj_create) { proj_destroy(nullptr); EXPECT_EQ(proj_create(m_ctxt, "invalid"), nullptr); { auto obj = proj_create(m_ctxt, GeographicCRS::EPSG_4326 ->exportToWKT(WKTFormatter::create().get()) .c_str()); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); // Check that functions that operate on 'non-C++' PJ don't crash constexpr double DEG_TO_RAD = .017453292519943296; PJ_COORD coord1; coord1.xyzt.x = 2 * DEG_TO_RAD; coord1.xyzt.y = 49 * DEG_TO_RAD; coord1.xyzt.z = 0; coord1.xyzt.t = 0; PJ_COORD coord2; coord2.xyzt.x = 2 * DEG_TO_RAD; coord2.xyzt.y = 50 * DEG_TO_RAD; coord2.xyzt.z = 0; coord2.xyzt.t = 0; EXPECT_EQ(proj_trans(obj, PJ_FWD, coord1).xyzt.x, std::numeric_limits<double>::infinity()); // and those ones actually work just fine EXPECT_NEAR(proj_geod(obj, coord1, coord2).xyzt.x, 111219.409, 1e-3); EXPECT_NEAR(proj_lp_dist(obj, coord1, coord2), 111219.409, 1e-3); auto info = proj_pj_info(obj); EXPECT_EQ(info.id, nullptr); ASSERT_NE(info.description, nullptr); EXPECT_EQ(info.description, std::string("WGS 84")); ASSERT_NE(info.definition, nullptr); EXPECT_EQ(info.definition, std::string("")); } { auto obj = proj_create(m_ctxt, "EPSG:4326"); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_from_wkt) { { EXPECT_EQ( proj_create_from_wkt(m_ctxt, "invalid", nullptr, nullptr, nullptr), nullptr); } { PROJ_STRING_LIST warningList = nullptr; PROJ_STRING_LIST errorList = nullptr; EXPECT_EQ(proj_create_from_wkt(m_ctxt, "invalid", nullptr, &warningList, &errorList), nullptr); EXPECT_EQ(warningList, nullptr); proj_string_list_destroy(warningList); EXPECT_NE(errorList, nullptr); proj_string_list_destroy(errorList); } { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); } { auto obj = proj_create_from_wkt( m_ctxt, "GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\"unused\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]]", nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); } { PROJ_STRING_LIST warningList = nullptr; PROJ_STRING_LIST errorList = nullptr; auto obj = proj_create_from_wkt( m_ctxt, "GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\"unused\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]]", nullptr, &warningList, &errorList); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); EXPECT_EQ(warningList, nullptr); proj_string_list_destroy(warningList); EXPECT_NE(errorList, nullptr); proj_string_list_destroy(errorList); } { PROJ_STRING_LIST warningList = nullptr; PROJ_STRING_LIST errorList = nullptr; const char *const options[] = {"STRICT=NO", nullptr}; auto obj = proj_create_from_wkt( m_ctxt, "GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563,\"unused\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]]", options, &warningList, &errorList); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); EXPECT_EQ(warningList, nullptr); proj_string_list_destroy(warningList); EXPECT_NE(errorList, nullptr); proj_string_list_destroy(errorList); } { PROJ_STRING_LIST warningList = nullptr; PROJ_STRING_LIST errorList = nullptr; const char *const options[] = { "UNSET_IDENTIFIERS_IF_INCOMPATIBLE_DEF=NO", nullptr}; auto wkt = "PROJCS[\"Merchich / Nord Maroc\"," " GEOGCS[\"Merchich\"," " DATUM[\"Merchich\"," " SPHEROID[\"Clarke 1880 (IGN)\"," "6378249.2,293.466021293627]]," " PRIMEM[\"Greenwich\",0]," " UNIT[\"grad\",0.015707963267949," " AUTHORITY[\"EPSG\",\"9105\"]]," " AUTHORITY[\"EPSG\",\"4261\"]]," " PROJECTION[\"Lambert_Conformal_Conic_1SP\"]," " PARAMETER[\"latitude_of_origin\",37]," " PARAMETER[\"central_meridian\",-6]," " PARAMETER[\"scale_factor\",0.999625769]," " PARAMETER[\"false_easting\",500000]," " PARAMETER[\"false_northing\",300000]," " UNIT[\"metre\",1," " AUTHORITY[\"EPSG\",\"9001\"]]," " AXIS[\"Easting\",EAST]," " AXIS[\"Northing\",NORTH]]"; auto obj = proj_create_from_wkt(m_ctxt, wkt, options, &warningList, &errorList); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); EXPECT_EQ(warningList, nullptr); proj_string_list_destroy(warningList); EXPECT_EQ(errorList, nullptr); proj_string_list_destroy(errorList); } { PROJ_STRING_LIST warningList = nullptr; PROJ_STRING_LIST errorList = nullptr; auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, &warningList, &errorList); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); EXPECT_EQ(warningList, nullptr); EXPECT_EQ(errorList, nullptr); } // Warnings: missing projection parameters { PROJ_STRING_LIST warningList = nullptr; PROJ_STRING_LIST errorList = nullptr; auto obj = proj_create_from_wkt( m_ctxt, "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",31],\n" " UNIT[\"metre\",1]]", nullptr, &warningList, &errorList); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); EXPECT_NE(warningList, nullptr); proj_string_list_destroy(warningList); EXPECT_EQ(errorList, nullptr); proj_string_list_destroy(errorList); } { auto obj = proj_create_from_wkt( m_ctxt, "PROJCS[\"test\",\n" " GEOGCS[\"WGS 84\",\n" " DATUM[\"WGS_1984\",\n" " SPHEROID[\"WGS 84\",6378137,298.257223563]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]],\n" " PROJECTION[\"Transverse_Mercator\"],\n" " PARAMETER[\"latitude_of_origin\",31],\n" " UNIT[\"metre\",1]]", nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); } { // Invalid ellipsoidal parameter (semi major axis) auto obj = proj_create_from_wkt( m_ctxt, "GEOGCS[\"test\",\n" " DATUM[\"test\",\n" " SPHEROID[\"test\",0,298.257223563,\"unused\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]]", nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); EXPECT_EQ(obj, nullptr); } { // Invalid ellipsoidal parameter (inverse flattening) auto obj = proj_create_from_wkt( m_ctxt, "GEOGCS[\"test\",\n" " DATUM[\"test\",\n" " SPHEROID[\"test\",6378137,-1,\"unused\"]],\n" " PRIMEM[\"Greenwich\",0],\n" " UNIT[\"degree\",0.0174532925199433]]", nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); EXPECT_EQ(obj, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_as_wkt) { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); { auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2019, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("GEOGCRS[") == 0) << wkt; } { auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2019_SIMPLIFIED, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("GEOGCRS[") == 0) << wkt; EXPECT_TRUE(std::string(wkt).find("ANGULARUNIT[") == std::string::npos) << wkt; } { auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2015, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("GEODCRS[") == 0) << wkt; } { auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2015_SIMPLIFIED, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("GEODCRS[") == 0) << wkt; EXPECT_TRUE(std::string(wkt).find("ANGULARUNIT[") == std::string::npos) << wkt; } { auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("GEOGCS[\"WGS 84\"") == 0) << wkt; } { auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_ESRI, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("GEOGCS[\"GCS_WGS_1984\"") == 0) << wkt; } // MULTILINE=NO { const char *const options[] = {"MULTILINE=NO", nullptr}; auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("\n") == std::string::npos) << wkt; } // INDENTATION_WIDTH=2 { const char *const options[] = {"INDENTATION_WIDTH=2", nullptr}; auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("\n DATUM") != std::string::npos) << wkt; } // OUTPUT_AXIS=NO { const char *const options[] = {"OUTPUT_AXIS=NO", nullptr}; auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("AXIS") == std::string::npos) << wkt; } // OUTPUT_AXIS=AUTO { const char *const options[] = {"OUTPUT_AXIS=AUTO", nullptr}; auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("AXIS") == std::string::npos) << wkt; } // OUTPUT_AXIS=YES { const char *const options[] = {"OUTPUT_AXIS=YES", nullptr}; auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("AXIS") != std::string::npos) << wkt; } auto crs4979 = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4979->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper_crs4979(crs4979); ASSERT_NE(crs4979, nullptr); EXPECT_EQ(proj_as_wkt(m_ctxt, crs4979, PJ_WKT1_GDAL, nullptr), nullptr); // STRICT=NO { const char *const options[] = {"STRICT=NO", nullptr}; auto wkt = proj_as_wkt(m_ctxt, crs4979, PJ_WKT1_GDAL, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("GEOGCS[\"WGS 84\"") == 0) << wkt; } // ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS=YES { const char *const options[] = { "ALLOW_ELLIPSOIDAL_HEIGHT_AS_VERTICAL_CRS=YES", nullptr}; auto wkt = proj_as_wkt(m_ctxt, crs4979, PJ_WKT1_GDAL, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find( "COMPD_CS[\"WGS 84 + Ellipsoid (metre)\"") == 0) << wkt; } // ALLOW_LINUNIT_NODE default value { auto wkt = proj_as_wkt(m_ctxt, crs4979, PJ_WKT1_ESRI, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("LINUNIT") != std::string::npos) << wkt; } // ALLOW_LINUNIT_NODE=NO { const char *const options[] = {"ALLOW_LINUNIT_NODE=NO", nullptr}; auto wkt = proj_as_wkt(m_ctxt, crs4979, PJ_WKT1_ESRI, options); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("LINUNIT") == std::string::npos) << wkt; } // unsupported option { const char *const options[] = {"unsupported=yes", nullptr}; auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT2_2019, options); EXPECT_EQ(wkt, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_as_wkt_check_db_use) { auto obj = proj_create_from_wkt( m_ctxt, "GEOGCS[\"AGD66\",DATUM[\"Australian_Geodetic_Datum_1966\"," "SPHEROID[\"Australian National Spheroid\",6378160,298.25]]," "PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433]]", nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto wkt = proj_as_wkt(m_ctxt, obj, PJ_WKT1_ESRI, nullptr); EXPECT_EQ(std::string(wkt), "GEOGCS[\"GCS_Australian_1966\",DATUM[\"D_Australian_1966\"," "SPHEROID[\"Australian\",6378160.0,298.25]]," "PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_as_wkt_incompatible_WKT1) { auto wkt = createBoundCRS()->exportToWKT(WKTFormatter::create().get()); auto obj = proj_create_from_wkt(m_ctxt, wkt.c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr) << wkt; auto wkt1_GDAL = proj_as_wkt(m_ctxt, obj, PJ_WKT1_GDAL, nullptr); ASSERT_EQ(wkt1_GDAL, nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_as_proj_string) { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); { auto proj_5 = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5, nullptr); EXPECT_EQ(std::string(proj_5), "+proj=longlat +datum=WGS84 +no_defs +type=crs"); } { auto proj_4 = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_4, nullptr); ASSERT_NE(proj_4, nullptr); EXPECT_EQ(std::string(proj_4), "+proj=longlat +datum=WGS84 +no_defs +type=crs"); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_as_proj_string_incompatible_WKT1) { auto obj = proj_create_from_wkt( m_ctxt, createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto str = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_5, nullptr); ASSERT_EQ(str, nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_as_proj_string_approx_tmerc_option_yes) { auto obj = proj_create(m_ctxt, "+proj=tmerc +type=crs"); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); const char *options[] = {"USE_APPROX_TMERC=YES", nullptr}; auto str = proj_as_proj_string(m_ctxt, obj, PJ_PROJ_4, options); ASSERT_NE(str, nullptr); EXPECT_EQ(str, std::string("+proj=tmerc +approx +lat_0=0 +lon_0=0 +k=1 +x_0=0 " "+y_0=0 +datum=WGS84 +units=m +no_defs +type=crs")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_create_bound_crs_to_WGS84) { auto crs = proj_create_from_database(m_ctxt, "EPSG", "4807", PJ_CATEGORY_CRS, false, nullptr); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); auto res = proj_crs_create_bound_crs_to_WGS84(m_ctxt, crs, nullptr); ObjectKeeper keeper_res(res); ASSERT_NE(res, nullptr); auto proj_4 = proj_as_proj_string(m_ctxt, res, PJ_PROJ_4, nullptr); ASSERT_NE(proj_4, nullptr); EXPECT_EQ(std::string(proj_4), "+proj=longlat +ellps=clrk80ign +pm=paris " "+towgs84=-168,-60,320,0,0,0,0 +no_defs +type=crs"); auto base_crs = proj_get_source_crs(m_ctxt, res); ObjectKeeper keeper_base_crs(base_crs); ASSERT_NE(base_crs, nullptr); auto hub_crs = proj_get_target_crs(m_ctxt, res); ObjectKeeper keeper_hub_crs(hub_crs); ASSERT_NE(hub_crs, nullptr); auto transf = proj_crs_get_coordoperation(m_ctxt, res); ObjectKeeper keeper_transf(transf); ASSERT_NE(transf, nullptr); std::vector<double> values(7, 0); EXPECT_TRUE(proj_coordoperation_get_towgs84_values(m_ctxt, transf, values.data(), 7, true)); auto expected = std::vector<double>{-168, -60, 320, 0, 0, 0, 0}; EXPECT_EQ(values, expected); auto res2 = proj_crs_create_bound_crs(m_ctxt, base_crs, hub_crs, transf); ObjectKeeper keeper_res2(res2); ASSERT_NE(res2, nullptr); EXPECT_TRUE(proj_is_equivalent_to(res, res2, PJ_COMP_STRICT)); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_create_bound_crs_to_WGS84_on_invalid_type) { auto wkt = createProjectedCRS()->derivingConversion()->exportToWKT( WKTFormatter::create().get()); auto obj = proj_create_from_wkt(m_ctxt, wkt.c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr) << wkt; auto res = proj_crs_create_bound_crs_to_WGS84(m_ctxt, obj, nullptr); ASSERT_EQ(res, nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_name) { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto name = proj_get_name(obj); ASSERT_TRUE(name != nullptr); EXPECT_EQ(name, std::string("WGS 84")); EXPECT_EQ(name, proj_get_name(obj)); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_id_auth_name) { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto auth = proj_get_id_auth_name(obj, 0); ASSERT_TRUE(auth != nullptr); EXPECT_EQ(auth, std::string("EPSG")); EXPECT_EQ(auth, proj_get_id_auth_name(obj, 0)); EXPECT_EQ(proj_get_id_auth_name(obj, -1), nullptr); EXPECT_EQ(proj_get_id_auth_name(obj, 1), nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_id_code) { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto code = proj_get_id_code(obj, 0); ASSERT_TRUE(code != nullptr); EXPECT_EQ(code, std::string("4326")); EXPECT_EQ(code, proj_get_id_code(obj, 0)); EXPECT_EQ(proj_get_id_code(obj, -1), nullptr); EXPECT_EQ(proj_get_id_code(obj, 1), nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_type) { { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEOGRAPHIC_2D_CRS); } { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4979->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEOGRAPHIC_3D_CRS); } { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4978->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEOCENTRIC_CRS); } { auto obj = proj_create_from_wkt(m_ctxt, GeographicCRS::EPSG_4326->datum() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_GEODETIC_REFERENCE_FRAME); } { auto obj = proj_create_from_wkt(m_ctxt, GeographicCRS::EPSG_4326->ellipsoid() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_ELLIPSOID); } { auto obj = proj_create_from_wkt(m_ctxt, createProjectedCRS() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_PROJECTED_CRS); } { auto obj = proj_create_from_wkt( m_ctxt, createDerivedProjectedCRS() ->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT2_2019) .get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_DERIVED_PROJECTED_CRS); } { auto obj = proj_create_from_wkt(m_ctxt, createVerticalCRS() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_VERTICAL_CRS); } { auto wkt = "TDATUM[\"Gregorian calendar\",\n" " CALENDAR[\"proleptic Gregorian\"],\n" " TIMEORIGIN[0000-01-01]]"; auto datum = proj_create_from_wkt(m_ctxt, wkt, nullptr, nullptr, nullptr); ObjectKeeper keeper(datum); ASSERT_NE(datum, nullptr); EXPECT_EQ(proj_get_type(datum), PJ_TYPE_TEMPORAL_DATUM); } { auto wkt = "ENGINEERINGDATUM[\"Engineering datum\"]"; auto datum = proj_create_from_wkt(m_ctxt, wkt, nullptr, nullptr, nullptr); ObjectKeeper keeper(datum); EXPECT_EQ(proj_get_type(datum), PJ_TYPE_ENGINEERING_DATUM); } { auto wkt = "PDATUM[\"Mean Sea Level\",ANCHOR[\"1013.25 hPa at 15°C\"]]"; auto datum = proj_create_from_wkt(m_ctxt, wkt, nullptr, nullptr, nullptr); ObjectKeeper keeper(datum); EXPECT_EQ(proj_get_type(datum), PJ_TYPE_PARAMETRIC_DATUM); } { auto obj = proj_create_from_wkt(m_ctxt, createVerticalCRS() ->datum() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_VERTICAL_REFERENCE_FRAME); } { auto obj = proj_create_from_wkt(m_ctxt, createProjectedCRS() ->derivingConversion() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_CONVERSION); } { auto obj = proj_create_from_wkt( m_ctxt, createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_BOUND_CRS); } { auto obj = proj_create_from_wkt(m_ctxt, createBoundCRS() ->transformation() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_TRANSFORMATION); } { auto obj = proj_create_from_wkt(m_ctxt, "AUTHORITY[\"EPSG\", 4326]", nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_get_type(obj), PJ_TYPE_UNKNOWN); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_from_database) { { auto crs = proj_create_from_database(m_ctxt, "EPSG", "-1", PJ_CATEGORY_CRS, false, nullptr); ASSERT_EQ(crs, nullptr); } { auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); EXPECT_TRUE(proj_is_crs(crs)); EXPECT_FALSE(proj_is_deprecated(crs)); EXPECT_EQ(proj_get_type(crs), PJ_TYPE_GEOGRAPHIC_2D_CRS); const char *code = proj_get_id_code(crs, 0); ASSERT_NE(code, nullptr); EXPECT_EQ(std::string(code), "4326"); } { auto crs = proj_create_from_database(m_ctxt, "EPSG", "6871", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); EXPECT_TRUE(proj_is_crs(crs)); EXPECT_EQ(proj_get_type(crs), PJ_TYPE_COMPOUND_CRS); } { auto ellipsoid = proj_create_from_database( m_ctxt, "EPSG", "7030", PJ_CATEGORY_ELLIPSOID, false, nullptr); ASSERT_NE(ellipsoid, nullptr); ObjectKeeper keeper(ellipsoid); EXPECT_EQ(proj_get_type(ellipsoid), PJ_TYPE_ELLIPSOID); } { auto pm = proj_create_from_database( m_ctxt, "EPSG", "8903", PJ_CATEGORY_PRIME_MERIDIAN, false, nullptr); ASSERT_NE(pm, nullptr); ObjectKeeper keeper(pm); EXPECT_EQ(proj_get_type(pm), PJ_TYPE_PRIME_MERIDIAN); } { auto datum = proj_create_from_database( m_ctxt, "EPSG", "6326", PJ_CATEGORY_DATUM, false, nullptr); ASSERT_NE(datum, nullptr); ObjectKeeper keeper(datum); EXPECT_EQ(proj_get_type(datum), PJ_TYPE_GEODETIC_REFERENCE_FRAME); } { auto ensemble = proj_create_from_database( m_ctxt, "EPSG", "6326", PJ_CATEGORY_DATUM_ENSEMBLE, false, nullptr); ASSERT_NE(ensemble, nullptr); ObjectKeeper keeper(ensemble); EXPECT_EQ(proj_get_type(ensemble), PJ_TYPE_DATUM_ENSEMBLE); } { // International Terrestrial Reference Frame 2008 auto datum = proj_create_from_database( m_ctxt, "EPSG", "1061", PJ_CATEGORY_DATUM, false, nullptr); ASSERT_NE(datum, nullptr); ObjectKeeper keeper(datum); EXPECT_EQ(proj_get_type(datum), PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME); EXPECT_EQ(proj_dynamic_datum_get_frame_reference_epoch(m_ctxt, datum), 2005.0); } { // Norway Normal Null 2000 auto datum = proj_create_from_database( m_ctxt, "EPSG", "1096", PJ_CATEGORY_DATUM, false, nullptr); ASSERT_NE(datum, nullptr); ObjectKeeper keeper(datum); EXPECT_EQ(proj_get_type(datum), PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME); EXPECT_EQ(proj_dynamic_datum_get_frame_reference_epoch(m_ctxt, datum), 2000.0); } { auto op = proj_create_from_database(m_ctxt, "EPSG", "16031", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ASSERT_NE(op, nullptr); ObjectKeeper keeper(op); EXPECT_EQ(proj_get_type(op), PJ_TYPE_CONVERSION); auto info = proj_pj_info(op); EXPECT_NE(info.id, nullptr); EXPECT_EQ(info.id, std::string("utm")); ASSERT_NE(info.description, nullptr); EXPECT_EQ(info.description, std::string("UTM zone 31N")); ASSERT_NE(info.definition, nullptr); EXPECT_EQ(info.definition, std::string("proj=utm zone=31 ellps=GRS80")); EXPECT_EQ(info.accuracy, 0); } { auto op = proj_create_from_database(m_ctxt, "EPSG", "1024", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ASSERT_NE(op, nullptr); ObjectKeeper keeper(op); EXPECT_EQ(proj_get_type(op), PJ_TYPE_TRANSFORMATION); auto info = proj_pj_info(op); EXPECT_NE(info.id, nullptr); EXPECT_EQ(info.id, std::string("pipeline")); ASSERT_NE(info.description, nullptr); EXPECT_EQ(info.description, std::string("MGI to ETRS89 (4)")); ASSERT_NE(info.definition, nullptr); EXPECT_EQ( info.definition, std::string("proj=pipeline step proj=axisswap " "order=2,1 step proj=unitconvert xy_in=deg xy_out=rad " "step proj=push v_3 " "step proj=cart ellps=bessel step proj=helmert " "x=601.705 y=84.263 z=485.227 rx=-4.7354 ry=-1.3145 " "rz=-5.393 s=-2.3887 convention=coordinate_frame " "step inv proj=cart ellps=GRS80 " "step proj=pop v_3 " "step proj=unitconvert xy_in=rad xy_out=deg " "step proj=axisswap order=2,1")); EXPECT_EQ(info.accuracy, 1); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs) { auto crs = proj_create_from_wkt( m_ctxt, createProjectedCRS() ->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()) .c_str(), nullptr, nullptr, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); EXPECT_TRUE(proj_is_crs(crs)); auto geodCRS = proj_crs_get_geodetic_crs(m_ctxt, crs); ASSERT_NE(geodCRS, nullptr); ObjectKeeper keeper_geogCRS(geodCRS); EXPECT_TRUE(proj_is_crs(geodCRS)); auto geogCRS_name = proj_get_name(geodCRS); ASSERT_TRUE(geogCRS_name != nullptr); EXPECT_EQ(geogCRS_name, std::string("WGS 84")); auto h_datum = proj_crs_get_horizontal_datum(m_ctxt, crs); ASSERT_NE(h_datum, nullptr); ObjectKeeper keeper_h_datum(h_datum); auto datum = proj_crs_get_datum(m_ctxt, crs); ASSERT_NE(datum, nullptr); ObjectKeeper keeper_datum(datum); EXPECT_TRUE(proj_is_equivalent_to(h_datum, datum, PJ_COMP_STRICT)); auto datum_name = proj_get_name(datum); ASSERT_TRUE(datum_name != nullptr); EXPECT_EQ(datum_name, std::string("World Geodetic System 1984")); auto ellipsoid = proj_get_ellipsoid(m_ctxt, crs); ASSERT_NE(ellipsoid, nullptr); ObjectKeeper keeper_ellipsoid(ellipsoid); auto ellipsoid_name = proj_get_name(ellipsoid); ASSERT_TRUE(ellipsoid_name != nullptr); EXPECT_EQ(ellipsoid_name, std::string("WGS 84")); auto ellipsoid_from_datum = proj_get_ellipsoid(m_ctxt, datum); ASSERT_NE(ellipsoid_from_datum, nullptr); ObjectKeeper keeper_ellipsoid_from_datum(ellipsoid_from_datum); EXPECT_EQ(proj_get_ellipsoid(m_ctxt, ellipsoid), nullptr); EXPECT_FALSE(proj_is_crs(ellipsoid)); double a; double b; int b_is_computed; double rf; EXPECT_TRUE(proj_ellipsoid_get_parameters(m_ctxt, ellipsoid, nullptr, nullptr, nullptr, nullptr)); EXPECT_TRUE(proj_ellipsoid_get_parameters(m_ctxt, ellipsoid, &a, &b, &b_is_computed, &rf)); EXPECT_FALSE(proj_ellipsoid_get_parameters(m_ctxt, crs, &a, &b, &b_is_computed, &rf)); EXPECT_EQ(a, 6378137); EXPECT_NEAR(b, 6356752.31424518, 1e-9); EXPECT_EQ(b_is_computed, 1); EXPECT_EQ(rf, 298.257223563); auto id = proj_get_id_code(ellipsoid, 0); ASSERT_TRUE(id != nullptr); EXPECT_EQ(id, std::string("7030")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_celestial_body_name) { // Geographic CRS { auto obj = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Projected CRS { auto obj = proj_create_from_database(m_ctxt, "EPSG", "32631", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Vertical CRS { auto obj = proj_create_from_database(m_ctxt, "EPSG", "3855", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Compound CRS { auto obj = proj_create_from_database(m_ctxt, "EPSG", "9518", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Geodetic datum { auto obj = proj_create_from_database(m_ctxt, "EPSG", "6267", PJ_CATEGORY_DATUM, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Datum ensemble { auto obj = proj_create_from_database( m_ctxt, "EPSG", "6326", PJ_CATEGORY_DATUM_ENSEMBLE, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Vertical datum { auto obj = proj_create_from_database(m_ctxt, "EPSG", "1027", PJ_CATEGORY_DATUM, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Ellipsoid { auto obj = proj_create_from_database( m_ctxt, "EPSG", "7030", PJ_CATEGORY_ELLIPSOID, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Earth"); } // Ellipsoid non-EARTH { auto obj = proj_create_from_database( m_ctxt, "ESRI", "107903", PJ_CATEGORY_ELLIPSOID, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_NE(celestial_body_name, nullptr); EXPECT_EQ(std::string(celestial_body_name), "Moon"); } // Coordinate operation -> error { auto obj = proj_create_from_database(m_ctxt, "EPSG", "1591", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); const char *celestial_body_name = proj_get_celestial_body_name(m_ctxt, obj); ASSERT_EQ(celestial_body_name, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_prime_meridian) { auto crs = proj_create_from_wkt( m_ctxt, createProjectedCRS() ->exportToWKT( WKTFormatter::create(WKTFormatter::Convention::WKT1_GDAL).get()) .c_str(), nullptr, nullptr, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); auto pm = proj_get_prime_meridian(m_ctxt, crs); ASSERT_NE(pm, nullptr); ObjectKeeper keeper_pm(pm); auto pm_name = proj_get_name(pm); ASSERT_TRUE(pm_name != nullptr); EXPECT_EQ(pm_name, std::string("Greenwich")); EXPECT_EQ(proj_get_prime_meridian(m_ctxt, pm), nullptr); EXPECT_TRUE(proj_prime_meridian_get_parameters(m_ctxt, pm, nullptr, nullptr, nullptr)); double longitude = -1; double longitude_unit = 0; const char *longitude_unit_name = nullptr; EXPECT_TRUE(proj_prime_meridian_get_parameters( m_ctxt, pm, &longitude, &longitude_unit, &longitude_unit_name)); EXPECT_EQ(longitude, 0); EXPECT_NEAR(longitude_unit, UnitOfMeasure::DEGREE.conversionToSI(), 1e-10); ASSERT_TRUE(longitude_unit_name != nullptr); EXPECT_EQ(longitude_unit_name, std::string("degree")); auto datum = proj_crs_get_horizontal_datum(m_ctxt, crs); ASSERT_NE(datum, nullptr); ObjectKeeper keeper_datum(datum); auto pm_from_datum = proj_get_prime_meridian(m_ctxt, datum); ASSERT_NE(pm_from_datum, nullptr); ObjectKeeper keeper_pm_from_datum(pm_from_datum); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_compound) { auto crs = proj_create_from_wkt( m_ctxt, createCompoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); EXPECT_EQ(proj_get_type(crs), PJ_TYPE_COMPOUND_CRS); EXPECT_EQ(proj_crs_get_sub_crs(m_ctxt, crs, -1), nullptr); EXPECT_EQ(proj_crs_get_sub_crs(m_ctxt, crs, 2), nullptr); auto subcrs_horiz = proj_crs_get_sub_crs(m_ctxt, crs, 0); ASSERT_NE(subcrs_horiz, nullptr); ObjectKeeper keeper_subcrs_horiz(subcrs_horiz); EXPECT_EQ(proj_get_type(subcrs_horiz), PJ_TYPE_PROJECTED_CRS); EXPECT_EQ(proj_crs_get_sub_crs(m_ctxt, subcrs_horiz, 0), nullptr); auto subcrs_vertical = proj_crs_get_sub_crs(m_ctxt, crs, 1); ASSERT_NE(subcrs_vertical, nullptr); ObjectKeeper keeper_subcrs_vertical(subcrs_vertical); EXPECT_EQ(proj_get_type(subcrs_vertical), PJ_TYPE_VERTICAL_CRS); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_source_target_crs_bound_crs) { auto crs = proj_create_from_wkt( m_ctxt, createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); auto sourceCRS = proj_get_source_crs(m_ctxt, crs); ASSERT_NE(sourceCRS, nullptr); ObjectKeeper keeper_sourceCRS(sourceCRS); EXPECT_EQ(std::string(proj_get_name(sourceCRS)), "NTF (Paris)"); auto targetCRS = proj_get_target_crs(m_ctxt, crs); ASSERT_NE(targetCRS, nullptr); ObjectKeeper keeper_targetCRS(targetCRS); EXPECT_EQ(std::string(proj_get_name(targetCRS)), "WGS 84"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_source_target_crs_transformation) { auto obj = proj_create_from_wkt(m_ctxt, createBoundCRS() ->transformation() ->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); auto sourceCRS = proj_get_source_crs(m_ctxt, obj); ASSERT_NE(sourceCRS, nullptr); ObjectKeeper keeper_sourceCRS(sourceCRS); EXPECT_EQ(std::string(proj_get_name(sourceCRS)), "NTF (Paris)"); auto targetCRS = proj_get_target_crs(m_ctxt, obj); ASSERT_NE(targetCRS, nullptr); ObjectKeeper keeper_targetCRS(targetCRS); EXPECT_EQ(std::string(proj_get_name(targetCRS)), "WGS 84"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_source_crs_of_projected_crs) { auto crs = proj_create_from_wkt( m_ctxt, createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); auto sourceCRS = proj_get_source_crs(m_ctxt, crs); ASSERT_NE(sourceCRS, nullptr); ObjectKeeper keeper_sourceCRS(sourceCRS); EXPECT_EQ(std::string(proj_get_name(sourceCRS)), "WGS 84"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_source_target_crs_conversion_without_crs) { auto obj = proj_create_from_database(m_ctxt, "EPSG", "16031", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); auto sourceCRS = proj_get_source_crs(m_ctxt, obj); ASSERT_EQ(sourceCRS, nullptr); auto targetCRS = proj_get_target_crs(m_ctxt, obj); ASSERT_EQ(targetCRS, nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_source_target_crs_invalid_object) { auto obj = proj_create_from_wkt( m_ctxt, "ELLIPSOID[\"WGS 84\",6378137,298.257223563]", nullptr, nullptr, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); auto sourceCRS = proj_get_source_crs(m_ctxt, obj); ASSERT_EQ(sourceCRS, nullptr); auto targetCRS = proj_get_target_crs(m_ctxt, obj); ASSERT_EQ(targetCRS, nullptr); } // --------------------------------------------------------------------------- struct ListFreer { PROJ_STRING_LIST list; ListFreer(PROJ_STRING_LIST ptrIn) : list(ptrIn) {} ~ListFreer() { proj_string_list_destroy(list); } ListFreer(const ListFreer &) = delete; ListFreer &operator=(const ListFreer &) = delete; }; // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_authorities_from_database) { auto list = proj_get_authorities_from_database(m_ctxt); ListFreer feer(list); ASSERT_NE(list, nullptr); ASSERT_TRUE(list[0] != nullptr); EXPECT_EQ(list[0], std::string("EPSG")); ASSERT_TRUE(list[1] != nullptr); EXPECT_EQ(list[1], std::string("ESRI")); ASSERT_TRUE(list[2] != nullptr); EXPECT_EQ(list[2], std::string("IAU_2015")); ASSERT_TRUE(list[3] != nullptr); EXPECT_EQ(list[3], std::string("IGNF")); ASSERT_TRUE(list[4] != nullptr); EXPECT_EQ(list[4], std::string("NKG")); ASSERT_TRUE(list[5] != nullptr); EXPECT_EQ(list[5], std::string("NRCAN")); ASSERT_TRUE(list[6] != nullptr); EXPECT_EQ(list[6], std::string("OGC")); ASSERT_TRUE(list[7] != nullptr); EXPECT_EQ(list[7], std::string("PROJ")); EXPECT_EQ(list[8], nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_codes_from_database) { auto listTypes = std::vector<PJ_TYPE>{PJ_TYPE_ELLIPSOID, PJ_TYPE_PRIME_MERIDIAN, PJ_TYPE_GEODETIC_REFERENCE_FRAME, PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME, PJ_TYPE_VERTICAL_REFERENCE_FRAME, PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME, PJ_TYPE_DATUM_ENSEMBLE, PJ_TYPE_TEMPORAL_DATUM, PJ_TYPE_ENGINEERING_DATUM, PJ_TYPE_PARAMETRIC_DATUM, PJ_TYPE_CRS, PJ_TYPE_GEODETIC_CRS, PJ_TYPE_GEOCENTRIC_CRS, PJ_TYPE_GEOGRAPHIC_CRS, PJ_TYPE_GEOGRAPHIC_2D_CRS, PJ_TYPE_GEOGRAPHIC_3D_CRS, PJ_TYPE_VERTICAL_CRS, PJ_TYPE_PROJECTED_CRS, PJ_TYPE_COMPOUND_CRS, PJ_TYPE_TEMPORAL_CRS, PJ_TYPE_BOUND_CRS, PJ_TYPE_OTHER_CRS, PJ_TYPE_CONVERSION, PJ_TYPE_TRANSFORMATION, PJ_TYPE_CONCATENATED_OPERATION, PJ_TYPE_OTHER_COORDINATE_OPERATION, PJ_TYPE_UNKNOWN}; for (const auto &type : listTypes) { auto list = proj_get_codes_from_database(m_ctxt, "EPSG", type, true); ListFreer feer(list); if (type == PJ_TYPE_TEMPORAL_CRS || type == PJ_TYPE_BOUND_CRS || type == PJ_TYPE_UNKNOWN || type == PJ_TYPE_TEMPORAL_DATUM || type == PJ_TYPE_ENGINEERING_DATUM || type == PJ_TYPE_PARAMETRIC_DATUM) { EXPECT_EQ(list, nullptr) << type; } else { ASSERT_NE(list, nullptr) << type; ASSERT_NE(list[0], nullptr) << type; if (type == PJ_TYPE_DYNAMIC_GEODETIC_REFERENCE_FRAME || type == PJ_TYPE_DYNAMIC_VERTICAL_REFERENCE_FRAME) { auto obj = proj_create_from_database( m_ctxt, "EPSG", list[0], PJ_CATEGORY_DATUM, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); EXPECT_EQ(proj_get_type(obj), type) << type << " " << list[0]; } } } } // --------------------------------------------------------------------------- TEST_F(CApi, conversion) { auto crs = proj_create_from_database(m_ctxt, "EPSG", "32631", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); // invalid object type EXPECT_FALSE(proj_coordoperation_get_method_info(m_ctxt, crs, nullptr, nullptr, nullptr)); { auto conv = proj_crs_get_coordoperation(m_ctxt, crs); ASSERT_NE(conv, nullptr); ObjectKeeper keeper_conv(conv); ASSERT_EQ(proj_crs_get_coordoperation(m_ctxt, conv), nullptr); } auto conv = proj_crs_get_coordoperation(m_ctxt, crs); ASSERT_NE(conv, nullptr); ObjectKeeper keeper_conv(conv); EXPECT_TRUE(proj_coordoperation_get_method_info(m_ctxt, conv, nullptr, nullptr, nullptr)); const char *methodName = nullptr; const char *methodAuthorityName = nullptr; const char *methodCode = nullptr; EXPECT_TRUE(proj_coordoperation_get_method_info( m_ctxt, conv, &methodName, &methodAuthorityName, &methodCode)); ASSERT_NE(methodName, nullptr); ASSERT_NE(methodAuthorityName, nullptr); ASSERT_NE(methodCode, nullptr); EXPECT_EQ(methodName, std::string("Transverse Mercator")); EXPECT_EQ(methodAuthorityName, std::string("EPSG")); EXPECT_EQ(methodCode, std::string("9807")); EXPECT_EQ(proj_coordoperation_get_param_count(m_ctxt, conv), 5); EXPECT_EQ(proj_coordoperation_get_param_index(m_ctxt, conv, "foo"), -1); EXPECT_EQ( proj_coordoperation_get_param_index(m_ctxt, conv, "False easting"), 3); EXPECT_FALSE(proj_coordoperation_get_param( m_ctxt, conv, -1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); EXPECT_FALSE(proj_coordoperation_get_param( m_ctxt, conv, 5, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); const char *name = nullptr; const char *nameAuthorityName = nullptr; const char *nameCode = nullptr; double value = 0; const char *valueString = nullptr; double valueUnitConvFactor = 0; const char *valueUnitName = nullptr; const char *unitAuthName = nullptr; const char *unitCode = nullptr; const char *unitCategory = nullptr; EXPECT_TRUE(proj_coordoperation_get_param( m_ctxt, conv, 3, &name, &nameAuthorityName, &nameCode, &value, &valueString, &valueUnitConvFactor, &valueUnitName, &unitAuthName, &unitCode, &unitCategory)); ASSERT_NE(name, nullptr); ASSERT_NE(nameAuthorityName, nullptr); ASSERT_NE(nameCode, nullptr); EXPECT_EQ(valueString, nullptr); ASSERT_NE(valueUnitName, nullptr); ASSERT_NE(unitAuthName, nullptr); ASSERT_NE(unitCategory, nullptr); ASSERT_NE(unitCategory, nullptr); EXPECT_EQ(name, std::string("False easting")); EXPECT_EQ(nameAuthorityName, std::string("EPSG")); EXPECT_EQ(nameCode, std::string("8806")); EXPECT_EQ(value, 500000.0); EXPECT_EQ(valueUnitConvFactor, 1.0); EXPECT_EQ(valueUnitName, std::string("metre")); EXPECT_EQ(unitAuthName, std::string("EPSG")); EXPECT_EQ(unitCode, std::string("9001")); EXPECT_EQ(unitCategory, std::string("linear")); } // --------------------------------------------------------------------------- TEST_F(CApi, transformation_from_boundCRS) { auto crs = proj_create_from_wkt( m_ctxt, createBoundCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); auto transf = proj_crs_get_coordoperation(m_ctxt, crs); ASSERT_NE(transf, nullptr); ObjectKeeper keeper_transf(transf); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_coordoperation_get_grid_used) { auto op = proj_create_from_database(m_ctxt, "EPSG", "1312", PJ_CATEGORY_COORDINATE_OPERATION, true, nullptr); ASSERT_NE(op, nullptr); ObjectKeeper keeper(op); const std::string old_endpoint = proj_context_get_url_endpoint(m_ctxt); proj_context_set_url_endpoint(m_ctxt, "https://example.com"); EXPECT_EQ(proj_coordoperation_get_grid_used_count(m_ctxt, op), 1); const char *shortName = nullptr; const char *fullName = nullptr; const char *packageName = nullptr; const char *url = nullptr; int directDownload = 0; int openLicense = 0; int available = 0; EXPECT_EQ(proj_coordoperation_get_grid_used(m_ctxt, op, -1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr), 0); EXPECT_EQ(proj_coordoperation_get_grid_used(m_ctxt, op, 1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr), 0); EXPECT_EQ(proj_coordoperation_get_grid_used( m_ctxt, op, 0, &shortName, &fullName, &packageName, &url, &directDownload, &openLicense, &available), 1); ASSERT_NE(shortName, nullptr); ASSERT_NE(fullName, nullptr); ASSERT_NE(packageName, nullptr); ASSERT_NE(url, nullptr); EXPECT_EQ(shortName, std::string("ca_nrc_ntv1_can.tif")); // EXPECT_EQ(fullName, std::string("")); EXPECT_EQ(packageName, std::string("")); EXPECT_EQ(std::string(url), "https://example.com/ca_nrc_ntv1_can.tif"); EXPECT_EQ(directDownload, 1); EXPECT_EQ(openLicense, 1); proj_context_set_url_endpoint(m_ctxt, old_endpoint.c_str()); } // --------------------------------------------------------------------------- #ifdef TIFF_ENABLED TEST_F(CApi, proj_coordoperation_get_grid_used_fullname_caching) { // Test bugfix for // https://github.com/OSGeo/PROJ/issues/3444#issuecomment-1309499342 for (int i = 0; i < 2; ++i) { const char *proj_string = "proj=vgridshift grids=tests/test_vgrid_int16.tif"; PJ *P = proj_create(m_ctxt, proj_string); ObjectKeeper keeper(P); const char *shortName = nullptr; const char *fullName = nullptr; const char *packageName = nullptr; const char *url = nullptr; int directDownload = 0; int openLicense = 0; int available = 0; proj_coordoperation_get_grid_used(m_ctxt, P, 0, &shortName, &fullName, &packageName, &url, &directDownload, &openLicense, &available); EXPECT_EQ(std::string(shortName), "tests/test_vgrid_int16.tif"); EXPECT_TRUE(std::string(fullName).find("tests/test_vgrid_int16.tif") != std::string::npos) << std::string(fullName); } } #endif // --------------------------------------------------------------------------- TEST_F(CApi, proj_coordoperation_is_instantiable) { auto op = proj_create_from_database(m_ctxt, "EPSG", "1671", PJ_CATEGORY_COORDINATE_OPERATION, true, nullptr); ASSERT_NE(op, nullptr); ObjectKeeper keeper(op); EXPECT_EQ(proj_coordoperation_is_instantiable(m_ctxt, op), 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_operations) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "4267", PJ_CATEGORY_CRS, false, nullptr); // NAD27 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "4269", PJ_CATEGORY_CRS, false, nullptr); // NAD83 ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 10); EXPECT_EQ(proj_list_get(m_ctxt, res, -1), nullptr); EXPECT_EQ(proj_list_get(m_ctxt, res, proj_list_get_count(res)), nullptr); { auto op = proj_list_get(m_ctxt, res, 0); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); EXPECT_FALSE( proj_coordoperation_has_ballpark_transformation(m_ctxt, op)); EXPECT_EQ(proj_get_name(op), std::string("NAD27 to NAD83 (4)")); } { PJ_COORD coord; coord.xy.x = 40; coord.xy.y = -100; int idx = proj_get_suggested_operation(m_ctxt, res, PJ_FWD, coord); ASSERT_GE(idx, 0); ASSERT_LT(idx, proj_list_get_count(res)); auto op = proj_list_get(m_ctxt, res, idx); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); // Transformation for USA, using NADCON5 EXPECT_EQ(proj_get_name(op), std::string("NAD27 to NAD83 (7)")); } { PJ_COORD coord; coord.xy.x = 40; coord.xy.y = 10; int idx = proj_get_suggested_operation(m_ctxt, res, PJ_FWD, coord); EXPECT_GE(idx, -1); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_suggested_operation_for_NAD83_to_NAD83_HARN) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "4269", PJ_CATEGORY_CRS, false, nullptr); // NAD83 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "4152", PJ_CATEGORY_CRS, false, nullptr); // NAD83(HARN) ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); { PJ_COORD coord; coord.xy.x = 40; coord.xy.y = -100; int idx = proj_get_suggested_operation(m_ctxt, res, PJ_FWD, coord); ASSERT_GE(idx, 0); ASSERT_LT(idx, proj_list_get_count(res)); auto op = proj_list_get(m_ctxt, res, idx); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); // Transformation for CONUS EXPECT_STREQ(proj_get_name(op), "NAD83 to NAD83(HARN) (47)"); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_operations_prime_meridian_non_greenwich) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "27562", PJ_CATEGORY_CRS, false, nullptr); // "NTF (Paris) / Lambert Centre France" ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "4258", PJ_CATEGORY_CRS, false, nullptr); // ETRS89 ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); { PJ_COORD coord; // lat,long=49,-4 if using grid coord.xy.x = 136555.58288992; coord.xy.y = 463344.51894296; int idx = proj_get_suggested_operation(m_ctxt, res, PJ_FWD, coord); ASSERT_GE(idx, 0); auto op = proj_list_get(m_ctxt, res, idx); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); // Transformation using grid EXPECT_EQ(proj_coordoperation_get_grid_used_count(m_ctxt, op), 1); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_suggested_operation_with_operations_without_area_of_use) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); // NAD83(2011) geocentric auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "6317", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); // NAD83(2011) 2D auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "6318", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); PJ_COORD coord; coord.xyz.x = -463930; coord.xyz.y = -4414006; coord.xyz.z = 4562247; int idx = proj_get_suggested_operation(m_ctxt, res, PJ_FWD, coord); EXPECT_GE(idx, 0); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_operations_discard_superseded) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "4203", PJ_CATEGORY_CRS, false, nullptr); // AGD84 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84 ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); proj_operation_factory_context_set_discard_superseded(m_ctxt, ctxt, true); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 4); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_operations_dont_discard_superseded) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "4203", PJ_CATEGORY_CRS, false, nullptr); // AGD84 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84 ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); proj_operation_factory_context_set_discard_superseded(m_ctxt, ctxt, false); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 5); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_operations_with_pivot) { auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "4230", PJ_CATEGORY_CRS, false, nullptr); // ED50 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "4171", PJ_CATEGORY_CRS, false, nullptr); // RGF93 v1 ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); // There is no direct transformations between both // Default behavior: allow any pivot { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); auto op = proj_list_get(m_ctxt, res, 0); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); EXPECT_EQ( proj_get_name(op), std::string( "ED50 to ETRS89 (10) + Inverse of RGF93 v1 to ETRS89 (1)")); } // Disallow pivots { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); proj_operation_factory_context_set_allow_use_intermediate_crs( m_ctxt, ctxt, PROJ_INTERMEDIATE_CRS_USE_NEVER); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); auto op = proj_list_get(m_ctxt, res, 0); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); EXPECT_EQ( proj_get_name(op), std::string("Ballpark geographic offset from ED50 to RGF93 v1")); } // Restrict pivot to ETRS89 { auto ctxt = proj_create_operation_factory_context(m_ctxt, "EPSG"); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); const char *pivots[] = {"EPSG", "4258", nullptr}; proj_operation_factory_context_set_allowed_intermediate_crs( m_ctxt, ctxt, pivots); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); auto op = proj_list_get(m_ctxt, res, 0); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); EXPECT_EQ( proj_get_name(op), std::string( "ED50 to ETRS89 (10) + Inverse of RGF93 v1 to ETRS89 (1)")); } // Restrict pivot to something unrelated { auto ctxt = proj_create_operation_factory_context(m_ctxt, "any"); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); const char *pivots[] = {"EPSG", "4267", nullptr}; // NAD27 proj_operation_factory_context_set_allowed_intermediate_crs( m_ctxt, ctxt, pivots); proj_operation_factory_context_set_allow_use_intermediate_crs( m_ctxt, ctxt, PROJ_INTERMEDIATE_CRS_USE_ALWAYS); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); auto op = proj_list_get(m_ctxt, res, 0); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); EXPECT_EQ( proj_get_name(op), std::string("Ballpark geographic offset from ED50 to RGF93 v1")); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_operations_allow_ballpark_transformations) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "4267", PJ_CATEGORY_CRS, false, nullptr); // NAD27 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "4258", PJ_CATEGORY_CRS, false, nullptr); // ETRS89 ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); // Default: allowed implicitly { auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); } // Allow explicitly { proj_operation_factory_context_set_allow_ballpark_transformations( m_ctxt, ctxt, true); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); } // Disallow { proj_operation_factory_context_set_allow_ballpark_transformations( m_ctxt, ctxt, false); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 0); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_set_database_path_null) { EXPECT_TRUE( proj_context_set_database_path(m_ctxt, nullptr, nullptr, nullptr)); auto source_crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_set_database_path_aux) { const std::string auxDbName( "file:proj_test_aux.db?mode=memory&cache=shared"); sqlite3 *dbAux = nullptr; sqlite3_open_v2( auxDbName.c_str(), &dbAux, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_URI, nullptr); ASSERT_TRUE(dbAux != nullptr); ASSERT_TRUE(sqlite3_exec(dbAux, "BEGIN", nullptr, nullptr, nullptr) == SQLITE_OK); { auto ctxt = DatabaseContext::create(); const auto dbStructure = ctxt->getDatabaseStructure(); for (const auto &sql : dbStructure) { ASSERT_TRUE(sqlite3_exec(dbAux, sql.c_str(), nullptr, nullptr, nullptr) == SQLITE_OK); } } ASSERT_TRUE(sqlite3_exec( dbAux, "INSERT INTO geodetic_crs VALUES('OTHER','OTHER_4326','WGS " "84',NULL,'geographic 2D','EPSG','6422','EPSG','6326'," "NULL,0);", nullptr, nullptr, nullptr) == SQLITE_OK); ASSERT_TRUE(sqlite3_exec(dbAux, "COMMIT", nullptr, nullptr, nullptr) == SQLITE_OK); const char *const aux_db_list[] = {auxDbName.c_str(), nullptr}; EXPECT_TRUE( proj_context_set_database_path(m_ctxt, nullptr, aux_db_list, nullptr)); sqlite3_close(dbAux); { auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84 ASSERT_NE(crs, nullptr); ObjectKeeper keeper_source_crs(crs); } { auto crs = proj_create_from_database(m_ctxt, "OTHER", "OTHER_4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84 ASSERT_NE(crs, nullptr); ObjectKeeper keeper_source_crs(crs); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_set_database_path_error_1) { EXPECT_FALSE(proj_context_set_database_path(m_ctxt, "i_do_not_exist.db", nullptr, nullptr)); // We will eventually re-open on the default DB auto source_crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_set_database_path_error_2) { const char *aux_db_list[] = {"i_do_not_exist.db", nullptr}; EXPECT_FALSE( proj_context_set_database_path(m_ctxt, nullptr, aux_db_list, nullptr)); // We will eventually re-open on the default DB auto source_crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); // WGS84 ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_guess_wkt_dialect) { EXPECT_EQ(proj_context_guess_wkt_dialect(nullptr, "LOCAL_CS[\"foo\"]"), PJ_GUESSED_WKT1_GDAL); EXPECT_EQ(proj_context_guess_wkt_dialect( nullptr, "GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_" "1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0]," "UNIT[\"Degree\",0.0174532925199433]]"), PJ_GUESSED_WKT1_ESRI); EXPECT_EQ(proj_context_guess_wkt_dialect( nullptr, " \n\t\rGEOGCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north],\n" " AXIS[\"geodetic longitude (Lon)\",east],\n" " UNIT[\"degree\",0.0174532925199433]]"), PJ_GUESSED_WKT2_2019); EXPECT_EQ(proj_context_guess_wkt_dialect( nullptr, "GEODCRS[\"WGS 84\",\n" " DATUM[\"World Geodetic System 1984\",\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north],\n" " AXIS[\"geodetic longitude (Lon)\",east],\n" " UNIT[\"degree\",0.0174532925199433]]"), PJ_GUESSED_WKT2_2015); EXPECT_EQ(proj_context_guess_wkt_dialect(nullptr, "foo"), PJ_GUESSED_NOT_WKT); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_from_name) { /* PJ_OBJ_LIST *proj_create_from_name( PJ_CONTEXT *ctx, const char *auth_name, const char *searchedName, const PJ_TYPE* types, size_t typesCount, int approximateMatch, size_t limitResultCount, const char* const *options); */ { auto res = proj_create_from_name(m_ctxt, nullptr, "WGS 84", nullptr, 0, false, 0, nullptr); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 5); } { auto res = proj_create_from_name(m_ctxt, "xx", "WGS 84", nullptr, 0, false, 0, nullptr); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 0); } { const PJ_TYPE types[] = {PJ_TYPE_GEODETIC_CRS, PJ_TYPE_PROJECTED_CRS}; auto res = proj_create_from_name(m_ctxt, nullptr, "WGS 84", types, 2, true, 10, nullptr); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 10); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_identify) { auto obj = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4807->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); { auto res = proj_identify(m_ctxt, obj, nullptr, nullptr, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); } { int *confidence = nullptr; auto res = proj_identify(m_ctxt, obj, "EPSG", nullptr, &confidence); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); EXPECT_EQ(confidence[0], 100); proj_int_list_destroy(confidence); } { auto objEllps = proj_create_from_wkt( m_ctxt, Ellipsoid::GRS1980->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeperEllps(objEllps); ASSERT_NE(objEllps, nullptr); auto res = proj_identify(m_ctxt, objEllps, nullptr, nullptr, nullptr); ObjListKeeper keeper_res(res); EXPECT_EQ(res, nullptr); } { auto obj2 = proj_create( m_ctxt, "+proj=longlat +datum=WGS84 +no_defs +type=crs"); ObjectKeeper keeper2(obj2); ASSERT_NE(obj2, nullptr); int *confidence = nullptr; auto res = proj_identify(m_ctxt, obj2, nullptr, nullptr, &confidence); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 4); proj_int_list_destroy(confidence); } { auto obj2 = proj_create_from_database(m_ctxt, "IGNF", "ETRS89UTM28", PJ_CATEGORY_CRS, false, nullptr); ObjectKeeper keeper2(obj2); ASSERT_NE(obj2, nullptr); int *confidence = nullptr; auto res = proj_identify(m_ctxt, obj2, "EPSG", nullptr, &confidence); ObjListKeeper keeper_res(res); EXPECT_EQ(proj_list_get_count(res), 1); auto gotCRS = proj_list_get(m_ctxt, res, 0); ASSERT_NE(gotCRS, nullptr); ObjectKeeper keeper_gotCRS(gotCRS); auto auth = proj_get_id_auth_name(gotCRS, 0); ASSERT_TRUE(auth != nullptr); EXPECT_EQ(auth, std::string("EPSG")); auto code = proj_get_id_code(gotCRS, 0); ASSERT_TRUE(code != nullptr); EXPECT_EQ(code, std::string("25828")); EXPECT_EQ(confidence[0], 70); proj_int_list_destroy(confidence); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_domain_count) { auto crs = proj_create_from_database(m_ctxt, "EPSG", "6316", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); EXPECT_EQ(proj_get_domain_count(crs), 2); const char *name = nullptr; EXPECT_TRUE(proj_get_area_of_use_ex(m_ctxt, crs, 0, nullptr, nullptr, nullptr, nullptr, &name)); ASSERT_TRUE(name != nullptr); EXPECT_EQ(std::string(name), "Bosnia and Herzegovina - east of 19°30'E; Kosovo; Montenegro - " "east of 19°30'E; Serbia - between 19°30'E and 22°30'E."); const char *scope = proj_get_scope_ex(crs, 0); ASSERT_TRUE(scope != nullptr); EXPECT_STREQ(scope, "Cadastre, engineering survey, topographic mapping " "(large and medium scale)."); EXPECT_TRUE(proj_get_area_of_use_ex(m_ctxt, crs, 1, nullptr, nullptr, nullptr, nullptr, &name)); ASSERT_TRUE(name != nullptr); EXPECT_EQ(std::string(name), "North Macedonia."); scope = proj_get_scope_ex(crs, 1); ASSERT_TRUE(scope != nullptr); EXPECT_STREQ(scope, "Cadastre."); EXPECT_FALSE(proj_get_area_of_use_ex(m_ctxt, crs, -1, nullptr, nullptr, nullptr, nullptr, &name)); EXPECT_FALSE(proj_get_area_of_use_ex(m_ctxt, crs, 2, nullptr, nullptr, nullptr, nullptr, &name)); EXPECT_EQ(proj_get_scope_ex(crs, -1), nullptr); EXPECT_EQ(proj_get_scope_ex(crs, 2), nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_area_of_use) { { auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); EXPECT_TRUE(proj_get_area_of_use(m_ctxt, crs, nullptr, nullptr, nullptr, nullptr, nullptr)); const char *name = nullptr; double w; double s; double e; double n; EXPECT_TRUE(proj_get_area_of_use(m_ctxt, crs, &w, &s, &e, &n, &name)); EXPECT_EQ(w, -180); EXPECT_EQ(s, -90); EXPECT_EQ(e, 180); EXPECT_EQ(n, 90); ASSERT_TRUE(name != nullptr); EXPECT_EQ(std::string(name), "World."); } { auto obj = proj_create(m_ctxt, "+proj=longlat +type=crs"); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_FALSE(proj_get_area_of_use(m_ctxt, obj, nullptr, nullptr, nullptr, nullptr, nullptr)); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_coordoperation_get_accuracy) { { auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); EXPECT_EQ(proj_coordoperation_get_accuracy(m_ctxt, crs), -1.0); } { auto obj = proj_create_from_database(m_ctxt, "EPSG", "1170", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); EXPECT_EQ(proj_coordoperation_get_accuracy(m_ctxt, obj), 16.0); } { auto obj = proj_create(m_ctxt, "+proj=helmert"); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); EXPECT_EQ(proj_coordoperation_get_accuracy(m_ctxt, obj), -1.0); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_geographic_crs) { auto cs = proj_create_ellipsoidal_2D_cs( m_ctxt, PJ_ELLPS2D_LATITUDE_LONGITUDE, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); { auto obj = proj_create_geographic_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto objRef = proj_create(m_ctxt, GeographicCRS::EPSG_4326 ->exportToWKT(WKTFormatter::create().get()) .c_str()); ObjectKeeper keeperobjRef(objRef); EXPECT_NE(objRef, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT)); auto datum = proj_crs_get_datum(m_ctxt, obj); ObjectKeeper keeper_datum(datum); ASSERT_NE(datum, nullptr); auto obj2 = proj_create_geographic_crs_from_datum(m_ctxt, "WGS 84", datum, cs); ObjectKeeper keeperObj(obj2); ASSERT_NE(obj2, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, obj2, PJ_COMP_STRICT)); } { auto obj = proj_create_geographic_crs(m_ctxt, nullptr, nullptr, nullptr, 1.0, 0.0, nullptr, 0.0, nullptr, 0.0, cs); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); } // Datum with GDAL_WKT1 spelling: special case of WGS_1984 { auto obj = proj_create_geographic_crs( m_ctxt, "WGS 84", "WGS_1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto objRef = proj_create(m_ctxt, GeographicCRS::EPSG_4326 ->exportToWKT(WKTFormatter::create().get()) .c_str()); ObjectKeeper keeperobjRef(objRef); EXPECT_NE(objRef, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT)); } // Datum with GDAL_WKT1 spelling: database query { auto obj = proj_create_geographic_crs( m_ctxt, "NAD83", "North_American_Datum_1983", "GRS 1980", 6378137, 298.257222101, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto objRef = proj_create(m_ctxt, GeographicCRS::EPSG_4269 ->exportToWKT(WKTFormatter::create().get()) .c_str()); ObjectKeeper keeperobjRef(objRef); EXPECT_NE(objRef, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT)); } // Datum with GDAL_WKT1 spelling: database query in alias_name table { auto crs = proj_create_geographic_crs( m_ctxt, "S-JTSK (Ferro)", "System_Jednotne_Trigonometricke_Site_Katastralni_Ferro", "Bessel 1841", 6377397.155, 299.1528128, "Ferro", -17.66666666666667, "Degree", 0.0174532925199433, cs); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); auto datum = proj_crs_get_datum(m_ctxt, crs); ASSERT_NE(datum, nullptr); ObjectKeeper keeper_datum(datum); auto datum_name = proj_get_name(datum); ASSERT_TRUE(datum_name != nullptr); EXPECT_EQ(datum_name, std::string("System of the Unified Trigonometrical Cadastral " "Network (Ferro)")); } // WKT1 with (deprecated) { auto crs = proj_create_geographic_crs( m_ctxt, "SAD69 (deprecated)", "South_American_Datum_1969", "GRS 1967", 6378160, 298.247167427, "Greenwich", 0, "Degree", 0.0174532925199433, cs); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); auto name = proj_get_name(crs); ASSERT_TRUE(name != nullptr); EXPECT_EQ(name, std::string("SAD69")); EXPECT_TRUE(proj_is_deprecated(crs)); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_geocentric_crs) { { auto obj = proj_create_geocentric_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto objRef = proj_create(m_ctxt, GeographicCRS::EPSG_4978 ->exportToWKT(WKTFormatter::create().get()) .c_str()); ObjectKeeper keeperobjRef(objRef); EXPECT_NE(objRef, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, objRef, PJ_COMP_EQUIVALENT)); auto datum = proj_crs_get_datum(m_ctxt, obj); ObjectKeeper keeper_datum(datum); ASSERT_NE(datum, nullptr); auto obj2 = proj_create_geocentric_crs_from_datum(m_ctxt, "WGS 84", datum, "Metre", 1.0); ObjectKeeper keeperObj(obj2); ASSERT_NE(obj2, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, obj2, PJ_COMP_STRICT)); } { auto obj = proj_create_geocentric_crs(m_ctxt, nullptr, nullptr, nullptr, 1.0, 0.0, nullptr, 0.0, nullptr, 0.0, nullptr, 0.0); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, check_coord_op_obj_can_be_used_with_proj_trans) { { auto projCRS = proj_create_conversion_utm(m_ctxt, 31, true); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); { PJ *pj_used = proj_trans_get_last_used_operation(projCRS); ASSERT_EQ(pj_used, nullptr); } PJ_COORD coord; coord.xyzt.x = proj_torad(3.0); coord.xyzt.y = 0; coord.xyzt.z = 0; coord.xyzt.t = 0; EXPECT_NEAR(proj_trans(projCRS, PJ_FWD, coord).xyzt.x, 500000.0, 1e-9); { PJ *pj_used = proj_trans_get_last_used_operation(projCRS); ASSERT_TRUE( proj_is_equivalent_to(pj_used, projCRS, PJ_COMP_STRICT)); proj_destroy(pj_used); } } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_projections) { { constexpr int invalid_zone_number = 0; auto projCRS = proj_create_conversion_utm(m_ctxt, invalid_zone_number, 0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_EQ(projCRS, nullptr); } /* BEGIN: Generated by scripts/create_c_api_projections.py*/ { auto projCRS = proj_create_conversion_utm(m_ctxt, 1, 0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_transverse_mercator( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_gauss_schreiber_transverse_mercator( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_transverse_mercator_south_oriented( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_two_point_equidistant( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_tunisia_mining_grid( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_albers_equal_area( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_conic_conformal_1sp( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_conic_conformal_1sp_variant_b( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_conic_conformal_2sp( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_conic_conformal_2sp_michigan( m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_conic_conformal_2sp_belgium( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_azimuthal_equidistant( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_guam_projection( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_bonne( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_cylindrical_equal_area_spherical( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_cylindrical_equal_area( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_cassini_soldner( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_equidistant_conic( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_eckert_i( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_eckert_ii( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_eckert_iii( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_eckert_iv( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_eckert_v( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_eckert_vi( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_equidistant_cylindrical( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_equidistant_cylindrical_spherical( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_gall( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_goode_homolosine( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_interrupted_goode_homolosine( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_geostationary_satellite_sweep_x( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_geostationary_satellite_sweep_y( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_gnomonic( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_hotine_oblique_mercator_variant_a( m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_hotine_oblique_mercator_variant_b( m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_hotine_oblique_mercator_two_point_natural_origin( m_ctxt, 0, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_laborde_oblique_mercator( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_international_map_world_polyconic( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_krovak_north_oriented( m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_krovak(m_ctxt, 0, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_lambert_azimuthal_equal_area( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_miller_cylindrical( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_mercator_variant_a( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_mercator_variant_b( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_popular_visualisation_pseudo_mercator( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_mollweide( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_new_zealand_mapping_grid( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_oblique_stereographic( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_orthographic( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_american_polyconic( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_polar_stereographic_variant_a( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_polar_stereographic_variant_b( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_robinson( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_sinusoidal( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_stereographic( m_ctxt, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_van_der_grinten( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_wagner_i( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_wagner_ii( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_wagner_iii( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_wagner_iv( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_wagner_v( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_wagner_vi( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_wagner_vii( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_quadrilateralized_spherical_cube( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_spherical_cross_track_height( m_ctxt, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_equal_earth( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_vertical_perspective( m_ctxt, 0, 0, 0, 0, 0, 0, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_pole_rotation_grib_convention( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } { auto projCRS = proj_create_conversion_pole_rotation_netcdf_cf_convention( m_ctxt, 0, 0, 0, "Degree", 0.0174532925199433); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } /* END: Generated by scripts/create_c_api_projections.py*/ } // --------------------------------------------------------------------------- TEST_F(CApi, proj_cs_get_axis_info) { { auto crs = proj_create_from_database(m_ctxt, "EPSG", "4326", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper(crs); auto cs = proj_crs_get_coordinate_system(m_ctxt, crs); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); EXPECT_EQ(proj_cs_get_type(m_ctxt, cs), PJ_CS_TYPE_ELLIPSOIDAL); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 2); EXPECT_FALSE(proj_cs_get_axis_info(m_ctxt, cs, -1, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); EXPECT_FALSE(proj_cs_get_axis_info(m_ctxt, cs, 2, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); const char *name = nullptr; const char *abbrev = nullptr; const char *direction = nullptr; double unitConvFactor = 0.0; const char *unitName = nullptr; const char *unitAuthority = nullptr; const char *unitCode = nullptr; EXPECT_TRUE(proj_cs_get_axis_info( m_ctxt, cs, 0, &name, &abbrev, &direction, &unitConvFactor, &unitName, &unitAuthority, &unitCode)); ASSERT_NE(name, nullptr); ASSERT_NE(abbrev, nullptr); ASSERT_NE(direction, nullptr); ASSERT_NE(unitName, nullptr); ASSERT_NE(unitAuthority, nullptr); ASSERT_NE(unitCode, nullptr); EXPECT_EQ(std::string(name), "Geodetic latitude"); EXPECT_EQ(std::string(abbrev), "Lat"); EXPECT_EQ(std::string(direction), "north"); EXPECT_EQ(unitConvFactor, 0.017453292519943295) << unitConvFactor; EXPECT_EQ(std::string(unitName), "degree"); EXPECT_EQ(std::string(unitAuthority), "EPSG"); EXPECT_EQ(std::string(unitCode), "9122"); } // Non CRS object { auto obj = proj_create_from_database(m_ctxt, "EPSG", "1170", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ASSERT_NE(obj, nullptr); ObjectKeeper keeper(obj); EXPECT_EQ(proj_crs_get_coordinate_system(m_ctxt, obj), nullptr); EXPECT_EQ(proj_cs_get_type(m_ctxt, obj), PJ_CS_TYPE_UNKNOWN); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, obj), -1); EXPECT_FALSE(proj_cs_get_axis_info(m_ctxt, obj, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_get_database_metadata) { EXPECT_TRUE(proj_context_get_database_metadata(m_ctxt, "IGNF.VERSION") != nullptr); EXPECT_TRUE(proj_context_get_database_metadata(m_ctxt, "FOO") == nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_get_database_structure) { auto list = proj_context_get_database_structure(m_ctxt, nullptr); ASSERT_NE(list, nullptr); ASSERT_NE(list[0], nullptr); proj_string_list_destroy(list); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_clone) { auto obj = proj_create(m_ctxt, "+proj=longlat"); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto clone = proj_clone(m_ctxt, obj); ObjectKeeper keeperClone(clone); ASSERT_NE(clone, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, clone, PJ_COMP_STRICT)); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_clone_of_obj_with_alternative_operations) { // NAD27 to NAD83 auto obj = proj_create_crs_to_crs(m_ctxt, "EPSG:4267", "EPSG:4269", nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); PJ_COORD c; c.xyzt.x = 40.5; c.xyzt.y = -60; c.xyzt.z = 0; c.xyzt.t = 2021; PJ_COORD c_trans_ref = proj_trans(obj, PJ_FWD, c); EXPECT_NE(c_trans_ref.xyzt.x, c.xyzt.x); EXPECT_NEAR(c_trans_ref.xyzt.x, c.xyzt.x, 1e-3); EXPECT_NEAR(c_trans_ref.xyzt.y, c.xyzt.y, 1e-3); PJ *pj_used = proj_trans_get_last_used_operation(obj); ASSERT_NE(pj_used, nullptr); proj_destroy(pj_used); auto clone = proj_clone(m_ctxt, obj); ObjectKeeper keeperClone(clone); ASSERT_NE(clone, nullptr); EXPECT_TRUE(proj_is_equivalent_to(obj, clone, PJ_COMP_STRICT)); keeper.clear(); obj = nullptr; (void)obj; PJ_COORD c_trans = proj_trans(clone, PJ_FWD, c); EXPECT_EQ(c_trans.xyzt.x, c_trans_ref.xyzt.x); EXPECT_EQ(c_trans.xyzt.y, c_trans_ref.xyzt.y); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_alter_geodetic_crs) { auto projCRS = proj_create_from_wkt( m_ctxt, createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(projCRS); ASSERT_NE(projCRS, nullptr); auto newGeodCRS = proj_create(m_ctxt, "+proj=longlat +type=crs"); ObjectKeeper keeper_newGeodCRS(newGeodCRS); ASSERT_NE(newGeodCRS, nullptr); auto geodCRS = proj_crs_get_geodetic_crs(m_ctxt, projCRS); ObjectKeeper keeper_geodCRS(geodCRS); ASSERT_NE(geodCRS, nullptr); auto geodCRSAltered = proj_crs_alter_geodetic_crs(m_ctxt, geodCRS, newGeodCRS); ObjectKeeper keeper_geodCRSAltered(geodCRSAltered); ASSERT_NE(geodCRSAltered, nullptr); EXPECT_TRUE( proj_is_equivalent_to(geodCRSAltered, newGeodCRS, PJ_COMP_STRICT)); { auto projCRSAltered = proj_crs_alter_geodetic_crs(m_ctxt, projCRS, newGeodCRS); ObjectKeeper keeper_projCRSAltered(projCRSAltered); ASSERT_NE(projCRSAltered, nullptr); EXPECT_EQ(proj_get_type(projCRSAltered), PJ_TYPE_PROJECTED_CRS); auto projCRSAltered_geodCRS = proj_crs_get_geodetic_crs(m_ctxt, projCRSAltered); ObjectKeeper keeper_projCRSAltered_geodCRS(projCRSAltered_geodCRS); ASSERT_NE(projCRSAltered_geodCRS, nullptr); EXPECT_TRUE(proj_is_equivalent_to(projCRSAltered_geodCRS, newGeodCRS, PJ_COMP_STRICT)); } // Check that proj_crs_alter_geodetic_crs preserves deprecation flag { auto projCRSDeprecated = proj_alter_name(m_ctxt, projCRS, "new name (deprecated)"); ObjectKeeper keeper_projCRSDeprecated(projCRSDeprecated); ASSERT_NE(projCRSDeprecated, nullptr); auto projCRSAltered = proj_crs_alter_geodetic_crs(m_ctxt, projCRSDeprecated, newGeodCRS); ObjectKeeper keeper_projCRSAltered(projCRSAltered); ASSERT_NE(projCRSAltered, nullptr); EXPECT_EQ(proj_get_name(projCRSAltered), std::string("new name")); EXPECT_TRUE(proj_is_deprecated(projCRSAltered)); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_alter_cs_angular_unit) { auto crs = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4326->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); { auto alteredCRS = proj_crs_alter_cs_angular_unit(m_ctxt, crs, "my unit", 2, nullptr, nullptr); ObjectKeeper keeper_alteredCRS(alteredCRS); ASSERT_NE(alteredCRS, nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); double unitConvFactor = 0.0; const char *unitName = nullptr; EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr, nullptr, &unitConvFactor, &unitName, nullptr, nullptr)); ASSERT_NE(unitName, nullptr); EXPECT_EQ(unitConvFactor, 2) << unitConvFactor; EXPECT_EQ(std::string(unitName), "my unit"); } { auto alteredCRS = proj_crs_alter_cs_angular_unit( m_ctxt, crs, "my unit", 2, "my auth", "my code"); ObjectKeeper keeper_alteredCRS(alteredCRS); ASSERT_NE(alteredCRS, nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); double unitConvFactor = 0.0; const char *unitName = nullptr; const char *unitAuthName = nullptr; const char *unitCode = nullptr; EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr, nullptr, &unitConvFactor, &unitName, &unitAuthName, &unitCode)); ASSERT_NE(unitName, nullptr); EXPECT_EQ(unitConvFactor, 2) << unitConvFactor; EXPECT_EQ(std::string(unitName), "my unit"); ASSERT_NE(unitAuthName, nullptr); EXPECT_EQ(std::string(unitAuthName), "my auth"); ASSERT_NE(unitCode, nullptr); EXPECT_EQ(std::string(unitCode), "my code"); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_alter_cs_linear_unit) { auto crs = proj_create_from_wkt( m_ctxt, createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); { auto alteredCRS = proj_crs_alter_cs_linear_unit(m_ctxt, crs, "my unit", 2, nullptr, nullptr); ObjectKeeper keeper_alteredCRS(alteredCRS); ASSERT_NE(alteredCRS, nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); double unitConvFactor = 0.0; const char *unitName = nullptr; EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr, nullptr, &unitConvFactor, &unitName, nullptr, nullptr)); ASSERT_NE(unitName, nullptr); EXPECT_EQ(unitConvFactor, 2) << unitConvFactor; EXPECT_EQ(std::string(unitName), "my unit"); } { auto alteredCRS = proj_crs_alter_cs_linear_unit( m_ctxt, crs, "my unit", 2, "my auth", "my code"); ObjectKeeper keeper_alteredCRS(alteredCRS); ASSERT_NE(alteredCRS, nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, alteredCRS); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); double unitConvFactor = 0.0; const char *unitName = nullptr; const char *unitAuthName = nullptr; const char *unitCode = nullptr; EXPECT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, nullptr, nullptr, nullptr, &unitConvFactor, &unitName, &unitAuthName, &unitCode)); ASSERT_NE(unitName, nullptr); EXPECT_EQ(unitConvFactor, 2) << unitConvFactor; EXPECT_EQ(std::string(unitName), "my unit"); ASSERT_NE(unitAuthName, nullptr); EXPECT_EQ(std::string(unitAuthName), "my auth"); ASSERT_NE(unitCode, nullptr); EXPECT_EQ(std::string(unitCode), "my code"); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_alter_parameters_linear_unit) { auto crs = proj_create_from_wkt( m_ctxt, createProjectedCRS()->exportToWKT(WKTFormatter::create().get()).c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); { auto alteredCRS = proj_crs_alter_parameters_linear_unit( m_ctxt, crs, "my unit", 2, nullptr, nullptr, false); ObjectKeeper keeper_alteredCRS(alteredCRS); ASSERT_NE(alteredCRS, nullptr); auto wkt = proj_as_wkt(m_ctxt, alteredCRS, PJ_WKT2_2019, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("500000") != std::string::npos) << wkt; EXPECT_TRUE(std::string(wkt).find("\"my unit\",2") != std::string::npos) << wkt; } { auto alteredCRS = proj_crs_alter_parameters_linear_unit( m_ctxt, crs, "my unit", 2, nullptr, nullptr, true); ObjectKeeper keeper_alteredCRS(alteredCRS); ASSERT_NE(alteredCRS, nullptr); auto wkt = proj_as_wkt(m_ctxt, alteredCRS, PJ_WKT2_2019, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_TRUE(std::string(wkt).find("250000") != std::string::npos) << wkt; EXPECT_TRUE(std::string(wkt).find("\"my unit\",2") != std::string::npos) << wkt; } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_engineering_crs) { auto crs = proj_create_engineering_crs(m_ctxt, "name"); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); auto wkt = proj_as_wkt(m_ctxt, crs, PJ_WKT1_GDAL, nullptr); ASSERT_NE(wkt, nullptr); EXPECT_EQ(std::string(wkt), "LOCAL_CS[\"name\",\n" " UNIT[\"metre\",1,\n" " AUTHORITY[\"EPSG\",\"9001\"]],\n" " AXIS[\"Easting\",EAST],\n" " AXIS[\"Northing\",NORTH]]") << wkt; } // --------------------------------------------------------------------------- TEST_F(CApi, proj_alter_name) { auto cs = proj_create_ellipsoidal_2D_cs( m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); auto obj = proj_create_geographic_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); { auto alteredObj = proj_alter_name(m_ctxt, obj, "new name"); ObjectKeeper keeper_alteredObj(alteredObj); ASSERT_NE(alteredObj, nullptr); EXPECT_EQ(std::string(proj_get_name(alteredObj)), "new name"); EXPECT_FALSE(proj_is_deprecated(alteredObj)); } { auto alteredObj = proj_alter_name(m_ctxt, obj, "new name (deprecated)"); ObjectKeeper keeper_alteredObj(alteredObj); ASSERT_NE(alteredObj, nullptr); EXPECT_EQ(std::string(proj_get_name(alteredObj)), "new name"); EXPECT_TRUE(proj_is_deprecated(alteredObj)); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_alter_id) { auto cs = proj_create_ellipsoidal_2D_cs( m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); auto obj = proj_create_geographic_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, cs); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); auto alteredObj = proj_alter_id(m_ctxt, obj, "auth", "code"); ObjectKeeper keeper_alteredObj(alteredObj); ASSERT_NE(alteredObj, nullptr); EXPECT_EQ(std::string(proj_get_id_auth_name(alteredObj, 0)), "auth"); EXPECT_EQ(std::string(proj_get_id_code(alteredObj, 0)), "code"); auto alteredObj2 = proj_alter_id(m_ctxt, alteredObj, "auth2", "code2"); ObjectKeeper keeper_alteredObj2(alteredObj2); ASSERT_NE(alteredObj2, nullptr); EXPECT_EQ(std::string(proj_get_id_auth_name(alteredObj2, 0)), "auth2"); EXPECT_EQ(std::string(proj_get_id_code(alteredObj2, 0)), "code2"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_projected_crs) { PJ_PARAM_DESCRIPTION param; param.name = "param name"; param.auth_name = nullptr; param.code = nullptr; param.value = 0.99; param.unit_name = nullptr; param.unit_conv_factor = 1.0; param.unit_type = PJ_UT_SCALE; auto conv = proj_create_conversion(m_ctxt, "conv", "conv auth", "conv code", "method", "method auth", "method code", 1, &param); ObjectKeeper keeper_conv(conv); ASSERT_NE(conv, nullptr); auto geog_cs = proj_create_ellipsoidal_2D_cs( m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); ObjectKeeper keeper_geog_cs(geog_cs); ASSERT_NE(geog_cs, nullptr); auto geogCRS = proj_create_geographic_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs); ObjectKeeper keeper_geogCRS(geogCRS); ASSERT_NE(geogCRS, nullptr); auto cs = proj_create_cartesian_2D_cs(m_ctxt, PJ_CART2D_EASTING_NORTHING, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); auto projCRS = proj_create_projected_crs(m_ctxt, "my CRS", geogCRS, conv, cs); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_transformation) { PJ_PARAM_DESCRIPTION param; param.name = "param name"; param.auth_name = nullptr; param.code = nullptr; param.value = 0.99; param.unit_name = nullptr; param.unit_conv_factor = 1.0; param.unit_type = PJ_UT_SCALE; auto geog_cs = proj_create_ellipsoidal_2D_cs( m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); ObjectKeeper keeper_geog_cs(geog_cs); ASSERT_NE(geog_cs, nullptr); auto source_crs = proj_create_geographic_crs( m_ctxt, "Source CRS", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs); ObjectKeeper keeper_source_crs(source_crs); ASSERT_NE(source_crs, nullptr); auto target_crs = proj_create_geographic_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs); ObjectKeeper keeper_target_crs(target_crs); ASSERT_NE(target_crs, nullptr); auto interp_crs = proj_create_geographic_crs( m_ctxt, "Interpolation CRS", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs); ObjectKeeper keeper_interp_crs(interp_crs); ASSERT_NE(interp_crs, nullptr); { auto transf = proj_create_transformation( m_ctxt, "transf", "transf auth", "transf code", source_crs, target_crs, interp_crs, "method", "method auth", "method code", 1, &param, 0); ObjectKeeper keeper_transf(transf); ASSERT_NE(transf, nullptr); EXPECT_EQ(proj_coordoperation_get_param_count(m_ctxt, transf), 1); auto got_source_crs = proj_get_source_crs(m_ctxt, transf); ObjectKeeper keeper_got_source_crs(got_source_crs); ASSERT_NE(got_source_crs, nullptr); EXPECT_TRUE( proj_is_equivalent_to(source_crs, got_source_crs, PJ_COMP_STRICT)); auto got_target_crs = proj_get_target_crs(m_ctxt, transf); ObjectKeeper keeper_got_target_crs(got_target_crs); ASSERT_NE(got_target_crs, nullptr); EXPECT_TRUE( proj_is_equivalent_to(target_crs, got_target_crs, PJ_COMP_STRICT)); } { auto transf = proj_create_transformation( m_ctxt, "transf", "transf auth", "transf code", source_crs, target_crs, nullptr, "method", "method auth", "method code", 1, &param, -1); ObjectKeeper keeper_transf(transf); ASSERT_NE(transf, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_compound_crs) { auto horiz_cs = proj_create_ellipsoidal_2D_cs( m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); ObjectKeeper keeper_horiz_cs(horiz_cs); ASSERT_NE(horiz_cs, nullptr); auto horiz_crs = proj_create_geographic_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, horiz_cs); ObjectKeeper keeper_horiz_crs(horiz_crs); ASSERT_NE(horiz_crs, nullptr); auto vert_crs = proj_create_vertical_crs(m_ctxt, "myVertCRS", "myVertDatum", nullptr, 0.0); ObjectKeeper keeper_vert_crs(vert_crs); ASSERT_NE(vert_crs, nullptr); EXPECT_EQ(proj_get_name(vert_crs), std::string("myVertCRS")); auto compound_crs = proj_create_compound_crs(m_ctxt, "myCompoundCRS", horiz_crs, vert_crs); ObjectKeeper keeper_compound_crss(compound_crs); ASSERT_NE(compound_crs, nullptr); EXPECT_EQ(proj_get_name(compound_crs), std::string("myCompoundCRS")); auto subcrs_horiz = proj_crs_get_sub_crs(m_ctxt, compound_crs, 0); ASSERT_NE(subcrs_horiz, nullptr); ObjectKeeper keeper_subcrs_horiz(subcrs_horiz); EXPECT_TRUE(proj_is_equivalent_to(subcrs_horiz, horiz_crs, PJ_COMP_STRICT)); auto subcrs_vert = proj_crs_get_sub_crs(m_ctxt, compound_crs, 1); ASSERT_NE(subcrs_vert, nullptr); ObjectKeeper keeper_subcrs_vert(subcrs_vert); EXPECT_TRUE(proj_is_equivalent_to(subcrs_vert, vert_crs, PJ_COMP_STRICT)); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_convert_conversion_to_other_method) { { auto geog_cs = proj_create_ellipsoidal_2D_cs( m_ctxt, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); ObjectKeeper keeper_geog_cs(geog_cs); ASSERT_NE(geog_cs, nullptr); auto geogCRS = proj_create_geographic_crs( m_ctxt, "WGS 84", "World Geodetic System 1984", "WGS 84", 6378137, 298.257223563, "Greenwich", 0.0, "Degree", 0.0174532925199433, geog_cs); ObjectKeeper keeper_geogCRS(geogCRS); ASSERT_NE(geogCRS, nullptr); auto cs = proj_create_cartesian_2D_cs( m_ctxt, PJ_CART2D_EASTING_NORTHING, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); auto conv = proj_create_conversion_mercator_variant_a( m_ctxt, 0, 1, 0.99, 2, 3, "Degree", 0.0174532925199433, "Metre", 1.0); ObjectKeeper keeper_conv(conv); ASSERT_NE(conv, nullptr); auto projCRS = proj_create_projected_crs(m_ctxt, "my CRS", geogCRS, conv, cs); ObjectKeeper keeper_projCRS(projCRS); ASSERT_NE(projCRS, nullptr); // Wrong object type EXPECT_EQ( proj_convert_conversion_to_other_method( m_ctxt, projCRS, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, nullptr), nullptr); auto conv_in_proj = proj_crs_get_coordoperation(m_ctxt, projCRS); ObjectKeeper keeper_conv_in_proj(conv_in_proj); ASSERT_NE(conv_in_proj, nullptr); // 3rd and 4th argument both 0/null EXPECT_EQ(proj_convert_conversion_to_other_method(m_ctxt, conv_in_proj, 0, nullptr), nullptr); auto new_conv = proj_convert_conversion_to_other_method( m_ctxt, conv_in_proj, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, nullptr); ObjectKeeper keeper_new_conv(new_conv); ASSERT_NE(new_conv, nullptr); EXPECT_FALSE( proj_is_equivalent_to(new_conv, conv_in_proj, PJ_COMP_STRICT)); EXPECT_TRUE( proj_is_equivalent_to(new_conv, conv_in_proj, PJ_COMP_EQUIVALENT)); auto new_conv_from_name = proj_convert_conversion_to_other_method( m_ctxt, conv_in_proj, 0, EPSG_NAME_METHOD_MERCATOR_VARIANT_B); ObjectKeeper keeper_new_conv_from_name(new_conv_from_name); ASSERT_NE(new_conv_from_name, nullptr); EXPECT_TRUE(proj_is_equivalent_to(new_conv, new_conv_from_name, PJ_COMP_STRICT)); auto new_conv_back = proj_convert_conversion_to_other_method( m_ctxt, conv_in_proj, 0, EPSG_NAME_METHOD_MERCATOR_VARIANT_A); ObjectKeeper keeper_new_conv_back(new_conv_back); ASSERT_NE(new_conv_back, nullptr); EXPECT_TRUE( proj_is_equivalent_to(conv_in_proj, new_conv_back, PJ_COMP_STRICT)); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_non_deprecated) { auto crs = proj_create_from_database(m_ctxt, "EPSG", "4226", PJ_CATEGORY_CRS, false, nullptr); ObjectKeeper keeper(crs); ASSERT_NE(crs, nullptr); auto list = proj_get_non_deprecated(m_ctxt, crs); ASSERT_NE(list, nullptr); ObjListKeeper keeper_list(list); EXPECT_EQ(proj_list_get_count(list), 2); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_query_geodetic_crs_from_datum) { { auto list = proj_query_geodetic_crs_from_datum(m_ctxt, nullptr, "EPSG", "6326", nullptr); ASSERT_NE(list, nullptr); ObjListKeeper keeper_list(list); EXPECT_GE(proj_list_get_count(list), 3); } { auto list = proj_query_geodetic_crs_from_datum(m_ctxt, "EPSG", "EPSG", "6326", "geographic 2D"); ASSERT_NE(list, nullptr); ObjListKeeper keeper_list(list); EXPECT_EQ(proj_list_get_count(list), 1); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_uom_get_info_from_database) { { EXPECT_FALSE(proj_uom_get_info_from_database( m_ctxt, "auth", "code", nullptr, nullptr, nullptr)); } { EXPECT_TRUE(proj_uom_get_info_from_database(m_ctxt, "EPSG", "9001", nullptr, nullptr, nullptr)); } { const char *name = nullptr; double conv_factor = 0.0; const char *category = nullptr; EXPECT_TRUE(proj_uom_get_info_from_database( m_ctxt, "EPSG", "9001", &name, &conv_factor, &category)); ASSERT_NE(name, nullptr); ASSERT_NE(category, nullptr); EXPECT_EQ(std::string(name), "metre"); EXPECT_EQ(conv_factor, 1.0); EXPECT_EQ(std::string(category), "linear"); } { const char *name = nullptr; double conv_factor = 0.0; const char *category = nullptr; EXPECT_TRUE(proj_uom_get_info_from_database( m_ctxt, "EPSG", "9102", &name, &conv_factor, &category)); ASSERT_NE(name, nullptr); ASSERT_NE(category, nullptr); EXPECT_EQ(std::string(name), "degree"); EXPECT_NEAR(conv_factor, UnitOfMeasure::DEGREE.conversionToSI(), 1e-10); EXPECT_EQ(std::string(category), "angular"); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_grid_get_info_from_database) { { EXPECT_FALSE(proj_grid_get_info_from_database(m_ctxt, "xxx", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); } { EXPECT_TRUE(proj_grid_get_info_from_database( m_ctxt, "au_icsm_GDA94_GDA2020_conformal.tif", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); } { const char *full_name = nullptr; const char *package_name = nullptr; const char *url = nullptr; int direct_download = 0; int open_license = 0; int available = 0; EXPECT_TRUE(proj_grid_get_info_from_database( m_ctxt, "au_icsm_GDA94_GDA2020_conformal.tif", &full_name, &package_name, &url, &direct_download, &open_license, &available)); ASSERT_NE(full_name, nullptr); // empty string expected as the file is not in test data EXPECT_TRUE(full_name[0] == 0); ASSERT_NE(package_name, nullptr); EXPECT_TRUE(package_name[0] == 0); // empty string expected ASSERT_NE(url, nullptr); EXPECT_EQ(std::string(url), "https://cdn.proj.org/au_icsm_GDA94_GDA2020_conformal.tif"); EXPECT_EQ(direct_download, 1); EXPECT_EQ(open_license, 1); } // Same test as above, but with PROJ 6 grid name { const char *full_name = nullptr; const char *package_name = nullptr; const char *url = nullptr; int direct_download = 0; int open_license = 0; int available = 0; EXPECT_TRUE(proj_grid_get_info_from_database( m_ctxt, "GDA94_GDA2020_conformal.gsb", &full_name, &package_name, &url, &direct_download, &open_license, &available)); ASSERT_NE(full_name, nullptr); // empty string expected as the file is not in test data EXPECT_TRUE(full_name[0] == 0); ASSERT_NE(package_name, nullptr); EXPECT_TRUE(package_name[0] == 0); // empty string expected ASSERT_NE(url, nullptr); EXPECT_EQ(std::string(url), "https://cdn.proj.org/au_icsm_GDA94_GDA2020_conformal.tif"); EXPECT_EQ(direct_download, 1); EXPECT_EQ(open_license, 1); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_cartesian_2D_cs) { { auto cs = proj_create_cartesian_2D_cs( m_ctxt, PJ_CART2D_EASTING_NORTHING, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); } { auto cs = proj_create_cartesian_2D_cs( m_ctxt, PJ_CART2D_NORTHING_EASTING, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); } { auto cs = proj_create_cartesian_2D_cs( m_ctxt, PJ_CART2D_NORTH_POLE_EASTING_SOUTH_NORTHING_SOUTH, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); } { auto cs = proj_create_cartesian_2D_cs( m_ctxt, PJ_CART2D_SOUTH_POLE_EASTING_NORTH_NORTHING_NORTH, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); } { auto cs = proj_create_cartesian_2D_cs( m_ctxt, PJ_CART2D_WESTING_SOUTHING, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_crs_info_list_from_database) { { proj_crs_info_list_destroy(nullptr); } { proj_get_crs_list_parameters_destroy(nullptr); } // All null parameters { auto list = proj_get_crs_info_list_from_database(nullptr, nullptr, nullptr, nullptr); ASSERT_NE(list, nullptr); ASSERT_NE(list[0], nullptr); EXPECT_NE(list[0]->auth_name, nullptr); EXPECT_NE(list[0]->code, nullptr); EXPECT_NE(list[0]->name, nullptr); proj_crs_info_list_destroy(list); } // Default parameters { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params, &result_count); proj_get_crs_list_parameters_destroy(params); ASSERT_NE(list, nullptr); EXPECT_GT(result_count, 1); EXPECT_EQ(list[result_count], nullptr); bool found4326 = false; bool found4978 = false; bool found4979 = false; bool found32631 = false; bool found3855 = false; bool found3901 = false; for (int i = 0; i < result_count; i++) { // EPSG should only include Earth CRS, at least for now... EXPECT_EQ(std::string(list[i]->celestial_body_name), "Earth"); auto code = std::string(list[i]->code); if (code == "4326") { found4326 = true; EXPECT_EQ(std::string(list[i]->auth_name), "EPSG"); EXPECT_EQ(std::string(list[i]->name), "WGS 84"); EXPECT_EQ(list[i]->type, PJ_TYPE_GEOGRAPHIC_2D_CRS); EXPECT_EQ(list[i]->deprecated, 0); EXPECT_EQ(list[i]->bbox_valid, 1); EXPECT_EQ(list[i]->west_lon_degree, -180.0); EXPECT_EQ(list[i]->south_lat_degree, -90.0); EXPECT_EQ(list[i]->east_lon_degree, 180.0); EXPECT_EQ(list[i]->north_lat_degree, 90.0); EXPECT_TRUE(std::string(list[i]->area_name).find("World") == 0) << std::string(list[i]->area_name); EXPECT_EQ(list[i]->projection_method_name, nullptr); } else if (code == "4978") { found4978 = true; EXPECT_EQ(list[i]->type, PJ_TYPE_GEOCENTRIC_CRS); } else if (code == "4979") { found4979 = true; EXPECT_EQ(list[i]->type, PJ_TYPE_GEOGRAPHIC_3D_CRS); } else if (code == "32631") { found32631 = true; EXPECT_EQ(list[i]->type, PJ_TYPE_PROJECTED_CRS); EXPECT_EQ(std::string(list[i]->projection_method_name), "Transverse Mercator"); } else if (code == "3855") { found3855 = true; EXPECT_EQ(list[i]->type, PJ_TYPE_VERTICAL_CRS); } else if (code == "3901") { found3901 = true; EXPECT_EQ(list[i]->type, PJ_TYPE_COMPOUND_CRS); } EXPECT_EQ(list[i]->deprecated, 0); } EXPECT_TRUE(found4326); EXPECT_TRUE(found4978); EXPECT_TRUE(found4979); EXPECT_TRUE(found32631); EXPECT_TRUE(found3855); EXPECT_TRUE(found3901); proj_crs_info_list_destroy(list); } // Filter on only geodetic crs { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); params->typesCount = 1; auto type = PJ_TYPE_GEODETIC_CRS; params->types = &type; auto list = proj_get_crs_info_list_from_database(m_ctxt, nullptr, params, &result_count); bool foundGeog2D = false; bool foundGeog3D = false; bool foundGeocentric = false; bool foundGeodeticCRS = false; // for now, only -ocentric ellipsoidal IAU CRS for (int i = 0; i < result_count; i++) { foundGeog2D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS; foundGeog3D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS; foundGeocentric |= list[i]->type == PJ_TYPE_GEOCENTRIC_CRS; foundGeodeticCRS |= list[i]->type == PJ_TYPE_GEODETIC_CRS; EXPECT_TRUE(list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS || list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS || list[i]->type == PJ_TYPE_GEOCENTRIC_CRS || list[i]->type == PJ_TYPE_GEODETIC_CRS); } EXPECT_TRUE(foundGeog2D); EXPECT_TRUE(foundGeog3D); EXPECT_TRUE(foundGeocentric); EXPECT_TRUE(foundGeodeticCRS); proj_get_crs_list_parameters_destroy(params); proj_crs_info_list_destroy(list); } // Filter on only geographic crs { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); params->typesCount = 1; auto type = PJ_TYPE_GEOGRAPHIC_CRS; params->types = &type; auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params, &result_count); bool foundGeog2D = false; bool foundGeog3D = false; for (int i = 0; i < result_count; i++) { foundGeog2D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS; foundGeog3D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS; EXPECT_TRUE(list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS || list[i]->type == PJ_TYPE_GEOGRAPHIC_3D_CRS); } EXPECT_TRUE(foundGeog2D); EXPECT_TRUE(foundGeog3D); proj_get_crs_list_parameters_destroy(params); proj_crs_info_list_destroy(list); } // Filter on only geographic 2D crs and projected CRS { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); params->typesCount = 2; const PJ_TYPE types[] = {PJ_TYPE_GEOGRAPHIC_2D_CRS, PJ_TYPE_PROJECTED_CRS}; params->types = types; auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params, &result_count); bool foundGeog2D = false; bool foundProjected = false; for (int i = 0; i < result_count; i++) { foundGeog2D |= list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS; foundProjected |= list[i]->type == PJ_TYPE_PROJECTED_CRS; EXPECT_TRUE(list[i]->type == PJ_TYPE_GEOGRAPHIC_2D_CRS || list[i]->type == PJ_TYPE_PROJECTED_CRS); } EXPECT_TRUE(foundGeog2D); EXPECT_TRUE(foundProjected); proj_get_crs_list_parameters_destroy(params); proj_crs_info_list_destroy(list); } // Filter on bbox (inclusion) { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); params->bbox_valid = 1; params->west_lon_degree = 2; params->south_lat_degree = 49; params->east_lon_degree = 2.1; params->north_lat_degree = 49.1; params->typesCount = 1; auto type = PJ_TYPE_PROJECTED_CRS; params->types = &type; auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params, &result_count); ASSERT_NE(list, nullptr); EXPECT_GT(result_count, 1); for (int i = 0; i < result_count; i++) { if (list[i]->west_lon_degree < list[i]->east_lon_degree) { EXPECT_LE(list[i]->west_lon_degree, params->west_lon_degree); EXPECT_GE(list[i]->east_lon_degree, params->east_lon_degree); } EXPECT_LE(list[i]->south_lat_degree, params->south_lat_degree); EXPECT_GE(list[i]->north_lat_degree, params->north_lat_degree); } proj_get_crs_list_parameters_destroy(params); proj_crs_info_list_destroy(list); } // Filter on bbox (intersection) { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); params->bbox_valid = 1; params->west_lon_degree = 2; params->south_lat_degree = 49; params->east_lon_degree = 2.1; params->north_lat_degree = 49.1; params->crs_area_of_use_contains_bbox = 0; params->typesCount = 1; auto type = PJ_TYPE_PROJECTED_CRS; params->types = &type; auto list = proj_get_crs_info_list_from_database(m_ctxt, "EPSG", params, &result_count); ASSERT_NE(list, nullptr); EXPECT_GT(result_count, 1); for (int i = 0; i < result_count; i++) { if (list[i]->west_lon_degree < list[i]->east_lon_degree) { EXPECT_LE(list[i]->west_lon_degree, params->west_lon_degree); EXPECT_GE(list[i]->east_lon_degree, params->east_lon_degree); } EXPECT_LE(list[i]->south_lat_degree, params->north_lat_degree); EXPECT_GE(list[i]->north_lat_degree, params->south_lat_degree); } proj_get_crs_list_parameters_destroy(params); proj_crs_info_list_destroy(list); } // Filter on celestial body { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); params->celestial_body_name = "non existing"; auto list = proj_get_crs_info_list_from_database(m_ctxt, nullptr, params, &result_count); ASSERT_NE(list, nullptr); EXPECT_EQ(result_count, 0); proj_get_crs_list_parameters_destroy(params); proj_crs_info_list_destroy(list); } // Filter on celestial body { int result_count = 0; auto params = proj_get_crs_list_parameters_create(); params->celestial_body_name = "Earth"; auto list = proj_get_crs_info_list_from_database(m_ctxt, nullptr, params, &result_count); ASSERT_NE(list, nullptr); EXPECT_GT(result_count, 0); proj_get_crs_list_parameters_destroy(params); proj_crs_info_list_destroy(list); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_units_from_database) { { proj_unit_list_destroy(nullptr); } { auto list = proj_get_units_from_database(nullptr, nullptr, nullptr, true, nullptr); ASSERT_NE(list, nullptr); ASSERT_NE(list[0], nullptr); ASSERT_NE(list[0]->auth_name, nullptr); ASSERT_NE(list[0]->code, nullptr); ASSERT_NE(list[0]->name, nullptr); proj_unit_list_destroy(list); } { int result_count = 0; auto list = proj_get_units_from_database(nullptr, "EPSG", "linear", false, &result_count); ASSERT_NE(list, nullptr); EXPECT_GT(result_count, 1); EXPECT_EQ(list[result_count], nullptr); bool found9001 = false; for (int i = 0; i < result_count; i++) { EXPECT_EQ(std::string(list[i]->auth_name), "EPSG"); if (std::string(list[i]->code) == "9001") { EXPECT_EQ(std::string(list[i]->name), "metre"); EXPECT_EQ(std::string(list[i]->category), "linear"); EXPECT_EQ(list[i]->conv_factor, 1.0); ASSERT_NE(list[i]->proj_short_name, nullptr); EXPECT_EQ(std::string(list[i]->proj_short_name), "m"); EXPECT_EQ(list[i]->deprecated, 0); found9001 = true; } EXPECT_EQ(list[i]->deprecated, 0); } EXPECT_TRUE(found9001); proj_unit_list_destroy(list); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_celestial_body_list_from_database) { { proj_celestial_body_list_destroy(nullptr); } { auto list = proj_get_celestial_body_list_from_database(nullptr, nullptr, nullptr); ASSERT_NE(list, nullptr); ASSERT_NE(list[0], nullptr); ASSERT_NE(list[0]->auth_name, nullptr); ASSERT_NE(list[0]->name, nullptr); proj_celestial_body_list_destroy(list); } { int result_count = 0; auto list = proj_get_celestial_body_list_from_database(nullptr, "ESRI", &result_count); ASSERT_NE(list, nullptr); EXPECT_GT(result_count, 1); EXPECT_EQ(list[result_count], nullptr); bool foundGanymede = false; for (int i = 0; i < result_count; i++) { EXPECT_EQ(std::string(list[i]->auth_name), "ESRI"); if (std::string(list[i]->name) == "Ganymede") { foundGanymede = true; } } EXPECT_TRUE(foundGanymede); proj_celestial_body_list_destroy(list); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_normalize_for_visualization) { { auto P = proj_create(m_ctxt, "+proj=utm +zone=31 +ellps=WGS84"); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper keeper_Pnormalized(Pnormalized); EXPECT_EQ(Pnormalized, nullptr); } auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4326", "EPSG:32631", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper keeper_Pnormalized(Pnormalized); ASSERT_NE(Pnormalized, nullptr); auto projstr = proj_as_proj_string(m_ctxt, Pnormalized, PJ_PROJ_5, nullptr); ASSERT_NE(projstr, nullptr); EXPECT_EQ(std::string(projstr), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=utm +zone=31 +ellps=WGS84"); EXPECT_TRUE(proj_degree_input(Pnormalized, PJ_FWD)); EXPECT_FALSE(proj_degree_output(Pnormalized, PJ_FWD)); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_normalize_for_visualization_with_alternatives) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4326", "EPSG:3003", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper keeper_Pnormalized(Pnormalized); ASSERT_NE(Pnormalized, nullptr); EXPECT_TRUE(proj_degree_input(Pnormalized, PJ_FWD)); EXPECT_FALSE(proj_degree_output(Pnormalized, PJ_FWD)); { PJ_COORD c; // Approximately Roma c.xyzt.x = 12.5; c.xyzt.y = 42; c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(Pnormalized, PJ_FWD, c); EXPECT_NEAR(c.xy.x, 1789912.46264783037, 1e-8); EXPECT_NEAR(c.xy.y, 4655716.25402576849, 1e-8); auto projstr = proj_pj_info(Pnormalized).definition; ASSERT_NE(projstr, nullptr); EXPECT_EQ(std::string(projstr), "proj=pipeline step proj=unitconvert xy_in=deg xy_out=rad " "step proj=push v_3 step proj=cart ellps=WGS84 " "step inv proj=helmert x=-104.1 y=-49.1 z=-9.9 rx=0.971 " "ry=-2.917 rz=0.714 s=-11.68 convention=position_vector " "step inv proj=cart ellps=intl step proj=pop v_3 " "step proj=tmerc lat_0=0 lon_0=9 k=0.9996 x_0=1500000 " "y_0=0 ellps=intl"); } { PJ_COORD c; // Approximately Roma c.xyzt.x = 1789912.46264783037; c.xyzt.y = 4655716.25402576849; c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(Pnormalized, PJ_INV, c); EXPECT_NEAR(c.lp.lam, 12.5, 1e-8); EXPECT_NEAR(c.lp.phi, 42, 1e-8); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_normalize_for_visualization_with_alternatives_reverse) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:3003", "EPSG:4326", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper keeper_Pnormalized(Pnormalized); ASSERT_NE(Pnormalized, nullptr); EXPECT_FALSE(proj_degree_input(Pnormalized, PJ_FWD)); EXPECT_TRUE(proj_degree_output(Pnormalized, PJ_FWD)); PJ_COORD c; // Approximately Roma c.xyzt.x = 1789912.46264783037; c.xyzt.y = 4655716.25402576849; c.xyzt.z = 0; c.xyzt.t = HUGE_VAL; c = proj_trans(Pnormalized, PJ_FWD, c); EXPECT_NEAR(c.lp.lam, 12.5, 1e-8); EXPECT_NEAR(c.lp.phi, 42, 1e-8); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_normalize_for_visualization_on_crs) { auto P = proj_create(m_ctxt, "EPSG:4326"); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper keeper_Pnormalized(Pnormalized); ASSERT_NE(Pnormalized, nullptr); EXPECT_EQ(proj_get_id_code(Pnormalized, 0), nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, Pnormalized); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); const char *name = nullptr; ASSERT_TRUE(proj_cs_get_axis_info(m_ctxt, cs, 0, &name, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr)); ASSERT_NE(name, nullptr); EXPECT_EQ(std::string(name), "Geodetic longitude"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_coordoperation_create_inverse) { auto P = proj_create( m_ctxt, "+proj=pipeline +step +proj=axisswap +order=2,1 +step " "+proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push " "+v_3 +step +proj=cart +ellps=evrst30 +step +proj=helmert " "+x=293 +y=836 +z=318 +rx=0.5 +ry=1.6 +rz=-2.8 +s=2.1 " "+convention=position_vector +step +inv +proj=cart " "+ellps=WGS84 +step +proj=pop +v_3 +step +proj=unitconvert " "+xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1"); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pinversed = proj_coordoperation_create_inverse(m_ctxt, P); ObjectKeeper keeper_Pinversed(Pinversed); ASSERT_NE(Pinversed, nullptr); const char *options[] = {"MULTILINE=YES", "INDENTATION_WIDTH=4", "MAX_LINE_LENGTH=40", nullptr}; auto projstr = proj_as_proj_string(m_ctxt, Pinversed, PJ_PROJ_5, options); ASSERT_NE(projstr, nullptr); const char *expected_projstr = "+proj=pipeline\n" " +step +proj=axisswap +order=2,1\n" " +step +proj=unitconvert +xy_in=deg\n" " +xy_out=rad\n" " +step +proj=push +v_3\n" " +step +proj=cart +ellps=WGS84\n" " +step +inv +proj=helmert +x=293\n" " +y=836 +z=318 +rx=0.5 +ry=1.6\n" " +rz=-2.8 +s=2.1\n" " +convention=position_vector\n" " +step +inv +proj=cart +ellps=evrst30\n" " +step +proj=pop +v_3\n" " +step +proj=unitconvert +xy_in=rad\n" " +xy_out=deg\n" " +step +proj=axisswap +order=2,1"; EXPECT_EQ(std::string(projstr), expected_projstr); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_remarks) { // Transformation { auto co = proj_create_from_database(m_ctxt, "EPSG", "8048", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ObjectKeeper keeper(co); ASSERT_NE(co, nullptr); auto remarks = proj_get_remarks(co); ASSERT_NE(remarks, nullptr); EXPECT_TRUE(std::string(remarks).find( "Scale difference in ppb where 1/billion = 1E-9.") == 0) << remarks; } // Conversion { auto co = proj_create_from_database(m_ctxt, "EPSG", "3811", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ObjectKeeper keeper(co); ASSERT_NE(co, nullptr); auto remarks = proj_get_remarks(co); ASSERT_NE(remarks, nullptr); EXPECT_EQ(remarks, std::string("Replaces Lambert 2005.")); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_scope) { // Transformation { auto co = proj_create_from_database(m_ctxt, "EPSG", "8048", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ObjectKeeper keeper(co); ASSERT_NE(co, nullptr); auto scope = proj_get_scope(co); ASSERT_NE(scope, nullptr); EXPECT_EQ(scope, std::string("Transformation of GDA94 coordinates that have " "been derived through GNSS CORS.")); } // Conversion { auto co = proj_create_from_database(m_ctxt, "EPSG", "3811", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ObjectKeeper keeper(co); ASSERT_NE(co, nullptr); auto scope = proj_get_scope(co); ASSERT_NE(scope, nullptr); EXPECT_EQ(scope, std::string("Engineering survey, topographic mapping.")); } { auto P = proj_create(m_ctxt, "+proj=noop"); ObjectKeeper keeper(P); ASSERT_NE(P, nullptr); auto scope = proj_get_scope(P); ASSERT_EQ(scope, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_concatoperation_get_step) { // Test on a non concatenated operation { auto co = proj_create_from_database(m_ctxt, "EPSG", "8048", PJ_CATEGORY_COORDINATE_OPERATION, false, nullptr); ObjectKeeper keeper(co); ASSERT_NE(co, nullptr); ASSERT_NE(proj_get_type(co), PJ_TYPE_CONCATENATED_OPERATION); ASSERT_EQ(proj_concatoperation_get_step_count(m_ctxt, co), 0); ASSERT_EQ(proj_concatoperation_get_step(m_ctxt, co, 0), nullptr); } // Test on a concatenated operation { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); // GDA94 / MGA zone 56 auto source_crs = proj_create_from_database( m_ctxt, "EPSG", "28356", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(source_crs, nullptr); ObjectKeeper keeper_source_crs(source_crs); // GDA2020 / MGA zone 56 auto target_crs = proj_create_from_database( m_ctxt, "EPSG", "7856", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(target_crs, nullptr); ObjectKeeper keeper_target_crs(target_crs); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); auto res = proj_create_operations(m_ctxt, source_crs, target_crs, ctxt); ASSERT_NE(res, nullptr); ObjListKeeper keeper_res(res); ASSERT_GT(proj_list_get_count(res), 0); auto op = proj_list_get(m_ctxt, res, 0); ASSERT_NE(op, nullptr); ObjectKeeper keeper_op(op); ASSERT_EQ(proj_get_type(op), PJ_TYPE_CONCATENATED_OPERATION); ASSERT_EQ(proj_concatoperation_get_step_count(m_ctxt, op), 3); EXPECT_EQ(proj_concatoperation_get_step(m_ctxt, op, -1), nullptr); EXPECT_EQ(proj_concatoperation_get_step(m_ctxt, op, 3), nullptr); auto step = proj_concatoperation_get_step(m_ctxt, op, 1); ASSERT_NE(step, nullptr); ObjectKeeper keeper_step(step); const char *scope = proj_get_scope(step); EXPECT_NE(scope, nullptr); EXPECT_NE(std::string(scope), std::string()); const char *remarks = proj_get_remarks(step); EXPECT_NE(remarks, nullptr); EXPECT_NE(std::string(remarks), std::string()); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_as_projjson) { auto obj = proj_create( m_ctxt, Ellipsoid::WGS84->exportToJSON(JSONFormatter::create().get()).c_str()); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr); { auto projjson = proj_as_projjson(m_ctxt, obj, nullptr); ASSERT_NE(projjson, nullptr); EXPECT_EQ(std::string(projjson), "{\n" " \"$schema\": " "\"https://proj.org/schemas/v0.7/projjson.schema.json\",\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7030\n" " }\n" "}"); } { const char *const options[] = {"INDENTATION_WIDTH=4", "SCHEMA=", nullptr}; auto projjson = proj_as_projjson(m_ctxt, obj, options); ASSERT_NE(projjson, nullptr); EXPECT_EQ(std::string(projjson), "{\n" " \"type\": \"Ellipsoid\",\n" " \"name\": \"WGS 84\",\n" " \"semi_major_axis\": 6378137,\n" " \"inverse_flattening\": 298.257223563,\n" " \"id\": {\n" " \"authority\": \"EPSG\",\n" " \"code\": 7030\n" " }\n" "}"); } { const char *const options[] = {"MULTILINE=NO", "SCHEMA=", nullptr}; auto projjson = proj_as_projjson(m_ctxt, obj, options); ASSERT_NE(projjson, nullptr); EXPECT_EQ(std::string(projjson), "{\"type\":\"Ellipsoid\",\"name\":\"WGS 84\"," "\"semi_major_axis\":6378137," "\"inverse_flattening\":298.257223563," "\"id\":{\"authority\":\"EPSG\",\"code\":7030}}"); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_copy_from_default) { auto c_path = proj_context_get_database_path(m_ctxt); ASSERT_TRUE(c_path != nullptr); std::string path(c_path); FILE *f = fopen(path.c_str(), "rb"); ASSERT_NE(f, nullptr); fseek(f, 0, SEEK_END); auto length = ftell(f); std::string content; content.resize(static_cast<size_t>(length)); fseek(f, 0, SEEK_SET); auto read_bytes = fread(&content[0], 1, content.size(), f); ASSERT_EQ(read_bytes, content.size()); fclose(f); const char *tempdir = getenv("TEMP"); if (!tempdir) { tempdir = getenv("TMP"); } if (!tempdir) { tempdir = "/tmp"; } std::string tmp_filename(std::string(tempdir) + "/test_proj_context_set_autoclose_database.db"); f = fopen(tmp_filename.c_str(), "wb"); if (!f) { std::cerr << "Cannot create " << tmp_filename << std::endl; return; } fwrite(content.data(), 1, content.size(), f); fclose(f); auto c_default_path = proj_context_get_database_path(nullptr); std::string default_path(c_default_path ? c_default_path : ""); EXPECT_TRUE(proj_context_set_database_path(nullptr, tmp_filename.c_str(), nullptr, nullptr)); PJ_CONTEXT *new_ctx = proj_context_create(); EXPECT_TRUE(proj_context_set_database_path( nullptr, default_path.empty() ? nullptr : default_path.c_str(), nullptr, nullptr)); EXPECT_NE(new_ctx, nullptr); PjContextKeeper keeper_ctxt(new_ctx); auto c_new_path = proj_context_get_database_path(new_ctx); ASSERT_TRUE(c_new_path != nullptr); std::string new_db_path(c_new_path); ASSERT_EQ(new_db_path, tmp_filename); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_clone) { int new_init_rules = proj_context_get_use_proj4_init_rules(nullptr, 0) > 0 ? 0 : 1; PJ_CONTEXT *new_ctx = proj_context_create(); EXPECT_NE(new_ctx, nullptr); PjContextKeeper keeper_ctxt(new_ctx); proj_context_use_proj4_init_rules(new_ctx, new_init_rules); PJ_CONTEXT *clone_ctx = proj_context_clone(new_ctx); EXPECT_NE(clone_ctx, nullptr); PjContextKeeper keeper_clone_ctxt(clone_ctx); ASSERT_EQ(proj_context_get_use_proj4_init_rules(new_ctx, 0), proj_context_get_use_proj4_init_rules(clone_ctx, 0)); EXPECT_NE(proj_context_get_use_proj4_init_rules(NULL, 0), proj_context_get_use_proj4_init_rules(clone_ctx, 0)); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_crs_to_crs_from_pj) { auto src = proj_create(m_ctxt, "EPSG:4326"); ObjectKeeper keeper_src(src); ASSERT_NE(src, nullptr); auto dst = proj_create(m_ctxt, "EPSG:32631"); ObjectKeeper keeper_dst(dst); ASSERT_NE(dst, nullptr); auto P = proj_create_crs_to_crs_from_pj(m_ctxt, src, dst, nullptr, nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper keeper_Pnormalized(Pnormalized); ASSERT_NE(Pnormalized, nullptr); auto projstr = proj_as_proj_string(m_ctxt, Pnormalized, PJ_PROJ_5, nullptr); ASSERT_NE(projstr, nullptr); EXPECT_EQ(std::string(projstr), "+proj=pipeline +step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=utm +zone=31 +ellps=WGS84"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_crs_to_crs_from_pj_accuracy_filter) { auto src = proj_create(m_ctxt, "EPSG:4326"); // WGS 84 ObjectKeeper keeper_src(src); ASSERT_NE(src, nullptr); auto dst = proj_create(m_ctxt, "EPSG:4258"); // ETRS89 ObjectKeeper keeper_dst(dst); ASSERT_NE(dst, nullptr); // No options { auto P = proj_create_crs_to_crs_from_pj(m_ctxt, src, dst, nullptr, nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); } { const char *const options[] = {"ACCURACY=0.05", nullptr}; auto P = proj_create_crs_to_crs_from_pj(m_ctxt, src, dst, nullptr, options); ObjectKeeper keeper_P(P); ASSERT_EQ(P, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_crs_to_crs_from_pj_ballpark_filter) { auto src = proj_create(m_ctxt, "EPSG:4267"); // NAD 27 ObjectKeeper keeper_src(src); ASSERT_NE(src, nullptr); auto dst = proj_create(m_ctxt, "EPSG:4258"); // ETRS89 ObjectKeeper keeper_dst(dst); ASSERT_NE(dst, nullptr); // No options { auto P = proj_create_crs_to_crs_from_pj(m_ctxt, src, dst, nullptr, nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); } { const char *const options[] = {"ALLOW_BALLPARK=NO", nullptr}; auto P = proj_create_crs_to_crs_from_pj(m_ctxt, src, dst, nullptr, options); ObjectKeeper keeper_P(P); ASSERT_EQ(P, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_crs_to_crs_coordinate_metadata_in_src) { auto P = proj_create_crs_to_crs(m_ctxt, "[email protected]", "GDA2020", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); PJ_COORD coord; coord.xyzt.x = -30; coord.xyzt.y = 130; coord.xyzt.z = 0; coord.xyzt.t = HUGE_VAL; coord = proj_trans(P, PJ_FWD, coord); EXPECT_NEAR(coord.xyzt.x, -30.0000026655, 1e-10); EXPECT_NEAR(coord.xyzt.y, 129.9999983712, 1e-10); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_crs_to_crs_coordinate_metadata_in_target) { auto P = proj_create_crs_to_crs(m_ctxt, "GDA2020", "[email protected]", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); PJ_COORD coord; coord.xyzt.x = -30.0000026655; coord.xyzt.y = 129.9999983712; coord.xyzt.z = 0; coord.xyzt.t = HUGE_VAL; coord = proj_trans(P, PJ_FWD, coord); EXPECT_NEAR(coord.xyzt.x, -30, 1e-10); EXPECT_NEAR(coord.xyzt.y, 130, 1e-10); } // --------------------------------------------------------------------------- static void check_axis_is_latitude(PJ_CONTEXT *ctx, PJ *cs, int axis_number, const char *unit_name = "degree", double unit_conv_factor = 0.017453292519943295, const char *auth = "EPSG", const char *code = "9122") { const char *name = nullptr; const char *abbrev = nullptr; const char *direction = nullptr; double unitConvFactor = 0.0; const char *unitName = nullptr; const char *unitAuthority = nullptr; const char *unitCode = nullptr; EXPECT_TRUE(proj_cs_get_axis_info(ctx, cs, axis_number, &name, &abbrev, &direction, &unitConvFactor, &unitName, &unitAuthority, &unitCode)); ASSERT_NE(name, nullptr); ASSERT_NE(abbrev, nullptr); ASSERT_NE(direction, nullptr); ASSERT_NE(unitName, nullptr); if (auth) { ASSERT_NE(unitAuthority, nullptr); ASSERT_NE(unitCode, nullptr); } EXPECT_EQ(std::string(name), "Latitude"); EXPECT_EQ(std::string(abbrev), "lat"); EXPECT_EQ(std::string(direction), "north"); EXPECT_EQ(unitConvFactor, unit_conv_factor) << unitConvFactor; EXPECT_EQ(std::string(unitName), unit_name); if (auth) { EXPECT_EQ(std::string(unitAuthority), auth); EXPECT_EQ(std::string(unitCode), code); } } // --------------------------------------------------------------------------- static void check_axis_is_longitude(PJ_CONTEXT *ctx, PJ *cs, int axis_number, const char *unit_name = "degree", double unit_conv_factor = 0.017453292519943295, const char *auth = "EPSG", const char *code = "9122") { const char *name = nullptr; const char *abbrev = nullptr; const char *direction = nullptr; double unitConvFactor = 0.0; const char *unitName = nullptr; const char *unitAuthority = nullptr; const char *unitCode = nullptr; EXPECT_TRUE(proj_cs_get_axis_info(ctx, cs, axis_number, &name, &abbrev, &direction, &unitConvFactor, &unitName, &unitAuthority, &unitCode)); ASSERT_NE(name, nullptr); ASSERT_NE(abbrev, nullptr); ASSERT_NE(direction, nullptr); ASSERT_NE(unitName, nullptr); if (auth) { ASSERT_NE(unitAuthority, nullptr); ASSERT_NE(unitCode, nullptr); } EXPECT_EQ(std::string(name), "Longitude"); EXPECT_EQ(std::string(abbrev), "lon"); EXPECT_EQ(std::string(direction), "east"); EXPECT_EQ(unitConvFactor, unit_conv_factor) << unitConvFactor; EXPECT_EQ(std::string(unitName), unit_name); if (auth) { EXPECT_EQ(std::string(unitAuthority), auth); EXPECT_EQ(std::string(unitCode), code); } } // --------------------------------------------------------------------------- static void check_axis_is_height(PJ_CONTEXT *ctx, PJ *cs, int axis_number, const char *unit_name = "metre", double unit_conv_factor = 1, const char *auth = "EPSG", const char *code = "9001") { const char *name = nullptr; const char *abbrev = nullptr; const char *direction = nullptr; double unitConvFactor = 0.0; const char *unitName = nullptr; const char *unitAuthority = nullptr; const char *unitCode = nullptr; EXPECT_TRUE(proj_cs_get_axis_info(ctx, cs, axis_number, &name, &abbrev, &direction, &unitConvFactor, &unitName, &unitAuthority, &unitCode)); ASSERT_NE(name, nullptr); ASSERT_NE(abbrev, nullptr); ASSERT_NE(direction, nullptr); ASSERT_NE(unitName, nullptr); if (auth) { ASSERT_NE(unitAuthority, nullptr); ASSERT_NE(unitCode, nullptr); } EXPECT_EQ(std::string(name), "Ellipsoidal height"); EXPECT_EQ(std::string(abbrev), "h"); EXPECT_EQ(std::string(direction), "up"); EXPECT_EQ(unitConvFactor, unit_conv_factor) << unitConvFactor; EXPECT_EQ(std::string(unitName), unit_name); if (auth) { EXPECT_EQ(std::string(unitAuthority), auth); EXPECT_EQ(std::string(unitCode), code); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_ellipsoidal_3D_cs) { { auto cs = proj_create_ellipsoidal_3D_cs( m_ctxt, PJ_ELLPS3D_LATITUDE_LONGITUDE_HEIGHT, nullptr, 0, nullptr, 0); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); EXPECT_EQ(proj_cs_get_type(m_ctxt, cs), PJ_CS_TYPE_ELLIPSOIDAL); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3); check_axis_is_latitude(m_ctxt, cs, 0); check_axis_is_longitude(m_ctxt, cs, 1); check_axis_is_height(m_ctxt, cs, 2); } { auto cs = proj_create_ellipsoidal_3D_cs( m_ctxt, PJ_ELLPS3D_LONGITUDE_LATITUDE_HEIGHT, "foo", 0.5, "bar", 0.6); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); EXPECT_EQ(proj_cs_get_type(m_ctxt, cs), PJ_CS_TYPE_ELLIPSOIDAL); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3); check_axis_is_longitude(m_ctxt, cs, 0, "foo", 0.5, nullptr, nullptr); check_axis_is_latitude(m_ctxt, cs, 1, "foo", 0.5, nullptr, nullptr); check_axis_is_height(m_ctxt, cs, 2, "bar", 0.6, nullptr, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_promote_to_3D) { auto crs2D = proj_create(m_ctxt, GeographicCRS::EPSG_4326 ->exportToWKT(WKTFormatter::create().get()) .c_str()); ObjectKeeper keeper_crs2D(crs2D); EXPECT_NE(crs2D, nullptr); auto crs3D = proj_crs_promote_to_3D(m_ctxt, nullptr, crs2D); ObjectKeeper keeper_crs3D(crs3D); EXPECT_NE(crs3D, nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, crs3D); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3); auto code = proj_get_id_code(crs3D, 0); ASSERT_TRUE(code != nullptr); EXPECT_EQ(code, std::string("4979")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_promote_to_3D_on_coordinate_metadata) { auto cm_crs2D = proj_create(m_ctxt, "[email protected]"); ObjectKeeper keeper_cm_crs2D(cm_crs2D); EXPECT_NE(cm_crs2D, nullptr); auto cm_crs3D = proj_crs_promote_to_3D(m_ctxt, nullptr, cm_crs2D); ObjectKeeper keeper_cm_crs3D(cm_crs3D); EXPECT_NE(cm_crs3D, nullptr); EXPECT_NEAR(proj_coordinate_metadata_get_epoch(m_ctxt, cm_crs3D), 2010.0, 1e-10); auto crs3D = proj_get_source_crs(m_ctxt, cm_crs3D); ObjectKeeper keeper_crs3D(crs3D); EXPECT_NE(crs3D, nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, crs3D); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3); auto code = proj_get_id_code(crs3D, 0); ASSERT_TRUE(code != nullptr); EXPECT_EQ(code, std::string("7912")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_demote_to_2D) { auto crs3D = proj_create(m_ctxt, GeographicCRS::EPSG_4979 ->exportToWKT(WKTFormatter::create().get()) .c_str()); ObjectKeeper keeper_crs3D(crs3D); EXPECT_NE(crs3D, nullptr); auto crs2D = proj_crs_demote_to_2D(m_ctxt, nullptr, crs3D); ObjectKeeper keeper_crs2D(crs2D); EXPECT_NE(crs2D, nullptr); auto cs = proj_crs_get_coordinate_system(m_ctxt, crs2D); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 2); auto code = proj_get_id_code(crs2D, 0); ASSERT_TRUE(code != nullptr); EXPECT_EQ(code, std::string("4326")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_create_projected_3D_crs_from_2D) { auto projCRS = proj_create_from_database(m_ctxt, "EPSG", "32631", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(projCRS, nullptr); ObjectKeeper keeper_projCRS(projCRS); { auto geog3DCRS = proj_create_from_database( m_ctxt, "EPSG", "4979", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(geog3DCRS, nullptr); ObjectKeeper keeper_geog3DCRS(geog3DCRS); auto crs3D = proj_crs_create_projected_3D_crs_from_2D( m_ctxt, nullptr, projCRS, geog3DCRS); ObjectKeeper keeper_crs3D(crs3D); EXPECT_NE(crs3D, nullptr); EXPECT_EQ(proj_get_type(crs3D), PJ_TYPE_PROJECTED_CRS); EXPECT_EQ(std::string(proj_get_name(crs3D)), std::string(proj_get_name(projCRS))); auto cs = proj_crs_get_coordinate_system(m_ctxt, crs3D); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3); } { auto crs3D = proj_crs_create_projected_3D_crs_from_2D(m_ctxt, nullptr, projCRS, nullptr); ObjectKeeper keeper_crs3D(crs3D); EXPECT_NE(crs3D, nullptr); EXPECT_EQ(proj_get_type(crs3D), PJ_TYPE_PROJECTED_CRS); EXPECT_EQ(std::string(proj_get_name(crs3D)), std::string(proj_get_name(projCRS))); auto cs = proj_crs_get_coordinate_system(m_ctxt, crs3D); ASSERT_NE(cs, nullptr); ObjectKeeper keeperCs(cs); EXPECT_EQ(proj_cs_get_axis_count(m_ctxt, cs), 3); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_create_bound_vertical_crs) { auto vert_crs = proj_create_vertical_crs(m_ctxt, "myVertCRS", "myVertDatum", nullptr, 0.0); ObjectKeeper keeper_vert_crs(vert_crs); ASSERT_NE(vert_crs, nullptr); auto crs4979 = proj_create_from_wkt( m_ctxt, GeographicCRS::EPSG_4979->exportToWKT(WKTFormatter::create().get()) .c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper_crs4979(crs4979); ASSERT_NE(crs4979, nullptr); auto bound_crs = proj_crs_create_bound_vertical_crs(m_ctxt, vert_crs, crs4979, "foo.gtx"); ObjectKeeper keeper_bound_crs(bound_crs); ASSERT_NE(bound_crs, nullptr); auto projCRS = proj_create_from_database(m_ctxt, "EPSG", "32631", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(projCRS, nullptr); ObjectKeeper keeper_projCRS(projCRS); auto compound_crs = proj_create_compound_crs(m_ctxt, "myCompoundCRS", projCRS, bound_crs); ObjectKeeper keeper_compound_crss(compound_crs); ASSERT_NE(compound_crs, nullptr); auto proj_4 = proj_as_proj_string(m_ctxt, compound_crs, PJ_PROJ_4, nullptr); ASSERT_NE(proj_4, nullptr); EXPECT_EQ(std::string(proj_4), "+proj=utm +zone=31 +datum=WGS84 +units=m +geoidgrids=foo.gtx " "+geoid_crs=WGS84 " "+vunits=m +no_defs +type=crs"); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_crs_to_crs_with_only_ballpark_transformations) { // ETRS89 / UTM zone 31N + EGM96 height to WGS 84 (G1762) auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:25831+5773", "EPSG:7665", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto Pnormalized = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper keeper_Pnormalized(Pnormalized); ASSERT_NE(Pnormalized, nullptr); PJ_COORD coord; coord.xyzt.x = 500000; coord.xyzt.y = 4500000; coord.xyzt.z = 0; coord.xyzt.t = 0; coord = proj_trans(Pnormalized, PJ_FWD, coord); EXPECT_NEAR(coord.xyzt.x, 3.0, 1e-9); EXPECT_NEAR(coord.xyzt.y, 40.65085651660555, 1e-9); EXPECT_NEAR(coord.xyzt.z, 47.72600023608570, 1e-3); } // --------------------------------------------------------------------------- TEST_F( CApi, proj_create_crs_to_crs_from_custom_compound_crs_with_NAD83_2011_and_geoidgrid_ref_against_WGS84_to_WGS84_G1762) { PJ *P; PJ *inCrsH = proj_create_from_database(m_ctxt, "EPSG", "6340", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(inCrsH, nullptr); PJ *inDummyCrs = proj_create_vertical_crs(m_ctxt, "VerticalDummyCrs", "DummyDatum", "metre", 1.0); ASSERT_NE(inDummyCrs, nullptr); auto crs4979 = proj_create_from_database(m_ctxt, "EPSG", "4979", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs4979, nullptr); PJ *inCrsV = proj_crs_create_bound_vertical_crs(m_ctxt, inDummyCrs, crs4979, "egm96_15.gtx"); ASSERT_NE(inCrsV, nullptr); proj_destroy(inDummyCrs); proj_destroy(crs4979); PJ *inCompound = proj_create_compound_crs(m_ctxt, "Compound", inCrsH, inCrsV); ASSERT_NE(inCompound, nullptr); proj_destroy(inCrsH); proj_destroy(inCrsV); PJ *outCrs = proj_create(m_ctxt, "EPSG:7665"); ASSERT_NE(outCrs, nullptr); // In this particular case, PROJ computes a transformation from NAD83(2011) // (EPSG:6318) to WGS84 (EPSG:4979) for the initial horizontal adjustment // before the geoidgrids application. There are 6 candidate transformations // for that in subzones of the US and one last no-op transformation flagged // as ballpark. That one used to be eliminated because by // proj_create_crs_to_crs() because there were non Ballpark transformations // available. This resulted thus in an error when transforming outside of // those few subzones. P = proj_create_crs_to_crs_from_pj(m_ctxt, inCompound, outCrs, nullptr, nullptr); ASSERT_NE(P, nullptr); proj_destroy(inCompound); proj_destroy(outCrs); PJ_COORD in_coord; in_coord.xyzt.x = 350499.911; in_coord.xyzt.y = 3884807.956; in_coord.xyzt.z = 150.072; in_coord.xyzt.t = 2010; PJ_COORD outcoord = proj_trans(P, PJ_FWD, in_coord); proj_destroy(P); EXPECT_NEAR(outcoord.xyzt.x, 35.09499307271, 1e-9); EXPECT_NEAR(outcoord.xyzt.y, -118.64014868921, 1e-9); EXPECT_NEAR(outcoord.xyzt.z, 117.655, 1e-3); } // --------------------------------------------------------------------------- TEST_F( CApi, proj_create_crs_to_crs_from_custom_compound_crs_with_NAD83_2011_and_geoidgrid_ref_against_NAD83_2011_to_WGS84_G1762) { PJ *P; // NAD83(2011) 2D PJ *inCrsH = proj_create_from_database(m_ctxt, "EPSG", "6318", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(inCrsH, nullptr); PJ *inDummyCrs = proj_create_vertical_crs(m_ctxt, "VerticalDummyCrs", "DummyDatum", "metre", 1.0); ASSERT_NE(inDummyCrs, nullptr); // NAD83(2011) 3D PJ *inGeog3DCRS = proj_create_from_database( m_ctxt, "EPSG", "6319", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(inCrsH, nullptr); // Note: this is actually a bad example since we tell here that egm96_15.gtx // is referenced against NAD83(2011) PJ *inCrsV = proj_crs_create_bound_vertical_crs( m_ctxt, inDummyCrs, inGeog3DCRS, "egm96_15.gtx"); ASSERT_NE(inCrsV, nullptr); proj_destroy(inDummyCrs); proj_destroy(inGeog3DCRS); PJ *inCompound = proj_create_compound_crs(m_ctxt, "Compound", inCrsH, inCrsV); ASSERT_NE(inCompound, nullptr); proj_destroy(inCrsH); proj_destroy(inCrsV); // WGS84 (G1762) PJ *outCrs = proj_create(m_ctxt, "EPSG:7665"); ASSERT_NE(outCrs, nullptr); P = proj_create_crs_to_crs_from_pj(m_ctxt, inCompound, outCrs, nullptr, nullptr); ASSERT_NE(P, nullptr); proj_destroy(inCompound); proj_destroy(outCrs); PJ_COORD in_coord; in_coord.xyzt.x = 35; in_coord.xyzt.y = -118; in_coord.xyzt.z = 0; in_coord.xyzt.t = 2010; PJ_COORD outcoord = proj_trans(P, PJ_FWD, in_coord); proj_destroy(P); EXPECT_NEAR(outcoord.xyzt.x, 35.000003665064803, 1e-9); EXPECT_NEAR(outcoord.xyzt.y, -118.00001414221214, 1e-9); EXPECT_NEAR(outcoord.xyzt.z, -32.8110, 1e-3); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_vertical_crs_ex) { // NAD83(2011) / UTM zone 11N auto horiz_crs = proj_create_from_database(m_ctxt, "EPSG", "6340", PJ_CATEGORY_CRS, false, nullptr); ObjectKeeper keeper_horiz_crs(horiz_crs); ASSERT_NE(horiz_crs, nullptr); const char *options[] = {"ACCURACY=123", nullptr}; auto vert_crs = proj_create_vertical_crs_ex( m_ctxt, "myVertCRS (ftUS)", "myVertDatum", nullptr, nullptr, "US survey foot", 0.304800609601219, "PROJ @foo.gtx", nullptr, nullptr, nullptr, options); ObjectKeeper keeper_vert_crs(vert_crs); ASSERT_NE(vert_crs, nullptr); auto compound = proj_create_compound_crs(m_ctxt, "Compound", horiz_crs, vert_crs); ObjectKeeper keeper_compound(compound); ASSERT_NE(compound, nullptr); // NAD83(2011) 3D PJ *geog_crs = proj_create(m_ctxt, "EPSG:6319"); ObjectKeeper keeper_geog_crs(geog_crs); ASSERT_NE(geog_crs, nullptr); PJ_OPERATION_FACTORY_CONTEXT *ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); PJ_OBJ_LIST *operations = proj_create_operations(m_ctxt, compound, geog_crs, ctxt); ASSERT_NE(operations, nullptr); ObjListKeeper keeper_operations(operations); EXPECT_GE(proj_list_get_count(operations), 1); auto P = proj_list_get(m_ctxt, operations, 0); ObjectKeeper keeper_transform(P); auto name = proj_get_name(P); ASSERT_TRUE(name != nullptr); EXPECT_EQ(name, std::string("Inverse of UTM zone 11N + " "Conversion from myVertCRS (ftUS) to myVertCRS + " "Transformation from myVertCRS to NAD83(2011)")); auto proj_5 = proj_as_proj_string(m_ctxt, P, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5, nullptr); EXPECT_EQ(std::string(proj_5), "+proj=pipeline " "+step +inv +proj=utm +zone=11 +ellps=GRS80 " "+step +proj=unitconvert +z_in=us-ft +z_out=m " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); ASSERT_EQ(proj_coordoperation_get_accuracy(m_ctxt, P), 123.0); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_vertical_crs_ex_with_geog_crs) { // NAD83(2011) / UTM zone 11N auto horiz_crs = proj_create_from_database(m_ctxt, "EPSG", "6340", PJ_CATEGORY_CRS, false, nullptr); ObjectKeeper keeper_horiz_crs(horiz_crs); ASSERT_NE(horiz_crs, nullptr); // WGS84 PJ *wgs84 = proj_create(m_ctxt, "EPSG:4979"); ObjectKeeper keeper_wgs84(wgs84); ASSERT_NE(wgs84, nullptr); auto vert_crs = proj_create_vertical_crs_ex( m_ctxt, "myVertCRS", "myVertDatum", nullptr, nullptr, "US survey foot", 0.304800609601219, "PROJ @foo.gtx", nullptr, nullptr, wgs84, nullptr); ObjectKeeper keeper_vert_crs(vert_crs); ASSERT_NE(vert_crs, nullptr); auto compound = proj_create_compound_crs(m_ctxt, "Compound", horiz_crs, vert_crs); ObjectKeeper keeper_compound(compound); ASSERT_NE(compound, nullptr); // NAD83(2011) 3D PJ *geog_crs = proj_create(m_ctxt, "EPSG:6319"); ObjectKeeper keeper_geog_crs(geog_crs); ASSERT_NE(geog_crs, nullptr); PJ_OPERATION_FACTORY_CONTEXT *ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); PJ_OBJ_LIST *operations = proj_create_operations(m_ctxt, compound, geog_crs, ctxt); ASSERT_NE(operations, nullptr); ObjListKeeper keeper_operations(operations); EXPECT_GE(proj_list_get_count(operations), 1); auto P = proj_list_get(m_ctxt, operations, 0); ObjectKeeper keeper_transform(P); auto name = proj_get_name(P); ASSERT_TRUE(name != nullptr); EXPECT_EQ(name, std::string("Inverse of UTM zone 11N + " "Conversion from myVertCRS to myVertCRS (metre) + " "Transformation from myVertCRS (metre) to WGS 84 " "using NAD83(2011) to WGS 84 (1)")); auto proj_5 = proj_as_proj_string(m_ctxt, P, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5, nullptr); EXPECT_EQ(std::string(proj_5), "+proj=pipeline " "+step +inv +proj=utm +zone=11 +ellps=GRS80 " "+step +proj=unitconvert +z_in=us-ft +z_out=m " "+step +proj=vgridshift [email protected] +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg " "+step +proj=axisswap +order=2,1"); // Check that we get the same results after an export of compoundCRS to // PROJJSON and a re-import from it. auto projjson = proj_as_projjson(m_ctxt, compound, nullptr); ASSERT_NE(projjson, nullptr); auto compound_from_projjson = proj_create(m_ctxt, projjson); ObjectKeeper keeper_compound_from_projjson(compound_from_projjson); ASSERT_NE(compound_from_projjson, nullptr); PJ_OBJ_LIST *operations2 = proj_create_operations(m_ctxt, compound_from_projjson, geog_crs, ctxt); ASSERT_NE(operations2, nullptr); ObjListKeeper keeper_operations2(operations2); EXPECT_GE(proj_list_get_count(operations2), 1); auto P2 = proj_list_get(m_ctxt, operations2, 0); ObjectKeeper keeper_transform2(P2); auto name_bis = proj_get_name(P2); ASSERT_TRUE(name_bis != nullptr); EXPECT_EQ(std::string(name_bis), std::string(name)); auto proj_5_bis = proj_as_proj_string(m_ctxt, P2, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5_bis, nullptr); EXPECT_EQ(std::string(proj_5_bis), std::string(proj_5)); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_vertical_crs_ex_implied_accuracy) { PJ *crsH = proj_create(m_ctxt, "EPSG:4283"); // GDA94 ASSERT_NE(crsH, nullptr); ObjectKeeper keeper_crsH(crsH); PJ *crsV = proj_create(m_ctxt, "EPSG:5711"); // AHD height ASSERT_NE(crsV, nullptr); ObjectKeeper keeper_crsV(crsV); PJ *crsGeoid = proj_create(m_ctxt, "EPSG:4939"); // GDA94 3D ASSERT_NE(crsGeoid, nullptr); ObjectKeeper keeper_crsGeoid(crsGeoid); PJ *vertDatum = proj_crs_get_datum(m_ctxt, crsV); ObjectKeeper keeper_vertDatum(vertDatum); const char *vertDatumName = proj_get_name(vertDatum); const char *vertDatumAuthority = proj_get_id_auth_name(vertDatum, 0); const char *vertDatumCode = proj_get_id_code(vertDatum, 0); PJ *crsVGeoid = proj_create_vertical_crs_ex( m_ctxt, "Vertical", vertDatumName, vertDatumAuthority, vertDatumCode, "metre", 1.0, "PROJ au_ga_AUSGeoid09_V1.01.tif", nullptr, nullptr, crsGeoid, nullptr); ObjectKeeper keeper_crsVGeoid(crsVGeoid); PJ *crsCompoundGeoid = proj_create_compound_crs( m_ctxt, "Compound with geoid", crsH, crsVGeoid); ObjectKeeper keeper_crsCompoundGeoid(crsCompoundGeoid); PJ_OPERATION_FACTORY_CONTEXT *ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); proj_operation_factory_context_set_grid_availability_use( m_ctxt, ctxt, PROJ_GRID_AVAILABILITY_IGNORED); proj_operation_factory_context_set_spatial_criterion( m_ctxt, ctxt, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); PJ_OBJ_LIST *operations = proj_create_operations(m_ctxt, crsCompoundGeoid, crsGeoid, ctxt); ASSERT_NE(operations, nullptr); ObjListKeeper keeper_operations(operations); EXPECT_GE(proj_list_get_count(operations), 1); PJ *transform = proj_list_get(m_ctxt, operations, 0); ObjectKeeper keeper_transform(transform); // This is the accuracy of operations EPSG:5656 / 5657 const double acc = proj_coordoperation_get_accuracy(m_ctxt, transform); EXPECT_NEAR(acc, 0.15, 1e-10); // Check there's an associated area of use double west_lon_degree = 0; double south_lat_degree = 0; double east_lon_degree = 0; double north_lat_degree = 0; ASSERT_EQ(proj_get_area_of_use(m_ctxt, transform, &west_lon_degree, &south_lat_degree, &east_lon_degree, &north_lat_degree, nullptr), true); EXPECT_LE(north_lat_degree, -10); EXPECT_GE(west_lon_degree, 110); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_derived_geographic_crs) { PJ *crs_4326 = proj_create(m_ctxt, "EPSG:4326"); ObjectKeeper keeper_crs_4326(crs_4326); ASSERT_NE(crs_4326, nullptr); PJ *conversion = proj_create_conversion_pole_rotation_grib_convention( m_ctxt, 2, 3, 4, "Degree", 0.0174532925199433); ObjectKeeper keeper_conversion(conversion); ASSERT_NE(conversion, nullptr); PJ *cs = proj_crs_get_coordinate_system(m_ctxt, crs_4326); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); ASSERT_EQ( proj_create_derived_geographic_crs(m_ctxt, "my rotated CRS", conversion, // wrong type of object conversion, cs), nullptr); ASSERT_EQ( proj_create_derived_geographic_crs(m_ctxt, "my rotated CRS", crs_4326, crs_4326, // wrong type of object cs), nullptr); ASSERT_EQ(proj_create_derived_geographic_crs( m_ctxt, "my rotated CRS", crs_4326, conversion, conversion // wrong type of object ), nullptr); PJ *derived_crs = proj_create_derived_geographic_crs( m_ctxt, "my rotated CRS", crs_4326, conversion, cs); ObjectKeeper keeper_derived_crs(derived_crs); ASSERT_NE(derived_crs, nullptr); EXPECT_FALSE(proj_is_derived_crs(m_ctxt, crs_4326)); EXPECT_TRUE(proj_is_derived_crs(m_ctxt, derived_crs)); auto wkt = proj_as_wkt(m_ctxt, derived_crs, PJ_WKT2_2019, nullptr); const char *expected_wkt = "GEOGCRS[\"my rotated CRS\",\n" " BASEGEOGCRS[\"WGS 84\",\n" " ENSEMBLE[\"World Geodetic System 1984 ensemble\",\n" " MEMBER[\"World Geodetic System 1984 (Transit)\"],\n" " MEMBER[\"World Geodetic System 1984 (G730)\"],\n" " MEMBER[\"World Geodetic System 1984 (G873)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1150)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1674)\"],\n" " MEMBER[\"World Geodetic System 1984 (G1762)\"],\n" " MEMBER[\"World Geodetic System 1984 (G2139)\"],\n" " ELLIPSOID[\"WGS 84\",6378137,298.257223563,\n" " LENGTHUNIT[\"metre\",1]],\n" " ENSEMBLEACCURACY[2.0]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Pole rotation (GRIB convention)\",\n" " METHOD[\"Pole rotation (GRIB convention)\"],\n" " PARAMETER[\"Latitude of the southern pole (GRIB " "convention)\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Longitude of the southern pole (GRIB " "convention)\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Axis rotation (GRIB convention)\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; ASSERT_NE(wkt, nullptr); EXPECT_EQ(wkt, std::string(expected_wkt)); auto proj_5 = proj_as_proj_string(m_ctxt, derived_crs, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5, nullptr); EXPECT_EQ(proj_5, std::string("+proj=ob_tran +o_proj=longlat +o_lon_p=-4 " "+o_lat_p=-2 +lon_0=3 +datum=WGS84 +no_defs " "+type=crs")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_create_derived_geographic_crs_netcdf_cf) { PJ *crs_4019 = proj_create(m_ctxt, "EPSG:4019"); ObjectKeeper keeper_crs_4019(crs_4019); ASSERT_NE(crs_4019, nullptr); PJ *conversion = proj_create_conversion_pole_rotation_netcdf_cf_convention( m_ctxt, 2, 3, 4, "Degree", 0.0174532925199433); ObjectKeeper keeper_conversion(conversion); ASSERT_NE(conversion, nullptr); PJ *cs = proj_crs_get_coordinate_system(m_ctxt, crs_4019); ObjectKeeper keeper_cs(cs); ASSERT_NE(cs, nullptr); PJ *derived_crs = proj_create_derived_geographic_crs( m_ctxt, "my rotated CRS", crs_4019, conversion, cs); ObjectKeeper keeper_derived_crs(derived_crs); ASSERT_NE(derived_crs, nullptr); auto wkt = proj_as_wkt(m_ctxt, derived_crs, PJ_WKT2_2019, nullptr); const char *expected_wkt = "GEOGCRS[\"my rotated CRS\",\n" " BASEGEOGCRS[\"Unknown datum based upon the GRS 1980 ellipsoid\",\n" " DATUM[\"Not specified (based on GRS 1980 ellipsoid)\",\n" " ELLIPSOID[\"GRS 1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]],\n" " DERIVINGCONVERSION[\"Pole rotation (netCDF CF convention)\",\n" " METHOD[\"Pole rotation (netCDF CF convention)\"],\n" " PARAMETER[\"Grid north pole latitude (netCDF CF " "convention)\",2,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"Grid north pole longitude (netCDF CF " "convention)\",3,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " PARAMETER[\"North pole grid longitude (netCDF CF " "convention)\",4,\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433,\n" " ID[\"EPSG\",9122]]]]"; ASSERT_NE(wkt, nullptr); EXPECT_EQ(wkt, std::string(expected_wkt)); auto proj_5 = proj_as_proj_string(m_ctxt, derived_crs, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5, nullptr); EXPECT_EQ(proj_5, std::string("+proj=ob_tran +o_proj=longlat +o_lon_p=4 " "+o_lat_p=2 +lon_0=183 +ellps=GRS80 +no_defs " "+type=crs")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_set_sqlite3_vfs_name) { PJ_CONTEXT *ctx = proj_context_create(); proj_log_func(ctx, nullptr, [](void *, int, const char *) -> void {}); // Set a dummy VFS and check it is taken into account // (failure to open proj.db) proj_context_set_sqlite3_vfs_name(ctx, "dummy_vfs_name"); ASSERT_EQ(proj_create(ctx, "EPSG:4326"), nullptr); // Restore default VFS proj_context_set_sqlite3_vfs_name(ctx, nullptr); PJ *crs_4326 = proj_create(ctx, "EPSG:4326"); ASSERT_NE(crs_4326, nullptr); proj_destroy(crs_4326); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_context_set_sqlite3_vfs_name__from_global_context) { // Set a dummy VFS and check it is taken into account // (failure to open proj.db) proj_context_set_sqlite3_vfs_name(nullptr, "dummy_vfs_name"); PJ_CONTEXT *ctx = proj_context_create(); proj_log_func(ctx, nullptr, [](void *, int, const char *) -> void {}); ASSERT_EQ(proj_create(ctx, "EPSG:4326"), nullptr); // Restore default VFS proj_context_set_sqlite3_vfs_name(nullptr, nullptr); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST_F(CApi, use_proj4_init_rules) { PJ_CONTEXT *ctx = proj_context_create(); proj_context_use_proj4_init_rules(ctx, true); ASSERT_TRUE(proj_context_get_use_proj4_init_rules(ctx, true)); { // Test +over auto crs = proj_create(ctx, "+init=epsg:28992 +over"); ObjectKeeper keeper_crs(crs); ASSERT_NE(crs, nullptr); auto datum = proj_crs_get_datum(ctx, crs); ASSERT_NE(datum, nullptr); ObjectKeeper keeper_datum(datum); auto datum_name = proj_get_name(datum); ASSERT_TRUE(datum_name != nullptr); EXPECT_EQ(datum_name, std::string("Amersfoort")); auto proj_5 = proj_as_proj_string(ctx, crs, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5, nullptr); EXPECT_EQ(std::string(proj_5), "+proj=sterea +lat_0=52.1561605555556 " "+lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 " "+y_0=463000 +ellps=bessel +units=m +over " "+no_defs +type=crs"); } { // Test +over on epsg:3857 auto crs = proj_create(ctx, "+init=epsg:3857 +over"); ObjectKeeper keeper_crs(crs); ASSERT_NE(crs, nullptr); auto proj_5 = proj_as_proj_string(ctx, crs, PJ_PROJ_5, nullptr); ASSERT_NE(proj_5, nullptr); EXPECT_EQ(std::string(proj_5), "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 " "+y_0=0 +k=1 +units=m +nadgrids=@null +over +wktext " "+no_defs +type=crs"); } proj_context_use_proj4_init_rules(ctx, false); ASSERT_TRUE(!proj_context_get_use_proj4_init_rules(ctx, true)); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST_F(CApi, use_proj4_init_rules_from_global_context) { int initial_rules = proj_context_get_use_proj4_init_rules(nullptr, true); proj_context_use_proj4_init_rules(nullptr, true); PJ_CONTEXT *ctx = proj_context_create(); ASSERT_TRUE(proj_context_get_use_proj4_init_rules(ctx, true)); proj_context_destroy(ctx); proj_context_use_proj4_init_rules(nullptr, false); ctx = proj_context_create(); ASSERT_TRUE(!proj_context_get_use_proj4_init_rules(ctx, true)); proj_context_destroy(ctx); proj_context_use_proj4_init_rules(nullptr, initial_rules); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_is_equivalent_to_with_ctx) { auto from_epsg = proj_create_from_database(m_ctxt, "EPSG", "7844", PJ_CATEGORY_CRS, false, nullptr); ObjectKeeper keeper_from_epsg(from_epsg); ASSERT_NE(from_epsg, nullptr); auto wkt = "GEOGCRS[\"GDA2020\",\n" " DATUM[\"GDA2020\",\n" " ELLIPSOID[\"GRS_1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; auto from_wkt = proj_create_from_wkt(m_ctxt, wkt, nullptr, nullptr, nullptr); ObjectKeeper keeper_from_wkt(from_wkt); EXPECT_NE(from_wkt, nullptr); EXPECT_TRUE(proj_is_equivalent_to_with_ctx(m_ctxt, from_epsg, from_wkt, PJ_COMP_EQUIVALENT)); } // --------------------------------------------------------------------------- TEST_F(CApi, datum_ensemble) { auto wkt = "GEOGCRS[\"ETRS89\"," " ENSEMBLE[\"European Terrestrial Reference System 1989 ensemble\"," " MEMBER[\"European Terrestrial Reference Frame 1989\"]," " MEMBER[\"European Terrestrial Reference Frame 1990\"]," " MEMBER[\"European Terrestrial Reference Frame 1991\"]," " MEMBER[\"European Terrestrial Reference Frame 1992\"]," " MEMBER[\"European Terrestrial Reference Frame 1993\"]," " MEMBER[\"European Terrestrial Reference Frame 1994\"]," " MEMBER[\"European Terrestrial Reference Frame 1996\"]," " MEMBER[\"European Terrestrial Reference Frame 1997\"]," " MEMBER[\"European Terrestrial Reference Frame 2000\"]," " MEMBER[\"European Terrestrial Reference Frame 2005\"]," " MEMBER[\"European Terrestrial Reference Frame 2014\"]," " ELLIPSOID[\"GRS 1980\",6378137,298.257222101," " LENGTHUNIT[\"metre\",1]]," " ENSEMBLEACCURACY[0.1]]," " PRIMEM[\"Greenwich\",0," " ANGLEUNIT[\"degree\",0.0174532925199433]]," " CS[ellipsoidal,2]," " AXIS[\"geodetic latitude (Lat)\",north," " ORDER[1]," " ANGLEUNIT[\"degree\",0.0174532925199433]]," " AXIS[\"geodetic longitude (Lon)\",east," " ORDER[2]," " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; auto from_wkt = proj_create_from_wkt(m_ctxt, wkt, nullptr, nullptr, nullptr); ObjectKeeper keeper_from_wkt(from_wkt); EXPECT_NE(from_wkt, nullptr); auto datum = proj_crs_get_datum(m_ctxt, from_wkt); ObjectKeeper keeper_datum(datum); ASSERT_EQ(datum, nullptr); auto datum_ensemble = proj_crs_get_datum_ensemble(m_ctxt, from_wkt); ObjectKeeper keeper_datum_ensemble(datum_ensemble); ASSERT_NE(datum_ensemble, nullptr); ASSERT_EQ(proj_datum_ensemble_get_member_count(m_ctxt, datum_ensemble), 11); ASSERT_EQ(proj_datum_ensemble_get_member(m_ctxt, datum_ensemble, -1), nullptr); ASSERT_EQ(proj_datum_ensemble_get_member(m_ctxt, datum_ensemble, 11), nullptr); { auto member = proj_datum_ensemble_get_member(m_ctxt, datum_ensemble, 0); ObjectKeeper keeper_member(member); ASSERT_NE(member, nullptr); EXPECT_EQ(proj_get_name(member), std::string("European Terrestrial Reference Frame 1989")); } { auto member = proj_datum_ensemble_get_member(m_ctxt, datum_ensemble, 10); ObjectKeeper keeper_member(member); ASSERT_NE(member, nullptr); EXPECT_EQ(proj_get_name(member), std::string("European Terrestrial Reference Frame 2014")); } ASSERT_EQ(proj_datum_ensemble_get_accuracy(m_ctxt, datum_ensemble), 0.1); auto datum_forced = proj_crs_get_datum_forced(m_ctxt, from_wkt); ObjectKeeper keeper_datum_forced(datum_forced); ASSERT_NE(datum_forced, nullptr); EXPECT_EQ(proj_get_name(datum_forced), std::string("European Terrestrial Reference System 1989")); auto cs = proj_crs_get_coordinate_system(m_ctxt, from_wkt); ObjectKeeper keeper_cs(cs); EXPECT_NE(cs, nullptr); { auto built_crs = proj_create_geographic_crs_from_datum( m_ctxt, proj_get_name(from_wkt), datum_ensemble, cs); ObjectKeeper keeper_built_crs(built_crs); EXPECT_NE(built_crs, nullptr); EXPECT_TRUE(proj_is_equivalent_to_with_ctx(m_ctxt, built_crs, from_wkt, PJ_COMP_EQUIVALENT)); } { auto built_crs = proj_create_geocentric_crs_from_datum( m_ctxt, proj_get_name(from_wkt), datum_ensemble, "metre", 1.0); ObjectKeeper keeper_built_crs(built_crs); EXPECT_NE(built_crs, nullptr); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_is_derived) { { auto wkt = createProjectedCRS()->exportToWKT(WKTFormatter::create().get()); auto obj = proj_create_from_wkt(m_ctxt, wkt.c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr) << wkt; EXPECT_TRUE(proj_crs_is_derived(m_ctxt, obj)); } { auto wkt = createProjectedCRS()->baseCRS()->exportToWKT( WKTFormatter::create().get()); auto obj = proj_create_from_wkt(m_ctxt, wkt.c_str(), nullptr, nullptr, nullptr); ObjectKeeper keeper(obj); ASSERT_NE(obj, nullptr) << wkt; EXPECT_FALSE(proj_crs_is_derived(m_ctxt, obj)); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_insert_statements) { { auto session = proj_insert_object_session_create(nullptr); EXPECT_NE(session, nullptr); EXPECT_EQ(proj_insert_object_session_create(nullptr), nullptr); proj_insert_object_session_destroy(nullptr, session); } { proj_insert_object_session_destroy(nullptr, nullptr); } { auto wkt = "GEOGCRS[\"myGDA2020\",\n" " DATUM[\"GDA2020\",\n" " ELLIPSOID[\"GRS_1980\",6378137,298.257222101,\n" " LENGTHUNIT[\"metre\",1]]],\n" " PRIMEM[\"Greenwich\",0,\n" " ANGLEUNIT[\"Degree\",0.0174532925199433]],\n" " CS[ellipsoidal,2],\n" " AXIS[\"geodetic latitude (Lat)\",north,\n" " ORDER[1],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]],\n" " AXIS[\"geodetic longitude (Lon)\",east,\n" " ORDER[2],\n" " ANGLEUNIT[\"degree\",0.0174532925199433]]]"; auto crs = proj_create_from_wkt(m_ctxt, wkt, nullptr, nullptr, nullptr); ObjectKeeper keeper_from_wkt(crs); EXPECT_NE(crs, nullptr); { char *code = proj_suggests_code_for(m_ctxt, crs, "HOBU", false, nullptr); ASSERT_NE(code, nullptr); EXPECT_EQ(std::string(code), "MYGDA2020"); proj_string_destroy(code); } { char *code = proj_suggests_code_for(m_ctxt, crs, "HOBU", true, nullptr); ASSERT_NE(code, nullptr); EXPECT_EQ(std::string(code), "1"); proj_string_destroy(code); } const auto sizeOfStringList = [](const char *const *list) { if (list == nullptr) return -1; int size = 0; for (auto iter = list; *iter; ++iter) { size += 1; } return size; }; // No session specified: we use a temporary session for (int i = 0; i < 2; i++) { auto list = proj_get_insert_statements( m_ctxt, nullptr, crs, "HOBU", "XXXX", false, nullptr, nullptr); ASSERT_NE(list, nullptr); ASSERT_NE(list[0], nullptr); EXPECT_EQ(std::string(list[0]), "INSERT INTO geodetic_datum VALUES('HOBU'," "'GEODETIC_DATUM_XXXX','GDA2020','','EPSG','7019'," "'EPSG','8901',NULL,NULL,NULL,NULL,NULL,0);"); EXPECT_EQ(sizeOfStringList(list), 4); proj_string_list_destroy(list); } // Pass an empty list of allowed authorities // We cannot reuse the EPSG ellipsoid and prime meridian { const char *const allowed_authorities[] = {nullptr}; auto list = proj_get_insert_statements(m_ctxt, nullptr, crs, "HOBU", "XXXX", false, allowed_authorities, nullptr); EXPECT_EQ(sizeOfStringList(list), 6); proj_string_list_destroy(list); } // Allow only PROJ // We cannot reuse the EPSG ellipsoid and prime meridian { const char *const allowed_authorities[] = {"PROJ", nullptr}; auto list = proj_get_insert_statements(m_ctxt, nullptr, crs, "HOBU", "XXXX", false, allowed_authorities, nullptr); EXPECT_EQ(sizeOfStringList(list), 6); proj_string_list_destroy(list); } // Allow EPSG { const char *const allowed_authorities[] = {"EPSG", nullptr}; auto list = proj_get_insert_statements(m_ctxt, nullptr, crs, "HOBU", "XXXX", false, allowed_authorities, nullptr); EXPECT_EQ(sizeOfStringList(list), 4); proj_string_list_destroy(list); } auto session = proj_insert_object_session_create(m_ctxt); EXPECT_NE(session, nullptr); { auto list = proj_get_insert_statements( m_ctxt, session, crs, "HOBU", "XXXX", false, nullptr, nullptr); ASSERT_NE(list, nullptr); ASSERT_NE(list[0], nullptr); EXPECT_EQ(std::string(list[0]), "INSERT INTO geodetic_datum VALUES('HOBU'," "'GEODETIC_DATUM_XXXX','GDA2020','','EPSG','7019'," "'EPSG','8901',NULL,NULL,NULL,NULL,NULL,0);"); proj_string_list_destroy(list); } // Object already inserted: return empty list { auto list = proj_get_insert_statements( m_ctxt, session, crs, "HOBU", "XXXX", false, nullptr, nullptr); ASSERT_NE(list, nullptr); ASSERT_EQ(list[0], nullptr); proj_string_list_destroy(list); } proj_insert_object_session_destroy(m_ctxt, session); } } // --------------------------------------------------------------------------- TEST_F(CApi, proj_get_geoid_models_from_database) { auto findInList = [](PROJ_STRING_LIST list, const std::string &ref) { while (list && *list) { if (std::string(*list) == ref) { return true; } list++; } return false; }; auto list = proj_get_geoid_models_from_database(m_ctxt, "EPSG", "5703", nullptr); ListFreer freer(list); EXPECT_TRUE(findInList(list, "GEOID12B")); EXPECT_TRUE(findInList(list, "GEOID18")); EXPECT_TRUE(findInList(list, "GGM10")); EXPECT_FALSE(findInList(list, "OSGM15")); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_densify_0) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4326", "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 " "+a=6370997 +b=6370997 +units=m +no_defs", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, 40, -120, 64, -80, &out_left, &out_bottom, &out_right, &out_top, 0); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -1684649.41338, 1); EXPECT_NEAR(out_bottom, -350356.81377, 1); EXPECT_NEAR(out_right, 1684649.41338, 1); EXPECT_NEAR(out_top, 2234551.18559, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_densify_100) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4326", "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 " "+a=6370997 +b=6370997 +units=m +no_defs", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, 40, -120, 64, -80, &out_left, &out_bottom, &out_right, &out_top, 100); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -1684649.41338, 1); EXPECT_NEAR(out_bottom, -555777.79210, 1); EXPECT_NEAR(out_right, 1684649.41338, 1); EXPECT_NEAR(out_top, 2234551.18559, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_normalized) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4326", "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 " "+a=6370997 +b=6370997 +units=m +no_defs", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto normalized_p = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper normal_keeper_P(normalized_p); ASSERT_NE(normalized_p, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, normalized_p, PJ_FWD, -120, 40, -80, 64, &out_left, &out_bottom, &out_right, &out_top, 100); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -1684649.41338, 1); EXPECT_NEAR(out_bottom, -555777.79210, 1); EXPECT_NEAR(out_right, 1684649.41338, 1); EXPECT_NEAR(out_top, 2234551.18559, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_antimeridian_xy) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4167", "EPSG:3851", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto normalized_p = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper normal_keeper_P(normalized_p); ASSERT_NE(normalized_p, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, normalized_p, PJ_FWD, 160.6, -55.95, -171.2, -25.88, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, 1722483.900174921, 1); EXPECT_NEAR(out_bottom, 5228058.6143420935, 1); EXPECT_NEAR(out_right, 4624385.494808555, 1); EXPECT_NEAR(out_top, 8692574.544944234, 1); double out_left_inv; double out_bottom_inv; double out_right_inv; double out_top_inv; int success_inv = proj_trans_bounds( m_ctxt, normalized_p, PJ_INV, 1722483.900174921, 5228058.6143420935, 4624385.494808555, 8692574.544944234, &out_left_inv, &out_bottom_inv, &out_right_inv, &out_top_inv, 21); EXPECT_TRUE(success_inv == 1); EXPECT_NEAR(out_left_inv, 153.2799922, 1); EXPECT_NEAR(out_bottom_inv, -56.7471249, 1); EXPECT_NEAR(out_right_inv, -162.1813873, 1); EXPECT_NEAR(out_top_inv, -24.6148194, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_antimeridian) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4167", "EPSG:3851", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, -55.95, 160.6, -25.88, -171.2, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, 5228058.6143420935, 1); EXPECT_NEAR(out_bottom, 1722483.900174921, 1); EXPECT_NEAR(out_right, 8692574.544944234, 1); EXPECT_NEAR(out_top, 4624385.494808555, 1); double out_left_inv; double out_bottom_inv; double out_right_inv; double out_top_inv; int success_inv = proj_trans_bounds( m_ctxt, P, PJ_INV, 5228058.6143420935, 1722483.900174921, 8692574.544944234, 4624385.494808555, &out_left_inv, &out_bottom_inv, &out_right_inv, &out_top_inv, 21); EXPECT_TRUE(success_inv == 1); EXPECT_NEAR(out_left_inv, -56.7471249, 1); EXPECT_NEAR(out_bottom_inv, 153.2799922, 1); EXPECT_NEAR(out_right_inv, -24.6148194, 1); EXPECT_NEAR(out_top_inv, -162.1813873, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_beyond_global_bounds) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:6933", "EPSG:4326", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto normalized_p = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper normal_keeper_P(normalized_p); ASSERT_NE(normalized_p, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, normalized_p, PJ_FWD, -17367531.3203125, -7314541.19921875, 17367531.3203125, 7314541.19921875, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -180, 1); EXPECT_NEAR(out_bottom, -85.0445994113099, 1); EXPECT_NEAR(out_right, 180, 1); EXPECT_NEAR(out_top, 85.0445994113099, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_ignore_inf) { auto P = proj_create_crs_to_crs(m_ctxt, "OGC:CRS84", "ESRI:102036", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; // Before the ellipsoidal version of the gnomonic projection was // implemented the WGS84 ellipsoid was treated as a sphere of radius // 6378137m and the equator was the "horizon" for the projection with the // south polar aspect. // // The boundary with ndiv = 21 then mapped into a line extending to ymin = // -89178007.2 which was the projection of lat = -90d/(ndiv+1), long = 180d. // // With the implementation of the ellipsoidal gnonomic projection, the // horizon is now at lat = +0.3035d. // // We move the north edge of the box to lat = -90+4.15*(ndiv+1) = +1.3d. // The northernmost point on the boundary which is within the horizon is // now lat = -90+4.15*ndiv = -2.85d, long = 180d for which y = -116576598.5. int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, -180.0, -90.0, 180.0, 1.3, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, 0, 1); EXPECT_NEAR(out_bottom, -116576598.5, 1); EXPECT_NEAR(out_right, 0, 1); EXPECT_NEAR(out_top, 0, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_ignore_inf_geographic) { auto P = proj_create_crs_to_crs( m_ctxt, "PROJCS[\"Interrupted_Goode_Homolosine\"," "GEOGCS[\"GCS_unnamed ellipse\",DATUM[\"D_unknown\"," "SPHEROID[\"Unknown\",6378137,298.257223563]]," "PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.0174532925199433]]," "PROJECTION[\"Interrupted_Goode_Homolosine\"]," "UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]]," "AXIS[\"Easting\",EAST],AXIS[\"Northing\",NORTH]]", "OGC:CRS84", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, -15028000.0, 7515000.0, -14975000.0, 7556000.0, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -179.2133, 1); EXPECT_NEAR(out_bottom, 70.9345, 1); EXPECT_NEAR(out_right, -177.9054, 1); EXPECT_NEAR(out_top, 71.4364, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds_noop_geographic) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:4284", "EPSG:4284", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, 19.57, 35.14, -168.97, 81.91, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, 19.57, 1); EXPECT_NEAR(out_bottom, 35.14, 1); EXPECT_NEAR(out_right, -168.97, 1); EXPECT_NEAR(out_top, 81.91, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds__north_pole_xy) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:32661", "EPSG:4326", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto normalized_p = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper normal_keeper_P(normalized_p); ASSERT_NE(normalized_p, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds( m_ctxt, normalized_p, PJ_FWD, -1371213.7625429356, -1405880.71737131, 5371213.762542935, 5405880.71737131, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -180.0, 1); EXPECT_NEAR(out_bottom, 48.656, 1); EXPECT_NEAR(out_right, 180.0, 1); EXPECT_NEAR(out_top, 90.0, 1); double out_left_inv; double out_bottom_inv; double out_right_inv; double out_top_inv; int success_inv = proj_trans_bounds( m_ctxt, normalized_p, PJ_INV, -180.0, 60.0, 180.0, 90.0, &out_left_inv, &out_bottom_inv, &out_right_inv, &out_top_inv, 21); EXPECT_TRUE(success_inv == 1); EXPECT_NEAR(out_left_inv, -1371213.76, 1); EXPECT_NEAR(out_bottom_inv, -1405880.72, 1); EXPECT_NEAR(out_right_inv, 5371213.76, 1); EXPECT_NEAR(out_top_inv, 5405880.72, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds__north_pole) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:32661", "EPSG:4326", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, -1405880.71737131, -1371213.7625429356, 5405880.71737131, 5371213.762542935, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, 48.656, 1); EXPECT_NEAR(out_bottom, -180.0, 1); EXPECT_NEAR(out_right, 90.0, 1); EXPECT_NEAR(out_top, 180.0, 1); double out_left_inv; double out_bottom_inv; double out_right_inv; double out_top_inv; int success_inv = proj_trans_bounds(m_ctxt, P, PJ_INV, 60.0, -180.0, 90.0, 180.0, &out_left_inv, &out_bottom_inv, &out_right_inv, &out_top_inv, 21); EXPECT_TRUE(success_inv == 1); EXPECT_NEAR(out_left_inv, -1405880.72, 1); EXPECT_NEAR(out_bottom_inv, -1371213.76, 1); EXPECT_NEAR(out_right_inv, 5405880.72, 1); EXPECT_NEAR(out_top_inv, 5371213.76, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds__south_pole_xy) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:32761", "EPSG:4326", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); auto normalized_p = proj_normalize_for_visualization(m_ctxt, P); ObjectKeeper normal_keeper_P(normalized_p); ASSERT_NE(normalized_p, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds( m_ctxt, normalized_p, PJ_FWD, -1371213.7625429356, -1405880.71737131, 5371213.762542935, 5405880.71737131, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -180.0, 1); EXPECT_NEAR(out_bottom, -90, 1); EXPECT_NEAR(out_right, 180.0, 1); EXPECT_NEAR(out_top, -48.656, 1); double out_left_inv; double out_bottom_inv; double out_right_inv; double out_top_inv; int success_inv = proj_trans_bounds( m_ctxt, normalized_p, PJ_INV, -180.0, -90.0, 180.0, -60.0, &out_left_inv, &out_bottom_inv, &out_right_inv, &out_top_inv, 21); EXPECT_TRUE(success_inv == 1); EXPECT_NEAR(out_left_inv, -1371213.76, 1); EXPECT_NEAR(out_bottom_inv, -1405880.72, 1); EXPECT_NEAR(out_right_inv, 5371213.76, 1); EXPECT_NEAR(out_top_inv, 5405880.72, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_trans_bounds__south_pole) { auto P = proj_create_crs_to_crs(m_ctxt, "EPSG:32761", "EPSG:4326", nullptr); ObjectKeeper keeper_P(P); ASSERT_NE(P, nullptr); double out_left; double out_bottom; double out_right; double out_top; int success = proj_trans_bounds(m_ctxt, P, PJ_FWD, -1405880.71737131, -1371213.7625429356, 5405880.71737131, 5371213.762542935, &out_left, &out_bottom, &out_right, &out_top, 21); EXPECT_TRUE(success == 1); EXPECT_NEAR(out_left, -90.0, 1); EXPECT_NEAR(out_bottom, -180.0, 1); EXPECT_NEAR(out_right, -48.656, 1); EXPECT_NEAR(out_top, 180.0, 1); double out_left_inv; double out_bottom_inv; double out_right_inv; double out_top_inv; int success_inv = proj_trans_bounds(m_ctxt, P, PJ_INV, -90.0, -180.0, -60.0, 180.0, &out_left_inv, &out_bottom_inv, &out_right_inv, &out_top_inv, 21); EXPECT_TRUE(success_inv == 1); EXPECT_NEAR(out_left_inv, -1405880.72, 1); EXPECT_NEAR(out_bottom_inv, -1371213.76, 1); EXPECT_NEAR(out_right_inv, 5405880.72, 1); EXPECT_NEAR(out_top_inv, 5371213.76, 1); } // --------------------------------------------------------------------------- TEST_F(CApi, proj_crs_has_point_motion_operation) { auto ctxt = proj_create_operation_factory_context(m_ctxt, nullptr); ASSERT_NE(ctxt, nullptr); ContextKeeper keeper_ctxt(ctxt); { auto crs = proj_create_from_database( m_ctxt, "EPSG", "4267", PJ_CATEGORY_CRS, false, nullptr); // NAD27 ASSERT_NE(crs, nullptr); ObjectKeeper keeper_crs(crs); EXPECT_FALSE(proj_crs_has_point_motion_operation(m_ctxt, crs)); } { // NAD83(CSRS)v7 auto crs = proj_create_from_database(m_ctxt, "EPSG", "8255", PJ_CATEGORY_CRS, false, nullptr); ASSERT_NE(crs, nullptr); ObjectKeeper keeper_crs(crs); EXPECT_TRUE(proj_crs_has_point_motion_operation(m_ctxt, crs)); } } // --------------------------------------------------------------------------- #if !defined(_WIN32) TEST_F(CApi, open_plenty_of_contexts) { // Test that we only consume 1 file handle for the connection to the // database std::vector<FILE *> dummyFilePointers; std::vector<PJ_CONTEXT *> ctxts; // The number of file descriptors that can be opened simultaneously by a // process varies across platforms so we make use of getrlimit(2) to // retrieve it. struct rlimit open_max; getrlimit(RLIMIT_NOFILE, &open_max); // On some platforms fopen returned nullptrs before reaching limit - 50, we // can avoid this by capping the limit to 1024. if (open_max.rlim_cur > 1024) { open_max.rlim_cur = 1024; setrlimit(RLIMIT_NOFILE, &open_max); } for (rlim_t i = 0; i < open_max.rlim_cur - 50; i++) { FILE *f = fopen("/dev/null", "rb"); ASSERT_TRUE(f != nullptr); dummyFilePointers.push_back(f); } for (int i = 0; i < 100; i++) { PJ_CONTEXT *ctxt = proj_context_create(); ASSERT_TRUE(ctxt != nullptr); auto obj = proj_create(ctxt, "EPSG:4326"); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); ctxts.push_back(ctxt); } for (PJ_CONTEXT *ctxt : ctxts) { proj_context_destroy(ctxt); } for (FILE *f : dummyFilePointers) { fclose(f); } proj_cleanup(); } #endif // !defined(_WIN32) // --------------------------------------------------------------------------- #ifndef __MINGW32__ // We need std::thread support TEST_F(CApi, concurrent_context) { // Test that concurrent access to the database is thread safe. std::vector<std::thread> threads; for (int i = 0; i < 4; i++) { threads.emplace_back(std::thread([] { for (int j = 0; j < 60; j++) { PJ_CONTEXT *ctxt = proj_context_create(); { auto obj = proj_create(ctxt, "EPSG:4326"); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); } { auto obj = proj_create( ctxt, ("EPSG:" + std::to_string(32600 + j)).c_str()); ObjectKeeper keeper(obj); EXPECT_NE(obj, nullptr); } proj_context_destroy(ctxt); } })); } for (auto &t : threads) { t.join(); } proj_cleanup(); } #endif // __MINGW32__ } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_network.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test networking * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2019, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include <memory> #include <stdio.h> #include <stdlib.h> #include "proj_internal.h" #include <proj.h> #include <sqlite3.h> #include <time.h> #ifdef CURL_ENABLED #include <curl/curl.h> #endif #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #endif namespace { static const int byte_order_test = 1; #define IS_LSB \ (1 == (reinterpret_cast<const unsigned char *>(&byte_order_test))[0]) static void swap_words(void *dataIn, size_t word_size, size_t word_count) { unsigned char *data = static_cast<unsigned char *>(dataIn); for (size_t word = 0; word < word_count; word++) { for (size_t i = 0; i < word_size / 2; i++) { unsigned char t; t = data[i]; data[i] = data[word_size - i - 1]; data[word_size - i - 1] = t; } data += word_size; } } // --------------------------------------------------------------------------- #ifdef CURL_ENABLED static bool networkAccessOK = false; static size_t noop_curl_write_func(void *, size_t, size_t nmemb, void *) { return nmemb; } TEST(networking, initial_check) { CURL *hCurlHandle = curl_easy_init(); if (!hCurlHandle) return; curl_easy_setopt(hCurlHandle, CURLOPT_URL, "https://cdn.proj.org/fr_ign_ntf_r93.tif"); curl_easy_setopt(hCurlHandle, CURLOPT_RANGE, "0-1"); curl_easy_setopt(hCurlHandle, CURLOPT_WRITEFUNCTION, noop_curl_write_func); curl_easy_perform(hCurlHandle); long response_code = 0; curl_easy_getinfo(hCurlHandle, CURLINFO_HTTP_CODE, &response_code); curl_easy_cleanup(hCurlHandle); networkAccessOK = (response_code == 206); if (!networkAccessOK) { fprintf(stderr, "network access not working"); } } #endif // --------------------------------------------------------------------------- static void silent_logger(void *, int, const char *) {} // --------------------------------------------------------------------------- TEST(networking, basic) { const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=https://cdn.proj.org/fr_ign_ntf_r93.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; // network access disabled by default auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_log_func(ctx, nullptr, silent_logger); auto P = proj_create(ctx, pipeline); ASSERT_EQ(P, nullptr); proj_context_destroy(ctx); proj_cleanup(); #ifdef CURL_ENABLED // enable through env variable putenv(const_cast<char *>("PROJ_NETWORK=ON")); ctx = proj_context_create(); P = proj_create(ctx, pipeline); if (networkAccessOK) { ASSERT_NE(P, nullptr); } proj_destroy(P); proj_context_destroy(ctx); putenv(const_cast<char *>("PROJ_NETWORK=")); #endif proj_cleanup(); // still disabled ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_log_func(ctx, nullptr, silent_logger); P = proj_create(ctx, pipeline); ASSERT_EQ(P, nullptr); proj_context_destroy(ctx); proj_cleanup(); // enable through API ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); P = proj_create(ctx, pipeline); #ifdef CURL_ENABLED if (networkAccessOK) { ASSERT_NE(P, nullptr); } else { ASSERT_EQ(P, nullptr); proj_context_destroy(ctx); return; } double longitude = 2; double lat = 49; proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, nullptr, 0, 0, nullptr, 0, 0); EXPECT_NEAR(longitude, 1.9992776848, 1e-10); EXPECT_NEAR(lat, 48.9999322600, 1e-10); proj_destroy(P); #else ASSERT_EQ(P, nullptr); #endif proj_context_destroy(ctx); proj_cleanup(); } // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, curl_invalid_resource) { auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); proj_log_func(ctx, nullptr, silent_logger); auto P = proj_create( ctx, "+proj=hgridshift +grids=https://i_do_not.exist/my.tif"); proj_context_destroy(ctx); ASSERT_EQ(P, nullptr); } #endif // --------------------------------------------------------------------------- struct Event { virtual ~Event(); std::string type{}; PJ_CONTEXT *ctx = nullptr; }; Event::~Event() = default; struct OpenEvent : public Event { OpenEvent() { type = "OpenEvent"; } std::string url{}; unsigned long long offset = 0; size_t size_to_read = 0; std::vector<unsigned char> response{}; std::string errorMsg{}; int file_id = 0; }; struct CloseEvent : public Event { CloseEvent() { type = "CloseEvent"; } int file_id = 0; }; struct GetHeaderValueEvent : public Event { GetHeaderValueEvent() { type = "GetHeaderValueEvent"; } int file_id = 0; std::string key{}; std::string value{}; }; struct ReadRangeEvent : public Event { ReadRangeEvent() { type = "ReadRangeEvent"; } unsigned long long offset = 0; size_t size_to_read = 0; std::vector<unsigned char> response{}; std::string errorMsg{}; int file_id = 0; }; struct File {}; struct ExchangeWithCallback { std::vector<std::unique_ptr<Event>> events{}; size_t nextEvent = 0; bool error = false; std::map<int, PROJ_NETWORK_HANDLE *> mapIdToHandle{}; bool allConsumedAndNoError() const { return nextEvent == events.size() && !error; } }; static PROJ_NETWORK_HANDLE *open_cbk(PJ_CONTEXT *ctx, const char *url, unsigned long long offset, size_t size_to_read, void *buffer, size_t *out_size_read, size_t error_string_max_size, char *out_error_string, void *user_data) { auto exchange = static_cast<ExchangeWithCallback *>(user_data); if (exchange->error) return nullptr; if (exchange->nextEvent >= exchange->events.size()) { fprintf(stderr, "unexpected call to open(%s, %ld, %ld)\n", url, (long)offset, (long)size_to_read); exchange->error = true; return nullptr; } auto openEvent = dynamic_cast<OpenEvent *>(exchange->events[exchange->nextEvent].get()); if (!openEvent) { fprintf(stderr, "unexpected call to open(%s, %ld, %ld). " "Was expecting a %s event\n", url, (long)offset, (long)size_to_read, exchange->events[exchange->nextEvent]->type.c_str()); exchange->error = true; return nullptr; } exchange->nextEvent++; if (openEvent->ctx != ctx || openEvent->url != url || openEvent->offset != offset || openEvent->size_to_read != size_to_read) { fprintf(stderr, "wrong call to open(%s, %ld, %ld). Was expecting " "open(%s, %ld, %ld)\n", url, (long)offset, (long)size_to_read, openEvent->url.c_str(), (long)openEvent->offset, (long)openEvent->size_to_read); exchange->error = true; return nullptr; } if (!openEvent->errorMsg.empty()) { snprintf(out_error_string, error_string_max_size, "%s", openEvent->errorMsg.c_str()); return nullptr; } memcpy(buffer, openEvent->response.data(), openEvent->response.size()); *out_size_read = openEvent->response.size(); auto handle = reinterpret_cast<PROJ_NETWORK_HANDLE *>(new File()); exchange->mapIdToHandle[openEvent->file_id] = handle; return handle; } static void close_cbk(PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, void *user_data) { auto exchange = static_cast<ExchangeWithCallback *>(user_data); if (exchange->error) return; if (exchange->nextEvent >= exchange->events.size()) { fprintf(stderr, "unexpected call to close()\n"); exchange->error = true; return; } auto closeEvent = dynamic_cast<CloseEvent *>(exchange->events[exchange->nextEvent].get()); if (!closeEvent) { fprintf(stderr, "unexpected call to close(). " "Was expecting a %s event\n", exchange->events[exchange->nextEvent]->type.c_str()); exchange->error = true; return; } if (closeEvent->ctx != ctx) { fprintf(stderr, "close() called with bad context\n"); exchange->error = true; return; } if (exchange->mapIdToHandle[closeEvent->file_id] != handle) { fprintf(stderr, "close() called with bad handle\n"); exchange->error = true; return; } exchange->nextEvent++; delete reinterpret_cast<File *>(handle); } static const char *get_header_value_cbk(PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, const char *header_name, void *user_data) { auto exchange = static_cast<ExchangeWithCallback *>(user_data); if (exchange->error) return nullptr; if (exchange->nextEvent >= exchange->events.size()) { fprintf(stderr, "unexpected call to get_header_value()\n"); exchange->error = true; return nullptr; } auto getHeaderValueEvent = dynamic_cast<GetHeaderValueEvent *>( exchange->events[exchange->nextEvent].get()); if (!getHeaderValueEvent) { fprintf(stderr, "unexpected call to get_header_value(). " "Was expecting a %s event\n", exchange->events[exchange->nextEvent]->type.c_str()); exchange->error = true; return nullptr; } if (getHeaderValueEvent->ctx != ctx) { fprintf(stderr, "get_header_value() called with bad context\n"); exchange->error = true; return nullptr; } if (getHeaderValueEvent->key != header_name) { fprintf(stderr, "wrong call to get_header_value(%s). Was expecting " "get_header_value(%s)\n", header_name, getHeaderValueEvent->key.c_str()); exchange->error = true; return nullptr; } if (exchange->mapIdToHandle[getHeaderValueEvent->file_id] != handle) { fprintf(stderr, "get_header_value() called with bad handle\n"); exchange->error = true; return nullptr; } exchange->nextEvent++; return getHeaderValueEvent->value.c_str(); } static size_t read_range_cbk(PJ_CONTEXT *ctx, PROJ_NETWORK_HANDLE *handle, unsigned long long offset, size_t size_to_read, void *buffer, size_t error_string_max_size, char *out_error_string, void *user_data) { auto exchange = static_cast<ExchangeWithCallback *>(user_data); if (exchange->error) return 0; if (exchange->nextEvent >= exchange->events.size()) { fprintf(stderr, "unexpected call to read_range(%ld, %ld)\n", (long)offset, (long)size_to_read); exchange->error = true; return 0; } auto readRangeEvent = dynamic_cast<ReadRangeEvent *>( exchange->events[exchange->nextEvent].get()); if (!readRangeEvent) { fprintf(stderr, "unexpected call to read_range(). " "Was expecting a %s event\n", exchange->events[exchange->nextEvent]->type.c_str()); exchange->error = true; return 0; } if (exchange->mapIdToHandle[readRangeEvent->file_id] != handle) { fprintf(stderr, "read_range() called with bad handle\n"); exchange->error = true; return 0; } if (readRangeEvent->ctx != ctx || readRangeEvent->offset != offset || readRangeEvent->size_to_read != size_to_read) { fprintf(stderr, "wrong call to read_range(%ld, %ld). Was expecting " "read_range(%ld, %ld)\n", (long)offset, (long)size_to_read, (long)readRangeEvent->offset, (long)readRangeEvent->size_to_read); exchange->error = true; return 0; } exchange->nextEvent++; if (!readRangeEvent->errorMsg.empty()) { snprintf(out_error_string, error_string_max_size, "%s", readRangeEvent->errorMsg.c_str()); return 0; } memcpy(buffer, readRangeEvent->response.data(), readRangeEvent->response.size()); return readRangeEvent->response.size(); } TEST(networking, custom) { auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); ExchangeWithCallback exchange; ASSERT_TRUE(proj_context_set_network_callbacks(ctx, open_cbk, close_cbk, get_header_value_cbk, read_range_cbk, &exchange)); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/my.tif"; event->offset = 0; event->size_to_read = 16384; event->response.resize(16384); event->file_id = 1; const char *proj_source_data = getenv("PROJ_SOURCE_DATA"); ASSERT_TRUE(proj_source_data != nullptr); std::string filename(proj_source_data); filename += "/tests/egm96_15_uncompressed_truncated.tif"; FILE *f = fopen(filename.c_str(), "rb"); ASSERT_TRUE(f != nullptr); ASSERT_EQ(fread(&event->response[0], 1, 956, f), 956U); fclose(f); exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } auto P = proj_create( ctx, "+proj=vgridshift +grids=https://foo/my.tif +multiplier=1"); ASSERT_NE(P, nullptr); ASSERT_TRUE(exchange.allConsumedAndNoError()); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/my.tif"; event->offset = 524288; event->size_to_read = 278528; event->response.resize(278528); event->file_id = 2; float f = 1.25; if (!IS_LSB) { swap_words(&f, sizeof(f), 1); } for (size_t i = 0; i < 278528 / sizeof(float); i++) { memcpy(&event->response[i * sizeof(float)], &f, sizeof(float)); } exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { double longitude = 2 / 180. * M_PI; double lat = 49 / 180. * M_PI; double z = 0; ASSERT_EQ(proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0), 1U); EXPECT_EQ(z, 1.25); } ASSERT_TRUE(exchange.allConsumedAndNoError()); { std::unique_ptr<ReadRangeEvent> event(new ReadRangeEvent()); event->ctx = ctx; event->offset = 3670016; event->size_to_read = 278528; event->response.resize(278528); event->file_id = 2; float f = 2.25; if (!IS_LSB) { swap_words(&f, sizeof(f), 1); } for (size_t i = 0; i < 278528 / sizeof(float); i++) { memcpy(&event->response[i * sizeof(float)], &f, sizeof(float)); } exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { double longitude = 2 / 180. * M_PI; double lat = -49 / 180. * M_PI; double z = 0; ASSERT_EQ(proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0), 1U); EXPECT_EQ(z, 2.25); } { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } proj_destroy(P); ASSERT_TRUE(exchange.allConsumedAndNoError()); // Once again ! No network access P = proj_create(ctx, "+proj=vgridshift +grids=https://foo/my.tif +multiplier=1"); ASSERT_NE(P, nullptr); { double longitude = 2 / 180. * M_PI; double lat = 49 / 180. * M_PI; double z = 0; ASSERT_EQ(proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0), 1U); EXPECT_EQ(z, 1.25); } proj_destroy(P); ASSERT_TRUE(exchange.allConsumedAndNoError()); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, getfilesize) { auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); ExchangeWithCallback exchange; ASSERT_TRUE(proj_context_set_network_callbacks(ctx, open_cbk, close_cbk, get_header_value_cbk, read_range_cbk, &exchange)); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/getfilesize.tif"; event->offset = 0; event->size_to_read = 16384; event->response.resize(16384); event->file_id = 1; const char *proj_source_data = getenv("PROJ_SOURCE_DATA"); ASSERT_TRUE(proj_source_data != nullptr); std::string filename(proj_source_data); filename += "/tests/test_vgrid_single_strip_truncated.tif"; FILE *f = fopen(filename.c_str(), "rb"); ASSERT_TRUE(f != nullptr); ASSERT_EQ(fread(&event->response[0], 1, 550, f), 550U); fclose(f); exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes 0-16383/4153510"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } auto P = proj_create( ctx, "+proj=vgridshift +grids=https://foo/getfilesize.tif +multiplier=1"); ASSERT_NE(P, nullptr); ASSERT_TRUE(exchange.allConsumedAndNoError()); proj_destroy(P); P = proj_create( ctx, "+proj=vgridshift +grids=https://foo/getfilesize.tif +multiplier=1"); ASSERT_NE(P, nullptr); ASSERT_TRUE(exchange.allConsumedAndNoError()); proj_destroy(P); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, simul_open_error) { auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_log_func(ctx, nullptr, silent_logger); proj_context_set_enable_network(ctx, true); ExchangeWithCallback exchange; ASSERT_TRUE(proj_context_set_network_callbacks(ctx, open_cbk, close_cbk, get_header_value_cbk, read_range_cbk, &exchange)); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/open_error.tif"; event->offset = 0; event->size_to_read = 16384; event->errorMsg = "Cannot open file"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } auto P = proj_create( ctx, "+proj=vgridshift +grids=https://foo/open_error.tif +multiplier=1"); ASSERT_EQ(P, nullptr); ASSERT_TRUE(exchange.allConsumedAndNoError()); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, simul_read_range_error) { auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); ExchangeWithCallback exchange; ASSERT_TRUE(proj_context_set_network_callbacks(ctx, open_cbk, close_cbk, get_header_value_cbk, read_range_cbk, &exchange)); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/read_range_error.tif"; event->offset = 0; event->size_to_read = 16384; event->response.resize(16384); event->file_id = 1; const char *proj_source_data = getenv("PROJ_SOURCE_DATA"); ASSERT_TRUE(proj_source_data != nullptr); std::string filename(proj_source_data); filename += "/tests/egm96_15_uncompressed_truncated.tif"; FILE *f = fopen(filename.c_str(), "rb"); ASSERT_TRUE(f != nullptr); ASSERT_EQ(fread(&event->response[0], 1, 956, f), 956U); fclose(f); exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } auto P = proj_create(ctx, "+proj=vgridshift " "+grids=https://foo/read_range_error.tif " "+multiplier=1"); ASSERT_NE(P, nullptr); ASSERT_TRUE(exchange.allConsumedAndNoError()); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/read_range_error.tif"; event->offset = 524288; event->size_to_read = 278528; event->response.resize(278528); event->file_id = 2; float f = 1.25; if (!IS_LSB) { swap_words(&f, sizeof(f), 1); } for (size_t i = 0; i < 278528 / sizeof(float); i++) { memcpy(&event->response[i * sizeof(float)], &f, sizeof(float)); } exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { double longitude = 2 / 180. * M_PI; double lat = 49 / 180. * M_PI; double z = 0; ASSERT_EQ(proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0), 1U); EXPECT_EQ(z, 1.25); } ASSERT_TRUE(exchange.allConsumedAndNoError()); { std::unique_ptr<ReadRangeEvent> event(new ReadRangeEvent()); event->ctx = ctx; event->offset = 3670016; event->size_to_read = 278528; event->errorMsg = "read range error"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { double longitude = 2 / 180. * M_PI; double lat = -49 / 180. * M_PI; double z = 0; proj_log_func(ctx, nullptr, silent_logger); ASSERT_EQ(proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0), 1U); EXPECT_EQ(z, HUGE_VAL); } { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } proj_destroy(P); ASSERT_TRUE(exchange.allConsumedAndNoError()); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, simul_file_change_while_opened) { auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); ExchangeWithCallback exchange; ASSERT_TRUE(proj_context_set_network_callbacks(ctx, open_cbk, close_cbk, get_header_value_cbk, read_range_cbk, &exchange)); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/file_change_while_opened.tif"; event->offset = 0; event->size_to_read = 16384; event->response.resize(16384); event->file_id = 1; const char *proj_source_data = getenv("PROJ_SOURCE_DATA"); ASSERT_TRUE(proj_source_data != nullptr); std::string filename(proj_source_data); filename += "/tests/egm96_15_uncompressed_truncated.tif"; FILE *f = fopen(filename.c_str(), "rb"); ASSERT_TRUE(f != nullptr); ASSERT_EQ(fread(&event->response[0], 1, 956, f), 956U); fclose(f); exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 1; exchange.events.emplace_back(std::move(event)); } auto P = proj_create(ctx, "+proj=vgridshift " "+grids=https://foo/file_change_while_opened.tif " "+multiplier=1"); ASSERT_NE(P, nullptr); ASSERT_TRUE(exchange.allConsumedAndNoError()); { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/file_change_while_opened.tif"; event->offset = 524288; event->size_to_read = 278528; event->response.resize(278528); event->file_id = 2; float f = 1.25; if (!IS_LSB) { swap_words(&f, sizeof(f), 1); } for (size_t i = 0; i < 278528 / sizeof(float); i++) { memcpy(&event->response[i * sizeof(float)], &f, sizeof(float)); } exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date CHANGED!!!!"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 2; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<OpenEvent> event(new OpenEvent()); event->ctx = ctx; event->url = "https://foo/file_change_while_opened.tif"; event->offset = 0; event->size_to_read = 16384; event->response.resize(16384); event->file_id = 3; const char *proj_source_data = getenv("PROJ_SOURCE_DATA"); ASSERT_TRUE(proj_source_data != nullptr); std::string filename(proj_source_data); filename += "/tests/egm96_15_uncompressed_truncated.tif"; FILE *f = fopen(filename.c_str(), "rb"); ASSERT_TRUE(f != nullptr); ASSERT_EQ(fread(&event->response[0], 1, 956, f), 956U); fclose(f); exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Content-Range"; event->value = "bytes=0-16383/10000000"; event->file_id = 3; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "Last-Modified"; event->value = "some_date CHANGED!!!!"; event->file_id = 3; exchange.events.emplace_back(std::move(event)); } { std::unique_ptr<GetHeaderValueEvent> event(new GetHeaderValueEvent()); event->ctx = ctx; event->key = "ETag"; event->value = "some_etag"; event->file_id = 3; exchange.events.emplace_back(std::move(event)); } { double longitude = 2 / 180. * M_PI; double lat = 49 / 180. * M_PI; double z = 0; ASSERT_EQ(proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0), 1U); EXPECT_EQ(z, 1.25); } ASSERT_TRUE(exchange.allConsumedAndNoError()); { std::unique_ptr<CloseEvent> event(new CloseEvent()); event->ctx = ctx; event->file_id = 3; exchange.events.emplace_back(std::move(event)); } proj_destroy(P); ASSERT_TRUE(exchange.allConsumedAndNoError()); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, curl_hgridshift) { if (!networkAccessOK) { return; } auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); // NTF to RGF93 v1. Using fr_ign_gr3df97a.tif auto P = proj_create_crs_to_crs(ctx, "EPSG:4275", "EPSG:4171", nullptr); ASSERT_NE(P, nullptr); PJ_COORD c; c.xyz.x = 49; // lat c.xyz.y = 2; // long c.xyz.z = 0; c = proj_trans(P, PJ_FWD, c); proj_assign_context(P, ctx); // (dummy) test context reassignment proj_destroy(P); proj_context_destroy(ctx); EXPECT_NEAR(c.xyz.x, 48.9999322600, 1e-8); EXPECT_NEAR(c.xyz.y, 1.9992776848, 1e-8); EXPECT_NEAR(c.xyz.z, 0, 1e-2); } #endif // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, curl_vgridshift) { if (!networkAccessOK) { return; } auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); // WGS84 to EGM2008 height. Using egm08_25.tif auto P = proj_create_crs_to_crs(ctx, "EPSG:4979", "EPSG:4326+3855", nullptr); ASSERT_NE(P, nullptr); PJ_COORD c; c.xyz.x = -30; // lat c.xyz.y = 150; // long c.xyz.z = 0; c = proj_trans(P, PJ_FWD, c); proj_assign_context(P, ctx); // (dummy) test context reassignment proj_destroy(P); proj_context_destroy(ctx); EXPECT_NEAR(c.xyz.x, -30, 1e-8); EXPECT_NEAR(c.xyz.y, 150, 1e-8); EXPECT_NEAR(c.xyz.z, -31.89, 1e-2); } #endif // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, curl_vgridshift_vertcon) { if (!networkAccessOK) { return; } auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); // NGVD29 to NAVD88 height. Using vertcone.tif auto P = proj_create_crs_to_crs(ctx, "EPSG:4269+7968", "EPSG:4269+5703", nullptr); ASSERT_NE(P, nullptr); PJ_COORD c; c.xyz.x = 40; // lat c.xyz.y = -80; // long c.xyz.z = 0; c = proj_trans(P, PJ_FWD, c); proj_destroy(P); proj_context_destroy(ctx); EXPECT_NEAR(c.xyz.x, 40, 1e-8); EXPECT_NEAR(c.xyz.y, -80, 1e-8); EXPECT_NEAR(c.xyz.z, -0.15, 1e-2); } #endif // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, network_endpoint_env_variable) { putenv(const_cast<char *>("PROJ_NETWORK_ENDPOINT=http://0.0.0.0/")); auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); // NAD83 to NAD83(HARN) in West-Virginia. Using wvhpgn.tif auto P = proj_create_crs_to_crs(ctx, "EPSG:4269", "EPSG:4152", nullptr); ASSERT_NE(P, nullptr); PJ_COORD c; c.xyz.x = 40; // lat c.xyz.y = -80; // long c.xyz.z = 0; c = proj_trans(P, PJ_FWD, c); putenv(const_cast<char *>("PROJ_NETWORK_ENDPOINT=")); proj_destroy(P); proj_context_destroy(ctx); EXPECT_EQ(c.xyz.x, HUGE_VAL); } #endif // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, network_endpoint_api) { auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); proj_context_set_url_endpoint(ctx, "http://0.0.0.0"); // NAD83 to NAD83(HARN) in West-Virginia. Using wvhpgn.tif auto P = proj_create_crs_to_crs(ctx, "EPSG:4269", "EPSG:4152", nullptr); ASSERT_NE(P, nullptr); PJ_COORD c; c.xyz.x = 40; // lat c.xyz.y = -80; // long c.xyz.z = 0; c = proj_trans(P, PJ_FWD, c); proj_destroy(P); proj_context_destroy(ctx); EXPECT_EQ(c.xyz.x, HUGE_VAL); } #endif // --------------------------------------------------------------------------- #ifdef CURL_ENABLED static PROJ_NETWORK_HANDLE *dummy_open_cbk(PJ_CONTEXT *, const char *, unsigned long long, size_t, void *, size_t *, size_t, char *, void *) { assert(false); return nullptr; } static void dummy_close_cbk(PJ_CONTEXT *, PROJ_NETWORK_HANDLE *, void *) { assert(false); } static const char *dummy_get_header_value_cbk(PJ_CONTEXT *, PROJ_NETWORK_HANDLE *, const char *, void *) { assert(false); return nullptr; } static size_t dummy_read_range_cbk(PJ_CONTEXT *, PROJ_NETWORK_HANDLE *, unsigned long long, size_t, void *, size_t, char *, void *) { assert(false); return 0; } TEST(networking, cache_basic) { if (!networkAccessOK) { return; } proj_cleanup(); const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=https://cdn.proj.org/fr_ign_ntf_r93.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; auto ctx = proj_context_create(); proj_context_set_enable_network(ctx, true); auto P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); proj_destroy(P); EXPECT_TRUE(!pj_context_get_grid_cache_filename(ctx).empty()); sqlite3 *hDB = nullptr; sqlite3_open_v2(pj_context_get_grid_cache_filename(ctx).c_str(), &hDB, SQLITE_OPEN_READONLY, nullptr); ASSERT_NE(hDB, nullptr); sqlite3_stmt *hStmt = nullptr; sqlite3_prepare_v2(hDB, "SELECT url, offset FROM chunks WHERE id = (" "SELECT chunk_id FROM linked_chunks WHERE id = (" "SELECT head FROM linked_chunks_head_tail))", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_ROW); const char *url = reinterpret_cast<const char *>(sqlite3_column_text(hStmt, 0)); ASSERT_NE(url, nullptr); ASSERT_EQ(std::string(url), "https://cdn.proj.org/fr_ign_ntf_r93.tif"); ASSERT_EQ(sqlite3_column_int64(hStmt, 1), 0); sqlite3_finalize(hStmt); sqlite3_close(hDB); proj_cleanup(); // Check that a second access doesn't trigger any network activity ASSERT_TRUE(proj_context_set_network_callbacks( ctx, dummy_open_cbk, dummy_close_cbk, dummy_get_header_value_cbk, dummy_read_range_cbk, nullptr)); P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); proj_destroy(P); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, proj_grid_cache_clear) { if (!networkAccessOK) { return; } const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=https://cdn.proj.org/fr_ign_ntf_r93.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; proj_cleanup(); auto ctx = proj_context_create(); proj_context_set_enable_network(ctx, true); proj_grid_cache_set_filename(ctx, "tmp_proj_db_cache.db"); EXPECT_EQ(pj_context_get_grid_cache_filename(ctx), std::string("tmp_proj_db_cache.db")); proj_grid_cache_clear(ctx); auto P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); proj_destroy(P); // Check that the file exists { sqlite3 *hDB = nullptr; ASSERT_EQ( sqlite3_open_v2(pj_context_get_grid_cache_filename(ctx).c_str(), &hDB, SQLITE_OPEN_READONLY, nullptr), SQLITE_OK); sqlite3_close(hDB); } proj_grid_cache_clear(ctx); // Check that the file no longer exists { sqlite3 *hDB = nullptr; ASSERT_NE( sqlite3_open_v2(pj_context_get_grid_cache_filename(ctx).c_str(), &hDB, SQLITE_OPEN_READONLY, nullptr), SQLITE_OK); sqlite3_close(hDB); } proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, cache_saturation) { if (!networkAccessOK) { return; } const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=https://cdn.proj.org/fr_ign_ntf_r93.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; proj_cleanup(); auto ctx = proj_context_create(); proj_context_set_enable_network(ctx, true); proj_grid_cache_set_filename(ctx, "tmp_proj_db_cache.db"); proj_grid_cache_clear(ctx); // Limit to two chunks putenv(const_cast<char *>("PROJ_GRID_CACHE_MAX_SIZE_BYTES=32768")); proj_grid_cache_set_max_size(ctx, 0); putenv(const_cast<char *>("PROJ_GRID_CACHE_MAX_SIZE_BYTES=")); auto P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); double longitude = 2; double lat = 49; proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, nullptr, 0, 0, nullptr, 0, 0); EXPECT_NEAR(longitude, 1.9992776848, 1e-10); EXPECT_NEAR(lat, 48.9999322600, 1e-10); proj_destroy(P); sqlite3 *hDB = nullptr; sqlite3_open_v2(pj_context_get_grid_cache_filename(ctx).c_str(), &hDB, SQLITE_OPEN_READONLY, nullptr); ASSERT_NE(hDB, nullptr); sqlite3_stmt *hStmt = nullptr; sqlite3_prepare_v2(hDB, "SELECT COUNT(*) FROM chunk_data UNION ALL " "SELECT COUNT(*) FROM chunks UNION ALL " "SELECT COUNT(*) FROM linked_chunks", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_ROW); ASSERT_EQ(sqlite3_column_int64(hStmt, 0), 2); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_ROW); ASSERT_EQ(sqlite3_column_int64(hStmt, 0), 2); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_ROW); ASSERT_EQ(sqlite3_column_int64(hStmt, 0), 2); sqlite3_finalize(hStmt); sqlite3_close(hDB); proj_grid_cache_clear(ctx); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, cache_ttl) { if (!networkAccessOK) { return; } const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=https://cdn.proj.org/fr_ign_ntf_r93.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; proj_cleanup(); auto ctx = proj_context_create(); proj_context_set_enable_network(ctx, true); proj_grid_cache_set_filename(ctx, "tmp_proj_db_cache.db"); proj_grid_cache_clear(ctx); auto P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); double longitude = 2; double lat = 49; proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, nullptr, 0, 0, nullptr, 0, 0); EXPECT_NEAR(longitude, 1.9992776848, 1e-10); EXPECT_NEAR(lat, 48.9999322600, 1e-10); proj_destroy(P); sqlite3 *hDB = nullptr; sqlite3_open_v2(pj_context_get_grid_cache_filename(ctx).c_str(), &hDB, SQLITE_OPEN_READWRITE, nullptr); ASSERT_NE(hDB, nullptr); // Force lastChecked to the Epoch so that data is expired. sqlite3_stmt *hStmt = nullptr; sqlite3_prepare_v2(hDB, "UPDATE properties SET lastChecked = 0, " "lastModified = 'foo', etag = 'bar'", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_DONE); sqlite3_finalize(hStmt); // Put junk in already cached data to check that we will refresh it. hStmt = nullptr; sqlite3_prepare_v2(hDB, "UPDATE chunk_data SET data = zeroblob(16384)", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_DONE); sqlite3_finalize(hStmt); sqlite3_close(hDB); proj_cleanup(); // Set a never expire ttl proj_grid_cache_set_ttl(ctx, -1); // We'll get junk data, hence the pipeline initialization fails proj_log_func(ctx, nullptr, silent_logger); P = proj_create(ctx, pipeline); ASSERT_EQ(P, nullptr); proj_destroy(P); proj_cleanup(); // Set a normal ttl proj_grid_cache_set_ttl(ctx, 86400); // Pipeline creation succeeds P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); proj_destroy(P); hDB = nullptr; sqlite3_open_v2(pj_context_get_grid_cache_filename(ctx).c_str(), &hDB, SQLITE_OPEN_READWRITE, nullptr); ASSERT_NE(hDB, nullptr); hStmt = nullptr; sqlite3_prepare_v2(hDB, "SELECT lastChecked, lastModified, etag FROM properties", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_ROW); ASSERT_NE(sqlite3_column_int64(hStmt, 0), 0); ASSERT_NE(sqlite3_column_text(hStmt, 1), nullptr); ASSERT_NE(std::string(reinterpret_cast<const char *>( sqlite3_column_text(hStmt, 1))), "foo"); ASSERT_NE(sqlite3_column_text(hStmt, 2), nullptr); ASSERT_NE(std::string(reinterpret_cast<const char *>( sqlite3_column_text(hStmt, 2))), "bar"); sqlite3_finalize(hStmt); sqlite3_close(hDB); proj_grid_cache_clear(ctx); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, cache_lock) { if (!networkAccessOK) { return; } const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=hgridshift +grids=https://cdn.proj.org/fr_ign_ntf_r93.tif " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; proj_cleanup(); auto ctx = proj_context_create(); proj_context_set_enable_network(ctx, true); proj_grid_cache_set_filename(ctx, "tmp_proj_db_cache.db"); proj_grid_cache_clear(ctx); auto P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); double longitude = 2; double lat = 49; proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, nullptr, 0, 0, nullptr, 0, 0); EXPECT_NEAR(longitude, 1.9992776848, 1e-10); EXPECT_NEAR(lat, 48.9999322600, 1e-10); proj_destroy(P); // Take a lock sqlite3 *hDB = nullptr; sqlite3_open_v2(pj_context_get_grid_cache_filename(ctx).c_str(), &hDB, SQLITE_OPEN_READWRITE, nullptr); ASSERT_NE(hDB, nullptr); sqlite3_stmt *hStmt = nullptr; sqlite3_prepare_v2(hDB, "BEGIN EXCLUSIVE", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_DONE); sqlite3_finalize(hStmt); proj_cleanup(); time_t start; time(&start); // 2 lock attempts, so we must sleep for each at least 0.5 ms putenv(const_cast<char *>("PROJ_LOCK_MAX_ITERS=25")); P = proj_create(ctx, pipeline); putenv(const_cast<char *>("PROJ_LOCK_MAX_ITERS=")); ASSERT_NE(P, nullptr); proj_destroy(P); // Check that we have spend more than 1 sec time_t end; time(&end); ASSERT_GE(end - start, 1U); sqlite3_close(hDB); proj_grid_cache_clear(ctx); proj_context_destroy(ctx); } // --------------------------------------------------------------------------- TEST(networking, download_whole_files) { if (!networkAccessOK) { return; } proj_cleanup(); unlink("proj_test_tmp/cache.db"); unlink("proj_test_tmp/dk_sdfe_dvr90.tif"); rmdir("proj_test_tmp"); putenv(const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=")); putenv(const_cast<char *>("PROJ_USER_WRITABLE_DIRECTORY=./proj_test_tmp")); putenv(const_cast<char *>("PROJ_FULL_FILE_CHUNK_SIZE=100000")); proj_context_set_enable_network(nullptr, true); const auto grid_info = proj_grid_info("dk_sdfe_dvr90.tif"); EXPECT_EQ(std::string(grid_info.filename), ""); EXPECT_EQ(std::string(grid_info.gridname), "dk_sdfe_dvr90.tif"); EXPECT_EQ(std::string(grid_info.format), "gtiff"); proj_context_set_enable_network(nullptr, false); auto ctx = proj_context_create(); proj_context_set_enable_network(ctx, true); ASSERT_TRUE(proj_is_download_needed(ctx, "dk_sdfe_dvr90.tif", false)); ASSERT_TRUE( proj_download_file(ctx, "dk_sdfe_dvr90.tif", false, nullptr, nullptr)); FILE *f = fopen("proj_test_tmp/dk_sdfe_dvr90.tif", "rb"); ASSERT_NE(f, nullptr); fclose(f); proj_context_set_enable_network(ctx, false); const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=dk_sdfe_dvr90.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; auto P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); double longitude = 12; double lat = 56; double z = 0; proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0); EXPECT_NEAR(z, 36.5909996032715, 1e-10); proj_destroy(P); proj_context_set_enable_network(ctx, true); ASSERT_FALSE(proj_is_download_needed(ctx, "dk_sdfe_dvr90.tif", false)); { sqlite3 *hDB = nullptr; sqlite3_open_v2("proj_test_tmp/cache.db", &hDB, SQLITE_OPEN_READWRITE, nullptr); ASSERT_NE(hDB, nullptr); // Force lastChecked to the Epoch so that data is expired. sqlite3_stmt *hStmt = nullptr; sqlite3_prepare_v2( hDB, "UPDATE downloaded_file_properties SET lastChecked = 0", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_DONE); sqlite3_finalize(hStmt); sqlite3_close(hDB); } // If we ignore TTL settings, then no network access will be done ASSERT_FALSE(proj_is_download_needed(ctx, "dk_sdfe_dvr90.tif", true)); { sqlite3 *hDB = nullptr; sqlite3_open_v2("proj_test_tmp/cache.db", &hDB, SQLITE_OPEN_READWRITE, nullptr); ASSERT_NE(hDB, nullptr); // Check that the lastChecked timestamp is still 0 sqlite3_stmt *hStmt = nullptr; sqlite3_prepare_v2(hDB, "SELECT lastChecked FROM downloaded_file_properties", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_ROW); ASSERT_EQ(sqlite3_column_int64(hStmt, 0), 0); sqlite3_finalize(hStmt); sqlite3_close(hDB); } // Should recheck from the CDN, update last_checked and do nothing ASSERT_FALSE(proj_is_download_needed(ctx, "dk_sdfe_dvr90.tif", false)); { sqlite3 *hDB = nullptr; sqlite3_open_v2("proj_test_tmp/cache.db", &hDB, SQLITE_OPEN_READWRITE, nullptr); ASSERT_NE(hDB, nullptr); sqlite3_stmt *hStmt = nullptr; // Check that the lastChecked timestamp has been updated sqlite3_prepare_v2(hDB, "SELECT lastChecked FROM downloaded_file_properties", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_ROW); ASSERT_NE(sqlite3_column_int64(hStmt, 0), 0); sqlite3_finalize(hStmt); hStmt = nullptr; // Now invalid lastModified. This should trigger a new download sqlite3_prepare_v2( hDB, "UPDATE downloaded_file_properties SET lastChecked = 0, " "lastModified = 'foo'", -1, &hStmt, nullptr); ASSERT_NE(hStmt, nullptr); ASSERT_EQ(sqlite3_step(hStmt), SQLITE_DONE); sqlite3_finalize(hStmt); sqlite3_close(hDB); } ASSERT_TRUE(proj_is_download_needed(ctx, "dk_sdfe_dvr90.tif", false)); // Redo download with a progress callback this time. unlink("proj_test_tmp/dk_sdfe_dvr90.tif"); const auto cbk = [](PJ_CONTEXT *l_ctx, double pct, void *user_data) -> int { auto vect = static_cast<std::vector<std::pair<PJ_CONTEXT *, double>> *>( user_data); vect->push_back(std::pair<PJ_CONTEXT *, double>(l_ctx, pct)); return true; }; std::vector<std::pair<PJ_CONTEXT *, double>> vectPct; ASSERT_TRUE( proj_download_file(ctx, "dk_sdfe_dvr90.tif", false, cbk, &vectPct)); ASSERT_EQ(vectPct.size(), 3U); ASSERT_EQ(vectPct.back().first, ctx); ASSERT_EQ(vectPct.back().second, 1.0); proj_context_destroy(ctx); putenv(const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=YES")); putenv(const_cast<char *>("PROJ_USER_WRITABLE_DIRECTORY=")); putenv(const_cast<char *>("PROJ_FULL_FILE_CHUNK_SIZE=")); unlink("proj_test_tmp/cache.db"); unlink("proj_test_tmp/dk_sdfe_dvr90.tif"); rmdir("proj_test_tmp"); } // --------------------------------------------------------------------------- TEST(networking, file_api) { if (!networkAccessOK) { return; } proj_cleanup(); unlink("proj_test_tmp/cache.db"); unlink("proj_test_tmp/dk_sdfe_dvr90.tif"); rmdir("proj_test_tmp"); putenv(const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=")); putenv(const_cast<char *>("PROJ_USER_WRITABLE_DIRECTORY=./proj_test_tmp")); putenv(const_cast<char *>("PROJ_FULL_FILE_CHUNK_SIZE=30000")); auto ctx = proj_context_create(); proj_context_set_enable_network(ctx, true); struct UserData { bool in_open = false; bool in_read = false; bool in_write = false; bool in_seek = false; bool in_tell = false; bool in_close = false; bool in_exists = false; bool in_mkdir = false; bool in_unlink = false; bool in_rename = false; }; struct PROJ_FILE_API api; api.version = 1; api.open_cbk = [](PJ_CONTEXT *, const char *filename, PROJ_OPEN_ACCESS access, void *user_data) -> PROJ_FILE_HANDLE * { static_cast<UserData *>(user_data)->in_open = true; return reinterpret_cast<PROJ_FILE_HANDLE *>( fopen(filename, access == PROJ_OPEN_ACCESS_READ_ONLY ? "rb" : access == PROJ_OPEN_ACCESS_READ_UPDATE ? "r+b" : "w+b")); }; api.read_cbk = [](PJ_CONTEXT *, PROJ_FILE_HANDLE *handle, void *buffer, size_t sizeBytes, void *user_data) -> size_t { static_cast<UserData *>(user_data)->in_read = true; return fread(buffer, 1, sizeBytes, reinterpret_cast<FILE *>(handle)); }; api.write_cbk = [](PJ_CONTEXT *, PROJ_FILE_HANDLE *handle, const void *buffer, size_t sizeBytes, void *user_data) -> size_t { static_cast<UserData *>(user_data)->in_write = true; return fwrite(buffer, 1, sizeBytes, reinterpret_cast<FILE *>(handle)); }; api.seek_cbk = [](PJ_CONTEXT *, PROJ_FILE_HANDLE *handle, long long offset, int whence, void *user_data) -> int { static_cast<UserData *>(user_data)->in_seek = true; return fseek(reinterpret_cast<FILE *>(handle), static_cast<long>(offset), whence) == 0; }; api.tell_cbk = [](PJ_CONTEXT *, PROJ_FILE_HANDLE *handle, void *user_data) -> unsigned long long { static_cast<UserData *>(user_data)->in_tell = true; return ftell(reinterpret_cast<FILE *>(handle)); }; api.close_cbk = [](PJ_CONTEXT *, PROJ_FILE_HANDLE *handle, void *user_data) -> void { static_cast<UserData *>(user_data)->in_close = true; fclose(reinterpret_cast<FILE *>(handle)); }; api.exists_cbk = [](PJ_CONTEXT *, const char *filename, void *user_data) -> int { static_cast<UserData *>(user_data)->in_exists = true; struct stat buf; return stat(filename, &buf) == 0; }; api.mkdir_cbk = [](PJ_CONTEXT *, const char *filename, void *user_data) -> int { static_cast<UserData *>(user_data)->in_mkdir = true; #ifdef _WIN32 return mkdir(filename) == 0; #else return mkdir(filename, 0755) == 0; #endif }; api.unlink_cbk = [](PJ_CONTEXT *, const char *filename, void *user_data) -> int { static_cast<UserData *>(user_data)->in_unlink = true; return unlink(filename) == 0; }; api.rename_cbk = [](PJ_CONTEXT *, const char *oldPath, const char *newPath, void *user_data) -> int { static_cast<UserData *>(user_data)->in_rename = true; return rename(oldPath, newPath) == 0; }; UserData userData; ASSERT_TRUE(proj_context_set_fileapi(ctx, &api, &userData)); ASSERT_TRUE(proj_is_download_needed(ctx, "dk_sdfe_dvr90.tif", false)); ASSERT_TRUE( proj_download_file(ctx, "dk_sdfe_dvr90.tif", false, nullptr, nullptr)); ASSERT_TRUE(userData.in_open); ASSERT_FALSE(userData.in_read); ASSERT_TRUE(userData.in_write); ASSERT_TRUE(userData.in_close); ASSERT_TRUE(userData.in_exists); ASSERT_TRUE(userData.in_mkdir); ASSERT_TRUE(userData.in_unlink); ASSERT_TRUE(userData.in_rename); proj_context_set_enable_network(ctx, false); const char *pipeline = "+proj=pipeline " "+step +proj=unitconvert +xy_in=deg +xy_out=rad " "+step +proj=vgridshift +grids=dk_sdfe_dvr90.tif +multiplier=1 " "+step +proj=unitconvert +xy_in=rad +xy_out=deg"; auto P = proj_create(ctx, pipeline); ASSERT_NE(P, nullptr); double longitude = 12; double lat = 56; double z = 0; proj_trans_generic(P, PJ_FWD, &longitude, sizeof(double), 1, &lat, sizeof(double), 1, &z, sizeof(double), 1, nullptr, 0, 0); EXPECT_NEAR(z, 36.5909996032715, 1e-10); proj_destroy(P); ASSERT_TRUE(userData.in_read); ASSERT_TRUE(userData.in_seek); proj_context_destroy(ctx); putenv(const_cast<char *>("PROJ_SKIP_READ_USER_WRITABLE_DIRECTORY=YES")); putenv(const_cast<char *>("PROJ_USER_WRITABLE_DIRECTORY=")); putenv(const_cast<char *>("PROJ_FULL_FILE_CHUNK_SIZE=")); unlink("proj_test_tmp/cache.db"); unlink("proj_test_tmp/dk_sdfe_dvr90.tif"); rmdir("proj_test_tmp"); } #endif // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, proj_coordoperation_get_grid_used) { if (!networkAccessOK) { return; } auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); // Test bugfix for // https://github.com/OSGeo/PROJ/issues/3444#issuecomment-1309499342 for (int i = 0; i < 2; ++i) { // This file is not in grid_alternatives, but in the CDN const char *proj_string = "proj=vgridshift grids=nz_linz_nzgd2000-c120100904-grid01.tif"; PJ *P = proj_create(ctx, proj_string); const char *shortName = nullptr; const char *fullName = nullptr; const char *packageName = nullptr; const char *url = nullptr; int directDownload = 0; int openLicense = 0; int available = 0; proj_coordoperation_get_grid_used(ctx, P, 0, &shortName, &fullName, &packageName, &url, &directDownload, &openLicense, &available); EXPECT_EQ(std::string(shortName), "nz_linz_nzgd2000-c120100904-grid01.tif"); EXPECT_EQ(std::string(fullName), ""); EXPECT_EQ( std::string(url), "https://cdn.proj.org/nz_linz_nzgd2000-c120100904-grid01.tif"); proj_destroy(P); } proj_context_destroy(ctx); } #endif // --------------------------------------------------------------------------- #ifdef CURL_ENABLED TEST(networking, pyproj_issue_1192) { if (!networkAccessOK) { return; } const auto doTest = [](PJ_CONTEXT *ctxt) { auto factory_context = proj_create_operation_factory_context(ctxt, nullptr); proj_operation_factory_context_set_grid_availability_use( ctxt, factory_context, PROJ_GRID_AVAILABILITY_IGNORED); proj_operation_factory_context_set_spatial_criterion( ctxt, factory_context, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); auto from = proj_create(ctxt, "EPSG:4326"); auto to = proj_create(ctxt, "EPSG:2964"); auto pj_operations = proj_create_operations(ctxt, from, to, factory_context); proj_destroy(from); proj_destroy(to); auto num_operations = proj_list_get_count(pj_operations); for (int i = 0; i < num_operations; ++i) { PJ *P = proj_list_get(ctxt, pj_operations, i); int is_instantiable = proj_coordoperation_is_instantiable(ctxt, P); if (is_instantiable) { EXPECT_TRUE(proj_pj_info(P).id != nullptr); } proj_destroy(P); } proj_operation_factory_context_destroy(factory_context); proj_list_destroy(pj_operations); }; auto ctx = proj_context_create(); proj_grid_cache_set_enable(ctx, false); proj_context_set_enable_network(ctx, true); doTest(ctx); proj_context_set_enable_network(ctx, false); doTest(ctx); proj_context_destroy(ctx); } #endif } // namespace
cpp
PROJ
data/projects/PROJ/test/unit/test_util.cpp
/****************************************************************************** * * Project: PROJ * Purpose: Test ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "gtest_include.h" #include "proj/util.hpp" #include <iostream> using namespace osgeo::proj::util; // --------------------------------------------------------------------------- TEST(util, NameFactory) { LocalNameNNPtr localname(NameFactory::createLocalName(nullptr, "foo")); auto ns = localname->scope(); EXPECT_EQ(ns->isGlobal(), true); EXPECT_EQ(ns->name()->toFullyQualifiedName()->toString(), "global"); EXPECT_EQ(localname->toFullyQualifiedName()->toString(), "foo"); } // --------------------------------------------------------------------------- TEST(util, NameFactory2) { PropertyMap map; map.set("separator", "/"); NameSpaceNNPtr nsIn(NameFactory::createNameSpace( NameFactory::createLocalName(nullptr, std::string("bar")), map)); LocalNameNNPtr localname( NameFactory::createLocalName(nsIn, std::string("foo"))); auto ns = localname->scope(); EXPECT_EQ(ns->isGlobal(), false); auto fullyqualifiedNS = ns->name()->toFullyQualifiedName(); EXPECT_EQ(fullyqualifiedNS->toString(), "bar"); EXPECT_EQ(fullyqualifiedNS->scope()->isGlobal(), true); EXPECT_EQ(fullyqualifiedNS->scope()->name()->scope()->isGlobal(), true); EXPECT_EQ(localname->toFullyQualifiedName()->toString(), "bar/foo"); }
cpp
PROJ
data/projects/PROJ/test/benchmark/bench_proj_trans.cpp
/****************************************************************************** * Project: PROJ * Purpose: Benchmark * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2022, Even Rouault, <even.rouault at spatialys.com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ #include "proj.h" #include <stdlib.h> // rand() #include <chrono> #include <cmath> // HUGE_VAL #include <cstdio> #include <cstdlib> #include <cstring> #include <string> static void usage() { printf("Usage: bench_proj_trans [(--source-crs|-s) string]\n"); printf(" [(--target-crs|-t) string]\n"); printf(" [(--pipeline|-p) string]\n"); printf(" [(--loops|-l) number]\n"); printf(" [--noise-x number] [--noise-y number]\n"); printf(" coord_comp_1 coord_comp_2 [coord_comp_3] " "[coord_comp_4]\n"); printf("\n"); printf("Both of --source-crs and --target_crs, or --pipeline must be " "specified.\n"); printf("\n"); printf("Example: bench_proj_trans -s EPSG:4326 -t EPSG:32631 49 2\n"); exit(1); } int main(int argc, char *argv[]) { std::string sourceCRS; std::string targetCRS; std::string pipeline; int loops = 5 * 1000 * 1000; double coord_comp[4] = {0, 0, 0, HUGE_VAL}; int coord_comp_counter = 0; double noiseX = 0; double noiseY = 0; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--source-crs") == 0 || strcmp(argv[i], "-s") == 0) { if (i + 1 >= argc) usage(); sourceCRS = argv[i + 1]; ++i; } else if (strcmp(argv[i], "--target-crs") == 0 || strcmp(argv[i], "-t") == 0) { if (i + 1 >= argc) usage(); targetCRS = argv[i + 1]; ++i; } else if (strcmp(argv[i], "--pipeline") == 0 || strcmp(argv[i], "-p") == 0) { if (i + 1 >= argc) usage(); pipeline = argv[i + 1]; ++i; } else if (strcmp(argv[i], "--loops") == 0 || strcmp(argv[i], "-l") == 0) { if (i + 1 >= argc) usage(); loops = atoi(argv[i + 1]); ++i; } else if (strcmp(argv[i], "--noise-x") == 0) { if (i + 1 >= argc) usage(); noiseX = atof(argv[i + 1]); ++i; } else if (strcmp(argv[i], "--noise-y") == 0) { if (i + 1 >= argc) usage(); noiseY = atof(argv[i + 1]); ++i; } else if (argv[i][0] == '-' && !(argv[i][1] >= '0' && argv[i][1] <= '9')) { usage(); } else if (coord_comp_counter < 4) { coord_comp[coord_comp_counter++] = atof(argv[i]); } else { usage(); } } if (coord_comp_counter < 2) usage(); PJ_CONTEXT *ctxt = proj_context_create(); PJ *P = nullptr; if (!pipeline.empty()) { P = proj_create(ctxt, pipeline.c_str()); } else if (!sourceCRS.empty() && !targetCRS.empty()) { P = proj_create_crs_to_crs(ctxt, sourceCRS.c_str(), targetCRS.c_str(), nullptr); } else { usage(); } if (P == nullptr) { exit(1); } PJ_COORD c; c.v[0] = coord_comp[0]; c.v[1] = coord_comp[1]; c.v[2] = coord_comp[2]; c.v[3] = coord_comp[3]; PJ_COORD c_ori = c; auto res = proj_trans(P, PJ_FWD, c); if (coord_comp_counter == 2) { printf("%.15g %.15g -> %.15g %.15g\n", c.v[0], c.v[1], res.v[0], res.v[1]); } else if (coord_comp_counter == 3) { printf("%.15g %.15g %.15g -> %.15g %.15g %.15g\n", c.v[0], c.v[1], c.v[2], res.v[0], res.v[1], res.v[2]); } else { printf("%.15g %.15g %.15g %.15g -> %.15g %.15g %.15g %.15g\n", c.v[0], c.v[1], c.v[2], c.v[3], res.v[0], res.v[1], res.v[2], res.v[3]); } // Start by timing just noise generation double dummy = 0; auto start_noise = std::chrono::system_clock::now(); for (int i = 0; i < loops; ++i) { if (noiseX != 0) c.v[0] = c_ori.v[0] + noiseX * (2 * double(rand()) / RAND_MAX - 1); if (noiseY != 0) c.v[1] = c_ori.v[1] + noiseY * (2 * double(rand()) / RAND_MAX - 1); dummy += c.v[0]; dummy += c.v[1]; } auto end_noise = std::chrono::system_clock::now(); auto start = std::chrono::system_clock::now(); for (int i = 0; i < loops; ++i) { if (noiseX != 0) c.v[0] = c_ori.v[0] + noiseX * (2 * double(rand()) / RAND_MAX - 1); if (noiseY != 0) c.v[1] = c_ori.v[1] + noiseY * (2 * double(rand()) / RAND_MAX - 1); dummy += c.v[0]; dummy += c.v[1]; proj_trans(P, PJ_FWD, c); } auto end = std::chrono::system_clock::now(); proj_destroy(P); proj_context_destroy(ctxt); auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>( (end - start) - (end_noise - start_noise)); printf("Duration: %d ms\n", static_cast<int>(elapsed_ms.count())); printf("Throughput: %.02f million coordinates/s\n", 1e-3 * static_cast<double>(loops) / static_cast<double>(elapsed_ms.count()) + dummy * 1e-300); return 0; }
cpp
PROJ
data/projects/PROJ/include/proj/metadata.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef METADATA_HH_INCLUDED #define METADATA_HH_INCLUDED #include <memory> #include <string> #include <vector> #include "io.hpp" #include "util.hpp" NS_PROJ_START namespace common { class UnitOfMeasure; using UnitOfMeasurePtr = std::shared_ptr<UnitOfMeasure>; using UnitOfMeasureNNPtr = util::nn<UnitOfMeasurePtr>; class IdentifiedObject; } // namespace common /** osgeo.proj.metadata namespace * * \brief Common classes from \ref ISO_19115 standard */ namespace metadata { // --------------------------------------------------------------------------- /** \brief Standardized resource reference. * * A citation contains a title. * * \remark Simplified version of [Citation] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/metadata/citation/Citation.html) * from \ref GeoAPI */ class PROJ_GCC_DLL Citation : public util::BaseObject { public: PROJ_DLL explicit Citation(const std::string &titleIn); //! @cond Doxygen_Suppress PROJ_DLL Citation(); PROJ_DLL Citation(const Citation &other); PROJ_DLL ~Citation() override; //! @endcond PROJ_DLL const util::optional<std::string> &title() PROJ_PURE_DECL; protected: PROJ_FRIEND_OPTIONAL(Citation); PROJ_INTERNAL Citation &operator=(const Citation &other); private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class GeographicExtent; /** Shared pointer of GeographicExtent. */ using GeographicExtentPtr = std::shared_ptr<GeographicExtent>; /** Non-null shared pointer of GeographicExtent. */ using GeographicExtentNNPtr = util::nn<GeographicExtentPtr>; /** \brief Base interface for geographic area of the dataset. * * \remark Simplified version of [GeographicExtent] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/metadata/extent/GeographicExtent.html) * from \ref GeoAPI */ class PROJ_GCC_DLL GeographicExtent : public util::BaseObject, public util::IComparable { public: //! @cond Doxygen_Suppress PROJ_DLL ~GeographicExtent() override; //! @endcond // GeoAPI has a getInclusion() method. We assume that it is included for our // use //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override = 0; //! @endcond /** \brief Returns whether this extent contains the other one. */ PROJ_DLL virtual bool contains(const GeographicExtentNNPtr &other) const = 0; /** \brief Returns whether this extent intersects the other one. */ PROJ_DLL virtual bool intersects(const GeographicExtentNNPtr &other) const = 0; /** \brief Returns the intersection of this extent with another one. */ PROJ_DLL virtual GeographicExtentPtr intersection(const GeographicExtentNNPtr &other) const = 0; protected: PROJ_INTERNAL GeographicExtent(); private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class GeographicBoundingBox; /** Shared pointer of GeographicBoundingBox. */ using GeographicBoundingBoxPtr = std::shared_ptr<GeographicBoundingBox>; /** Non-null shared pointer of GeographicBoundingBox. */ using GeographicBoundingBoxNNPtr = util::nn<GeographicBoundingBoxPtr>; /** \brief Geographic position of the dataset. * * This is only an approximate so specifying the coordinate reference system is * unnecessary. * * \remark Implements [GeographicBoundingBox] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/metadata/extent/GeographicBoundingBox.html) * from \ref GeoAPI */ class PROJ_GCC_DLL GeographicBoundingBox : public GeographicExtent { public: //! @cond Doxygen_Suppress PROJ_DLL ~GeographicBoundingBox() override; //! @endcond PROJ_DLL double westBoundLongitude() PROJ_PURE_DECL; PROJ_DLL double southBoundLatitude() PROJ_PURE_DECL; PROJ_DLL double eastBoundLongitude() PROJ_PURE_DECL; PROJ_DLL double northBoundLatitude() PROJ_PURE_DECL; PROJ_DLL static GeographicBoundingBoxNNPtr create(double west, double south, double east, double north); //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond PROJ_INTERNAL bool contains(const GeographicExtentNNPtr &other) const override; PROJ_INTERNAL bool intersects(const GeographicExtentNNPtr &other) const override; PROJ_INTERNAL GeographicExtentPtr intersection(const GeographicExtentNNPtr &other) const override; protected: PROJ_INTERNAL GeographicBoundingBox(double west, double south, double east, double north); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class TemporalExtent; /** Shared pointer of TemporalExtent. */ using TemporalExtentPtr = std::shared_ptr<TemporalExtent>; /** Non-null shared pointer of TemporalExtent. */ using TemporalExtentNNPtr = util::nn<TemporalExtentPtr>; /** \brief Time period covered by the content of the dataset. * * \remark Simplified version of [TemporalExtent] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/metadata/extent/TemporalExtent.html) * from \ref GeoAPI */ class PROJ_GCC_DLL TemporalExtent : public util::BaseObject, public util::IComparable { public: //! @cond Doxygen_Suppress PROJ_DLL ~TemporalExtent() override; //! @endcond PROJ_DLL const std::string &start() PROJ_PURE_DECL; PROJ_DLL const std::string &stop() PROJ_PURE_DECL; PROJ_DLL static TemporalExtentNNPtr create(const std::string &start, const std::string &stop); //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond PROJ_DLL bool contains(const TemporalExtentNNPtr &other) const; PROJ_DLL bool intersects(const TemporalExtentNNPtr &other) const; protected: PROJ_INTERNAL TemporalExtent(const std::string &start, const std::string &stop); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class VerticalExtent; /** Shared pointer of VerticalExtent. */ using VerticalExtentPtr = std::shared_ptr<VerticalExtent>; /** Non-null shared pointer of VerticalExtent. */ using VerticalExtentNNPtr = util::nn<VerticalExtentPtr>; /** \brief Vertical domain of dataset. * * \remark Simplified version of [VerticalExtent] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/metadata/extent/VerticalExtent.html) * from \ref GeoAPI */ class PROJ_GCC_DLL VerticalExtent : public util::BaseObject, public util::IComparable { public: //! @cond Doxygen_Suppress PROJ_DLL ~VerticalExtent() override; //! @endcond PROJ_DLL double minimumValue() PROJ_PURE_DECL; PROJ_DLL double maximumValue() PROJ_PURE_DECL; PROJ_DLL common::UnitOfMeasureNNPtr &unit() PROJ_PURE_DECL; PROJ_DLL static VerticalExtentNNPtr create(double minimumValue, double maximumValue, const common::UnitOfMeasureNNPtr &unitIn); //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond PROJ_DLL bool contains(const VerticalExtentNNPtr &other) const; PROJ_DLL bool intersects(const VerticalExtentNNPtr &other) const; protected: PROJ_INTERNAL VerticalExtent(double minimumValue, double maximumValue, const common::UnitOfMeasureNNPtr &unitIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class Extent; /** Shared pointer of Extent. */ using ExtentPtr = std::shared_ptr<Extent>; /** Non-null shared pointer of Extent. */ using ExtentNNPtr = util::nn<ExtentPtr>; /** \brief Information about spatial, vertical, and temporal extent. * * \remark Simplified version of [Extent] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/metadata/extent/Extent.html) * from \ref GeoAPI */ class PROJ_GCC_DLL Extent : public util::BaseObject, public util::IComparable { public: //! @cond Doxygen_Suppress PROJ_DLL Extent(const Extent &other); PROJ_DLL ~Extent() override; //! @endcond PROJ_DLL const util::optional<std::string> &description() PROJ_PURE_DECL; PROJ_DLL const std::vector<GeographicExtentNNPtr> & geographicElements() PROJ_PURE_DECL; PROJ_DLL const std::vector<TemporalExtentNNPtr> & temporalElements() PROJ_PURE_DECL; PROJ_DLL const std::vector<VerticalExtentNNPtr> & verticalElements() PROJ_PURE_DECL; PROJ_DLL static ExtentNNPtr create(const util::optional<std::string> &descriptionIn, const std::vector<GeographicExtentNNPtr> &geographicElementsIn, const std::vector<VerticalExtentNNPtr> &verticalElementsIn, const std::vector<TemporalExtentNNPtr> &temporalElementsIn); PROJ_DLL static ExtentNNPtr createFromBBOX(double west, double south, double east, double north, const util::optional<std::string> &descriptionIn = util::optional<std::string>()); //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond PROJ_DLL bool contains(const ExtentNNPtr &other) const; PROJ_DLL bool intersects(const ExtentNNPtr &other) const; PROJ_DLL ExtentPtr intersection(const ExtentNNPtr &other) const; PROJ_DLL static const ExtentNNPtr WORLD; protected: PROJ_INTERNAL Extent(); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA Extent &operator=(const Extent &other) = delete; }; // --------------------------------------------------------------------------- class Identifier; /** Shared pointer of Identifier. */ using IdentifierPtr = std::shared_ptr<Identifier>; /** Non-null shared pointer of Identifier. */ using IdentifierNNPtr = util::nn<IdentifierPtr>; /** \brief Value uniquely identifying an object within a namespace. * * \remark Implements Identifier as described in \ref ISO_19111_2019 but which * originates from \ref ISO_19115 */ class PROJ_GCC_DLL Identifier : public util::BaseObject, public io::IWKTExportable, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL Identifier(const Identifier &other); PROJ_DLL ~Identifier() override; //! @endcond PROJ_DLL static IdentifierNNPtr create(const std::string &codeIn = std::string(), const util::PropertyMap &properties = util::PropertyMap()); // throw(InvalidValueTypeException) PROJ_DLL static const std::string AUTHORITY_KEY; PROJ_DLL static const std::string CODE_KEY; PROJ_DLL static const std::string CODESPACE_KEY; PROJ_DLL static const std::string VERSION_KEY; PROJ_DLL static const std::string DESCRIPTION_KEY; PROJ_DLL static const std::string URI_KEY; PROJ_DLL static const std::string EPSG; PROJ_DLL static const std::string OGC; PROJ_DLL const util::optional<Citation> &authority() PROJ_PURE_DECL; PROJ_DLL const std::string &code() PROJ_PURE_DECL; PROJ_DLL const util::optional<std::string> &codeSpace() PROJ_PURE_DECL; PROJ_DLL const util::optional<std::string> &version() PROJ_PURE_DECL; PROJ_DLL const util::optional<std::string> &description() PROJ_PURE_DECL; PROJ_DLL const util::optional<std::string> &uri() PROJ_PURE_DECL; PROJ_DLL static bool isEquivalentName(const char *a, const char *b) noexcept; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL static std::string canonicalizeName(const std::string &str); PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(io::FormattingException) //! @endcond protected: PROJ_INTERNAL explicit Identifier(const std::string &codeIn, const util::PropertyMap &properties); PROJ_INTERNAL explicit Identifier(); PROJ_FRIEND_OPTIONAL(Identifier); INLINED_MAKE_SHARED Identifier &operator=(const Identifier &other) = delete; PROJ_FRIEND(common::IdentifiedObject); PROJ_INTERNAL static IdentifierNNPtr createFromDescription(const std::string &descriptionIn); private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class PositionalAccuracy; /** Shared pointer of PositionalAccuracy. */ using PositionalAccuracyPtr = std::shared_ptr<PositionalAccuracy>; /** Non-null shared pointer of PositionalAccuracy. */ using PositionalAccuracyNNPtr = util::nn<PositionalAccuracyPtr>; /** \brief Accuracy of the position of features. * * \remark Simplified version of [PositionalAccuracy] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/metadata/quality/PositionalAccuracy.html) * from \ref GeoAPI, which originates from \ref ISO_19115 */ class PROJ_GCC_DLL PositionalAccuracy : public util::BaseObject { public: //! @cond Doxygen_Suppress PROJ_DLL ~PositionalAccuracy() override; //! @endcond PROJ_DLL const std::string &value() PROJ_PURE_DECL; PROJ_DLL static PositionalAccuracyNNPtr create(const std::string &valueIn); protected: PROJ_INTERNAL explicit PositionalAccuracy(const std::string &valueIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA PositionalAccuracy(const PositionalAccuracy &other) = delete; PositionalAccuracy &operator=(const PositionalAccuracy &other) = delete; }; } // namespace metadata NS_PROJ_END #endif // METADATA_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/util.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef UTIL_HH_INCLUDED #define UTIL_HH_INCLUDED #if !(__cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)) #error Must have C++11 or newer. #endif // windows.h can conflict with Criterion::STRICT #ifdef STRICT #undef STRICT #endif #include <exception> #include <map> #include <memory> #include <string> #include <type_traits> #include <vector> #ifndef NS_PROJ /** osgeo namespace */ namespace osgeo { /** osgeo.proj namespace */ namespace proj {} } // namespace osgeo #endif //! @cond Doxygen_Suppress #ifndef PROJ_DLL #if defined(_MSC_VER) #ifdef PROJ_MSVC_DLL_EXPORT #define PROJ_DLL __declspec(dllexport) #else #define PROJ_DLL __declspec(dllimport) #endif #elif defined(__GNUC__) #define PROJ_DLL __attribute__((visibility("default"))) #else #define PROJ_DLL #endif #endif #ifndef PROJ_MSVC_DLL #if defined(_MSC_VER) #define PROJ_MSVC_DLL PROJ_DLL #define PROJ_GCC_DLL #define PROJ_INTERNAL #elif defined(__GNUC__) #define PROJ_MSVC_DLL #define PROJ_GCC_DLL PROJ_DLL #if !defined(__MINGW32__) #define PROJ_INTERNAL __attribute__((visibility("hidden"))) #else #define PROJ_INTERNAL #endif #else #define PROJ_MSVC_DLL #define PROJ_GCC_DLL #define PROJ_INTERNAL #endif #define PROJ_FOR_TEST PROJ_DLL #endif #include "nn.hpp" /* To allow customizing the base namespace of PROJ */ #ifdef PROJ_INTERNAL_CPP_NAMESPACE #define NS_PROJ osgeo::internalproj #define NS_PROJ_START \ namespace osgeo { \ namespace internalproj { #define NS_PROJ_END \ } \ } #else #ifndef NS_PROJ #define NS_PROJ osgeo::proj #define NS_PROJ_START \ namespace osgeo { \ namespace proj { #define NS_PROJ_END \ } \ } #endif #endif // Private-implementation (Pimpl) pattern #define PROJ_OPAQUE_PRIVATE_DATA \ private: \ struct PROJ_INTERNAL Private; \ std::unique_ptr<Private> d; \ \ protected: \ PROJ_INTERNAL Private *getPrivate() noexcept { return d.get(); } \ PROJ_INTERNAL const Private *getPrivate() const noexcept { \ return d.get(); \ } \ \ private: // To include in the protected/private section of a class definition, // to be able to call make_shared on a protected/private constructor #define INLINED_MAKE_SHARED \ template <typename T, typename... Args> \ static std::shared_ptr<T> make_shared(Args &&...args) { \ return std::shared_ptr<T>(new T(std::forward<Args>(args)...)); \ } \ template <typename T, typename... Args> \ static util::nn_shared_ptr<T> nn_make_shared(Args &&...args) { \ return util::nn_shared_ptr<T>( \ util::i_promise_i_checked_for_null, \ std::shared_ptr<T>(new T(std::forward<Args>(args)...))); \ } // To include in the protected/private section of a class definition, // to be able to call make_unique on a protected/private constructor #define INLINED_MAKE_UNIQUE \ template <typename T, typename... Args> \ static std::unique_ptr<T> make_unique(Args &&...args) { \ return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); \ } #ifdef DOXYGEN_ENABLED #define PROJ_FRIEND(mytype) #define PROJ_FRIEND_OPTIONAL(mytype) #else #define PROJ_FRIEND(mytype) friend class mytype #define PROJ_FRIEND_OPTIONAL(mytype) friend class util::optional<mytype> #endif #ifndef PROJ_PRIVATE #define PROJ_PRIVATE public #endif #if defined(__GNUC__) #define PROJ_NO_INLINE __attribute__((noinline)) #define PROJ_NO_RETURN __attribute__((noreturn)) // Applies to a function that has no side effect. #define PROJ_PURE_DECL const noexcept __attribute__((pure)) #else #define PROJ_NO_RETURN #define PROJ_NO_INLINE #define PROJ_PURE_DECL const noexcept #endif #define PROJ_PURE_DEFN const noexcept //! @endcond NS_PROJ_START //! @cond Doxygen_Suppress namespace io { class DatabaseContext; using DatabaseContextPtr = std::shared_ptr<DatabaseContext>; } // namespace io //! @endcond /** osgeo.proj.util namespace. * * \brief A set of base types from ISO 19103, \ref GeoAPI and other PROJ * specific classes. */ namespace util { //! @cond Doxygen_Suppress // Import a few classes from nn.hpp to expose them under our ::util namespace // for conveniency. using ::dropbox::oxygen::i_promise_i_checked_for_null; using ::dropbox::oxygen::nn; using ::dropbox::oxygen::nn_dynamic_pointer_cast; using ::dropbox::oxygen::nn_make_shared; // For return statements, to convert from derived type to base type using ::dropbox::oxygen::nn_static_pointer_cast; template <typename T> using nn_shared_ptr = nn<std::shared_ptr<T>>; // Possible implementation of C++14 std::remove_reference_t // (cf https://en.cppreference.com/w/cpp/types/remove_cv) template <class T> using remove_reference_t = typename std::remove_reference<T>::type; // Possible implementation of C++14 std::remove_cv_t // (cf https://en.cppreference.com/w/cpp/types/remove_cv) template <class T> using remove_cv_t = typename std::remove_cv<T>::type; // Possible implementation of C++20 std::remove_cvref // (cf https://en.cppreference.com/w/cpp/types/remove_cvref) template <class T> struct remove_cvref { typedef remove_cv_t<remove_reference_t<T>> type; }; #define NN_NO_CHECK(p) \ ::dropbox::oxygen::nn< \ typename ::NS_PROJ::util::remove_cvref<decltype(p)>::type>( \ ::dropbox::oxygen::i_promise_i_checked_for_null, (p)) //! @endcond // To avoid formatting differences between clang-format 3.8 and 7 #define PROJ_NOEXCEPT noexcept //! @cond Doxygen_Suppress // isOfExactType<MyType>(*p) checks that the type of *p is exactly MyType template <typename TemplateT, typename ObjectT> inline bool isOfExactType(const ObjectT &o) { return typeid(TemplateT).hash_code() == typeid(o).hash_code(); } //! @endcond /** \brief Loose transposition of [std::optional] * (https://en.cppreference.com/w/cpp/utility/optional) available from C++17. */ template <class T> class optional { public: //! @cond Doxygen_Suppress inline optional() : hasVal_(false) {} inline explicit optional(const T &val) : hasVal_(true), val_(val) {} inline explicit optional(T &&val) : hasVal_(true), val_(std::forward<T>(val)) {} inline optional(const optional &) = default; inline optional(optional &&other) PROJ_NOEXCEPT : hasVal_(other.hasVal_), // cppcheck-suppress functionStatic val_(std::forward<T>(other.val_)) { other.hasVal_ = false; } inline optional &operator=(const T &val) { hasVal_ = true; val_ = val; return *this; } inline optional &operator=(T &&val) noexcept { hasVal_ = true; val_ = std::forward<T>(val); return *this; } inline optional &operator=(const optional &) = default; inline optional &operator=(optional &&other) noexcept { hasVal_ = other.hasVal_; val_ = std::forward<T>(other.val_); other.hasVal_ = false; return *this; } inline T *operator->() { return &val_; } inline T &operator*() { return val_; } //! @endcond /** Returns a pointer to the contained value. */ inline const T *operator->() const { return &val_; } /** Returns a reference to the contained value. */ inline const T &operator*() const { return val_; } /** Return whether the optional has a value */ inline explicit operator bool() const noexcept { return hasVal_; } /** Return whether the optional has a value */ inline bool has_value() const noexcept { return hasVal_; } private: bool hasVal_; T val_{}; }; // --------------------------------------------------------------------------- class BaseObject; /** Shared pointer of BaseObject. */ using BaseObjectPtr = std::shared_ptr<BaseObject>; #if 1 /** Non-null shared pointer of BaseObject. */ struct BaseObjectNNPtr : public util::nn<BaseObjectPtr> { // This trick enables to avoid inlining of the destructor. // This is mostly an alias of the base class. //! @cond Doxygen_Suppress template <class T> // cppcheck-suppress noExplicitConstructor BaseObjectNNPtr(const util::nn<std::shared_ptr<T>> &x) : util::nn<BaseObjectPtr>(x) {} template <class T> // cppcheck-suppress noExplicitConstructor BaseObjectNNPtr(util::nn<std::shared_ptr<T>> &&x) noexcept : util::nn<BaseObjectPtr>(NN_NO_CHECK(std::move(x.as_nullable()))) {} explicit BaseObjectNNPtr(::dropbox::oxygen::i_promise_i_checked_for_null_t, BaseObjectPtr &&arg) noexcept : util::nn<BaseObjectPtr>(i_promise_i_checked_for_null, std::move(arg)) {} BaseObjectNNPtr(const BaseObjectNNPtr &) = default; BaseObjectNNPtr &operator=(const BaseObjectNNPtr &) = default; PROJ_DLL ~BaseObjectNNPtr(); //! @endcond }; #else using BaseObjectNNPtr = util::nn<BaseObjectPtr>; #endif /** \brief Class that can be derived from, to emulate Java's Object behavior. */ class PROJ_GCC_DLL BaseObject { public: //! @cond Doxygen_Suppress virtual PROJ_DLL ~BaseObject(); //! @endcond PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL BaseObjectNNPtr shared_from_this() const; //! @endcond protected: PROJ_INTERNAL BaseObject(); PROJ_INTERNAL void assignSelf(const BaseObjectNNPtr &self); PROJ_INTERNAL BaseObject &operator=(BaseObject &&other); private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Interface for an object that can be compared to another. */ class PROJ_GCC_DLL IComparable { public: //! @cond Doxygen_Suppress PROJ_DLL virtual ~IComparable(); //! @endcond /** \brief Comparison criterion. */ enum class PROJ_MSVC_DLL Criterion { /** All properties are identical. */ STRICT, /** The objects are equivalent for the purpose of coordinate * operations. They can differ by the name of their objects, * identifiers, other metadata. * Parameters may be expressed in different units, provided that the * value is (with some tolerance) the same once expressed in a * common unit. */ EQUIVALENT, /** Same as EQUIVALENT, relaxed with an exception that the axis order * of the base CRS of a DerivedCRS/ProjectedCRS or the axis order of * a GeographicCRS is ignored. Only to be used * with DerivedCRS/ProjectedCRS/GeographicCRS */ EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS, }; PROJ_DLL bool isEquivalentTo(const IComparable *other, Criterion criterion = Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL virtual bool _isEquivalentTo( const IComparable *other, Criterion criterion = Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const = 0; //! @endcond }; // --------------------------------------------------------------------------- /** \brief Encapsulate standard datatypes in an object. */ class BoxedValue final : public BaseObject { public: //! @cond Doxygen_Suppress /** Type of data stored in the BoxedValue. */ enum class Type { /** a std::string */ STRING, /** an integer */ INTEGER, /** a boolean */ BOOLEAN }; //! @endcond // cppcheck-suppress noExplicitConstructor PROJ_DLL BoxedValue(const char *stringValueIn); // needed to avoid the bool // constructor to be taken ! // cppcheck-suppress noExplicitConstructor PROJ_DLL BoxedValue(const std::string &stringValueIn); // cppcheck-suppress noExplicitConstructor PROJ_DLL BoxedValue(int integerValueIn); // cppcheck-suppress noExplicitConstructor PROJ_DLL BoxedValue(bool booleanValueIn); PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL BoxedValue(const BoxedValue &other); PROJ_DLL ~BoxedValue() override; PROJ_INTERNAL const Type &type() const; PROJ_INTERNAL const std::string &stringValue() const; PROJ_INTERNAL int integerValue() const; PROJ_INTERNAL bool booleanValue() const; //! @endcond private: PROJ_OPAQUE_PRIVATE_DATA BoxedValue &operator=(const BoxedValue &) = delete; PROJ_INTERNAL BoxedValue(); }; /** Shared pointer of BoxedValue. */ using BoxedValuePtr = std::shared_ptr<BoxedValue>; /** Non-null shared pointer of BoxedValue. */ using BoxedValueNNPtr = util::nn<BoxedValuePtr>; // --------------------------------------------------------------------------- class ArrayOfBaseObject; /** Shared pointer of ArrayOfBaseObject. */ using ArrayOfBaseObjectPtr = std::shared_ptr<ArrayOfBaseObject>; /** Non-null shared pointer of ArrayOfBaseObject. */ using ArrayOfBaseObjectNNPtr = util::nn<ArrayOfBaseObjectPtr>; /** \brief Array of BaseObject. */ class ArrayOfBaseObject final : public BaseObject { public: //! @cond Doxygen_Suppress PROJ_DLL ~ArrayOfBaseObject() override; //! @endcond PROJ_DLL void add(const BaseObjectNNPtr &obj); PROJ_DLL static ArrayOfBaseObjectNNPtr create(); PROJ_PRIVATE : //! @cond Doxygen_Suppress std::vector<BaseObjectNNPtr>::const_iterator begin() const; std::vector<BaseObjectNNPtr>::const_iterator end() const; bool empty() const; //! @endcond protected: ArrayOfBaseObject(); INLINED_MAKE_SHARED private: ArrayOfBaseObject(const ArrayOfBaseObject &other) = delete; ArrayOfBaseObject &operator=(const ArrayOfBaseObject &other) = delete; PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Wrapper of a std::map<std::string, BaseObjectNNPtr> */ class PropertyMap { public: PROJ_DLL PropertyMap(); //! @cond Doxygen_Suppress PROJ_DLL PropertyMap(const PropertyMap &other); PROJ_DLL ~PropertyMap(); //! @endcond PROJ_DLL PropertyMap &set(const std::string &key, const BaseObjectNNPtr &val); //! @cond Doxygen_Suppress template <class T> inline PropertyMap &set(const std::string &key, const nn_shared_ptr<T> &val) { return set( key, BaseObjectNNPtr(i_promise_i_checked_for_null, BaseObjectPtr(val.as_nullable(), val.get()))); } //! @endcond // needed to avoid the bool constructor to be taken ! PROJ_DLL PropertyMap &set(const std::string &key, const char *val); PROJ_DLL PropertyMap &set(const std::string &key, const std::string &val); PROJ_DLL PropertyMap &set(const std::string &key, int val); PROJ_DLL PropertyMap &set(const std::string &key, bool val); PROJ_DLL PropertyMap &set(const std::string &key, const std::vector<std::string> &array); PROJ_PRIVATE : //! @cond Doxygen_Suppress const BaseObjectNNPtr * get(const std::string &key) const; // throw(InvalidValueTypeException) bool getStringValue(const std::string &key, std::string &outVal) const; bool getStringValue(const std::string &key, optional<std::string> &outVal) const; void unset(const std::string &key); static PropertyMap createAndSetName(const char *name); static PropertyMap createAndSetName(const std::string &name); //! @endcond private: PropertyMap &operator=(const PropertyMap &) = delete; PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class LocalName; /** Shared pointer of LocalName. */ using LocalNamePtr = std::shared_ptr<LocalName>; /** Non-null shared pointer of LocalName. */ using LocalNameNNPtr = util::nn<LocalNamePtr>; class NameSpace; /** Shared pointer of NameSpace. */ using NameSpacePtr = std::shared_ptr<NameSpace>; /** Non-null shared pointer of NameSpace. */ using NameSpaceNNPtr = util::nn<NameSpacePtr>; class GenericName; /** Shared pointer of GenericName. */ using GenericNamePtr = std::shared_ptr<GenericName>; /** Non-null shared pointer of GenericName. */ using GenericNameNNPtr = util::nn<GenericNamePtr>; // --------------------------------------------------------------------------- /** \brief A sequence of identifiers rooted within the context of a namespace. * * \remark Simplified version of [GenericName] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/util/GenericName.html) * from \ref GeoAPI */ class GenericName : public BaseObject { public: //! @cond Doxygen_Suppress PROJ_DLL virtual ~GenericName() override; //! @endcond /** \brief Return the scope of the object, possibly a global one. */ PROJ_DLL virtual const NameSpacePtr scope() const = 0; /** \brief Return the LocalName as a string. */ PROJ_DLL virtual std::string toString() const = 0; /** \brief Return a fully qualified name corresponding to the local name. * * The namespace of the resulting name is a global one. */ PROJ_DLL virtual GenericNameNNPtr toFullyQualifiedName() const = 0; protected: GenericName(); GenericName(const GenericName &other); private: PROJ_OPAQUE_PRIVATE_DATA GenericName &operator=(const GenericName &other) = delete; }; // --------------------------------------------------------------------------- /** \brief A domain in which names given by strings are defined. * * \remark Simplified version of [NameSpace] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/util/NameSpace.html) * from \ref GeoAPI */ class NameSpace { public: //! @cond Doxygen_Suppress PROJ_DLL ~NameSpace(); //! @endcond PROJ_DLL bool isGlobal() const; PROJ_DLL const GenericNamePtr &name() const; protected: PROJ_FRIEND(NameFactory); PROJ_FRIEND(LocalName); explicit NameSpace(const GenericNamePtr &name); NameSpace(const NameSpace &other); NameSpaceNNPtr getGlobalFromThis() const; const std::string &separator() const; static const NameSpaceNNPtr GLOBAL; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA NameSpace &operator=(const NameSpace &other) = delete; static NameSpaceNNPtr createGLOBAL(); }; // --------------------------------------------------------------------------- /** \brief Identifier within a NameSpace for a local object. * * Local names are names which are directly accessible to and maintained by a * NameSpace within which they are local, indicated by the scope. * * \remark Simplified version of [LocalName] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/util/LocalName.html) * from \ref GeoAPI */ class LocalName : public GenericName { public: //! @cond Doxygen_Suppress PROJ_DLL ~LocalName() override; //! @endcond PROJ_DLL const NameSpacePtr scope() const override; PROJ_DLL std::string toString() const override; PROJ_DLL GenericNameNNPtr toFullyQualifiedName() const override; protected: PROJ_FRIEND(NameFactory); PROJ_FRIEND(NameSpace); explicit LocalName(const std::string &nameIn); LocalName(const LocalName &other); LocalName(const NameSpacePtr &ns, const std::string &name); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA LocalName &operator=(const LocalName &other) = delete; }; // --------------------------------------------------------------------------- /** \brief Factory for generic names. * * \remark Simplified version of [NameFactory] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/util/NameFactory.html) * from \ref GeoAPI */ class NameFactory { public: PROJ_DLL static NameSpaceNNPtr createNameSpace(const GenericNameNNPtr &name, const PropertyMap &properties); PROJ_DLL static LocalNameNNPtr createLocalName(const NameSpacePtr &scope, const std::string &name); PROJ_DLL static GenericNameNNPtr createGenericName(const NameSpacePtr &scope, const std::vector<std::string> &parsedNames); }; // --------------------------------------------------------------------------- /** \brief Abstract class to define an enumeration of values. */ class CodeList { public: //! @cond Doxygen_Suppress PROJ_DLL ~CodeList(); //! @endcond /** Return the CodeList item as a string. */ // cppcheck-suppress functionStatic inline const std::string &toString() PROJ_PURE_DECL { return name_; } /** Return the CodeList item as a string. */ inline operator std::string() PROJ_PURE_DECL { return toString(); } //! @cond Doxygen_Suppress inline bool operator==(const CodeList &other) PROJ_PURE_DECL { return name_ == other.name_; } inline bool operator!=(const CodeList &other) PROJ_PURE_DECL { return name_ != other.name_; } //! @endcond protected: explicit CodeList(const std::string &nameIn) : name_(nameIn) {} CodeList(const CodeList &) = default; CodeList &operator=(const CodeList &other); private: std::string name_{}; }; // --------------------------------------------------------------------------- /** \brief Root exception class. */ class PROJ_GCC_DLL Exception : public std::exception { std::string msg_; public: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit Exception(const char *message); PROJ_INTERNAL explicit Exception(const std::string &message); PROJ_DLL Exception(const Exception &other); PROJ_DLL ~Exception() override; //! @endcond PROJ_DLL virtual const char *what() const noexcept override; }; // --------------------------------------------------------------------------- /** \brief Exception thrown when an invalid value type is set as the value of * a key of a PropertyMap. */ class PROJ_GCC_DLL InvalidValueTypeException : public Exception { public: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit InvalidValueTypeException(const char *message); PROJ_INTERNAL explicit InvalidValueTypeException( const std::string &message); PROJ_DLL InvalidValueTypeException(const InvalidValueTypeException &other); PROJ_DLL ~InvalidValueTypeException() override; //! @endcond }; // --------------------------------------------------------------------------- /** \brief Exception Thrown to indicate that the requested operation is not * supported. */ class PROJ_GCC_DLL UnsupportedOperationException : public Exception { public: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit UnsupportedOperationException(const char *message); PROJ_INTERNAL explicit UnsupportedOperationException( const std::string &message); PROJ_DLL UnsupportedOperationException(const UnsupportedOperationException &other); PROJ_DLL ~UnsupportedOperationException() override; //! @endcond }; } // namespace util NS_PROJ_END #endif // UTIL_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/nn.hpp
#pragma once /* * Copyright (c) 2015 Dropbox, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cassert> #include <cstdlib> #include <functional> #include <memory> #include <type_traits> namespace dropbox { namespace oxygen { // Marker type and value for use by nn below. struct i_promise_i_checked_for_null_t {}; static constexpr i_promise_i_checked_for_null_t i_promise_i_checked_for_null{}; // Helper to get the type pointed to by a raw or smart pointer. This can be // explicitly // specialized if need be to provide compatibility with user-defined smart // pointers. namespace nn_detail { template <typename T> struct element_type { using type = typename T::element_type; }; template <typename Pointee> struct element_type<Pointee *> { using type = Pointee; }; } template <typename PtrType> class nn; // Trait to check whether a given type is a non-nullable pointer template <typename T> struct is_nn : public std::false_type {}; template <typename PtrType> struct is_nn<nn<PtrType>> : public std::true_type {}; /* nn<PtrType> * * Wrapper around a pointer that is guaranteed to not be null. This works with * raw pointers * as well as any smart pointer: nn<int *>, nn<shared_ptr<DbxTable>>, * nn<unique_ptr<Foo>>, * etc. An nn<PtrType> can be used just like a PtrType. * * An nn<PtrType> can be constructed from another nn<PtrType>, if the underlying * type would * allow such construction. For example, nn<shared_ptr<PtrType>> can be copied * and moved, but * nn<unique_ptr<PtrType>> can only be moved; an nn<unique_ptr<PtrType>> can be * explicitly * (but not implicitly) created from an nn<PtrType*>; implicit upcasts are * allowed; and so on. * * Similarly, non-nullable pointers can be compared with regular or other * non-nullable * pointers, using the same rules as the underlying pointer types. * * This module also provides helpers for creating an nn<PtrType> from operations * that would * always return a non-null pointer: nn_make_unique, nn_make_shared, * nn_shared_from_this, and * nn_addr (a replacement for operator&). * * We abbreviate nn<unique_ptr> as nn_unique_ptr - it's a little more readable. * Likewise, * nn<shared_ptr> can be written as nn_shared_ptr. * * Finally, we define macros NN_CHECK_ASSERT and NN_CHECK_THROW, to convert a * nullable pointer * to a non-nullable pointer. At Dropbox, these use customized error-handling * infrastructure * and are in a separate file. We've included sample implementations here. */ template <typename PtrType> class nn { public: static_assert(!is_nn<PtrType>::value, "nn<nn<T>> is disallowed"); using element_type = typename nn_detail::element_type<PtrType>::type; // Pass through calls to operator* and operator-> transparently element_type &operator*() const { return *ptr; } element_type *operator->() const { return &*ptr; } // Expose the underlying PtrType operator const PtrType &() const & { return ptr; } operator PtrType &&() && { return std::move(ptr); } // Trying to use the assignment operator to assign a nn<PtrType> to a PtrType // using the // above conversion functions hits an ambiguous resolution bug in clang: // http://llvm.org/bugs/show_bug.cgi?id=18359 // While that exists, we can use these as simple ways of accessing the // underlying type // (instead of workarounds calling the operators explicitly or adding a // constructor call). const PtrType &as_nullable() const & { return ptr; } PtrType &&as_nullable() && { return std::move(ptr); } // Can't convert to bool (that would be silly). The explicit delete results in // "value of type 'nn<...>' is not contextually convertible to 'bool'", rather // than // "no viable conversion", which is a bit more clear. operator bool() const = delete; // Explicitly deleted constructors. These help produce clearer error messages, // as trying // to use them will result in clang printing the whole line, including the // comment. nn(std::nullptr_t) = delete; // nullptr is not allowed here nn &operator=(std::nullptr_t) = delete; // nullptr is not allowed here nn(PtrType) = delete; // must use NN_CHECK_ASSERT or NN_CHECK_THROW nn &operator=(PtrType) = delete; // must use NN_CHECK_ASSERT or NN_CHECK_THROW //PROJ_DLL ~nn(); // Semi-private constructor for use by NN_CHECK_ macros. explicit nn(i_promise_i_checked_for_null_t, const PtrType &arg) noexcept : ptr(arg) { } explicit nn(i_promise_i_checked_for_null_t, PtrType &&arg) noexcept : ptr(std::move(arg)) { } // Type-converting move and copy constructor. We have four separate cases // here, for // implicit and explicit move and copy. template <typename OtherType, typename std::enable_if< std::is_constructible<PtrType, OtherType>::value && !std::is_convertible<OtherType, PtrType>::value, int>::type = 0> explicit nn(const nn<OtherType> &other) : ptr(other.operator const OtherType &()) {} template <typename OtherType, typename std::enable_if< std::is_constructible<PtrType, OtherType>::value && !std::is_convertible<OtherType, PtrType>::value && !std::is_pointer<OtherType>::value, int>::type = 0> explicit nn(nn<OtherType> &&other) : ptr(std::move(other).operator OtherType &&()) {} template <typename OtherType, typename std::enable_if< std::is_convertible<OtherType, PtrType>::value, int>::type = 0> nn(const nn<OtherType> &other) : ptr(other.operator const OtherType &()) {} template < typename OtherType, typename std::enable_if<std::is_convertible<OtherType, PtrType>::value && !std::is_pointer<OtherType>::value, int>::type = 0> nn(nn<OtherType> &&other) : ptr(std::move(other).operator OtherType &&()) {} // A type-converting move and copy assignment operator aren't necessary; // writing // "base_ptr = derived_ptr;" will run the type-converting constructor followed // by the // implicit move assignment operator. // Two-argument constructor, designed for use with the shared_ptr aliasing // constructor. // This will not be instantiated if PtrType doesn't have a suitable // constructor. template < typename OtherType, typename std::enable_if< std::is_constructible<PtrType, OtherType, element_type *>::value, int>::type = 0> nn(const nn<OtherType> &ownership_ptr, nn<element_type *> target_ptr) : ptr(ownership_ptr.operator const OtherType &(), target_ptr) {} // Comparisons. Other comparisons are implemented in terms of these. template <typename L, typename R> friend bool operator==(const nn<L> &, const R &); template <typename L, typename R> friend bool operator==(const L &, const nn<R> &); template <typename L, typename R> friend bool operator==(const nn<L> &, const nn<R> &); template <typename L, typename R> friend bool operator<(const nn<L> &, const R &); template <typename L, typename R> friend bool operator<(const L &, const nn<R> &); template <typename L, typename R> friend bool operator<(const nn<L> &, const nn<R> &); // ostream operator template <typename T> friend std::ostream &operator<<(std::ostream &, const nn<T> &); template <typename T = PtrType> element_type *get() const { return ptr.get(); } private: // Backing pointer PtrType ptr; }; // Base comparisons - these are friends of nn<PtrType>, so they can access .ptr // directly. template <typename L, typename R> bool operator==(const nn<L> &l, const R &r) { return l.ptr == r; } template <typename L, typename R> bool operator==(const L &l, const nn<R> &r) { return l == r.ptr; } template <typename L, typename R> bool operator==(const nn<L> &l, const nn<R> &r) { return l.ptr == r.ptr; } template <typename L, typename R> bool operator<(const nn<L> &l, const R &r) { return l.ptr < r; } template <typename L, typename R> bool operator<(const L &l, const nn<R> &r) { return l < r.ptr; } template <typename L, typename R> bool operator<(const nn<L> &l, const nn<R> &r) { return l.ptr < r.ptr; } template <typename T> std::ostream &operator<<(std::ostream &os, const nn<T> &p) { return os << p.ptr; } #define NN_DERIVED_OPERATORS(op, base) \ template <typename L, typename R> \ bool operator op(const nn<L> &l, const R &r) { \ return base; \ } \ template <typename L, typename R> \ bool operator op(const L &l, const nn<R> &r) { \ return base; \ } \ template <typename L, typename R> \ bool operator op(const nn<L> &l, const nn<R> &r) { \ return base; \ } NN_DERIVED_OPERATORS(>, r < l) NN_DERIVED_OPERATORS(<=, !(l > r)) NN_DERIVED_OPERATORS(>=, !(l < r)) NN_DERIVED_OPERATORS(!=, !(l == r)) #undef NN_DERIVED_OPERATORS // Convenience typedefs template <typename T> using nn_unique_ptr = nn<std::unique_ptr<T>>; template <typename T> using nn_shared_ptr = nn<std::shared_ptr<T>>; template <typename T, typename... Args> nn_unique_ptr<T> nn_make_unique(Args &&... args) { return nn_unique_ptr<T>( i_promise_i_checked_for_null, std::unique_ptr<T>(new T(std::forward<Args>(args)...))); } template <typename T, typename... Args> nn_shared_ptr<T> nn_make_shared(Args &&... args) { return nn_shared_ptr<T>(i_promise_i_checked_for_null, std::make_shared<T>(std::forward<Args>(args)...)); } template <typename T> class nn_enable_shared_from_this : public std::enable_shared_from_this<T> { public: using std::enable_shared_from_this<T>::enable_shared_from_this; nn_shared_ptr<T> nn_shared_from_this() { return nn_shared_ptr<T>(i_promise_i_checked_for_null, this->shared_from_this()); } nn_shared_ptr<const T> nn_shared_from_this() const { return nn_shared_ptr<const T>(i_promise_i_checked_for_null, this->shared_from_this()); } }; template <typename T> nn<T *> nn_addr(T &object) { return nn<T *>(i_promise_i_checked_for_null, &object); } template <typename T> nn<const T *> nn_addr(const T &object) { return nn<const T *>(i_promise_i_checked_for_null, &object); } /* Non-nullable equivalents of shared_ptr's specialized casting functions. * These convert through a shared_ptr since nn<shared_ptr<T>> lacks the * ref-count-sharing cast * constructor, but thanks to moves there shouldn't be any significant extra * cost. */ template <typename T, typename U> nn_shared_ptr<T> nn_static_pointer_cast(const nn_shared_ptr<U> &org_ptr) { auto raw_ptr = static_cast<typename nn_shared_ptr<T>::element_type *>(org_ptr.get()); std::shared_ptr<T> nullable_ptr(org_ptr.as_nullable(), raw_ptr); return nn_shared_ptr<T>(i_promise_i_checked_for_null, std::move(nullable_ptr)); } template <typename T, typename U> std::shared_ptr<T> nn_dynamic_pointer_cast(const nn_shared_ptr<U> &org_ptr) { auto raw_ptr = dynamic_cast<typename std::shared_ptr<T>::element_type *>(org_ptr.get()); if (!raw_ptr) { return nullptr; } else { return std::shared_ptr<T>(org_ptr.as_nullable(), raw_ptr); } } template <typename T, typename U> nn_shared_ptr<T> nn_const_pointer_cast(const nn_shared_ptr<U> &org_ptr) { auto raw_ptr = const_cast<typename nn_shared_ptr<T>::element_type *>(org_ptr.get()); std::shared_ptr<T> nullable_ptr(org_ptr.as_nullable(), raw_ptr); return nn_shared_ptr<T>(i_promise_i_checked_for_null, std::move(nullable_ptr)); } } } /* end namespace dropbox::oxygen */ namespace std { template <typename T> struct hash<::dropbox::oxygen::nn<T>> { using argument_type = ::dropbox::oxygen::nn<T>; using result_type = size_t; result_type operator()(const argument_type &obj) const { return std::hash<T>{}(obj.as_nullable()); } }; } /* These have to be macros because our internal versions invoke other macros * that use * __FILE__ and __LINE__, which we want to correctly point to the call site. * We're looking * forward to std::source_location :) * * The lambdas ensure that we only evaluate _e once. */ #include <stdexcept> // NN_CHECK_ASSERT takes a pointer of type PT (e.g. raw pointer, std::shared_ptr // or std::unique_ptr) // and returns a non-nullable pointer of type nn<PT>. // Triggers an assertion if expression evaluates to null. #define NN_CHECK_ASSERT(_e) \ (([&](typename std::remove_reference<decltype(_e)>::type p) { \ /* note: assert() alone is not sufficient here, because it might be \ * compiled out. */ \ assert(p &&#_e " must not be null"); \ if (!p) \ std::abort(); \ return dropbox::oxygen::nn< \ typename std::remove_reference<decltype(p)>::type>( \ dropbox::oxygen::i_promise_i_checked_for_null, std::move(p)); \ })(_e)) // NN_CHECK_THROW takes a pointer of type PT (e.g. raw pointer, std::shared_ptr // or std::unique_ptr) // and returns a non-nullable pointer of type nn<PT>. // Throws if expression evaluates to null. #define NN_CHECK_THROW(_e) \ (([&](typename std::remove_reference<decltype(_e)>::type p) { \ if (!p) \ throw std::runtime_error(#_e " must not be null"); \ return dropbox::oxygen::nn< \ typename std::remove_reference<decltype(p)>::type>( \ dropbox::oxygen::i_promise_i_checked_for_null, std::move(p)); \ })(_e))
hpp
PROJ
data/projects/PROJ/include/proj/coordinatesystem.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef CS_HH_INCLUDED #define CS_HH_INCLUDED #include <memory> #include <set> #include <string> #include <vector> #include "common.hpp" #include "io.hpp" #include "util.hpp" NS_PROJ_START /** osgeo.proj.cs namespace \brief Coordinate systems and their axis. */ namespace cs { // --------------------------------------------------------------------------- /** \brief The direction of positive increase in the coordinate value for a * coordinate system axis. * * \remark Implements AxisDirection from \ref ISO_19111_2019 */ class AxisDirection : public util::CodeList { public: //! @cond Doxygen_Suppress PROJ_DLL static const AxisDirection * valueOf(const std::string &nameIn) noexcept; //! @endcond AxisDirection(const AxisDirection&) = delete; AxisDirection& operator=(const AxisDirection&) = delete; AxisDirection(AxisDirection&&) = delete; AxisDirection& operator=(AxisDirection&&) = delete; PROJ_DLL static const AxisDirection NORTH; PROJ_DLL static const AxisDirection NORTH_NORTH_EAST; PROJ_DLL static const AxisDirection NORTH_EAST; PROJ_DLL static const AxisDirection EAST_NORTH_EAST; PROJ_DLL static const AxisDirection EAST; PROJ_DLL static const AxisDirection EAST_SOUTH_EAST; PROJ_DLL static const AxisDirection SOUTH_EAST; PROJ_DLL static const AxisDirection SOUTH_SOUTH_EAST; PROJ_DLL static const AxisDirection SOUTH; PROJ_DLL static const AxisDirection SOUTH_SOUTH_WEST; PROJ_DLL static const AxisDirection SOUTH_WEST; PROJ_DLL static const AxisDirection WEST_SOUTH_WEST; // note: was forgotten in WKT2-2015 PROJ_DLL static const AxisDirection WEST; PROJ_DLL static const AxisDirection WEST_NORTH_WEST; PROJ_DLL static const AxisDirection NORTH_WEST; PROJ_DLL static const AxisDirection NORTH_NORTH_WEST; PROJ_DLL static const AxisDirection UP; PROJ_DLL static const AxisDirection DOWN; PROJ_DLL static const AxisDirection GEOCENTRIC_X; PROJ_DLL static const AxisDirection GEOCENTRIC_Y; PROJ_DLL static const AxisDirection GEOCENTRIC_Z; PROJ_DLL static const AxisDirection COLUMN_POSITIVE; PROJ_DLL static const AxisDirection COLUMN_NEGATIVE; PROJ_DLL static const AxisDirection ROW_POSITIVE; PROJ_DLL static const AxisDirection ROW_NEGATIVE; PROJ_DLL static const AxisDirection DISPLAY_RIGHT; PROJ_DLL static const AxisDirection DISPLAY_LEFT; PROJ_DLL static const AxisDirection DISPLAY_UP; PROJ_DLL static const AxisDirection DISPLAY_DOWN; PROJ_DLL static const AxisDirection FORWARD; PROJ_DLL static const AxisDirection AFT; PROJ_DLL static const AxisDirection PORT; PROJ_DLL static const AxisDirection STARBOARD; PROJ_DLL static const AxisDirection CLOCKWISE; PROJ_DLL static const AxisDirection COUNTER_CLOCKWISE; PROJ_DLL static const AxisDirection TOWARDS; PROJ_DLL static const AxisDirection AWAY_FROM; PROJ_DLL static const AxisDirection FUTURE; PROJ_DLL static const AxisDirection PAST; PROJ_DLL static const AxisDirection UNSPECIFIED; private: explicit AxisDirection(const std::string &nameIn); static std::map<std::string, const AxisDirection *> registry; }; // --------------------------------------------------------------------------- /** \brief Meaning of the axis value range specified through minimumValue and * maximumValue * * \remark Implements RangeMeaning from \ref ISO_19111_2019 * \since 9.2 */ class RangeMeaning : public util::CodeList { public: //! @cond Doxygen_Suppress PROJ_DLL static const RangeMeaning * valueOf(const std::string &nameIn) noexcept; //! @endcond PROJ_DLL static const RangeMeaning EXACT; PROJ_DLL static const RangeMeaning WRAPAROUND; protected: friend class util::optional<RangeMeaning>; RangeMeaning(); private: explicit RangeMeaning(const std::string &nameIn); static std::map<std::string, const RangeMeaning *> registry; }; // --------------------------------------------------------------------------- class Meridian; /** Shared pointer of Meridian. */ using MeridianPtr = std::shared_ptr<Meridian>; /** Non-null shared pointer of Meridian. */ using MeridianNNPtr = util::nn<MeridianPtr>; /** \brief The meridian that the axis follows from the pole, for a coordinate * reference system centered on a pole. * * \note There is no modelling for this concept in \ref ISO_19111_2019 * * \remark Implements MERIDIAN from \ref WKT2 */ class PROJ_GCC_DLL Meridian : public common::IdentifiedObject, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~Meridian() override; //! @endcond PROJ_DLL const common::Angle &longitude() PROJ_PURE_DECL; // non-standard PROJ_DLL static MeridianNNPtr create(const common::Angle &longitudeIn); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) //! @endcond protected: #ifdef DOXYGEN_ENABLED Angle angle_; #endif PROJ_INTERNAL explicit Meridian(const common::Angle &longitudeIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA Meridian(const Meridian &other) = delete; Meridian &operator=(const Meridian &other) = delete; }; // --------------------------------------------------------------------------- class CoordinateSystemAxis; /** Shared pointer of CoordinateSystemAxis. */ using CoordinateSystemAxisPtr = std::shared_ptr<CoordinateSystemAxis>; /** Non-null shared pointer of CoordinateSystemAxis. */ using CoordinateSystemAxisNNPtr = util::nn<CoordinateSystemAxisPtr>; /** \brief The definition of a coordinate system axis. * * \remark Implements CoordinateSystemAxis from \ref ISO_19111_2019 */ class PROJ_GCC_DLL CoordinateSystemAxis final : public common::IdentifiedObject, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~CoordinateSystemAxis() override; //! @endcond PROJ_DLL const std::string &abbreviation() PROJ_PURE_DECL; PROJ_DLL const AxisDirection &direction() PROJ_PURE_DECL; PROJ_DLL const common::UnitOfMeasure &unit() PROJ_PURE_DECL; PROJ_DLL const util::optional<double> &minimumValue() PROJ_PURE_DECL; PROJ_DLL const util::optional<double> &maximumValue() PROJ_PURE_DECL; PROJ_DLL const util::optional<RangeMeaning> &rangeMeaning() PROJ_PURE_DECL; PROJ_DLL const MeridianPtr &meridian() PROJ_PURE_DECL; // Non-standard PROJ_DLL static CoordinateSystemAxisNNPtr create(const util::PropertyMap &properties, const std::string &abbreviationIn, const AxisDirection &directionIn, const common::UnitOfMeasure &unitIn, const MeridianPtr &meridianIn = nullptr); PROJ_DLL static CoordinateSystemAxisNNPtr create(const util::PropertyMap &properties, const std::string &abbreviationIn, const AxisDirection &directionIn, const common::UnitOfMeasure &unitIn, const util::optional<double> &minimumValueIn, const util::optional<double> &maximumValueIn, const util::optional<RangeMeaning> &rangeMeaningIn, const MeridianPtr &meridianIn = nullptr); PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter, int order, bool disableAbbrev) const; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL static std::string normalizeAxisName(const std::string &str); PROJ_INTERNAL static CoordinateSystemAxisNNPtr createLAT_NORTH(const common::UnitOfMeasure &unit); PROJ_INTERNAL static CoordinateSystemAxisNNPtr createLONG_EAST(const common::UnitOfMeasure &unit); PROJ_INTERNAL CoordinateSystemAxisNNPtr alterUnit(const common::UnitOfMeasure &newUnit) const; //! @endcond private: PROJ_OPAQUE_PRIVATE_DATA CoordinateSystemAxis(const CoordinateSystemAxis &other) = delete; CoordinateSystemAxis &operator=(const CoordinateSystemAxis &other) = delete; PROJ_INTERNAL CoordinateSystemAxis(); /* cppcheck-suppress unusedPrivateFunction */ INLINED_MAKE_SHARED }; // --------------------------------------------------------------------------- /** \brief Abstract class modelling a coordinate system (CS) * * A CS is the non-repeating sequence of coordinate system axes that spans a * given coordinate space. A CS is derived from a set of mathematical rules for * specifying how coordinates in a given space are to be assigned to points. * The coordinate values in a coordinate tuple shall be recorded in the order * in which the coordinate system axes associations are recorded. * * \remark Implements CoordinateSystem from \ref ISO_19111_2019 */ class PROJ_GCC_DLL CoordinateSystem : public common::IdentifiedObject, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~CoordinateSystem() override; //! @endcond PROJ_DLL const std::vector<CoordinateSystemAxisNNPtr> & axisList() PROJ_PURE_DECL; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL virtual std::string getWKT2Type(bool) const = 0; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL explicit CoordinateSystem( const std::vector<CoordinateSystemAxisNNPtr> &axisIn); private: PROJ_OPAQUE_PRIVATE_DATA CoordinateSystem(const CoordinateSystem &other) = delete; CoordinateSystem &operator=(const CoordinateSystem &other) = delete; }; /** Shared pointer of CoordinateSystem. */ using CoordinateSystemPtr = std::shared_ptr<CoordinateSystem>; /** Non-null shared pointer of CoordinateSystem. */ using CoordinateSystemNNPtr = util::nn<CoordinateSystemPtr>; // --------------------------------------------------------------------------- class SphericalCS; /** Shared pointer of SphericalCS. */ using SphericalCSPtr = std::shared_ptr<SphericalCS>; /** Non-null shared pointer of SphericalCS. */ using SphericalCSNNPtr = util::nn<SphericalCSPtr>; /** \brief A three-dimensional coordinate system in Euclidean space with one * distance measured from the origin and two angular coordinates. * * Not to be confused with an ellipsoidal coordinate system based on an * ellipsoid "degenerated" into a sphere. A SphericalCS shall have three * axis associations. * * \remark Implements SphericalCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL SphericalCS final : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~SphericalCS() override; //! @endcond // non-standard PROJ_DLL static SphericalCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3); PROJ_DLL static SphericalCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2); /** Value of getWKT2Type() */ static constexpr const char *WKT2_TYPE = "spherical"; protected: PROJ_INTERNAL explicit SphericalCS( const std::vector<CoordinateSystemAxisNNPtr> &axisIn); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool) const override { return WKT2_TYPE; } private: SphericalCS(const SphericalCS &other) = delete; }; // --------------------------------------------------------------------------- class EllipsoidalCS; /** Shared pointer of EllipsoidalCS. */ using EllipsoidalCSPtr = std::shared_ptr<EllipsoidalCS>; /** Non-null shared pointer of EllipsoidalCS. */ using EllipsoidalCSNNPtr = util::nn<EllipsoidalCSPtr>; /** \brief A two- or three-dimensional coordinate system in which position is * specified by geodetic latitude, geodetic longitude, and (in the * three-dimensional case) ellipsoidal height. * * An EllipsoidalCS shall have two or three associations. * * \remark Implements EllipsoidalCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL EllipsoidalCS final : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~EllipsoidalCS() override; //! @endcond // non-standard PROJ_DLL static EllipsoidalCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2); PROJ_DLL static EllipsoidalCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3); PROJ_DLL static EllipsoidalCSNNPtr createLatitudeLongitude(const common::UnitOfMeasure &unit); PROJ_DLL static EllipsoidalCSNNPtr createLatitudeLongitudeEllipsoidalHeight( const common::UnitOfMeasure &angularUnit, const common::UnitOfMeasure &linearUnit); PROJ_DLL static EllipsoidalCSNNPtr createLongitudeLatitude(const common::UnitOfMeasure &unit); PROJ_DLL static EllipsoidalCSNNPtr createLongitudeLatitudeEllipsoidalHeight( const common::UnitOfMeasure &angularUnit, const common::UnitOfMeasure &linearUnit); /** Value of getWKT2Type() */ static constexpr const char *WKT2_TYPE = "ellipsoidal"; //! @cond Doxygen_Suppress /** \brief Typical axis order. */ enum class AxisOrder { /** Latitude(North), Longitude(East) */ LAT_NORTH_LONG_EAST, /** Latitude(North), Longitude(East), Height(up) */ LAT_NORTH_LONG_EAST_HEIGHT_UP, /** Longitude(East), Latitude(North) */ LONG_EAST_LAT_NORTH, /** Longitude(East), Latitude(North), Height(up) */ LONG_EAST_LAT_NORTH_HEIGHT_UP, /** Other axis order. */ OTHER }; PROJ_INTERNAL AxisOrder axisOrder() const; PROJ_INTERNAL EllipsoidalCSNNPtr alterAngularUnit(const common::UnitOfMeasure &angularUnit) const; PROJ_INTERNAL EllipsoidalCSNNPtr alterLinearUnit(const common::UnitOfMeasure &linearUnit) const; //! @endcond protected: PROJ_INTERNAL explicit EllipsoidalCS( const std::vector<CoordinateSystemAxisNNPtr> &axisIn); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool) const override { return WKT2_TYPE; } protected: EllipsoidalCS(const EllipsoidalCS &other) = delete; }; // --------------------------------------------------------------------------- class VerticalCS; /** Shared pointer of VerticalCS. */ using VerticalCSPtr = std::shared_ptr<VerticalCS>; /** Non-null shared pointer of VerticalCS. */ using VerticalCSNNPtr = util::nn<VerticalCSPtr>; /** \brief A one-dimensional coordinate system used to record the heights or * depths of points. * * Such a coordinate system is usually dependent on the Earth's gravity field. * A VerticalCS shall have one axis association. * * \remark Implements VerticalCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL VerticalCS final : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~VerticalCS() override; //! @endcond PROJ_DLL static VerticalCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis); PROJ_DLL static VerticalCSNNPtr createGravityRelatedHeight(const common::UnitOfMeasure &unit); /** Value of getWKT2Type() */ static constexpr const char *WKT2_TYPE = "vertical"; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL VerticalCSNNPtr alterUnit(const common::UnitOfMeasure &unit) const; //! @endcond protected: PROJ_INTERNAL explicit VerticalCS(const CoordinateSystemAxisNNPtr &axisIn); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool) const override { return WKT2_TYPE; } private: VerticalCS(const VerticalCS &other) = delete; }; // --------------------------------------------------------------------------- class CartesianCS; /** Shared pointer of CartesianCS. */ using CartesianCSPtr = std::shared_ptr<CartesianCS>; /** Non-null shared pointer of CartesianCS. */ using CartesianCSNNPtr = util::nn<CartesianCSPtr>; /** \brief A two- or three-dimensional coordinate system in Euclidean space * with orthogonal straight axes. * * All axes shall have the same length unit. A CartesianCS shall have two or * three axis associations; the number of associations shall equal the * dimension of the CS. * * \remark Implements CartesianCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL CartesianCS final : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~CartesianCS() override; //! @endcond PROJ_DLL static CartesianCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2); PROJ_DLL static CartesianCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3); PROJ_DLL static CartesianCSNNPtr createEastingNorthing(const common::UnitOfMeasure &unit); PROJ_DLL static CartesianCSNNPtr createNorthingEasting(const common::UnitOfMeasure &unit); PROJ_DLL static CartesianCSNNPtr createNorthPoleEastingSouthNorthingSouth(const common::UnitOfMeasure &unit); PROJ_DLL static CartesianCSNNPtr createSouthPoleEastingNorthNorthingNorth(const common::UnitOfMeasure &unit); PROJ_DLL static CartesianCSNNPtr createWestingSouthing(const common::UnitOfMeasure &unit); PROJ_DLL static CartesianCSNNPtr createGeocentric(const common::UnitOfMeasure &unit); /** Value of getWKT2Type() */ static constexpr const char *WKT2_TYPE = "Cartesian"; // uppercase is intended PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL CartesianCSNNPtr alterUnit(const common::UnitOfMeasure &unit) const; //! @endcond protected: PROJ_INTERNAL explicit CartesianCS( const std::vector<CoordinateSystemAxisNNPtr> &axisIn); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool) const override { return WKT2_TYPE; } private: CartesianCS(const CartesianCS &other) = delete; }; // --------------------------------------------------------------------------- class AffineCS; /** Shared pointer of AffineCS. */ using AffineCSPtr = std::shared_ptr<AffineCS>; /** Non-null shared pointer of AffineCS. */ using AffineCSNNPtr = util::nn<AffineCSPtr>; /** \brief A two- or three-dimensional coordinate system in Euclidean space * with straight axes that are not necessarily orthogonal. * * \remark Implements AffineCS from \ref ISO_19111_2019 * \since 9.2 */ class PROJ_GCC_DLL AffineCS final : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~AffineCS() override; //! @endcond /** Value of getWKT2Type() */ static constexpr const char *WKT2_TYPE = "affine"; PROJ_DLL static AffineCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2); PROJ_DLL static AffineCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis1, const CoordinateSystemAxisNNPtr &axis2, const CoordinateSystemAxisNNPtr &axis3); PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL AffineCSNNPtr alterUnit(const common::UnitOfMeasure &unit) const; //! @endcond protected: PROJ_INTERNAL explicit AffineCS( const std::vector<CoordinateSystemAxisNNPtr> &axisIn); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool) const override { return WKT2_TYPE; } private: AffineCS(const AffineCS &other) = delete; }; // --------------------------------------------------------------------------- class OrdinalCS; /** Shared pointer of OrdinalCS. */ using OrdinalCSPtr = std::shared_ptr<OrdinalCS>; /** Non-null shared pointer of OrdinalCS. */ using OrdinalCSNNPtr = util::nn<OrdinalCSPtr>; /** \brief n-dimensional coordinate system in which every axis uses integers. * * The number of associations shall equal the * dimension of the CS. * * \remark Implements OrdinalCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL OrdinalCS final : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~OrdinalCS() override; //! @endcond PROJ_DLL static OrdinalCSNNPtr create(const util::PropertyMap &properties, const std::vector<CoordinateSystemAxisNNPtr> &axisIn); /** Value of getWKT2Type() */ static constexpr const char *WKT2_TYPE = "ordinal"; protected: PROJ_INTERNAL explicit OrdinalCS( const std::vector<CoordinateSystemAxisNNPtr> &axisIn); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool) const override { return WKT2_TYPE; } private: OrdinalCS(const OrdinalCS &other) = delete; }; // --------------------------------------------------------------------------- class ParametricCS; /** Shared pointer of ParametricCS. */ using ParametricCSPtr = std::shared_ptr<ParametricCS>; /** Non-null shared pointer of ParametricCS. */ using ParametricCSNNPtr = util::nn<ParametricCSPtr>; /** \brief one-dimensional coordinate reference system which uses parameter * values or functions that may vary monotonically with height. * * \remark Implements ParametricCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ParametricCS final : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~ParametricCS() override; //! @endcond PROJ_DLL static ParametricCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axisIn); /** Value of getWKT2Type() */ static constexpr const char *WKT2_TYPE = "parametric"; protected: PROJ_INTERNAL explicit ParametricCS( const std::vector<CoordinateSystemAxisNNPtr> &axisIn); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool) const override { return WKT2_TYPE; } private: ParametricCS(const ParametricCS &other) = delete; }; // --------------------------------------------------------------------------- class TemporalCS; /** Shared pointer of TemporalCS. */ using TemporalCSPtr = std::shared_ptr<TemporalCS>; /** Non-null shared pointer of TemporalCS. */ using TemporalCSNNPtr = util::nn<TemporalCSPtr>; /** \brief (Abstract class) A one-dimensional coordinate system used to record * time. * * A TemporalCS shall have one axis association. * * \remark Implements TemporalCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL TemporalCS : public CoordinateSystem { public: //! @cond Doxygen_Suppress PROJ_DLL ~TemporalCS() override; //! @endcond /** WKT2:2015 type */ static constexpr const char *WKT2_2015_TYPE = "temporal"; protected: PROJ_INTERNAL explicit TemporalCS(const CoordinateSystemAxisNNPtr &axis); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool use2019Keywords) const override = 0; private: TemporalCS(const TemporalCS &other) = delete; }; // --------------------------------------------------------------------------- class DateTimeTemporalCS; /** Shared pointer of DateTimeTemporalCS. */ using DateTimeTemporalCSPtr = std::shared_ptr<DateTimeTemporalCS>; /** Non-null shared pointer of DateTimeTemporalCS. */ using DateTimeTemporalCSNNPtr = util::nn<DateTimeTemporalCSPtr>; /** \brief A one-dimensional coordinate system used to record time in dateTime * representation as defined in ISO 8601. * * A DateTimeTemporalCS shall have one axis association. It does not use * axisUnitID; the temporal quantities are defined through the ISO 8601 * representation. * * \remark Implements DateTimeTemporalCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DateTimeTemporalCS final : public TemporalCS { public: //! @cond Doxygen_Suppress PROJ_DLL ~DateTimeTemporalCS() override; //! @endcond PROJ_DLL static DateTimeTemporalCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis); /** WKT2:2019 type */ static constexpr const char *WKT2_2019_TYPE = "TemporalDateTime"; protected: PROJ_INTERNAL explicit DateTimeTemporalCS( const CoordinateSystemAxisNNPtr &axis); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool use2019Keywords) const override; private: DateTimeTemporalCS(const DateTimeTemporalCS &other) = delete; }; // --------------------------------------------------------------------------- class TemporalCountCS; /** Shared pointer of TemporalCountCS. */ using TemporalCountCSPtr = std::shared_ptr<TemporalCountCS>; /** Non-null shared pointer of TemporalCountCS. */ using TemporalCountCSNNPtr = util::nn<TemporalCountCSPtr>; /** \brief A one-dimensional coordinate system used to record time as an * integer count. * * A TemporalCountCS shall have one axis association. * * \remark Implements TemporalCountCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL TemporalCountCS final : public TemporalCS { public: //! @cond Doxygen_Suppress PROJ_DLL ~TemporalCountCS() override; //! @endcond PROJ_DLL static TemporalCountCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis); /** WKT2:2019 type */ static constexpr const char *WKT2_2019_TYPE = "TemporalCount"; protected: PROJ_INTERNAL explicit TemporalCountCS( const CoordinateSystemAxisNNPtr &axis); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool use2019Keywords) const override; private: TemporalCountCS(const TemporalCountCS &other) = delete; }; // --------------------------------------------------------------------------- class TemporalMeasureCS; /** Shared pointer of TemporalMeasureCS. */ using TemporalMeasureCSPtr = std::shared_ptr<TemporalMeasureCS>; /** Non-null shared pointer of TemporalMeasureCS. */ using TemporalMeasureCSNNPtr = util::nn<TemporalMeasureCSPtr>; /** \brief A one-dimensional coordinate system used to record a time as a * real number. * * A TemporalMeasureCS shall have one axis association. * * \remark Implements TemporalMeasureCS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL TemporalMeasureCS final : public TemporalCS { public: //! @cond Doxygen_Suppress PROJ_DLL ~TemporalMeasureCS() override; //! @endcond PROJ_DLL static TemporalMeasureCSNNPtr create(const util::PropertyMap &properties, const CoordinateSystemAxisNNPtr &axis); /** WKT2:2019 type */ static constexpr const char *WKT2_2019_TYPE = "TemporalMeasure"; protected: PROJ_INTERNAL explicit TemporalMeasureCS( const CoordinateSystemAxisNNPtr &axis); INLINED_MAKE_SHARED PROJ_INTERNAL std::string getWKT2Type(bool use2019Keywords) const override; private: TemporalMeasureCS(const TemporalMeasureCS &other) = delete; }; } // namespace cs NS_PROJ_END #endif // CS_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/crs.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef CRS_HH_INCLUDED #define CRS_HH_INCLUDED #include <memory> #include <string> #include <vector> #include "common.hpp" #include "coordinateoperation.hpp" #include "coordinatesystem.hpp" #include "datum.hpp" #include "io.hpp" #include "util.hpp" NS_PROJ_START /** osgeo.proj.crs namespace \brief CRS (coordinate reference system = coordinate system with a datum). */ namespace crs { // --------------------------------------------------------------------------- class GeographicCRS; /** Shared pointer of GeographicCRS */ using GeographicCRSPtr = std::shared_ptr<GeographicCRS>; /** Non-null shared pointer of GeographicCRS */ using GeographicCRSNNPtr = util::nn<GeographicCRSPtr>; class VerticalCRS; /** Shared pointer of VerticalCRS */ using VerticalCRSPtr = std::shared_ptr<VerticalCRS>; /** Non-null shared pointer of VerticalCRS */ using VerticalCRSNNPtr = util::nn<VerticalCRSPtr>; class BoundCRS; /** Shared pointer of BoundCRS */ using BoundCRSPtr = std::shared_ptr<BoundCRS>; /** Non-null shared pointer of BoundCRS */ using BoundCRSNNPtr = util::nn<BoundCRSPtr>; class CompoundCRS; /** Shared pointer of CompoundCRS */ using CompoundCRSPtr = std::shared_ptr<CompoundCRS>; /** Non-null shared pointer of CompoundCRS */ using CompoundCRSNNPtr = util::nn<CompoundCRSPtr>; // --------------------------------------------------------------------------- class CRS; /** Shared pointer of CRS */ using CRSPtr = std::shared_ptr<CRS>; /** Non-null shared pointer of CRS */ using CRSNNPtr = util::nn<CRSPtr>; /** \brief Abstract class modelling a coordinate reference system which is * usually single but may be compound. * * \remark Implements CRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL CRS : public common::ObjectUsage, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~CRS() override; //! @endcond // Non-standard PROJ_DLL bool isDynamic(bool considerWGS84AsDynamic = false) const; PROJ_DLL GeodeticCRSPtr extractGeodeticCRS() const; PROJ_DLL GeographicCRSPtr extractGeographicCRS() const; PROJ_DLL VerticalCRSPtr extractVerticalCRS() const; PROJ_DLL CRSNNPtr createBoundCRSToWGS84IfPossible( const io::DatabaseContextPtr &dbContext, operation::CoordinateOperationContext::IntermediateCRSUse allowIntermediateCRSUse) const; PROJ_DLL CRSNNPtr stripVerticalComponent() const; PROJ_DLL const BoundCRSPtr &canonicalBoundCRS() PROJ_PURE_DECL; PROJ_DLL std::list<std::pair<CRSNNPtr, int>> identify(const io::AuthorityFactoryPtr &authorityFactory) const; PROJ_DLL std::list<CRSNNPtr> getNonDeprecated(const io::DatabaseContextNNPtr &dbContext) const; PROJ_DLL CRSNNPtr promoteTo3D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; PROJ_DLL CRSNNPtr demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL const GeodeticCRS * extractGeodeticCRSRaw() const; PROJ_FOR_TEST CRSNNPtr shallowClone() const; PROJ_FOR_TEST CRSNNPtr alterName(const std::string &newName) const; PROJ_FOR_TEST CRSNNPtr alterId(const std::string &authName, const std::string &code) const; PROJ_INTERNAL const std::string &getExtensionProj4() const noexcept; PROJ_FOR_TEST CRSNNPtr alterGeodeticCRS(const GeodeticCRSNNPtr &newGeodCRS) const; PROJ_FOR_TEST CRSNNPtr alterCSLinearUnit(const common::UnitOfMeasure &unit) const; PROJ_INTERNAL bool mustAxisOrderBeSwitchedForVisualization() const; PROJ_INTERNAL CRSNNPtr applyAxisOrderReversal(const char *nameSuffix) const; PROJ_FOR_TEST CRSNNPtr normalizeForVisualization() const; PROJ_INTERNAL CRSNNPtr allowNonConformantWKT1Export() const; PROJ_INTERNAL CRSNNPtr attachOriginalCompoundCRS(const CompoundCRSNNPtr &compoundCRS) const; PROJ_INTERNAL CRSNNPtr promoteTo3D( const std::string &newName, const io::DatabaseContextPtr &dbContext, const cs::CoordinateSystemAxisNNPtr &verticalAxisIfNotAlreadyPresent) const; PROJ_INTERNAL bool hasImplicitCS() const; PROJ_INTERNAL bool hasOver() const; PROJ_INTERNAL static CRSNNPtr getResolvedCRS(const CRSNNPtr &crs, const io::AuthorityFactoryPtr &authFactory, metadata::ExtentPtr &extentOut); //! @endcond protected: PROJ_INTERNAL CRS(); PROJ_INTERNAL CRS(const CRS &other); friend class BoundCRS; PROJ_INTERNAL void setCanonicalBoundCRS(const BoundCRSNNPtr &boundCRS); PROJ_INTERNAL virtual CRSNNPtr _shallowClone() const = 0; PROJ_INTERNAL virtual std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const; PROJ_INTERNAL void setProperties(const util::PropertyMap &properties); // throw(InvalidValueTypeException) private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Abstract class modelling a coordinate reference system consisting of * one Coordinate System and either one datum::Datum or one * datum::DatumEnsemble. * * \remark Implements SingleCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL SingleCRS : public CRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~SingleCRS() override; //! @endcond PROJ_DLL const datum::DatumPtr &datum() PROJ_PURE_DECL; PROJ_DLL const datum::DatumEnsemblePtr &datumEnsemble() PROJ_PURE_DECL; PROJ_DLL const cs::CoordinateSystemNNPtr &coordinateSystem() PROJ_PURE_DECL; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void exportDatumOrDatumEnsembleToWkt(io::WKTFormatter *formatter) const; // throw(io::FormattingException) PROJ_INTERNAL const datum::DatumNNPtr datumNonNull(const io::DatabaseContextPtr &dbContext) const; //! @endcond protected: PROJ_INTERNAL SingleCRS(const datum::DatumPtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::CoordinateSystemNNPtr &csIn); PROJ_INTERNAL SingleCRS(const SingleCRS &other); PROJ_INTERNAL bool baseIsEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const; private: PROJ_OPAQUE_PRIVATE_DATA SingleCRS &operator=(const SingleCRS &other) = delete; }; /** Shared pointer of SingleCRS */ using SingleCRSPtr = std::shared_ptr<SingleCRS>; /** Non-null shared pointer of SingleCRS */ using SingleCRSNNPtr = util::nn<SingleCRSPtr>; // --------------------------------------------------------------------------- class GeodeticCRS; /** Shared pointer of GeodeticCRS */ using GeodeticCRSPtr = std::shared_ptr<GeodeticCRS>; /** Non-null shared pointer of GeodeticCRS */ using GeodeticCRSNNPtr = util::nn<GeodeticCRSPtr>; /** \brief A coordinate reference system associated with a geodetic reference * frame and a three-dimensional Cartesian or spherical coordinate system. * * If the geodetic reference frame is dynamic or if the geodetic CRS has an * association to a velocity model then the geodetic CRS is dynamic, else it * is static. * * \remark Implements GeodeticCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL GeodeticCRS : virtual public SingleCRS, public io::IPROJStringExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~GeodeticCRS() override; //! @endcond PROJ_DLL const datum::GeodeticReferenceFramePtr &datum() PROJ_PURE_DECL; PROJ_DLL const datum::PrimeMeridianNNPtr &primeMeridian() PROJ_PURE_DECL; PROJ_DLL const datum::EllipsoidNNPtr &ellipsoid() PROJ_PURE_DECL; // coordinateSystem() returns either a EllipsoidalCS, SphericalCS or // CartesianCS PROJ_DLL const std::vector<operation::PointMotionOperationNNPtr> & velocityModel() PROJ_PURE_DECL; // Non-standard PROJ_DLL bool isGeocentric() PROJ_PURE_DECL; PROJ_DLL bool isSphericalPlanetocentric() PROJ_PURE_DECL; PROJ_DLL static GeodeticCRSNNPtr create(const util::PropertyMap &properties, const datum::GeodeticReferenceFrameNNPtr &datum, const cs::SphericalCSNNPtr &cs); PROJ_DLL static GeodeticCRSNNPtr create(const util::PropertyMap &properties, const datum::GeodeticReferenceFrameNNPtr &datum, const cs::CartesianCSNNPtr &cs); PROJ_DLL static GeodeticCRSNNPtr create(const util::PropertyMap &properties, const datum::GeodeticReferenceFramePtr &datum, const datum::DatumEnsemblePtr &datumEnsemble, const cs::SphericalCSNNPtr &cs); PROJ_DLL static GeodeticCRSNNPtr create(const util::PropertyMap &properties, const datum::GeodeticReferenceFramePtr &datum, const datum::DatumEnsemblePtr &datumEnsemble, const cs::CartesianCSNNPtr &cs); PROJ_DLL static const GeodeticCRSNNPtr EPSG_4978; // WGS 84 Geocentric PROJ_DLL std::list<std::pair<GeodeticCRSNNPtr, int>> identify(const io::AuthorityFactoryPtr &authorityFactory) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void addDatumInfoToPROJString(io::PROJStringFormatter *formatter) const; PROJ_INTERNAL const datum::GeodeticReferenceFrameNNPtr datumNonNull(const io::DatabaseContextPtr &dbContext) const; PROJ_INTERNAL void addGeocentricUnitConversionIntoPROJString( io::PROJStringFormatter *formatter) const; PROJ_INTERNAL void addAngularUnitConvertAndAxisSwap(io::PROJStringFormatter *formatter) const; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL GeodeticCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::EllipsoidalCSNNPtr &csIn); PROJ_INTERNAL GeodeticCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::SphericalCSNNPtr &csIn); PROJ_INTERNAL GeodeticCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::CartesianCSNNPtr &csIn); PROJ_INTERNAL GeodeticCRS(const GeodeticCRS &other); PROJ_INTERNAL static GeodeticCRSNNPtr createEPSG_4978(); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL void _exportToJSONInternal( io::JSONFormatter *formatter, const char *objectName) const; // throw(FormattingException) PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; PROJ_INTERNAL bool _isEquivalentToNoTypeCheck(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA GeodeticCRS &operator=(const GeodeticCRS &other) = delete; }; // --------------------------------------------------------------------------- /** \brief A coordinate reference system associated with a geodetic reference * frame and a two- or three-dimensional ellipsoidal coordinate system. * * If the geodetic reference frame is dynamic or if the geographic CRS has an * association to a velocity model then the geodetic CRS is dynamic, else it is * static. * * \remark Implements GeographicCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL GeographicCRS : public GeodeticCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~GeographicCRS() override; //! @endcond PROJ_DLL const cs::EllipsoidalCSNNPtr &coordinateSystem() PROJ_PURE_DECL; // Non-standard PROJ_DLL static GeographicCRSNNPtr create(const util::PropertyMap &properties, const datum::GeodeticReferenceFrameNNPtr &datum, const cs::EllipsoidalCSNNPtr &cs); PROJ_DLL static GeographicCRSNNPtr create(const util::PropertyMap &properties, const datum::GeodeticReferenceFramePtr &datum, const datum::DatumEnsemblePtr &datumEnsemble, const cs::EllipsoidalCSNNPtr &cs); PROJ_DLL GeographicCRSNNPtr demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; PROJ_DLL static const GeographicCRSNNPtr EPSG_4267; // NAD27 PROJ_DLL static const GeographicCRSNNPtr EPSG_4269; // NAD83 PROJ_DLL static const GeographicCRSNNPtr EPSG_4326; // WGS 84 2D PROJ_DLL static const GeographicCRSNNPtr OGC_CRS84; // CRS84 (Long, Lat) PROJ_DLL static const GeographicCRSNNPtr EPSG_4807; // NTF Paris PROJ_DLL static const GeographicCRSNNPtr EPSG_4979; // WGS 84 3D PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_DLL bool is2DPartOf3D( util::nn<const GeographicCRS *> other, const io::DatabaseContextPtr &dbContext = nullptr) PROJ_PURE_DECL; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL GeographicCRS(const datum::GeodeticReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::EllipsoidalCSNNPtr &csIn); PROJ_INTERNAL GeographicCRS(const GeographicCRS &other); PROJ_INTERNAL static GeographicCRSNNPtr createEPSG_4267(); PROJ_INTERNAL static GeographicCRSNNPtr createEPSG_4269(); PROJ_INTERNAL static GeographicCRSNNPtr createEPSG_4326(); PROJ_INTERNAL static GeographicCRSNNPtr createOGC_CRS84(); PROJ_INTERNAL static GeographicCRSNNPtr createEPSG_4807(); PROJ_INTERNAL static GeographicCRSNNPtr createEPSG_4979(); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA GeographicCRS &operator=(const GeographicCRS &other) = delete; }; // --------------------------------------------------------------------------- /** \brief A coordinate reference system having a vertical reference frame and * a one-dimensional vertical coordinate system used for recording * gravity-related heights or depths. * * Vertical CRSs make use of the direction of gravity to define the concept of * height or depth, but the relationship with gravity may not be * straightforward. If the vertical reference frame is dynamic or if the * vertical CRS has an association to a velocity model then the CRS is dynamic, * else it is static. * * \note Ellipsoidal heights cannot be captured in a vertical coordinate * reference system. They exist only as an inseparable part of a 3D coordinate * tuple defined in a geographic 3D coordinate reference system. * * \remark Implements VerticalCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL VerticalCRS : virtual public SingleCRS, public io::IPROJStringExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~VerticalCRS() override; //! @endcond PROJ_DLL const datum::VerticalReferenceFramePtr datum() const; PROJ_DLL const cs::VerticalCSNNPtr coordinateSystem() const; PROJ_DLL const std::vector<operation::TransformationNNPtr> & geoidModel() PROJ_PURE_DECL; PROJ_DLL const std::vector<operation::PointMotionOperationNNPtr> & velocityModel() PROJ_PURE_DECL; PROJ_DLL static VerticalCRSNNPtr create(const util::PropertyMap &properties, const datum::VerticalReferenceFrameNNPtr &datumIn, const cs::VerticalCSNNPtr &csIn); PROJ_DLL static VerticalCRSNNPtr create(const util::PropertyMap &properties, const datum::VerticalReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::VerticalCSNNPtr &csIn); PROJ_DLL std::list<std::pair<VerticalCRSNNPtr, int>> identify(const io::AuthorityFactoryPtr &authorityFactory) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void addLinearUnitConvert(io::PROJStringFormatter *formatter) const; PROJ_INTERNAL const datum::VerticalReferenceFrameNNPtr datumNonNull(const io::DatabaseContextPtr &dbContext) const; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL VerticalCRS(const datum::VerticalReferenceFramePtr &datumIn, const datum::DatumEnsemblePtr &datumEnsembleIn, const cs::VerticalCSNNPtr &csIn); PROJ_INTERNAL VerticalCRS(const VerticalCRS &other); PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; INLINED_MAKE_SHARED PROJ_INTERNAL CRSNNPtr _shallowClone() const override; private: PROJ_OPAQUE_PRIVATE_DATA VerticalCRS &operator=(const VerticalCRS &other) = delete; }; // --------------------------------------------------------------------------- /** \brief Abstract class modelling a single coordinate reference system that * is defined through the application of a specified coordinate conversion to * the definition of a previously established single coordinate reference * system referred to as the base CRS. * * A derived coordinate reference system inherits its datum (or datum ensemble) * from its base CRS. The coordinate conversion between the base and derived * coordinate reference system is implemented using the parameters and * formula(s) specified in the definition of the coordinate conversion. * * \remark Implements DerivedCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DerivedCRS : virtual public SingleCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~DerivedCRS() override; //! @endcond PROJ_DLL const SingleCRSNNPtr &baseCRS() PROJ_PURE_DECL; PROJ_DLL const operation::ConversionNNPtr derivingConversion() const; PROJ_PRIVATE : //! @cond Doxygen_Suppress // Use this method with extreme care ! It should never be used // to recreate a new Derived/ProjectedCRS ! PROJ_INTERNAL const operation::ConversionNNPtr & derivingConversionRef() PROJ_PURE_DECL; PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) //! @endcond protected: PROJ_INTERNAL DerivedCRS(const SingleCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CoordinateSystemNNPtr &cs); PROJ_INTERNAL DerivedCRS(const DerivedCRS &other); PROJ_INTERNAL void setDerivingConversionCRS(); PROJ_INTERNAL void baseExportToWKT( io::WKTFormatter *formatter, const std::string &keyword, const std::string &baseKeyword) const; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL virtual const char *className() const = 0; private: PROJ_OPAQUE_PRIVATE_DATA DerivedCRS &operator=(const DerivedCRS &other) = delete; }; /** Shared pointer of DerivedCRS */ using DerivedCRSPtr = std::shared_ptr<DerivedCRS>; /** Non-null shared pointer of DerivedCRS */ using DerivedCRSNNPtr = util::nn<DerivedCRSPtr>; // --------------------------------------------------------------------------- class ProjectedCRS; /** Shared pointer of ProjectedCRS */ using ProjectedCRSPtr = std::shared_ptr<ProjectedCRS>; /** Non-null shared pointer of ProjectedCRS */ using ProjectedCRSNNPtr = util::nn<ProjectedCRSPtr>; /** \brief A derived coordinate reference system which has a geodetic * (usually geographic) coordinate reference system as its base CRS, thereby * inheriting a geodetic reference frame, and is converted using a map * projection. * * It has a Cartesian coordinate system, usually two-dimensional but may be * three-dimensional; in the 3D case the base geographic CRSs ellipsoidal * height is passed through unchanged and forms the vertical axis of the * projected CRS's Cartesian coordinate system. * * \remark Implements ProjectedCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ProjectedCRS final : public DerivedCRS, public io::IPROJStringExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~ProjectedCRS() override; //! @endcond PROJ_DLL const GeodeticCRSNNPtr &baseCRS() PROJ_PURE_DECL; PROJ_DLL const cs::CartesianCSNNPtr &coordinateSystem() PROJ_PURE_DECL; PROJ_DLL static ProjectedCRSNNPtr create(const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn); PROJ_DLL std::list<std::pair<ProjectedCRSNNPtr, int>> identify(const io::AuthorityFactoryPtr &authorityFactory) const; PROJ_DLL ProjectedCRSNNPtr demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void addUnitConvertAndAxisSwap(io::PROJStringFormatter *formatter, bool axisSpecFound) const; PROJ_INTERNAL static void addUnitConvertAndAxisSwap( const std::vector<cs::CoordinateSystemAxisNNPtr> &axisListIn, io::PROJStringFormatter *formatter, bool axisSpecFound); PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_FOR_TEST ProjectedCRSNNPtr alterParametersLinearUnit( const common::UnitOfMeasure &unit, bool convertToNewUnit) const; //! @endcond protected: PROJ_INTERNAL ProjectedCRS(const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn); PROJ_INTERNAL ProjectedCRS(const ProjectedCRS &other); PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; PROJ_INTERNAL const char *className() const override { return "ProjectedCRS"; } INLINED_MAKE_SHARED PROJ_INTERNAL CRSNNPtr _shallowClone() const override; private: PROJ_OPAQUE_PRIVATE_DATA ProjectedCRS &operator=(const ProjectedCRS &other) = delete; }; // --------------------------------------------------------------------------- class TemporalCRS; /** Shared pointer of TemporalCRS */ using TemporalCRSPtr = std::shared_ptr<TemporalCRS>; /** Non-null shared pointer of TemporalCRS */ using TemporalCRSNNPtr = util::nn<TemporalCRSPtr>; /** \brief A coordinate reference system associated with a temporal datum and a * one-dimensional temporal coordinate system. * * \remark Implements TemporalCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL TemporalCRS : virtual public SingleCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~TemporalCRS() override; //! @endcond PROJ_DLL const datum::TemporalDatumNNPtr datum() const; PROJ_DLL const cs::TemporalCSNNPtr coordinateSystem() const; PROJ_DLL static TemporalCRSNNPtr create(const util::PropertyMap &properties, const datum::TemporalDatumNNPtr &datumIn, const cs::TemporalCSNNPtr &csIn); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) //! @endcond protected: PROJ_INTERNAL TemporalCRS(const datum::TemporalDatumNNPtr &datumIn, const cs::TemporalCSNNPtr &csIn); PROJ_INTERNAL TemporalCRS(const TemporalCRS &other); INLINED_MAKE_SHARED PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; private: PROJ_OPAQUE_PRIVATE_DATA TemporalCRS &operator=(const TemporalCRS &other) = delete; }; // --------------------------------------------------------------------------- class EngineeringCRS; /** Shared pointer of EngineeringCRS */ using EngineeringCRSPtr = std::shared_ptr<EngineeringCRS>; /** Non-null shared pointer of EngineeringCRS */ using EngineeringCRSNNPtr = util::nn<EngineeringCRSPtr>; /** \brief Contextually local coordinate reference system associated with an * engineering datum. * * It is applied either to activities on or near the surface of the Earth * without geodetic corrections, or on moving platforms such as road vehicles, * vessels, aircraft or spacecraft, or as the internal CRS of an image. * * In \ref WKT2, it maps to a ENGINEERINGCRS / ENGCRS keyword. In \ref WKT1, * it maps to a LOCAL_CS keyword. * * \remark Implements EngineeringCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL EngineeringCRS : virtual public SingleCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~EngineeringCRS() override; //! @endcond PROJ_DLL const datum::EngineeringDatumNNPtr datum() const; PROJ_DLL static EngineeringCRSNNPtr create(const util::PropertyMap &properties, const datum::EngineeringDatumNNPtr &datumIn, const cs::CoordinateSystemNNPtr &csIn); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) //! @endcond protected: PROJ_INTERNAL EngineeringCRS(const datum::EngineeringDatumNNPtr &datumIn, const cs::CoordinateSystemNNPtr &csIn); PROJ_INTERNAL EngineeringCRS(const EngineeringCRS &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA EngineeringCRS &operator=(const EngineeringCRS &other) = delete; }; // --------------------------------------------------------------------------- class ParametricCRS; /** Shared pointer of ParametricCRS */ using ParametricCRSPtr = std::shared_ptr<ParametricCRS>; /** Non-null shared pointer of ParametricCRS */ using ParametricCRSNNPtr = util::nn<ParametricCRSPtr>; /** \brief Contextually local coordinate reference system associated with an * engineering datum. * * This is applied either to activities on or near the surface of the Earth * without geodetic corrections, or on moving platforms such as road vehicles * vessels, aircraft or spacecraft, or as the internal CRS of an image. * * \remark Implements ParametricCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ParametricCRS : virtual public SingleCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~ParametricCRS() override; //! @endcond PROJ_DLL const datum::ParametricDatumNNPtr datum() const; PROJ_DLL const cs::ParametricCSNNPtr coordinateSystem() const; PROJ_DLL static ParametricCRSNNPtr create(const util::PropertyMap &properties, const datum::ParametricDatumNNPtr &datumIn, const cs::ParametricCSNNPtr &csIn); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) //! @endcond protected: PROJ_INTERNAL ParametricCRS(const datum::ParametricDatumNNPtr &datumIn, const cs::ParametricCSNNPtr &csIn); PROJ_INTERNAL ParametricCRS(const ParametricCRS &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA ParametricCRS &operator=(const ParametricCRS &other) = delete; }; // --------------------------------------------------------------------------- /** \brief Exception thrown when attempting to create an invalid compound CRS */ class PROJ_GCC_DLL InvalidCompoundCRSException : public util::Exception { public: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit InvalidCompoundCRSException(const char *message); PROJ_INTERNAL explicit InvalidCompoundCRSException( const std::string &message); PROJ_DLL InvalidCompoundCRSException(const InvalidCompoundCRSException &other); PROJ_DLL ~InvalidCompoundCRSException() override; //! @endcond }; // --------------------------------------------------------------------------- /** \brief A coordinate reference system describing the position of points * through two or more independent single coordinate reference systems. * * \note Two coordinate reference systems are independent of each other * if coordinate values in one cannot be converted or transformed into * coordinate values in the other. * * \note As a departure to \ref ISO_19111_2019, we allow to build a CompoundCRS * from CRS objects, whereas ISO19111:2019 restricts the components to * SingleCRS. * * \remark Implements CompoundCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL CompoundCRS final : public CRS, public io::IPROJStringExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~CompoundCRS() override; //! @endcond PROJ_DLL const std::vector<CRSNNPtr> & componentReferenceSystems() PROJ_PURE_DECL; PROJ_DLL std::list<std::pair<CompoundCRSNNPtr, int>> identify(const io::AuthorityFactoryPtr &authorityFactory) const; //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) //! @endcond PROJ_DLL static CompoundCRSNNPtr create(const util::PropertyMap &properties, const std::vector<CRSNNPtr> &components); // throw InvalidCompoundCRSException //! @cond Doxygen_Suppress PROJ_INTERNAL static CRSNNPtr createLax(const util::PropertyMap &properties, const std::vector<CRSNNPtr> &components, const io::DatabaseContextPtr &dbContext); // throw InvalidCompoundCRSException //! @endcond protected: // relaxed: standard say SingleCRSNNPtr PROJ_INTERNAL explicit CompoundCRS(const std::vector<CRSNNPtr> &components); PROJ_INTERNAL CompoundCRS(const CompoundCRS &other); PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA CompoundCRS &operator=(const CompoundCRS &other) = delete; }; // --------------------------------------------------------------------------- /** \brief A coordinate reference system with an associated transformation to * a target/hub CRS. * * The definition of a CRS is not dependent upon any relationship to an * independent CRS. However in an implementation that merges datasets * referenced to differing CRSs, it is sometimes useful to associate the * definition of the transformation that has been used with the CRS definition. * This facilitates the interrelationship of CRS by concatenating * transformations via a common or hub CRS. This is sometimes referred to as * "early-binding". \ref WKT2 permits the association of an abridged coordinate * transformation description with a coordinate reference system description in * a single text string. In a BoundCRS, the abridged coordinate transformation * is applied to the source CRS with the target CRS being the common or hub * system. * * Coordinates referring to a BoundCRS are expressed into its source/base CRS. * * This abstraction can for example model the concept of TOWGS84 datum shift * present in \ref WKT1. * * \note Contrary to other CRS classes of this package, there is no * \ref ISO_19111_2019 modelling of a BoundCRS. * * \remark Implements BoundCRS from \ref WKT2 */ class PROJ_GCC_DLL BoundCRS final : public CRS, public io::IPROJStringExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~BoundCRS() override; //! @endcond PROJ_DLL const CRSNNPtr &baseCRS() PROJ_PURE_DECL; PROJ_DLL CRSNNPtr baseCRSWithCanonicalBoundCRS() const; PROJ_DLL const CRSNNPtr &hubCRS() PROJ_PURE_DECL; PROJ_DLL const operation::TransformationNNPtr & transformation() PROJ_PURE_DECL; //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) //! @endcond PROJ_DLL static BoundCRSNNPtr create(const util::PropertyMap &properties, const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn); PROJ_DLL static BoundCRSNNPtr create(const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn); PROJ_DLL static BoundCRSNNPtr createFromTOWGS84(const CRSNNPtr &baseCRSIn, const std::vector<double> &TOWGS84Parameters); PROJ_DLL static BoundCRSNNPtr createFromNadgrids(const CRSNNPtr &baseCRSIn, const std::string &filename); protected: PROJ_INTERNAL BoundCRS(const CRSNNPtr &baseCRSIn, const CRSNNPtr &hubCRSIn, const operation::TransformationNNPtr &transformationIn); PROJ_INTERNAL BoundCRS(const BoundCRS &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL BoundCRSNNPtr shallowCloneAsBoundCRS() const; PROJ_INTERNAL bool isTOWGS84Compatible() const; PROJ_INTERNAL std::string getHDatumPROJ4GRIDS() const; PROJ_INTERNAL std::string getVDatumPROJ4GRIDS(const crs::GeographicCRS *geogCRSOfCompoundCRS, const char **outGeoidCRSValue) const; PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA BoundCRS &operator=(const BoundCRS &other) = delete; }; // --------------------------------------------------------------------------- class DerivedGeodeticCRS; /** Shared pointer of DerivedGeodeticCRS */ using DerivedGeodeticCRSPtr = std::shared_ptr<DerivedGeodeticCRS>; /** Non-null shared pointer of DerivedGeodeticCRS */ using DerivedGeodeticCRSNNPtr = util::nn<DerivedGeodeticCRSPtr>; /** \brief A derived coordinate reference system which has either a geodetic * or a geographic coordinate reference system as its base CRS, thereby * inheriting a geodetic reference frame, and associated with a 3D Cartesian * or spherical coordinate system. * * \remark Implements DerivedGeodeticCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DerivedGeodeticCRS final : public GeodeticCRS, public DerivedCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~DerivedGeodeticCRS() override; //! @endcond PROJ_DLL const GeodeticCRSNNPtr baseCRS() const; PROJ_DLL static DerivedGeodeticCRSNNPtr create(const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn); PROJ_DLL static DerivedGeodeticCRSNNPtr create(const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::SphericalCSNNPtr &csIn); //! @cond Doxygen_Suppress void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override { return DerivedCRS::_exportToJSON(formatter); } //! @endcond protected: PROJ_INTERNAL DerivedGeodeticCRS(const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CartesianCSNNPtr &csIn); PROJ_INTERNAL DerivedGeodeticCRS(const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::SphericalCSNNPtr &csIn); PROJ_INTERNAL DerivedGeodeticCRS(const DerivedGeodeticCRS &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; // cppcheck-suppress functionStatic PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL const char *className() const override { return "DerivedGeodeticCRS"; } INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA DerivedGeodeticCRS &operator=(const DerivedGeodeticCRS &other) = delete; }; // --------------------------------------------------------------------------- class DerivedGeographicCRS; /** Shared pointer of DerivedGeographicCRS */ using DerivedGeographicCRSPtr = std::shared_ptr<DerivedGeographicCRS>; /** Non-null shared pointer of DerivedGeographicCRS */ using DerivedGeographicCRSNNPtr = util::nn<DerivedGeographicCRSPtr>; /** \brief A derived coordinate reference system which has either a geodetic or * a geographic coordinate reference system as its base CRS, thereby inheriting * a geodetic reference frame, and an ellipsoidal coordinate system. * * A derived geographic CRS can be based on a geodetic CRS only if that * geodetic CRS definition includes an ellipsoid. * * \remark Implements DerivedGeographicCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DerivedGeographicCRS final : public GeographicCRS, public DerivedCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~DerivedGeographicCRS() override; //! @endcond PROJ_DLL const GeodeticCRSNNPtr baseCRS() const; PROJ_DLL static DerivedGeographicCRSNNPtr create(const util::PropertyMap &properties, const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::EllipsoidalCSNNPtr &csIn); PROJ_DLL DerivedGeographicCRSNNPtr demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override { return DerivedCRS::_exportToJSON(formatter); } //! @endcond protected: PROJ_INTERNAL DerivedGeographicCRS(const GeodeticCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::EllipsoidalCSNNPtr &csIn); PROJ_INTERNAL DerivedGeographicCRS(const DerivedGeographicCRS &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; PROJ_INTERNAL const char *className() const override { return "DerivedGeographicCRS"; } // cppcheck-suppress functionStatic PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA DerivedGeographicCRS &operator=(const DerivedGeographicCRS &other) = delete; }; // --------------------------------------------------------------------------- class DerivedProjectedCRS; /** Shared pointer of DerivedProjectedCRS */ using DerivedProjectedCRSPtr = std::shared_ptr<DerivedProjectedCRS>; /** Non-null shared pointer of DerivedProjectedCRS */ using DerivedProjectedCRSNNPtr = util::nn<DerivedProjectedCRSPtr>; /** \brief A derived coordinate reference system which has a projected * coordinate reference system as its base CRS, thereby inheriting a geodetic * reference frame, but also inheriting the distortion characteristics of the * base projected CRS. * * A DerivedProjectedCRS is not a ProjectedCRS. * * \remark Implements DerivedProjectedCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DerivedProjectedCRS final : public DerivedCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~DerivedProjectedCRS() override; //! @endcond PROJ_DLL const ProjectedCRSNNPtr baseCRS() const; PROJ_DLL static DerivedProjectedCRSNNPtr create(const util::PropertyMap &properties, const ProjectedCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CoordinateSystemNNPtr &csIn); PROJ_DLL DerivedProjectedCRSNNPtr demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void addUnitConvertAndAxisSwap(io::PROJStringFormatter *formatter) const; //! @endcond protected: PROJ_INTERNAL DerivedProjectedCRS(const ProjectedCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::CoordinateSystemNNPtr &csIn); PROJ_INTERNAL DerivedProjectedCRS(const DerivedProjectedCRS &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL const char *className() const override { return "DerivedProjectedCRS"; } INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA DerivedProjectedCRS &operator=(const DerivedProjectedCRS &other) = delete; }; // --------------------------------------------------------------------------- class DerivedVerticalCRS; /** Shared pointer of DerivedVerticalCRS */ using DerivedVerticalCRSPtr = std::shared_ptr<DerivedVerticalCRS>; /** Non-null shared pointer of DerivedVerticalCRS */ using DerivedVerticalCRSNNPtr = util::nn<DerivedVerticalCRSPtr>; /** \brief A derived coordinate reference system which has a vertical * coordinate reference system as its base CRS, thereby inheriting a vertical * reference frame, and a vertical coordinate system. * * \remark Implements DerivedVerticalCRS from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DerivedVerticalCRS final : public VerticalCRS, public DerivedCRS { public: //! @cond Doxygen_Suppress PROJ_DLL ~DerivedVerticalCRS() override; //! @endcond PROJ_DLL const VerticalCRSNNPtr baseCRS() const; PROJ_DLL static DerivedVerticalCRSNNPtr create(const util::PropertyMap &properties, const VerticalCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::VerticalCSNNPtr &csIn); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override { return DerivedCRS::_exportToJSON(formatter); } //! @endcond protected: PROJ_INTERNAL DerivedVerticalCRS(const VerticalCRSNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const cs::VerticalCSNNPtr &csIn); PROJ_INTERNAL DerivedVerticalCRS(const DerivedVerticalCRS &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL std::list<std::pair<CRSNNPtr, int>> _identify(const io::AuthorityFactoryPtr &authorityFactory) const override; PROJ_INTERNAL const char *className() const override { return "DerivedVerticalCRS"; } // cppcheck-suppress functionStatic PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA DerivedVerticalCRS &operator=(const DerivedVerticalCRS &other) = delete; }; // --------------------------------------------------------------------------- /** \brief Template representing a derived coordinate reference system. */ template <class DerivedCRSTraits> class PROJ_GCC_DLL DerivedCRSTemplate final : public DerivedCRSTraits::BaseType, public DerivedCRS { protected: /** Base type */ typedef typename DerivedCRSTraits::BaseType BaseType; /** CSType */ typedef typename DerivedCRSTraits::CSType CSType; public: //! @cond Doxygen_Suppress PROJ_DLL ~DerivedCRSTemplate() override; //! @endcond /** Non-null shared pointer of DerivedCRSTemplate */ typedef typename util::nn<std::shared_ptr<DerivedCRSTemplate>> NNPtr; /** Non-null shared pointer of BaseType */ typedef util::nn<std::shared_ptr<BaseType>> BaseNNPtr; /** Non-null shared pointer of CSType */ typedef util::nn<std::shared_ptr<CSType>> CSNNPtr; /** \brief Return the base CRS of a DerivedCRSTemplate. * * @return the base CRS. */ PROJ_DLL const BaseNNPtr baseCRS() const; /** \brief Instantiate a DerivedCRSTemplate from a base CRS, a deriving * conversion and a cs::CoordinateSystem. * * @param properties See \ref general_properties. * At minimum the name should be defined. * @param baseCRSIn base CRS. * @param derivingConversionIn the deriving conversion from the base CRS to * this * CRS. * @param csIn the coordinate system. * @return new DerivedCRSTemplate. */ PROJ_DLL static NNPtr create(const util::PropertyMap &properties, const BaseNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const CSNNPtr &csIn); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override { return DerivedCRS::_exportToJSON(formatter); } //! @endcond protected: PROJ_INTERNAL DerivedCRSTemplate(const BaseNNPtr &baseCRSIn, const operation::ConversionNNPtr &derivingConversionIn, const CSNNPtr &csIn); // cppcheck-suppress noExplicitConstructor PROJ_INTERNAL DerivedCRSTemplate(const DerivedCRSTemplate &other); PROJ_INTERNAL CRSNNPtr _shallowClone() const override; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL const char *className() const override; INLINED_MAKE_SHARED private: struct PROJ_INTERNAL Private; std::unique_ptr<Private> d; DerivedCRSTemplate &operator=(const DerivedCRSTemplate &other) = delete; }; // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PROJ_GCC_DLL DerivedEngineeringCRSTraits { typedef EngineeringCRS BaseType; typedef cs::CoordinateSystem CSType; // old x86_64-w64-mingw32-g++ has issues with static variables. use method // instead inline static const std::string &CRSName(); inline static const std::string &WKTKeyword(); inline static const std::string &WKTBaseKeyword(); static const bool wkt2_2019_only = true; }; //! @endcond /** \brief A derived coordinate reference system which has an engineering * coordinate reference system as its base CRS, thereby inheriting an * engineering datum, and is associated with one of the coordinate system * types for an EngineeringCRS * * \remark Implements DerivedEngineeringCRS from \ref ISO_19111_2019 */ #ifdef DOXYGEN_ENABLED class DerivedEngineeringCRS : public DerivedCRSTemplate<DerivedEngineeringCRSTraits> {}; #else using DerivedEngineeringCRS = DerivedCRSTemplate<DerivedEngineeringCRSTraits>; #endif #ifndef DO_NOT_DEFINE_EXTERN_DERIVED_CRS_TEMPLATE extern template class DerivedCRSTemplate<DerivedEngineeringCRSTraits>; #endif /** Shared pointer of DerivedEngineeringCRS */ using DerivedEngineeringCRSPtr = std::shared_ptr<DerivedEngineeringCRS>; /** Non-null shared pointer of DerivedEngineeringCRS */ using DerivedEngineeringCRSNNPtr = util::nn<DerivedEngineeringCRSPtr>; // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PROJ_GCC_DLL DerivedParametricCRSTraits { typedef ParametricCRS BaseType; typedef cs::ParametricCS CSType; // old x86_64-w64-mingw32-g++ has issues with static variables. use method // instead inline static const std::string &CRSName(); inline static const std::string &WKTKeyword(); inline static const std::string &WKTBaseKeyword(); static const bool wkt2_2019_only = false; }; //! @endcond /** \brief A derived coordinate reference system which has a parametric * coordinate reference system as its base CRS, thereby inheriting a parametric * datum, and a parametric coordinate system. * * \remark Implements DerivedParametricCRS from \ref ISO_19111_2019 */ #ifdef DOXYGEN_ENABLED class DerivedParametricCRS : public DerivedCRSTemplate<DerivedParametricCRSTraits> {}; #else using DerivedParametricCRS = DerivedCRSTemplate<DerivedParametricCRSTraits>; #endif #ifndef DO_NOT_DEFINE_EXTERN_DERIVED_CRS_TEMPLATE extern template class DerivedCRSTemplate<DerivedParametricCRSTraits>; #endif /** Shared pointer of DerivedParametricCRS */ using DerivedParametricCRSPtr = std::shared_ptr<DerivedParametricCRS>; /** Non-null shared pointer of DerivedParametricCRS */ using DerivedParametricCRSNNPtr = util::nn<DerivedParametricCRSPtr>; // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct PROJ_GCC_DLL DerivedTemporalCRSTraits { typedef TemporalCRS BaseType; typedef cs::TemporalCS CSType; // old x86_64-w64-mingw32-g++ has issues with static variables. use method // instead inline static const std::string &CRSName(); inline static const std::string &WKTKeyword(); inline static const std::string &WKTBaseKeyword(); static const bool wkt2_2019_only = false; }; //! @endcond /** \brief A derived coordinate reference system which has a temporal * coordinate reference system as its base CRS, thereby inheriting a temporal * datum, and a temporal coordinate system. * * \remark Implements DerivedTemporalCRS from \ref ISO_19111_2019 */ #ifdef DOXYGEN_ENABLED class DerivedTemporalCRS : public DerivedCRSTemplate<DerivedTemporalCRSTraits> { }; #else using DerivedTemporalCRS = DerivedCRSTemplate<DerivedTemporalCRSTraits>; #endif #ifndef DO_NOT_DEFINE_EXTERN_DERIVED_CRS_TEMPLATE extern template class DerivedCRSTemplate<DerivedTemporalCRSTraits>; #endif /** Shared pointer of DerivedTemporalCRS */ using DerivedTemporalCRSPtr = std::shared_ptr<DerivedTemporalCRS>; /** Non-null shared pointer of DerivedTemporalCRS */ using DerivedTemporalCRSNNPtr = util::nn<DerivedTemporalCRSPtr>; // --------------------------------------------------------------------------- } // namespace crs NS_PROJ_END #endif // CRS_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/coordinateoperation.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef COORDINATEOPERATION_HH_INCLUDED #define COORDINATEOPERATION_HH_INCLUDED #include <memory> #include <string> #include <utility> #include <vector> #include "common.hpp" #include "io.hpp" #include "metadata.hpp" #include "proj.h" NS_PROJ_START namespace crs { class CRS; using CRSPtr = std::shared_ptr<CRS>; using CRSNNPtr = util::nn<CRSPtr>; class DerivedCRS; class ProjectedCRS; } // namespace crs namespace io { class JSONParser; } // namespace io namespace coordinates { class CoordinateMetadata; using CoordinateMetadataPtr = std::shared_ptr<CoordinateMetadata>; using CoordinateMetadataNNPtr = util::nn<CoordinateMetadataPtr>; } // namespace coordinates /** osgeo.proj.operation namespace \brief Coordinate operations (relationship between any two coordinate reference systems). This covers Conversion, Transformation, PointMotionOperation or ConcatenatedOperation. */ namespace operation { // --------------------------------------------------------------------------- /** \brief Grid description */ struct GridDescription { std::string shortName; /**< Grid short filename */ std::string fullName; /**< Grid full path name (if found) */ std::string packageName; /**< Package name (or empty) */ std::string url; /**< Grid URL (if packageName is empty), or package URL (or empty) */ bool directDownload; /**< Whether url can be fetched directly. */ /** Whether the grid is released with an open license. */ bool openLicense; bool available; /**< Whether GRID is available. */ //! @cond Doxygen_Suppress bool operator<(const GridDescription &other) const { return shortName < other.shortName; } PROJ_DLL GridDescription(); PROJ_DLL ~GridDescription(); PROJ_DLL GridDescription(const GridDescription &); PROJ_DLL GridDescription(GridDescription &&) noexcept; //! @endcond }; // --------------------------------------------------------------------------- class CoordinateOperation; /** Shared pointer of CoordinateOperation */ using CoordinateOperationPtr = std::shared_ptr<CoordinateOperation>; /** Non-null shared pointer of CoordinateOperation */ using CoordinateOperationNNPtr = util::nn<CoordinateOperationPtr>; // --------------------------------------------------------------------------- class CoordinateTransformer; /** Shared pointer of CoordinateTransformer */ using CoordinateTransformerPtr = std::unique_ptr<CoordinateTransformer>; /** Non-null shared pointer of CoordinateTransformer */ using CoordinateTransformerNNPtr = util::nn<CoordinateTransformerPtr>; /** \brief Coordinate transformer. * * Performs coordinate transformation of coordinate tuplies. * * @since 9.3 */ class PROJ_GCC_DLL CoordinateTransformer { public: //! @cond Doxygen_Suppress PROJ_DLL ~CoordinateTransformer(); //! @endcond PROJ_DLL PJ_COORD transform(PJ_COORD coord); protected: PROJ_FRIEND(CoordinateOperation); PROJ_INTERNAL CoordinateTransformer(); PROJ_INTERNAL static CoordinateTransformerNNPtr create(const CoordinateOperationNNPtr &op, PJ_CONTEXT *ctx); private: PROJ_OPAQUE_PRIVATE_DATA INLINED_MAKE_UNIQUE CoordinateTransformer & operator=(const CoordinateTransformer &other) = delete; }; // --------------------------------------------------------------------------- class Transformation; /** Shared pointer of Transformation */ using TransformationPtr = std::shared_ptr<Transformation>; /** Non-null shared pointer of Transformation */ using TransformationNNPtr = util::nn<TransformationPtr>; /** \brief Abstract class for a mathematical operation on coordinates. * * A mathematical operation: * <ul> * <li>on coordinates that transforms or converts them from one coordinate * reference system to another coordinate reference system</li> * <li>or that describes the change of coordinate values within one coordinate * reference system due to the motion of the point between one coordinate epoch * and another coordinate epoch.</li> * </ul> * Many but not all coordinate operations (from CRS A to CRS B) also uniquely * define the inverse coordinate operation (from CRS B to CRS A). In some cases, * the coordinate operation method algorithm for the inverse coordinate * operation is the same as for the forward algorithm, but the signs of some * coordinate operation parameter values have to be reversed. In other cases, * different algorithms are required for the forward and inverse coordinate * operations, but the same coordinate operation parameter values are used. If * (some) entirely different parameter values are needed, a different coordinate * operation shall be defined. * * \remark Implements CoordinateOperation from \ref ISO_19111_2019 */ class PROJ_GCC_DLL CoordinateOperation : public common::ObjectUsage, public io::IPROJStringExportable, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~CoordinateOperation() override; //! @endcond PROJ_DLL const util::optional<std::string> &operationVersion() const; PROJ_DLL const std::vector<metadata::PositionalAccuracyNNPtr> & coordinateOperationAccuracies() const; PROJ_DLL const crs::CRSPtr sourceCRS() const; PROJ_DLL const crs::CRSPtr targetCRS() const; PROJ_DLL const crs::CRSPtr &interpolationCRS() const; PROJ_DLL const util::optional<common::DataEpoch> & sourceCoordinateEpoch() const; PROJ_DLL const util::optional<common::DataEpoch> & targetCoordinateEpoch() const; PROJ_DLL CoordinateTransformerNNPtr coordinateTransformer(PJ_CONTEXT *ctx) const; /** \brief Return the inverse of the coordinate operation. * @throw util::UnsupportedOperationException */ PROJ_DLL virtual CoordinateOperationNNPtr inverse() const = 0; /** \brief Return grids needed by an operation. */ PROJ_DLL virtual std::set<GridDescription> gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const = 0; PROJ_DLL bool isPROJInstantiable(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const; PROJ_DLL bool hasBallparkTransformation() const; PROJ_DLL static const std::string OPERATION_VERSION_KEY; PROJ_DLL CoordinateOperationNNPtr normalizeForVisualization() const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_FOR_TEST CoordinateOperationNNPtr shallowClone() const; //! @endcond protected: PROJ_INTERNAL CoordinateOperation(); PROJ_INTERNAL CoordinateOperation(const CoordinateOperation &other); PROJ_FRIEND(crs::DerivedCRS); PROJ_FRIEND(io::AuthorityFactory); PROJ_FRIEND(CoordinateOperationFactory); PROJ_FRIEND(ConcatenatedOperation); PROJ_FRIEND(io::WKTParser); PROJ_FRIEND(io::JSONParser); PROJ_INTERNAL void setWeakSourceTargetCRS(std::weak_ptr<crs::CRS> sourceCRSIn, std::weak_ptr<crs::CRS> targetCRSIn); PROJ_INTERNAL void setCRSs(const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn); PROJ_INTERNAL void setInterpolationCRS(const crs::CRSPtr &interpolationCRSIn); PROJ_INTERNAL void setCRSs(const CoordinateOperation *in, bool inverseSourceTarget); PROJ_INTERNAL void setAccuracies( const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_INTERNAL void setHasBallparkTransformation(bool b); PROJ_INTERNAL void setSourceCoordinateEpoch(const util::optional<common::DataEpoch> &epoch); PROJ_INTERNAL void setTargetCoordinateEpoch(const util::optional<common::DataEpoch> &epoch); PROJ_INTERNAL void setProperties(const util::PropertyMap &properties); // throw(InvalidValueTypeException) PROJ_INTERNAL virtual CoordinateOperationNNPtr _shallowClone() const = 0; private: PROJ_OPAQUE_PRIVATE_DATA CoordinateOperation &operator=(const CoordinateOperation &other) = delete; }; // --------------------------------------------------------------------------- /** \brief Abstract class modelling a parameter value (OperationParameter) * or group of parameters. * * \remark Implements GeneralOperationParameter from \ref ISO_19111_2019 */ class PROJ_GCC_DLL GeneralOperationParameter : public common::IdentifiedObject { public: //! @cond Doxygen_Suppress PROJ_DLL ~GeneralOperationParameter() override; //! @endcond //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override = 0; //! @endcond protected: PROJ_INTERNAL GeneralOperationParameter(); PROJ_INTERNAL GeneralOperationParameter(const GeneralOperationParameter &other); private: PROJ_OPAQUE_PRIVATE_DATA GeneralOperationParameter & operator=(const GeneralOperationParameter &other) = delete; }; /** Shared pointer of GeneralOperationParameter */ using GeneralOperationParameterPtr = std::shared_ptr<GeneralOperationParameter>; /** Non-null shared pointer of GeneralOperationParameter */ using GeneralOperationParameterNNPtr = util::nn<GeneralOperationParameterPtr>; // --------------------------------------------------------------------------- class OperationParameter; /** Shared pointer of OperationParameter */ using OperationParameterPtr = std::shared_ptr<OperationParameter>; /** Non-null shared pointer of OperationParameter */ using OperationParameterNNPtr = util::nn<OperationParameterPtr>; /** \brief The definition of a parameter used by a coordinate operation method. * * Most parameter values are numeric, but other types of parameter values are * possible. * * \remark Implements OperationParameter from \ref ISO_19111_2019 */ class PROJ_GCC_DLL OperationParameter final : public GeneralOperationParameter { public: //! @cond Doxygen_Suppress PROJ_DLL ~OperationParameter() override; //! @endcond //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond // non-standard PROJ_DLL static OperationParameterNNPtr create(const util::PropertyMap &properties); PROJ_DLL int getEPSGCode() PROJ_PURE_DECL; PROJ_DLL static const char *getNameForEPSGCode(int epsg_code) noexcept; protected: PROJ_INTERNAL OperationParameter(); PROJ_INTERNAL OperationParameter(const OperationParameter &other); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA OperationParameter &operator=(const OperationParameter &other) = delete; // cppcheck-suppress functionStatic PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) }; // --------------------------------------------------------------------------- //! @cond Doxygen_Suppress struct MethodMapping; //! @endcond /** \brief Abstract class modelling a parameter value (OperationParameterValue) * or group of parameter values. * * \remark Implements GeneralParameterValue from \ref ISO_19111_2019 */ class PROJ_GCC_DLL GeneralParameterValue : public util::BaseObject, public io::IWKTExportable, public io::IJSONExportable, public util::IComparable { public: //! @cond Doxygen_Suppress PROJ_DLL ~GeneralParameterValue() override; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override = 0; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override = 0; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override = 0; //! @endcond protected: //! @cond Doxygen_Suppress PROJ_INTERNAL GeneralParameterValue(); PROJ_INTERNAL GeneralParameterValue(const GeneralParameterValue &other); friend class Conversion; friend class SingleOperation; friend class PointMotionOperation; PROJ_INTERNAL virtual void _exportToWKT(io::WKTFormatter *formatter, const MethodMapping *mapping) const = 0; // throw(io::FormattingException) //! @endcond private: PROJ_OPAQUE_PRIVATE_DATA GeneralParameterValue & operator=(const GeneralParameterValue &other) = delete; }; /** Shared pointer of GeneralParameterValue */ using GeneralParameterValuePtr = std::shared_ptr<GeneralParameterValue>; /** Non-null shared pointer of GeneralParameterValue */ using GeneralParameterValueNNPtr = util::nn<GeneralParameterValuePtr>; // --------------------------------------------------------------------------- class ParameterValue; /** Shared pointer of ParameterValue */ using ParameterValuePtr = std::shared_ptr<ParameterValue>; /** Non-null shared pointer of ParameterValue */ using ParameterValueNNPtr = util::nn<ParameterValuePtr>; /** \brief The value of the coordinate operation parameter. * * Most parameter values are numeric, but other types of parameter values are * possible. * * \remark Implements ParameterValue from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ParameterValue final : public util::BaseObject, public io::IWKTExportable, public util::IComparable { public: /** Type of the value. */ enum class Type { /** Measure (i.e. value with a unit) */ MEASURE, /** String */ STRING, /** Integer */ INTEGER, /** Boolean */ BOOLEAN, /** Filename */ FILENAME }; //! @cond Doxygen_Suppress PROJ_DLL ~ParameterValue() override; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) //! @endcond PROJ_DLL static ParameterValueNNPtr create(const common::Measure &measureIn); PROJ_DLL static ParameterValueNNPtr create(const char *stringValueIn); PROJ_DLL static ParameterValueNNPtr create(const std::string &stringValueIn); PROJ_DLL static ParameterValueNNPtr create(int integerValueIn); PROJ_DLL static ParameterValueNNPtr create(bool booleanValueIn); PROJ_DLL static ParameterValueNNPtr createFilename(const std::string &stringValueIn); PROJ_DLL const Type &type() PROJ_PURE_DECL; PROJ_DLL const common::Measure &value() PROJ_PURE_DECL; PROJ_DLL const std::string &stringValue() PROJ_PURE_DECL; PROJ_DLL const std::string &valueFile() PROJ_PURE_DECL; PROJ_DLL int integerValue() PROJ_PURE_DECL; PROJ_DLL bool booleanValue() PROJ_PURE_DECL; //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL explicit ParameterValue(const common::Measure &measureIn); PROJ_INTERNAL explicit ParameterValue(const std::string &stringValueIn, Type typeIn); PROJ_INTERNAL explicit ParameterValue(int integerValueIn); PROJ_INTERNAL explicit ParameterValue(bool booleanValueIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA ParameterValue &operator=(const ParameterValue &other) = delete; }; // --------------------------------------------------------------------------- class OperationParameterValue; /** Shared pointer of OperationParameterValue */ using OperationParameterValuePtr = std::shared_ptr<OperationParameterValue>; /** Non-null shared pointer of OperationParameterValue */ using OperationParameterValueNNPtr = util::nn<OperationParameterValuePtr>; /** \brief A parameter value, ordered sequence of values, or reference to a * file of parameter values. * * This combines a OperationParameter with the corresponding ParameterValue. * * \remark Implements OperationParameterValue from \ref ISO_19111_2019 */ class PROJ_GCC_DLL OperationParameterValue final : public GeneralParameterValue { public: //! @cond Doxygen_Suppress PROJ_DLL ~OperationParameterValue() override; //! @endcond PROJ_DLL const OperationParameterNNPtr &parameter() PROJ_PURE_DECL; PROJ_DLL const ParameterValueNNPtr &parameterValue() PROJ_PURE_DECL; PROJ_DLL static OperationParameterValueNNPtr create(const OperationParameterNNPtr &parameterIn, const ParameterValueNNPtr &valueIn); PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL static bool convertFromAbridged(const std::string &paramName, double &val, const common::UnitOfMeasure *&unit, int &paramEPSGCode); PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL OperationParameterValue(const OperationParameterNNPtr &parameterIn, const ParameterValueNNPtr &valueIn); PROJ_INTERNAL OperationParameterValue(const OperationParameterValue &other); INLINED_MAKE_SHARED PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter, const MethodMapping *mapping) const override; // throw(io::FormattingException) private: PROJ_OPAQUE_PRIVATE_DATA OperationParameterValue & operator=(const OperationParameterValue &other) = delete; }; // --------------------------------------------------------------------------- class OperationMethod; /** Shared pointer of OperationMethod */ using OperationMethodPtr = std::shared_ptr<OperationMethod>; /** Non-null shared pointer of OperationMethod */ using OperationMethodNNPtr = util::nn<OperationMethodPtr>; /** \brief The method (algorithm or procedure) used to perform the * coordinate operation. * * For a projection method, this contains the name of the projection method * and the name of the projection parameters. * * \remark Implements OperationMethod from \ref ISO_19111_2019 */ class PROJ_GCC_DLL OperationMethod : public common::IdentifiedObject, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~OperationMethod() override; //! @endcond PROJ_DLL const util::optional<std::string> &formula() PROJ_PURE_DECL; PROJ_DLL const util::optional<metadata::Citation> & formulaCitation() PROJ_PURE_DECL; PROJ_DLL const std::vector<GeneralOperationParameterNNPtr> & parameters() PROJ_PURE_DECL; PROJ_DLL static OperationMethodNNPtr create(const util::PropertyMap &properties, const std::vector<GeneralOperationParameterNNPtr> &parameters); PROJ_DLL static OperationMethodNNPtr create(const util::PropertyMap &properties, const std::vector<OperationParameterNNPtr> &parameters); PROJ_DLL int getEPSGCode() PROJ_PURE_DECL; //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL OperationMethod(); PROJ_INTERNAL OperationMethod(const OperationMethod &other); INLINED_MAKE_SHARED friend class Conversion; private: PROJ_OPAQUE_PRIVATE_DATA OperationMethod &operator=(const OperationMethod &other) = delete; }; // --------------------------------------------------------------------------- /** \brief Exception that can be thrown when an invalid operation is attempted * to be constructed. */ class PROJ_GCC_DLL InvalidOperation : public util::Exception { public: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit InvalidOperation(const char *message); PROJ_INTERNAL explicit InvalidOperation(const std::string &message); PROJ_DLL InvalidOperation(const InvalidOperation &other); PROJ_DLL ~InvalidOperation() override; //! @endcond }; // --------------------------------------------------------------------------- class SingleOperation; /** Shared pointer of SingleOperation */ using SingleOperationPtr = std::shared_ptr<SingleOperation>; /** Non-null shared pointer of SingleOperation */ using SingleOperationNNPtr = util::nn<SingleOperationPtr>; /** \brief A single (not concatenated) coordinate operation * (CoordinateOperation) * * \remark Implements SingleOperation from \ref ISO_19111_2019 */ class PROJ_GCC_DLL SingleOperation : virtual public CoordinateOperation { public: //! @cond Doxygen_Suppress PROJ_DLL ~SingleOperation() override; //! @endcond PROJ_DLL const std::vector<GeneralParameterValueNNPtr> & parameterValues() PROJ_PURE_DECL; PROJ_DLL const OperationMethodNNPtr &method() PROJ_PURE_DECL; PROJ_DLL const ParameterValuePtr & parameterValue(const std::string &paramName, int epsg_code = 0) const noexcept; PROJ_DLL const ParameterValuePtr & parameterValue(int epsg_code) const noexcept; PROJ_DLL const common::Measure & parameterValueMeasure(const std::string &paramName, int epsg_code = 0) const noexcept; PROJ_DLL const common::Measure & parameterValueMeasure(int epsg_code) const noexcept; PROJ_DLL static SingleOperationNNPtr createPROJBased( const util::PropertyMap &properties, const std::string &PROJString, const crs::CRSPtr &sourceCRS, const crs::CRSPtr &targetCRS, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies = std::vector<metadata::PositionalAccuracyNNPtr>()); PROJ_DLL std::set<GridDescription> gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const override; PROJ_DLL std::list<std::string> validateParameters() const; PROJ_DLL TransformationNNPtr substitutePROJAlternativeGridNames( io::DatabaseContextNNPtr databaseContext) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_DLL double parameterValueNumeric( int epsg_code, const common::UnitOfMeasure &targetUnit) const noexcept; PROJ_INTERNAL double parameterValueNumeric( const char *param_name, const common::UnitOfMeasure &targetUnit) const noexcept; PROJ_INTERNAL double parameterValueNumericAsSI(int epsg_code) const noexcept; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL bool isLongitudeRotation() const; //! @endcond protected: PROJ_INTERNAL explicit SingleOperation( const OperationMethodNNPtr &methodIn); PROJ_INTERNAL SingleOperation(const SingleOperation &other); PROJ_INTERNAL void setParameterValues(const std::vector<GeneralParameterValueNNPtr> &values); PROJ_INTERNAL void exportTransformationToWKT(io::WKTFormatter *formatter) const; PROJ_INTERNAL bool exportToPROJStringGeneric(io::PROJStringFormatter *formatter) const; PROJ_INTERNAL bool _isEquivalentTo(const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext, bool inOtherDirection) const; PROJ_INTERNAL static GeneralParameterValueNNPtr createOperationParameterValueFromInterpolationCRS(int methodEPSGCode, int crsEPSGCode); PROJ_INTERNAL static void exportToPROJStringChangeVerticalUnit(io::PROJStringFormatter *formatter, double convFactor); private: PROJ_OPAQUE_PRIVATE_DATA SingleOperation &operator=(const SingleOperation &other) = delete; }; // --------------------------------------------------------------------------- class Conversion; /** Shared pointer of Conversion */ using ConversionPtr = std::shared_ptr<Conversion>; /** Non-null shared pointer of Conversion */ using ConversionNNPtr = util::nn<ConversionPtr>; /** \brief A mathematical operation on coordinates in which the parameter * values are defined rather than empirically derived. * * Application of the coordinate conversion introduces no error into output * coordinates. The best-known example of a coordinate conversion is a map * projection. For coordinate conversions the output coordinates are referenced * to the same datum as are the input coordinates. * * Coordinate conversions forming a component of a derived CRS have a source * crs::CRS and a target crs::CRS that are NOT specified through the source and * target * associations, but through associations from crs::DerivedCRS to * crs::SingleCRS. * * \remark Implements Conversion from \ref ISO_19111_2019 */ /*! \section projection_parameters Projection parameters \subsection colatitude_cone_axis Co-latitude of cone axis The rotation applied to spherical coordinates for the oblique projection, measured on the conformal sphere in the plane of the meridian of origin. EPSG:1036 \subsection center_latitude Latitude of natural origin/Center Latitude The latitude of the point from which the values of both the geographical coordinates on the ellipsoid and the grid coordinates on the projection are deemed to increment or decrement for computational purposes. Alternatively it may be considered as the latitude of the point which in the absence of application of false coordinates has grid coordinates of (0,0). EPSG:8801 \subsection center_longitude Longitude of natural origin/Central Meridian The longitude of the point from which the values of both the geographical coordinates on the ellipsoid and the grid coordinates on the projection are deemed to increment or decrement for computational purposes. Alternatively it may be considered as the longitude of the point which in the absence of application of false coordinates has grid coordinates of (0,0). Sometimes known as "central meridian (CM)". EPSG:8802 \subsection scale Scale Factor The factor by which the map grid is reduced or enlarged during the projection process, defined by its value at the natural origin. EPSG:8805 \subsection false_easting False Easting Since the natural origin may be at or near the centre of the projection and under normal coordinate circumstances would thus give rise to negative coordinates over parts of the mapped area, this origin is usually given false coordinates which are large enough to avoid this inconvenience. The False Easting, FE, is the value assigned to the abscissa (east or west) axis of the projection grid at the natural origin. EPSG:8806 \subsection false_northing False Northing Since the natural origin may be at or near the centre of the projection and under normal coordinate circumstances would thus give rise to negative coordinates over parts of the mapped area, this origin is usually given false coordinates which are large enough to avoid this inconvenience. The False Northing, FN, is the value assigned to the ordinate (north or south) axis of the projection grid at the natural origin. EPSG:8807 \subsection latitude_projection_centre Latitude of projection centre For an oblique projection, this is the latitude of the point at which the azimuth of the central line is defined. EPSG:8811 \subsection longitude_projection_centre Longitude of projection centre For an oblique projection, this is the longitude of the point at which the azimuth of the central line is defined. EPSG:8812 \subsection azimuth_initial_line Azimuth of initial line The azimuthal direction (north zero, east of north being positive) of the great circle which is the centre line of an oblique projection. The azimuth is given at the projection centre. EPSG:8813 \subsection angle_from_recitfied_to_skrew_grid Angle from Rectified to Skew Grid The angle at the natural origin of an oblique projection through which the natural coordinate reference system is rotated to make the projection north axis parallel with true north. EPSG:8814 \subsection scale_factor_initial_line Scale factor on initial line The factor by which the map grid is reduced or enlarged during the projection process, defined by its value at the projection center. EPSG:8815 \subsection easting_projection_centre Easting at projection centre The easting value assigned to the projection centre. EPSG:8816 \subsection northing_projection_centre Northing at projection centre The northing value assigned to the projection centre. EPSG:8817 \subsection latitude_pseudo_standard_parallel Latitude of pseudo standard parallel Latitude of the parallel on which the conic or cylindrical projection is based. This latitude is not geographic, but is defined on the conformal sphere AFTER its rotation to obtain the oblique aspect of the projection. EPSG:8818 \subsection scale_factor_pseudo_standard_parallel Scale factor on pseudo standard parallel The factor by which the map grid is reduced or enlarged during the projection process, defined by its value at the pseudo-standard parallel. EPSG:8819 \subsection latitude_false_origin Latitude of false origin The latitude of the point which is not the natural origin and at which grid coordinate values false easting and false northing are defined. EPSG:8821 \subsection longitude_false_origin Longitude of false origin The longitude of the point which is not the natural origin and at which grid coordinate values false easting and false northing are defined. EPSG:8822 \subsection latitude_first_std_parallel Latitude of 1st standard parallel For a conic projection with two standard parallels, this is the latitude of one of the parallels of intersection of the cone with the ellipsoid. It is normally but not necessarily that nearest to the pole. Scale is true along this parallel. EPSG:8823 \subsection latitude_second_std_parallel Latitude of 2nd standard parallel For a conic projection with two standard parallels, this is the latitude of one of the parallels at which the cone intersects with the ellipsoid. It is normally but not necessarily that nearest to the equator. Scale is true along this parallel. EPSG:8824 \subsection easting_false_origin Easting of false origin The easting value assigned to the false origin. EPSG:8826 \subsection northing_false_origin Northing of false origin The northing value assigned to the false origin. EPSG:8827 \subsection latitude_std_parallel Latitude of standard parallel For polar aspect azimuthal projections, the parallel on which the scale factor is defined to be unity. EPSG:8832 \subsection longitude_of_origin Longitude of origin For polar aspect azimuthal projections, the meridian along which the northing axis increments and also across which parallels of latitude increment towards the north pole. EPSG:8833 */ class PROJ_GCC_DLL Conversion : public SingleOperation { public: //! @cond Doxygen_Suppress PROJ_DLL ~Conversion() override; //! @endcond PROJ_DLL CoordinateOperationNNPtr inverse() const override; //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) //! @endcond PROJ_DLL bool isUTM(int &zone, bool &north) const; PROJ_DLL ConversionNNPtr identify() const; PROJ_DLL static ConversionNNPtr create(const util::PropertyMap &properties, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values); // throw InvalidOperation PROJ_DLL static ConversionNNPtr create(const util::PropertyMap &propertiesConversion, const util::PropertyMap &propertiesOperationMethod, const std::vector<OperationParameterNNPtr> &parameters, const std::vector<ParameterValueNNPtr> &values); // throw InvalidOperation PROJ_DLL static ConversionNNPtr createUTM(const util::PropertyMap &properties, int zone, bool north); PROJ_DLL static ConversionNNPtr createTransverseMercator( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createGaussSchreiberTransverseMercator( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createTransverseMercatorSouthOriented( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createTwoPointEquidistant(const util::PropertyMap &properties, const common::Angle &latitudeFirstPoint, const common::Angle &longitudeFirstPoint, const common::Angle &latitudeSecondPoint, const common::Angle &longitudeSeconPoint, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createTunisiaMappingGrid( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createTunisiaMiningGrid( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createAlbersEqualArea(const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin); PROJ_DLL static ConversionNNPtr createLambertConicConformal_1SP( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createLambertConicConformal_1SP_VariantB( const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Scale &scale, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin); PROJ_DLL static ConversionNNPtr createLambertConicConformal_2SP(const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin); PROJ_DLL static ConversionNNPtr createLambertConicConformal_2SP_Michigan( const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin, const common::Scale &ellipsoidScalingFactor); PROJ_DLL static ConversionNNPtr createLambertConicConformal_2SP_Belgium( const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin); PROJ_DLL static ConversionNNPtr createAzimuthalEquidistant(const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createGuamProjection(const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createBonne(const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createLambertCylindricalEqualAreaSpherical( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createLambertCylindricalEqualArea( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createCassiniSoldner( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEquidistantConic(const util::PropertyMap &properties, const common::Angle &latitudeFalseOrigin, const common::Angle &longitudeFalseOrigin, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &eastingFalseOrigin, const common::Length &northingFalseOrigin); PROJ_DLL static ConversionNNPtr createEckertI(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEckertII(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEckertIII(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEckertIV(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEckertV(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEckertVI(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEquidistantCylindrical(const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createEquidistantCylindricalSpherical( const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createGall(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createGoodeHomolosine(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createInterruptedGoodeHomolosine(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createGeostationarySatelliteSweepX( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &height, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createGeostationarySatelliteSweepY( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &height, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createGnomonic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createHotineObliqueMercatorVariantA( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeProjectionCentre, const common::Angle &azimuthInitialLine, const common::Angle &angleFromRectifiedToSkrewGrid, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createHotineObliqueMercatorVariantB( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeProjectionCentre, const common::Angle &azimuthInitialLine, const common::Angle &angleFromRectifiedToSkrewGrid, const common::Scale &scale, const common::Length &eastingProjectionCentre, const common::Length &northingProjectionCentre); PROJ_DLL static ConversionNNPtr createHotineObliqueMercatorTwoPointNaturalOrigin( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &latitudePoint1, const common::Angle &longitudePoint1, const common::Angle &latitudePoint2, const common::Angle &longitudePoint2, const common::Scale &scale, const common::Length &eastingProjectionCentre, const common::Length &northingProjectionCentre); PROJ_DLL static ConversionNNPtr createLabordeObliqueMercator(const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeProjectionCentre, const common::Angle &azimuthInitialLine, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createInternationalMapWorldPolyconic( const util::PropertyMap &properties, const common::Angle &centerLong, const common::Angle &latitudeFirstParallel, const common::Angle &latitudeSecondParallel, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createKrovakNorthOriented( const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeOfOrigin, const common::Angle &colatitudeConeAxis, const common::Angle &latitudePseudoStandardParallel, const common::Scale &scaleFactorPseudoStandardParallel, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createKrovak(const util::PropertyMap &properties, const common::Angle &latitudeProjectionCentre, const common::Angle &longitudeOfOrigin, const common::Angle &colatitudeConeAxis, const common::Angle &latitudePseudoStandardParallel, const common::Scale &scaleFactorPseudoStandardParallel, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createLambertAzimuthalEqualArea(const util::PropertyMap &properties, const common::Angle &latitudeNatOrigin, const common::Angle &longitudeNatOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createMillerCylindrical(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createMercatorVariantA( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createMercatorVariantB(const util::PropertyMap &properties, const common::Angle &latitudeFirstParallel, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createPopularVisualisationPseudoMercator( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createMercatorSpherical( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createMollweide(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createNewZealandMappingGrid( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createObliqueStereographic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createOrthographic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createAmericanPolyconic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createPolarStereographicVariantA( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createPolarStereographicVariantB( const util::PropertyMap &properties, const common::Angle &latitudeStandardParallel, const common::Angle &longitudeOfOrigin, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createRobinson(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createSinusoidal(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createStereographic( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Scale &scale, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createVanDerGrinten(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createWagnerI(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createWagnerII(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createWagnerIII(const util::PropertyMap &properties, const common::Angle &latitudeTrueScale, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createWagnerIV(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createWagnerV(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createWagnerVI(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createWagnerVII(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createQuadrilateralizedSphericalCube( const util::PropertyMap &properties, const common::Angle &centerLat, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createSphericalCrossTrackHeight( const util::PropertyMap &properties, const common::Angle &pegPointLat, const common::Angle &pegPointLong, const common::Angle &pegPointHeading, const common::Length &pegPointHeight); PROJ_DLL static ConversionNNPtr createEqualEarth(const util::PropertyMap &properties, const common::Angle &centerLong, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createVerticalPerspective(const util::PropertyMap &properties, const common::Angle &topoOriginLat, const common::Angle &topoOriginLong, const common::Length &topoOriginHeight, const common::Length &viewPointHeight, const common::Length &falseEasting, const common::Length &falseNorthing); PROJ_DLL static ConversionNNPtr createPoleRotationGRIBConvention( const util::PropertyMap &properties, const common::Angle &southPoleLatInUnrotatedCRS, const common::Angle &southPoleLongInUnrotatedCRS, const common::Angle &axisRotation); PROJ_DLL static ConversionNNPtr createPoleRotationNetCDFCFConvention( const util::PropertyMap &properties, const common::Angle &gridNorthPoleLatitude, const common::Angle &gridNorthPoleLongitude, const common::Angle &northPoleGridLongitude); PROJ_DLL static ConversionNNPtr createChangeVerticalUnit(const util::PropertyMap &properties, const common::Scale &factor); PROJ_DLL static ConversionNNPtr createChangeVerticalUnit(const util::PropertyMap &properties); PROJ_DLL static ConversionNNPtr createHeightDepthReversal(const util::PropertyMap &properties); PROJ_DLL static ConversionNNPtr createAxisOrderReversal(bool is3D); PROJ_DLL static ConversionNNPtr createGeographicGeocentric(const util::PropertyMap &properties); PROJ_DLL static ConversionNNPtr createGeographic2DOffsets(const util::PropertyMap &properties, const common::Angle &offsetLat, const common::Angle &offsetLong); PROJ_DLL static ConversionNNPtr createGeographic3DOffsets( const util::PropertyMap &properties, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight); PROJ_DLL static ConversionNNPtr createGeographic2DWithHeightOffsets( const util::PropertyMap &properties, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight); PROJ_DLL static ConversionNNPtr createVerticalOffset(const util::PropertyMap &properties, const common::Length &offsetHeight); PROJ_DLL ConversionPtr convertToOtherMethod(int targetEPSGCode) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL const char *getESRIMethodName() const; PROJ_INTERNAL const char *getWKT1GDALMethodName() const; PROJ_INTERNAL ConversionNNPtr shallowClone() const; PROJ_INTERNAL ConversionNNPtr alterParametersLinearUnit( const common::UnitOfMeasure &unit, bool convertToNewUnit) const; PROJ_INTERNAL static ConversionNNPtr createGeographicGeocentric(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS); PROJ_INTERNAL static ConversionNNPtr createGeographicGeocentricLatitude(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS); //! @endcond protected: PROJ_INTERNAL Conversion(const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values); PROJ_INTERNAL Conversion(const Conversion &other); INLINED_MAKE_SHARED PROJ_FRIEND(crs::ProjectedCRS); PROJ_INTERNAL bool addWKTExtensionNode(io::WKTFormatter *formatter) const; PROJ_INTERNAL CoordinateOperationNNPtr _shallowClone() const override; private: PROJ_OPAQUE_PRIVATE_DATA Conversion &operator=(const Conversion &other) = delete; PROJ_INTERNAL static ConversionNNPtr create(const util::PropertyMap &properties, int method_epsg_code, const std::vector<ParameterValueNNPtr> &values); PROJ_INTERNAL static ConversionNNPtr create(const util::PropertyMap &properties, const char *method_wkt2_name, const std::vector<ParameterValueNNPtr> &values); }; // --------------------------------------------------------------------------- /** \brief A mathematical operation on coordinates in which parameters are * empirically derived from data containing the coordinates of a series of * points in both coordinate reference systems. * * This computational process is usually "over-determined", allowing derivation * of error (or accuracy) estimates for the coordinate transformation. Also, * the stochastic nature of the parameters may result in multiple (different) * versions of the same coordinate transformations between the same source and * target CRSs. Any single coordinate operation in which the input and output * coordinates are referenced to different datums (reference frames) will be a * coordinate transformation. * * \remark Implements Transformation from \ref ISO_19111_2019 */ class PROJ_GCC_DLL Transformation : public SingleOperation { public: //! @cond Doxygen_Suppress PROJ_DLL ~Transformation() override; //! @endcond PROJ_DLL const crs::CRSNNPtr &sourceCRS() PROJ_PURE_DECL; PROJ_DLL const crs::CRSNNPtr &targetCRS() PROJ_PURE_DECL; PROJ_DLL CoordinateOperationNNPtr inverse() const override; PROJ_DLL static TransformationNNPtr create(const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); // throw InvalidOperation PROJ_DLL static TransformationNNPtr create(const util::PropertyMap &propertiesTransformation, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const util::PropertyMap &propertiesOperationMethod, const std::vector<OperationParameterNNPtr> &parameters, const std::vector<ParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); // throw InvalidOperation PROJ_DLL static TransformationNNPtr createGeocentricTranslations( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createPositionVector( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createCoordinateFrameRotation( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createTimeDependentPositionVector( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, double rateTranslationX, double rateTranslationY, double rateTranslationZ, double rateRotationX, double rateRotationY, double rateRotationZ, double rateScaleDifference, double referenceEpochYear, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createTimeDependentCoordinateFrameRotation( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double rotationXArcSecond, double rotationYArcSecond, double rotationZArcSecond, double scaleDifferencePPM, double rateTranslationX, double rateTranslationY, double rateTranslationZ, double rateRotationX, double rateRotationY, double rateRotationZ, double rateScaleDifference, double referenceEpochYear, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createTOWGS84( const crs::CRSNNPtr &sourceCRSIn, const std::vector<double> &TOWGS84Parameters); // throw InvalidOperation PROJ_DLL static TransformationNNPtr createNTv2( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createMolodensky( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double semiMajorAxisDifferenceMetre, double flattingDifference, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createAbridgedMolodensky( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, double translationXMetre, double translationYMetre, double translationZMetre, double semiMajorAxisDifferenceMetre, double flattingDifference, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createGravityRelatedHeightToGeographic3D( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createVERTCON( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const std::string &filename, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createLongitudeRotation( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offset); PROJ_DLL static TransformationNNPtr createGeographic2DOffsets( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offsetLat, const common::Angle &offsetLong, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createGeographic3DOffsets( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createGeographic2DWithHeightOffsets( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Angle &offsetLat, const common::Angle &offsetLong, const common::Length &offsetHeight, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createVerticalOffset( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Length &offsetHeight, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_DLL static TransformationNNPtr createChangeVerticalUnit( const util::PropertyMap &properties, const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const common::Scale &factor, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL const std::string & getNTv2Filename() const; PROJ_FOR_TEST std::vector<double> getTOWGS84Parameters() const; // throw(io::FormattingException) PROJ_INTERNAL const std::string &getHeightToGeographic3DFilename() const; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL TransformationNNPtr shallowClone() const; PROJ_INTERNAL TransformationNNPtr promoteTo3D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; PROJ_INTERNAL TransformationNNPtr demoteTo2D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; PROJ_INTERNAL static bool isGeographic3DToGravityRelatedHeight(const OperationMethodNNPtr &method, bool allowInverse); //! @endcond protected: PROJ_INTERNAL Transformation( const crs::CRSNNPtr &sourceCRSIn, const crs::CRSNNPtr &targetCRSIn, const crs::CRSPtr &interpolationCRSIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_INTERNAL Transformation(const Transformation &other); INLINED_MAKE_SHARED PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_FRIEND(CoordinateOperationFactory); PROJ_FRIEND(SingleOperation); PROJ_INTERNAL TransformationNNPtr inverseAsTransformation() const; PROJ_INTERNAL CoordinateOperationNNPtr _shallowClone() const override; private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class PointMotionOperation; /** Shared pointer of PointMotionOperation */ using PointMotionOperationPtr = std::shared_ptr<PointMotionOperation>; /** Non-null shared pointer of PointMotionOperation */ using PointMotionOperationNNPtr = util::nn<PointMotionOperationPtr>; /** \brief A mathematical operation that describes the change of coordinate * values within one coordinate reference system due to the motion of the * point between one coordinate epoch and another coordinate epoch. * * The motion is due to tectonic plate movement or deformation. * * \remark Implements PointMotionOperation from \ref ISO_19111_2019 */ class PROJ_GCC_DLL PointMotionOperation : public SingleOperation { public: // TODO //! @cond Doxygen_Suppress PROJ_DLL ~PointMotionOperation() override; //! @endcond PROJ_DLL const crs::CRSNNPtr &sourceCRS() PROJ_PURE_DECL; PROJ_DLL CoordinateOperationNNPtr inverse() const override; PROJ_DLL static PointMotionOperationNNPtr create(const util::PropertyMap &properties, const crs::CRSNNPtr &crsIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); // throw InvalidOperation PROJ_DLL static PointMotionOperationNNPtr create(const util::PropertyMap &propertiesOperation, const crs::CRSNNPtr &crsIn, const util::PropertyMap &propertiesOperationMethod, const std::vector<OperationParameterNNPtr> &parameters, const std::vector<ParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); // throw InvalidOperation PROJ_DLL PointMotionOperationNNPtr substitutePROJAlternativeGridNames( io::DatabaseContextNNPtr databaseContext) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL PointMotionOperationNNPtr shallowClone() const; PROJ_INTERNAL PointMotionOperationNNPtr cloneWithEpochs(const common::DataEpoch &sourceEpoch, const common::DataEpoch &targetEpoch) const; PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) //! @endcond protected: PROJ_INTERNAL PointMotionOperation( const crs::CRSNNPtr &crsIn, const OperationMethodNNPtr &methodIn, const std::vector<GeneralParameterValueNNPtr> &values, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); PROJ_INTERNAL PointMotionOperation(const PointMotionOperation &other); INLINED_MAKE_SHARED PROJ_INTERNAL CoordinateOperationNNPtr _shallowClone() const override; private: PointMotionOperation &operator=(const PointMotionOperation &) = delete; }; // --------------------------------------------------------------------------- class ConcatenatedOperation; /** Shared pointer of ConcatenatedOperation */ using ConcatenatedOperationPtr = std::shared_ptr<ConcatenatedOperation>; /** Non-null shared pointer of ConcatenatedOperation */ using ConcatenatedOperationNNPtr = util::nn<ConcatenatedOperationPtr>; /** \brief An ordered sequence of two or more single coordinate operations * (SingleOperation). * * The sequence of coordinate operations is constrained by the requirement * that * the source coordinate reference system of step n+1 shall be the same as * the target coordinate reference system of step n. * * \remark Implements ConcatenatedOperation from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ConcatenatedOperation final : public CoordinateOperation { public: //! @cond Doxygen_Suppress PROJ_DLL ~ConcatenatedOperation() override; //! @endcond PROJ_DLL const std::vector<CoordinateOperationNNPtr> &operations() const; PROJ_DLL CoordinateOperationNNPtr inverse() const override; PROJ_DLL static ConcatenatedOperationNNPtr create(const util::PropertyMap &properties, const std::vector<CoordinateOperationNNPtr> &operationsIn, const std::vector<metadata::PositionalAccuracyNNPtr> &accuracies); // throw InvalidOperation PROJ_DLL static CoordinateOperationNNPtr createComputeMetadata( const std::vector<CoordinateOperationNNPtr> &operationsIn, bool checkExtent); // throw InvalidOperation PROJ_DLL std::set<GridDescription> gridsNeeded(const io::DatabaseContextPtr &databaseContext, bool considerKnownGridsAsAvailable) const override; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL static void fixStepsDirection(const crs::CRSNNPtr &concatOpSourceCRS, const crs::CRSNNPtr &concatOpTargetCRS, std::vector<CoordinateOperationNNPtr> &operationsInOut, const io::DatabaseContextPtr &dbContext); //! @endcond protected: PROJ_INTERNAL ConcatenatedOperation(const ConcatenatedOperation &other); PROJ_INTERNAL explicit ConcatenatedOperation( const std::vector<CoordinateOperationNNPtr> &operationsIn); PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL CoordinateOperationNNPtr _shallowClone() const override; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA ConcatenatedOperation & operator=(const ConcatenatedOperation &other) = delete; }; // --------------------------------------------------------------------------- class CoordinateOperationContext; /** Unique pointer of CoordinateOperationContext */ using CoordinateOperationContextPtr = std::unique_ptr<CoordinateOperationContext>; /** Non-null unique pointer of CoordinateOperationContext */ using CoordinateOperationContextNNPtr = util::nn<CoordinateOperationContextPtr>; /** \brief Context in which a coordinate operation is to be used. * * \remark Implements [CoordinateOperationFactory * https://sis.apache.org/apidocs/org/apache/sis/referencing/operation/CoordinateOperationContext.html] * from * Apache SIS */ class PROJ_GCC_DLL CoordinateOperationContext { public: //! @cond Doxygen_Suppress PROJ_DLL virtual ~CoordinateOperationContext(); //! @endcond PROJ_DLL const io::AuthorityFactoryPtr &getAuthorityFactory() const; PROJ_DLL const metadata::ExtentPtr &getAreaOfInterest() const; PROJ_DLL void setAreaOfInterest(const metadata::ExtentPtr &extent); PROJ_DLL double getDesiredAccuracy() const; PROJ_DLL void setDesiredAccuracy(double accuracy); PROJ_DLL void setAllowBallparkTransformations(bool allow); PROJ_DLL bool getAllowBallparkTransformations() const; /** Specify how source and target CRS extent should be used to restrict * candidate operations (only taken into account if no explicit area of * interest is specified. */ enum class SourceTargetCRSExtentUse { /** Ignore CRS extent */ NONE, /** Test coordinate operation extent against both CRS extent. */ BOTH, /** Test coordinate operation extent against the intersection of both CRS extent. */ INTERSECTION, /** Test coordinate operation against the smallest of both CRS extent. */ SMALLEST, }; PROJ_DLL void setSourceAndTargetCRSExtentUse(SourceTargetCRSExtentUse use); PROJ_DLL SourceTargetCRSExtentUse getSourceAndTargetCRSExtentUse() const; /** Spatial criterion to restrict candidate operations. */ enum class SpatialCriterion { /** The area of validity of transforms should strictly contain the * are of interest. */ STRICT_CONTAINMENT, /** The area of validity of transforms should at least intersect the * area of interest. */ PARTIAL_INTERSECTION }; PROJ_DLL void setSpatialCriterion(SpatialCriterion criterion); PROJ_DLL SpatialCriterion getSpatialCriterion() const; PROJ_DLL void setUsePROJAlternativeGridNames(bool usePROJNames); PROJ_DLL bool getUsePROJAlternativeGridNames() const; PROJ_DLL void setDiscardSuperseded(bool discard); PROJ_DLL bool getDiscardSuperseded() const; /** Describe how grid availability is used. */ enum class GridAvailabilityUse { /** Grid availability is only used for sorting results. Operations * where some grids are missing will be sorted last. */ USE_FOR_SORTING, /** Completely discard an operation if a required grid is missing. */ DISCARD_OPERATION_IF_MISSING_GRID, /** Ignore grid availability at all. Results will be presented as if * all grids were available. */ IGNORE_GRID_AVAILABILITY, /** Results will be presented as if grids known to PROJ (that is * registered in the grid_alternatives table of its database) were * available. Used typically when networking is enabled. */ KNOWN_AVAILABLE, }; PROJ_DLL void setGridAvailabilityUse(GridAvailabilityUse use); PROJ_DLL GridAvailabilityUse getGridAvailabilityUse() const; /** Describe if and how intermediate CRS should be used */ enum class IntermediateCRSUse { /** Always search for intermediate CRS. */ ALWAYS, /** Only attempt looking for intermediate CRS if there is no direct * transformation available. */ IF_NO_DIRECT_TRANSFORMATION, /* Do not attempt looking for intermediate CRS. */ NEVER, }; PROJ_DLL void setAllowUseIntermediateCRS(IntermediateCRSUse use); PROJ_DLL IntermediateCRSUse getAllowUseIntermediateCRS() const; PROJ_DLL void setIntermediateCRS(const std::vector<std::pair<std::string, std::string>> &intermediateCRSAuthCodes); PROJ_DLL const std::vector<std::pair<std::string, std::string>> & getIntermediateCRS() const; PROJ_DLL void setSourceCoordinateEpoch(const util::optional<common::DataEpoch> &epoch); PROJ_DLL const util::optional<common::DataEpoch> & getSourceCoordinateEpoch() const; PROJ_DLL void setTargetCoordinateEpoch(const util::optional<common::DataEpoch> &epoch); PROJ_DLL const util::optional<common::DataEpoch> & getTargetCoordinateEpoch() const; PROJ_DLL static CoordinateOperationContextNNPtr create(const io::AuthorityFactoryPtr &authorityFactory, const metadata::ExtentPtr &extent, double accuracy); PROJ_DLL CoordinateOperationContextNNPtr clone() const; protected: PROJ_INTERNAL CoordinateOperationContext(); PROJ_INTERNAL CoordinateOperationContext(const CoordinateOperationContext &); INLINED_MAKE_UNIQUE private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class CoordinateOperationFactory; /** Unique pointer of CoordinateOperationFactory */ using CoordinateOperationFactoryPtr = std::unique_ptr<CoordinateOperationFactory>; /** Non-null unique pointer of CoordinateOperationFactory */ using CoordinateOperationFactoryNNPtr = util::nn<CoordinateOperationFactoryPtr>; /** \brief Creates coordinate operations. This factory is capable to find * coordinate transformations or conversions between two coordinate * reference * systems. * * \remark Implements (partially) CoordinateOperationFactory from \ref * GeoAPI */ class PROJ_GCC_DLL CoordinateOperationFactory { public: //! @cond Doxygen_Suppress PROJ_DLL virtual ~CoordinateOperationFactory(); //! @endcond PROJ_DLL CoordinateOperationPtr createOperation( const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS) const; PROJ_DLL std::vector<CoordinateOperationNNPtr> createOperations(const crs::CRSNNPtr &sourceCRS, const crs::CRSNNPtr &targetCRS, const CoordinateOperationContextNNPtr &context) const; PROJ_DLL std::vector<CoordinateOperationNNPtr> createOperations( const coordinates::CoordinateMetadataNNPtr &sourceCoordinateMetadata, const crs::CRSNNPtr &targetCRS, const CoordinateOperationContextNNPtr &context) const; PROJ_DLL std::vector<CoordinateOperationNNPtr> createOperations( const crs::CRSNNPtr &sourceCRS, const coordinates::CoordinateMetadataNNPtr &targetCoordinateMetadata, const CoordinateOperationContextNNPtr &context) const; PROJ_DLL std::vector<CoordinateOperationNNPtr> createOperations( const coordinates::CoordinateMetadataNNPtr &sourceCoordinateMetadata, const coordinates::CoordinateMetadataNNPtr &targetCoordinateMetadata, const CoordinateOperationContextNNPtr &context) const; PROJ_DLL static CoordinateOperationFactoryNNPtr create(); protected: PROJ_INTERNAL CoordinateOperationFactory(); INLINED_MAKE_UNIQUE private: PROJ_OPAQUE_PRIVATE_DATA }; } // namespace operation NS_PROJ_END #endif // COORDINATEOPERATION_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/coordinates.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2023, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef COORDINATES_HH_INCLUDED #define COORDINATES_HH_INCLUDED #include <memory> #include "common.hpp" #include "crs.hpp" #include "io.hpp" #include "util.hpp" NS_PROJ_START /** osgeo.proj.coordinates namespace \brief Coordinates package */ namespace coordinates { class CoordinateMetadata; /** Shared pointer of CoordinateMetadata */ using CoordinateMetadataPtr = std::shared_ptr<CoordinateMetadata>; /** Non-null shared pointer of CoordinateMetadata */ using CoordinateMetadataNNPtr = util::nn<CoordinateMetadataPtr>; // --------------------------------------------------------------------------- /** \brief Associates a CRS with a coordinate epoch. * * \remark Implements CoordinateMetadata from \ref ISO_19111_2019 * \since 9.2 */ class PROJ_GCC_DLL CoordinateMetadata : public util::BaseObject, public io::IWKTExportable, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~CoordinateMetadata() override; //! @endcond PROJ_DLL const crs::CRSNNPtr &crs() PROJ_PURE_DECL; PROJ_DLL const util::optional<common::DataEpoch> & coordinateEpoch() PROJ_PURE_DECL; PROJ_DLL double coordinateEpochAsDecimalYear() PROJ_PURE_DECL; PROJ_DLL static CoordinateMetadataNNPtr create(const crs::CRSNNPtr &crsIn); PROJ_DLL static CoordinateMetadataNNPtr create(const crs::CRSNNPtr &crsIn, double coordinateEpochAsDecimalYear); PROJ_DLL static CoordinateMetadataNNPtr create(const crs::CRSNNPtr &crsIn, double coordinateEpochAsDecimalYear, const io::DatabaseContextPtr &dbContext); PROJ_DLL CoordinateMetadataNNPtr promoteTo3D(const std::string &newName, const io::DatabaseContextPtr &dbContext) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) //! @endcond protected: PROJ_INTERNAL explicit CoordinateMetadata(const crs::CRSNNPtr &crsIn); PROJ_INTERNAL CoordinateMetadata(const crs::CRSNNPtr &crsIn, double coordinateEpochAsDecimalYear); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA CoordinateMetadata &operator=(const CoordinateMetadata &other) = delete; }; // --------------------------------------------------------------------------- } // namespace coordinates NS_PROJ_END #endif // COORDINATES_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/io.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef IO_HH_INCLUDED #define IO_HH_INCLUDED #include <list> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include "proj.h" #include "util.hpp" NS_PROJ_START class CPLJSonStreamingWriter; namespace common { class UnitOfMeasure; using UnitOfMeasurePtr = std::shared_ptr<UnitOfMeasure>; using UnitOfMeasureNNPtr = util::nn<UnitOfMeasurePtr>; class IdentifiedObject; using IdentifiedObjectPtr = std::shared_ptr<IdentifiedObject>; using IdentifiedObjectNNPtr = util::nn<IdentifiedObjectPtr>; } // namespace common namespace cs { class CoordinateSystem; using CoordinateSystemPtr = std::shared_ptr<CoordinateSystem>; using CoordinateSystemNNPtr = util::nn<CoordinateSystemPtr>; } // namespace cs namespace metadata { class Extent; using ExtentPtr = std::shared_ptr<Extent>; using ExtentNNPtr = util::nn<ExtentPtr>; } // namespace metadata namespace datum { class Datum; using DatumPtr = std::shared_ptr<Datum>; using DatumNNPtr = util::nn<DatumPtr>; class DatumEnsemble; using DatumEnsemblePtr = std::shared_ptr<DatumEnsemble>; using DatumEnsembleNNPtr = util::nn<DatumEnsemblePtr>; class Ellipsoid; using EllipsoidPtr = std::shared_ptr<Ellipsoid>; using EllipsoidNNPtr = util::nn<EllipsoidPtr>; class PrimeMeridian; using PrimeMeridianPtr = std::shared_ptr<PrimeMeridian>; using PrimeMeridianNNPtr = util::nn<PrimeMeridianPtr>; class GeodeticReferenceFrame; using GeodeticReferenceFramePtr = std::shared_ptr<GeodeticReferenceFrame>; using GeodeticReferenceFrameNNPtr = util::nn<GeodeticReferenceFramePtr>; class VerticalReferenceFrame; using VerticalReferenceFramePtr = std::shared_ptr<VerticalReferenceFrame>; using VerticalReferenceFrameNNPtr = util::nn<VerticalReferenceFramePtr>; } // namespace datum namespace crs { class CRS; using CRSPtr = std::shared_ptr<CRS>; using CRSNNPtr = util::nn<CRSPtr>; class GeodeticCRS; using GeodeticCRSPtr = std::shared_ptr<GeodeticCRS>; using GeodeticCRSNNPtr = util::nn<GeodeticCRSPtr>; class GeographicCRS; using GeographicCRSPtr = std::shared_ptr<GeographicCRS>; using GeographicCRSNNPtr = util::nn<GeographicCRSPtr>; class VerticalCRS; using VerticalCRSPtr = std::shared_ptr<VerticalCRS>; using VerticalCRSNNPtr = util::nn<VerticalCRSPtr>; class ProjectedCRS; using ProjectedCRSPtr = std::shared_ptr<ProjectedCRS>; using ProjectedCRSNNPtr = util::nn<ProjectedCRSPtr>; class CompoundCRS; using CompoundCRSPtr = std::shared_ptr<CompoundCRS>; using CompoundCRSNNPtr = util::nn<CompoundCRSPtr>; } // namespace crs namespace coordinates { class CoordinateMetadata; /** Shared pointer of CoordinateMetadata */ using CoordinateMetadataPtr = std::shared_ptr<CoordinateMetadata>; /** Non-null shared pointer of CoordinateMetadata */ using CoordinateMetadataNNPtr = util::nn<CoordinateMetadataPtr>; } // namespace coordinates namespace operation { class Conversion; using ConversionPtr = std::shared_ptr<Conversion>; using ConversionNNPtr = util::nn<ConversionPtr>; class CoordinateOperation; using CoordinateOperationPtr = std::shared_ptr<CoordinateOperation>; using CoordinateOperationNNPtr = util::nn<CoordinateOperationPtr>; class PointMotionOperation; using PointMotionOperationPtr = std::shared_ptr<PointMotionOperation>; using PointMotionOperationNNPtr = util::nn<PointMotionOperationPtr>; } // namespace operation /** osgeo.proj.io namespace. * * \brief I/O classes */ namespace io { class DatabaseContext; /** Shared pointer of DatabaseContext. */ using DatabaseContextPtr = std::shared_ptr<DatabaseContext>; /** Non-null shared pointer of DatabaseContext. */ using DatabaseContextNNPtr = util::nn<DatabaseContextPtr>; // --------------------------------------------------------------------------- class WKTNode; /** Unique pointer of WKTNode. */ using WKTNodePtr = std::unique_ptr<WKTNode>; /** Non-null unique pointer of WKTNode. */ using WKTNodeNNPtr = util::nn<WKTNodePtr>; // --------------------------------------------------------------------------- class WKTFormatter; /** WKTFormatter unique pointer. */ using WKTFormatterPtr = std::unique_ptr<WKTFormatter>; /** Non-null WKTFormatter unique pointer. */ using WKTFormatterNNPtr = util::nn<WKTFormatterPtr>; /** \brief Formatter to WKT strings. * * An instance of this class can only be used by a single * thread at a time. */ class PROJ_GCC_DLL WKTFormatter { public: /** WKT variant. */ enum class PROJ_MSVC_DLL Convention { /** Full WKT2 string, conforming to ISO 19162:2015(E) / OGC 12-063r5 * (\ref WKT2_2015) with all possible nodes and new keyword names. */ WKT2, WKT2_2015 = WKT2, /** Same as WKT2 with the following exceptions: * <ul> * <li>UNIT keyword used.</li> * <li>ID node only on top element.</li> * <li>No ORDER element in AXIS element.</li> * <li>PRIMEM node omitted if it is Greenwich.</li> * <li>ELLIPSOID.UNIT node omitted if it is * UnitOfMeasure::METRE.</li> * <li>PARAMETER.UNIT / PRIMEM.UNIT omitted if same as AXIS.</li> * <li>AXIS.UNIT omitted and replaced by a common GEODCRS.UNIT if * they are all the same on all axis.</li> * </ul> */ WKT2_SIMPLIFIED, WKT2_2015_SIMPLIFIED = WKT2_SIMPLIFIED, /** Full WKT2 string, conforming to ISO 19162:2019 / OGC 18-010, with * (\ref WKT2_2019) all possible nodes and new keyword names. * Non-normative list of differences: * <ul> * <li>WKT2_2019 uses GEOGCRS / BASEGEOGCRS keywords for * GeographicCRS.</li> * </ul> */ WKT2_2019, /** Deprecated alias for WKT2_2019 */ WKT2_2018 = WKT2_2019, /** WKT2_2019 with the simplification rule of WKT2_SIMPLIFIED */ WKT2_2019_SIMPLIFIED, /** Deprecated alias for WKT2_2019_SIMPLIFIED */ WKT2_2018_SIMPLIFIED = WKT2_2019_SIMPLIFIED, /** WKT1 as traditionally output by GDAL, deriving from OGC 01-009. A notable departure from WKT1_GDAL with respect to OGC 01-009 is that in WKT1_GDAL, the unit of the PRIMEM value is always degrees. */ WKT1_GDAL, /** WKT1 as traditionally output by ESRI software, * deriving from OGC 99-049. */ WKT1_ESRI, }; PROJ_DLL static WKTFormatterNNPtr create(Convention convention = Convention::WKT2, DatabaseContextPtr dbContext = nullptr); PROJ_DLL static WKTFormatterNNPtr create(const WKTFormatterNNPtr &other); //! @cond Doxygen_Suppress PROJ_DLL ~WKTFormatter(); //! @endcond PROJ_DLL WKTFormatter &setMultiLine(bool multiLine) noexcept; PROJ_DLL WKTFormatter &setIndentationWidth(int width) noexcept; /** Rule for output AXIS nodes */ enum class OutputAxisRule { /** Always include AXIS nodes */ YES, /** Never include AXIS nodes */ NO, /** Includes them only on PROJCS node if it uses Easting/Northing *ordering. Typically used for WKT1_GDAL */ WKT1_GDAL_EPSG_STYLE, }; PROJ_DLL WKTFormatter &setOutputAxis(OutputAxisRule outputAxis) noexcept; PROJ_DLL WKTFormatter &setStrict(bool strict) noexcept; PROJ_DLL bool isStrict() const noexcept; PROJ_DLL WKTFormatter & setAllowEllipsoidalHeightAsVerticalCRS(bool allow) noexcept; PROJ_DLL bool isAllowedEllipsoidalHeightAsVerticalCRS() const noexcept; PROJ_DLL WKTFormatter &setAllowLINUNITNode(bool allow) noexcept; PROJ_DLL bool isAllowedLINUNITNode() const noexcept; PROJ_DLL const std::string &toString() const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_DLL WKTFormatter & setOutputId(bool outputIdIn); PROJ_INTERNAL void enter(); PROJ_INTERNAL void leave(); PROJ_INTERNAL void startNode(const std::string &keyword, bool hasId); PROJ_INTERNAL void endNode(); PROJ_INTERNAL bool isAtTopLevel() const; PROJ_DLL WKTFormatter &simulCurNodeHasId(); PROJ_INTERNAL void addQuotedString(const char *str); PROJ_INTERNAL void addQuotedString(const std::string &str); PROJ_INTERNAL void add(const std::string &str); PROJ_INTERNAL void add(int number); PROJ_INTERNAL void add(size_t number) = delete; PROJ_INTERNAL void add(double number, int precision = 15); PROJ_INTERNAL void pushOutputUnit(bool outputUnitIn); PROJ_INTERNAL void popOutputUnit(); PROJ_INTERNAL bool outputUnit() const; PROJ_INTERNAL void pushOutputId(bool outputIdIn); PROJ_INTERNAL void popOutputId(); PROJ_INTERNAL bool outputId() const; PROJ_INTERNAL void pushHasId(bool hasId); PROJ_INTERNAL void popHasId(); PROJ_INTERNAL void pushDisableUsage(); PROJ_INTERNAL void popDisableUsage(); PROJ_INTERNAL bool outputUsage() const; PROJ_INTERNAL void pushAxisLinearUnit(const common::UnitOfMeasureNNPtr &unit); PROJ_INTERNAL void popAxisLinearUnit(); PROJ_INTERNAL const common::UnitOfMeasureNNPtr &axisLinearUnit() const; PROJ_INTERNAL void pushAxisAngularUnit(const common::UnitOfMeasureNNPtr &unit); PROJ_INTERNAL void popAxisAngularUnit(); PROJ_INTERNAL const common::UnitOfMeasureNNPtr &axisAngularUnit() const; PROJ_INTERNAL void setAbridgedTransformation(bool abriged); PROJ_INTERNAL bool abridgedTransformation() const; PROJ_INTERNAL void setUseDerivingConversion(bool useDerivingConversionIn); PROJ_INTERNAL bool useDerivingConversion() const; PROJ_INTERNAL void setTOWGS84Parameters(const std::vector<double> &params); PROJ_INTERNAL const std::vector<double> &getTOWGS84Parameters() const; PROJ_INTERNAL void setVDatumExtension(const std::string &filename); PROJ_INTERNAL const std::string &getVDatumExtension() const; PROJ_INTERNAL void setHDatumExtension(const std::string &filename); PROJ_INTERNAL const std::string &getHDatumExtension() const; PROJ_INTERNAL void setGeogCRSOfCompoundCRS(const crs::GeographicCRSPtr &crs); PROJ_INTERNAL const crs::GeographicCRSPtr &getGeogCRSOfCompoundCRS() const; PROJ_INTERNAL static std::string morphNameToESRI(const std::string &name); #ifdef unused PROJ_INTERNAL void startInversion(); PROJ_INTERNAL void stopInversion(); PROJ_INTERNAL bool isInverted() const; #endif PROJ_INTERNAL OutputAxisRule outputAxis() const; PROJ_INTERNAL bool outputAxisOrder() const; PROJ_INTERNAL bool primeMeridianOmittedIfGreenwich() const; PROJ_INTERNAL bool ellipsoidUnitOmittedIfMetre() const; PROJ_INTERNAL bool forceUNITKeyword() const; PROJ_INTERNAL bool primeMeridianOrParameterUnitOmittedIfSameAsAxis() const; PROJ_INTERNAL bool primeMeridianInDegree() const; PROJ_INTERNAL bool outputCSUnitOnlyOnceIfSame() const; PROJ_INTERNAL bool idOnTopLevelOnly() const; PROJ_INTERNAL bool topLevelHasId() const; /** WKT version. */ enum class Version { /** WKT1 */ WKT1, /** WKT2 / ISO 19162 */ WKT2 }; PROJ_INTERNAL Version version() const; PROJ_INTERNAL bool use2019Keywords() const; PROJ_INTERNAL bool useESRIDialect() const; PROJ_INTERNAL const DatabaseContextPtr &databaseContext() const; PROJ_INTERNAL void ingestWKTNode(const WKTNodeNNPtr &node); //! @endcond protected: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit WKTFormatter(Convention convention); WKTFormatter(const WKTFormatter &other) = delete; INLINED_MAKE_UNIQUE //! @endcond private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class PROJStringFormatter; /** PROJStringFormatter unique pointer. */ using PROJStringFormatterPtr = std::unique_ptr<PROJStringFormatter>; /** Non-null PROJStringFormatter unique pointer. */ using PROJStringFormatterNNPtr = util::nn<PROJStringFormatterPtr>; /** \brief Formatter to PROJ strings. * * An instance of this class can only be used by a single * thread at a time. */ class PROJ_GCC_DLL PROJStringFormatter { public: /** PROJ variant. */ enum class PROJ_MSVC_DLL Convention { /** PROJ v5 (or later versions) string. */ PROJ_5, /** PROJ v4 string as output by GDAL exportToProj4() */ PROJ_4 }; PROJ_DLL static PROJStringFormatterNNPtr create(Convention conventionIn = Convention::PROJ_5, DatabaseContextPtr dbContext = nullptr); //! @cond Doxygen_Suppress PROJ_DLL ~PROJStringFormatter(); //! @endcond PROJ_DLL PROJStringFormatter &setMultiLine(bool multiLine) noexcept; PROJ_DLL PROJStringFormatter &setIndentationWidth(int width) noexcept; PROJ_DLL PROJStringFormatter &setMaxLineLength(int maxLineLength) noexcept; PROJ_DLL void setUseApproxTMerc(bool flag); PROJ_DLL const std::string &toString() const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_DLL void setCRSExport(bool b); PROJ_INTERNAL bool getCRSExport() const; PROJ_DLL void startInversion(); PROJ_DLL void stopInversion(); PROJ_INTERNAL bool isInverted() const; PROJ_INTERNAL bool getUseApproxTMerc() const; PROJ_INTERNAL void setCoordinateOperationOptimizations(bool enable); PROJ_DLL void ingestPROJString(const std::string &str); // throw ParsingException PROJ_DLL void addStep(const char *step); PROJ_DLL void addStep(const std::string &step); PROJ_DLL void setCurrentStepInverted(bool inverted); PROJ_DLL void addParam(const std::string &paramName); PROJ_DLL void addParam(const char *paramName, double val); PROJ_DLL void addParam(const std::string &paramName, double val); PROJ_DLL void addParam(const char *paramName, int val); PROJ_DLL void addParam(const std::string &paramName, int val); PROJ_DLL void addParam(const char *paramName, const char *val); PROJ_DLL void addParam(const char *paramName, const std::string &val); PROJ_DLL void addParam(const std::string &paramName, const char *val); PROJ_DLL void addParam(const std::string &paramName, const std::string &val); PROJ_DLL void addParam(const char *paramName, const std::vector<double> &vals); PROJ_INTERNAL bool hasParam(const char *paramName) const; PROJ_INTERNAL void addNoDefs(bool b); PROJ_INTERNAL bool getAddNoDefs() const; PROJ_INTERNAL std::set<std::string> getUsedGridNames() const; PROJ_INTERNAL void setTOWGS84Parameters(const std::vector<double> &params); PROJ_INTERNAL const std::vector<double> &getTOWGS84Parameters() const; PROJ_INTERNAL void setVDatumExtension(const std::string &filename, const std::string &geoidCRSValue); PROJ_INTERNAL const std::string &getVDatumExtension() const; PROJ_INTERNAL const std::string &getGeoidCRSValue() const; PROJ_INTERNAL void setHDatumExtension(const std::string &filename); PROJ_INTERNAL const std::string &getHDatumExtension() const; PROJ_INTERNAL void setGeogCRSOfCompoundCRS(const crs::GeographicCRSPtr &crs); PROJ_INTERNAL const crs::GeographicCRSPtr &getGeogCRSOfCompoundCRS() const; PROJ_INTERNAL void setOmitProjLongLatIfPossible(bool omit); PROJ_INTERNAL bool omitProjLongLatIfPossible() const; PROJ_INTERNAL void pushOmitZUnitConversion(); PROJ_INTERNAL void popOmitZUnitConversion(); PROJ_INTERNAL bool omitZUnitConversion() const; PROJ_INTERNAL void pushOmitHorizontalConversionInVertTransformation(); PROJ_INTERNAL void popOmitHorizontalConversionInVertTransformation(); PROJ_INTERNAL bool omitHorizontalConversionInVertTransformation() const; PROJ_INTERNAL void setLegacyCRSToCRSContext(bool legacyContext); PROJ_INTERNAL bool getLegacyCRSToCRSContext() const; PROJ_INTERNAL PROJStringFormatter &setNormalizeOutput(); PROJ_INTERNAL const DatabaseContextPtr &databaseContext() const; PROJ_INTERNAL Convention convention() const; PROJ_INTERNAL size_t getStepCount() const; //! @endcond protected: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit PROJStringFormatter( Convention conventionIn, const DatabaseContextPtr &dbContext); PROJStringFormatter(const PROJStringFormatter &other) = delete; INLINED_MAKE_UNIQUE //! @endcond private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class JSONFormatter; /** JSONFormatter unique pointer. */ using JSONFormatterPtr = std::unique_ptr<JSONFormatter>; /** Non-null JSONFormatter unique pointer. */ using JSONFormatterNNPtr = util::nn<JSONFormatterPtr>; /** \brief Formatter to JSON strings. * * An instance of this class can only be used by a single * thread at a time. */ class PROJ_GCC_DLL JSONFormatter { public: PROJ_DLL static JSONFormatterNNPtr create(DatabaseContextPtr dbContext = nullptr); //! @cond Doxygen_Suppress PROJ_DLL ~JSONFormatter(); //! @endcond PROJ_DLL JSONFormatter &setMultiLine(bool multiLine) noexcept; PROJ_DLL JSONFormatter &setIndentationWidth(int width) noexcept; PROJ_DLL JSONFormatter &setSchema(const std::string &schema) noexcept; PROJ_DLL const std::string &toString() const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL CPLJSonStreamingWriter * writer() const; PROJ_INTERNAL const DatabaseContextPtr &databaseContext() const; struct ObjectContext { JSONFormatter &m_formatter; ObjectContext(const ObjectContext &) = delete; ObjectContext(ObjectContext &&) = default; explicit ObjectContext(JSONFormatter &formatter, const char *objectType, bool hasId); ~ObjectContext(); }; PROJ_INTERNAL inline ObjectContext MakeObjectContext(const char *objectType, bool hasId) { return ObjectContext(*this, objectType, hasId); } PROJ_INTERNAL void setAllowIDInImmediateChild(); PROJ_INTERNAL void setOmitTypeInImmediateChild(); PROJ_INTERNAL void setAbridgedTransformation(bool abriged); PROJ_INTERNAL bool abridgedTransformation() const; PROJ_INTERNAL void setAbridgedTransformationWriteSourceCRS(bool writeCRS); PROJ_INTERNAL bool abridgedTransformationWriteSourceCRS() const; // cppcheck-suppress functionStatic PROJ_INTERNAL bool outputId() const; PROJ_INTERNAL bool outputUsage(bool calledBeforeObjectContext = false) const; PROJ_INTERNAL static const char *PROJJSON_v0_7; //! @endcond protected: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit JSONFormatter(); JSONFormatter(const JSONFormatter &other) = delete; INLINED_MAKE_UNIQUE //! @endcond private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Interface for an object that can be exported to JSON. */ class PROJ_GCC_DLL IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL virtual ~IJSONExportable(); //! @endcond /** Builds a JSON representation. May throw a FormattingException */ PROJ_DLL std::string exportToJSON(JSONFormatter *formatter) const; // throw(FormattingException) PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL virtual void _exportToJSON( JSONFormatter *formatter) const = 0; // throw(FormattingException) //! @endcond }; // --------------------------------------------------------------------------- /** \brief Exception possibly thrown by IWKTExportable::exportToWKT() or * IPROJStringExportable::exportToPROJString(). */ class PROJ_GCC_DLL FormattingException : public util::Exception { public: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit FormattingException(const char *message); PROJ_INTERNAL explicit FormattingException(const std::string &message); PROJ_DLL FormattingException(const FormattingException &other); PROJ_DLL virtual ~FormattingException() override; PROJ_INTERNAL static void Throw(const char *msg) PROJ_NO_RETURN; PROJ_INTERNAL static void Throw(const std::string &msg) PROJ_NO_RETURN; //! @endcond }; // --------------------------------------------------------------------------- /** \brief Exception possibly thrown by WKTNode::createFrom() or * WKTParser::createFromWKT(). */ class PROJ_GCC_DLL ParsingException : public util::Exception { public: //! @cond Doxygen_Suppress PROJ_INTERNAL explicit ParsingException(const char *message); PROJ_INTERNAL explicit ParsingException(const std::string &message); PROJ_DLL ParsingException(const ParsingException &other); PROJ_DLL virtual ~ParsingException() override; //! @endcond }; // --------------------------------------------------------------------------- /** \brief Interface for an object that can be exported to WKT. */ class PROJ_GCC_DLL IWKTExportable { public: //! @cond Doxygen_Suppress PROJ_DLL virtual ~IWKTExportable(); //! @endcond /** Builds a WKT representation. May throw a FormattingException */ PROJ_DLL std::string exportToWKT(WKTFormatter *formatter) const; // throw(FormattingException) PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL virtual void _exportToWKT( WKTFormatter *formatter) const = 0; // throw(FormattingException) //! @endcond }; // --------------------------------------------------------------------------- class IPROJStringExportable; /** Shared pointer of IPROJStringExportable. */ using IPROJStringExportablePtr = std::shared_ptr<IPROJStringExportable>; /** Non-null shared pointer of IPROJStringExportable. */ using IPROJStringExportableNNPtr = util::nn<IPROJStringExportablePtr>; /** \brief Interface for an object that can be exported to a PROJ string. */ class PROJ_GCC_DLL IPROJStringExportable { public: //! @cond Doxygen_Suppress PROJ_DLL virtual ~IPROJStringExportable(); //! @endcond /** \brief Builds a PROJ string representation. * * <ul> * <li>For PROJStringFormatter::Convention::PROJ_5 (the default), * <ul> * <li>For a crs::CRS, returns the same as * PROJStringFormatter::Convention::PROJ_4. It should be noted that the * export of a CRS as a PROJ string may cause loss of many important aspects * of a CRS definition. Consequently it is discouraged to use it for * interoperability in newer projects. The choice of a WKT representation * will be a better option.</li> * <li>For operation::CoordinateOperation, returns a PROJ * pipeline.</li> * </ul> * * <li>For PROJStringFormatter::Convention::PROJ_4, format a string * compatible with the OGRSpatialReference::exportToProj4() of GDAL * &lt;=2.3. It is only compatible of a few CRS objects. The PROJ string * will also contain a +type=crs parameter to disambiguate the nature of * the string from a CoordinateOperation. * <ul> * <li>For a crs::GeographicCRS, returns a proj=longlat string, with * ellipsoid / datum / prime meridian information, ignoring axis order * and unit information.</li> * <li>For a geocentric crs::GeodeticCRS, returns the transformation from * geographic coordinates into geocentric coordinates.</li> * <li>For a crs::ProjectedCRS, returns the projection method, ignoring * axis order.</li> * <li>For a crs::BoundCRS, returns the PROJ string of its source/base CRS, * amended with towgs84 / nadgrids parameter when the deriving conversion * can be expressed in that way.</li> * </ul> * </li> * * </ul> * * @param formatter PROJ string formatter. * @return a PROJ string. * @throw FormattingException */ PROJ_DLL std::string exportToPROJString( PROJStringFormatter *formatter) const; // throw(FormattingException) PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL virtual void _exportToPROJString(PROJStringFormatter *formatter) const = 0; // throw(FormattingException) //! @endcond }; // --------------------------------------------------------------------------- /** \brief Node in the tree-splitted WKT representation. */ class PROJ_GCC_DLL WKTNode { public: PROJ_DLL explicit WKTNode(const std::string &valueIn); //! @cond Doxygen_Suppress PROJ_DLL ~WKTNode(); //! @endcond PROJ_DLL const std::string &value() const; PROJ_DLL const std::vector<WKTNodeNNPtr> &children() const; PROJ_DLL void addChild(WKTNodeNNPtr &&child); PROJ_DLL const WKTNodePtr &lookForChild(const std::string &childName, int occurrence = 0) const noexcept; PROJ_DLL int countChildrenOfName(const std::string &childName) const noexcept; PROJ_DLL std::string toString() const; PROJ_DLL static WKTNodeNNPtr createFrom(const std::string &wkt, size_t indexStart = 0); protected: PROJ_INTERNAL static WKTNodeNNPtr createFrom(const std::string &wkt, size_t indexStart, int recLevel, size_t &indexEnd); // throw(ParsingException) private: friend class WKTParser; PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- PROJ_DLL util::BaseObjectNNPtr createFromUserInput(const std::string &text, const DatabaseContextPtr &dbContext, bool usePROJ4InitRules = false); PROJ_DLL util::BaseObjectNNPtr createFromUserInput(const std::string &text, PJ_CONTEXT *ctx); // --------------------------------------------------------------------------- /** \brief Parse a WKT string into the appropriate subclass of util::BaseObject. */ class PROJ_GCC_DLL WKTParser { public: PROJ_DLL WKTParser(); //! @cond Doxygen_Suppress PROJ_DLL ~WKTParser(); //! @endcond PROJ_DLL WKTParser & attachDatabaseContext(const DatabaseContextPtr &dbContext); PROJ_DLL WKTParser &setStrict(bool strict); PROJ_DLL std::list<std::string> warningList() const; PROJ_DLL WKTParser &setUnsetIdentifiersIfIncompatibleDef(bool unset); PROJ_DLL util::BaseObjectNNPtr createFromWKT(const std::string &wkt); // throw(ParsingException) /** Guessed WKT "dialect" */ enum class PROJ_MSVC_DLL WKTGuessedDialect { /** \ref WKT2_2019 */ WKT2_2019, /** Deprecated alias for WKT2_2019 */ WKT2_2018 = WKT2_2019, /** \ref WKT2_2015 */ WKT2_2015, /** \ref WKT1 */ WKT1_GDAL, /** ESRI variant of WKT1 */ WKT1_ESRI, /** Not WKT / unrecognized */ NOT_WKT }; // cppcheck-suppress functionStatic PROJ_DLL WKTGuessedDialect guessDialect(const std::string &wkt) noexcept; private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Parse a PROJ string into the appropriate subclass of * util::BaseObject. */ class PROJ_GCC_DLL PROJStringParser { public: PROJ_DLL PROJStringParser(); //! @cond Doxygen_Suppress PROJ_DLL ~PROJStringParser(); //! @endcond PROJ_DLL PROJStringParser & attachDatabaseContext(const DatabaseContextPtr &dbContext); PROJ_DLL PROJStringParser &setUsePROJ4InitRules(bool enable); PROJ_DLL std::vector<std::string> warningList() const; PROJ_DLL util::BaseObjectNNPtr createFromPROJString( const std::string &projString); // throw(ParsingException) PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJStringParser & attachContext(PJ_CONTEXT *ctx); //! @endcond private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Database context. * * A database context should be used only by one thread at a time. */ class PROJ_GCC_DLL DatabaseContext { public: //! @cond Doxygen_Suppress PROJ_DLL ~DatabaseContext(); //! @endcond PROJ_DLL static DatabaseContextNNPtr create(const std::string &databasePath = std::string(), const std::vector<std::string> &auxiliaryDatabasePaths = std::vector<std::string>(), PJ_CONTEXT *ctx = nullptr); PROJ_DLL const std::string &getPath() const; PROJ_DLL const char *getMetadata(const char *key) const; PROJ_DLL std::set<std::string> getAuthorities() const; PROJ_DLL std::vector<std::string> getDatabaseStructure() const; PROJ_DLL void startInsertStatementsSession(); PROJ_DLL std::string suggestsCodeFor(const common::IdentifiedObjectNNPtr &object, const std::string &authName, bool numericCode); PROJ_DLL std::vector<std::string> getInsertStatementsFor( const common::IdentifiedObjectNNPtr &object, const std::string &authName, const std::string &code, bool numericCode, const std::vector<std::string> &allowedAuthorities = {"EPSG", "PROJ"}); PROJ_DLL void stopInsertStatementsSession(); PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_DLL void * getSqliteHandle() const; PROJ_DLL static DatabaseContextNNPtr create(void *sqlite_handle); PROJ_INTERNAL bool lookForGridAlternative(const std::string &officialName, std::string &projFilename, std::string &projFormat, bool &inverse) const; PROJ_DLL bool lookForGridInfo(const std::string &projFilename, bool considerKnownGridsAsAvailable, std::string &fullFilename, std::string &packageName, std::string &url, bool &directDownload, bool &openLicense, bool &gridAvailable) const; PROJ_INTERNAL std::string getProjGridName(const std::string &oldProjGridName); PROJ_INTERNAL std::string getOldProjGridName(const std::string &gridName); PROJ_INTERNAL std::string getAliasFromOfficialName(const std::string &officialName, const std::string &tableName, const std::string &source) const; PROJ_INTERNAL std::list<std::string> getAliases(const std::string &authName, const std::string &code, const std::string &officialName, const std::string &tableName, const std::string &source) const; PROJ_INTERNAL bool isKnownName(const std::string &name, const std::string &tableName) const; PROJ_INTERNAL std::string getName(const std::string &tableName, const std::string &authName, const std::string &code) const; PROJ_INTERNAL std::string getTextDefinition(const std::string &tableName, const std::string &authName, const std::string &code) const; PROJ_INTERNAL std::vector<std::string> getAllowedAuthorities(const std::string &sourceAuthName, const std::string &targetAuthName) const; PROJ_INTERNAL std::list<std::pair<std::string, std::string>> getNonDeprecated(const std::string &tableName, const std::string &authName, const std::string &code) const; PROJ_INTERNAL static std::vector<operation::CoordinateOperationNNPtr> getTransformationsForGridName(const DatabaseContextNNPtr &databaseContext, const std::string &gridName); PROJ_INTERNAL bool getAuthorityAndVersion(const std::string &versionedAuthName, std::string &authNameOut, std::string &versionOut); PROJ_INTERNAL bool getVersionedAuthority(const std::string &authName, const std::string &version, std::string &versionedAuthNameOut); PROJ_DLL std::vector<std::string> getVersionedAuthoritiesFromName(const std::string &authName); //! @endcond protected: PROJ_INTERNAL DatabaseContext(); INLINED_MAKE_SHARED PROJ_FRIEND(AuthorityFactory); private: PROJ_OPAQUE_PRIVATE_DATA DatabaseContext(const DatabaseContext &) = delete; DatabaseContext &operator=(const DatabaseContext &other) = delete; }; // --------------------------------------------------------------------------- class AuthorityFactory; /** Shared pointer of AuthorityFactory. */ using AuthorityFactoryPtr = std::shared_ptr<AuthorityFactory>; /** Non-null shared pointer of AuthorityFactory. */ using AuthorityFactoryNNPtr = util::nn<AuthorityFactoryPtr>; /** \brief Builds object from an authority database. * * A AuthorityFactory should be used only by one thread at a time. * * \remark Implements [AuthorityFactory] * (http://www.geoapi.org/3.0/javadoc/org.opengis.geoapi/org/opengis/referencing/AuthorityFactory.html) * from \ref GeoAPI */ class PROJ_GCC_DLL AuthorityFactory { public: //! @cond Doxygen_Suppress PROJ_DLL ~AuthorityFactory(); //! @endcond PROJ_DLL util::BaseObjectNNPtr createObject(const std::string &code) const; PROJ_DLL common::UnitOfMeasureNNPtr createUnitOfMeasure(const std::string &code) const; PROJ_DLL metadata::ExtentNNPtr createExtent(const std::string &code) const; PROJ_DLL datum::PrimeMeridianNNPtr createPrimeMeridian(const std::string &code) const; PROJ_DLL std::string identifyBodyFromSemiMajorAxis(double a, double tolerance) const; PROJ_DLL datum::EllipsoidNNPtr createEllipsoid(const std::string &code) const; PROJ_DLL datum::DatumNNPtr createDatum(const std::string &code) const; PROJ_DLL datum::DatumEnsembleNNPtr createDatumEnsemble(const std::string &code, const std::string &type = std::string()) const; PROJ_DLL datum::GeodeticReferenceFrameNNPtr createGeodeticDatum(const std::string &code) const; PROJ_DLL datum::VerticalReferenceFrameNNPtr createVerticalDatum(const std::string &code) const; PROJ_DLL cs::CoordinateSystemNNPtr createCoordinateSystem(const std::string &code) const; PROJ_DLL crs::GeodeticCRSNNPtr createGeodeticCRS(const std::string &code) const; PROJ_DLL crs::GeographicCRSNNPtr createGeographicCRS(const std::string &code) const; PROJ_DLL crs::VerticalCRSNNPtr createVerticalCRS(const std::string &code) const; PROJ_DLL operation::ConversionNNPtr createConversion(const std::string &code) const; PROJ_DLL crs::ProjectedCRSNNPtr createProjectedCRS(const std::string &code) const; PROJ_DLL crs::CompoundCRSNNPtr createCompoundCRS(const std::string &code) const; PROJ_DLL crs::CRSNNPtr createCoordinateReferenceSystem(const std::string &code) const; PROJ_DLL coordinates::CoordinateMetadataNNPtr createCoordinateMetadata(const std::string &code) const; PROJ_DLL operation::CoordinateOperationNNPtr createCoordinateOperation(const std::string &code, bool usePROJAlternativeGridNames) const; PROJ_DLL std::vector<operation::CoordinateOperationNNPtr> createFromCoordinateReferenceSystemCodes( const std::string &sourceCRSCode, const std::string &targetCRSCode) const; PROJ_DLL std::list<std::string> getGeoidModels(const std::string &code) const; PROJ_DLL const std::string &getAuthority() PROJ_PURE_DECL; /** Object type. */ enum class ObjectType { /** Object of type datum::PrimeMeridian */ PRIME_MERIDIAN, /** Object of type datum::Ellipsoid */ ELLIPSOID, /** Object of type datum::Datum (and derived classes) */ DATUM, /** Object of type datum::GeodeticReferenceFrame (and derived classes) */ GEODETIC_REFERENCE_FRAME, /** Object of type datum::VerticalReferenceFrame (and derived classes) */ VERTICAL_REFERENCE_FRAME, /** Object of type crs::CRS (and derived classes) */ CRS, /** Object of type crs::GeodeticCRS (and derived classes) */ GEODETIC_CRS, /** GEODETIC_CRS of type geocentric */ GEOCENTRIC_CRS, /** Object of type crs::GeographicCRS (and derived classes) */ GEOGRAPHIC_CRS, /** GEOGRAPHIC_CRS of type Geographic 2D */ GEOGRAPHIC_2D_CRS, /** GEOGRAPHIC_CRS of type Geographic 3D */ GEOGRAPHIC_3D_CRS, /** Object of type crs::ProjectedCRS (and derived classes) */ PROJECTED_CRS, /** Object of type crs::VerticalCRS (and derived classes) */ VERTICAL_CRS, /** Object of type crs::CompoundCRS (and derived classes) */ COMPOUND_CRS, /** Object of type operation::CoordinateOperation (and derived classes) */ COORDINATE_OPERATION, /** Object of type operation::Conversion (and derived classes) */ CONVERSION, /** Object of type operation::Transformation (and derived classes) */ TRANSFORMATION, /** Object of type operation::ConcatenatedOperation (and derived classes) */ CONCATENATED_OPERATION, /** Object of type datum::DynamicGeodeticReferenceFrame */ DYNAMIC_GEODETIC_REFERENCE_FRAME, /** Object of type datum::DynamicVerticalReferenceFrame */ DYNAMIC_VERTICAL_REFERENCE_FRAME, /** Object of type datum::DatumEnsemble */ DATUM_ENSEMBLE, }; PROJ_DLL std::set<std::string> getAuthorityCodes(const ObjectType &type, bool allowDeprecated = true) const; PROJ_DLL std::string getDescriptionText(const std::string &code) const; // non-standard /** CRS information */ struct CRSInfo { /** Authority name */ std::string authName; /** Code */ std::string code; /** Name */ std::string name; /** Type */ ObjectType type; /** Whether the object is deprecated */ bool deprecated; /** Whereas the west_lon_degree, south_lat_degree, east_lon_degree and * north_lat_degree fields are valid. */ bool bbox_valid; /** Western-most longitude of the area of use, in degrees. */ double west_lon_degree; /** Southern-most latitude of the area of use, in degrees. */ double south_lat_degree; /** Eastern-most longitude of the area of use, in degrees. */ double east_lon_degree; /** Northern-most latitude of the area of use, in degrees. */ double north_lat_degree; /** Name of the area of use. */ std::string areaName; /** Name of the projection method for a projected CRS. Might be empty * even for projected CRS in some cases. */ std::string projectionMethodName; /** Name of the celestial body of the CRS (e.g. "Earth") */ std::string celestialBodyName; //! @cond Doxygen_Suppress CRSInfo(); //! @endcond }; PROJ_DLL std::list<CRSInfo> getCRSInfoList() const; /** Unit information */ struct UnitInfo { /** Authority name */ std::string authName; /** Code */ std::string code; /** Name */ std::string name; /** Category: one of "linear", "linear_per_time", "angular", * "angular_per_time", "scale", "scale_per_time" or "time" */ std::string category; /** Conversion factor to the SI unit. * It might be 0 in some cases to indicate no known conversion factor. */ double convFactor; /** PROJ short name (may be empty) */ std::string projShortName; /** Whether the object is deprecated */ bool deprecated; //! @cond Doxygen_Suppress UnitInfo(); //! @endcond }; PROJ_DLL std::list<UnitInfo> getUnitList() const; /** Celestial Body information */ struct CelestialBodyInfo { /** Authority name */ std::string authName; /** Name */ std::string name; //! @cond Doxygen_Suppress CelestialBodyInfo(); //! @endcond }; PROJ_DLL std::list<CelestialBodyInfo> getCelestialBodyList() const; PROJ_DLL static AuthorityFactoryNNPtr create(const DatabaseContextNNPtr &context, const std::string &authorityName); PROJ_DLL const DatabaseContextNNPtr &databaseContext() const; PROJ_DLL std::vector<operation::CoordinateOperationNNPtr> createFromCoordinateReferenceSystemCodes( const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, const std::string &targetCRSAuthName, const std::string &targetCRSCode, bool usePROJAlternativeGridNames, bool discardIfMissingGrid, bool considerKnownGridsAsAvailable, bool discardSuperseded, bool tryReverseOrder = false, bool reportOnlyIntersectingTransformations = false, const metadata::ExtentPtr &intersectingExtent1 = nullptr, const metadata::ExtentPtr &intersectingExtent2 = nullptr) const; PROJ_DLL std::vector<operation::CoordinateOperationNNPtr> createFromCRSCodesWithIntermediates( const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, const std::string &targetCRSAuthName, const std::string &targetCRSCode, bool usePROJAlternativeGridNames, bool discardIfMissingGrid, bool considerKnownGridsAsAvailable, bool discardSuperseded, const std::vector<std::pair<std::string, std::string>> &intermediateCRSAuthCodes, ObjectType allowedIntermediateObjectType = ObjectType::CRS, const std::vector<std::string> &allowedAuthorities = std::vector<std::string>(), const metadata::ExtentPtr &intersectingExtent1 = nullptr, const metadata::ExtentPtr &intersectingExtent2 = nullptr) const; PROJ_DLL std::string getOfficialNameFromAlias( const std::string &aliasedName, const std::string &tableName, const std::string &source, bool tryEquivalentNameSpelling, std::string &outTableName, std::string &outAuthName, std::string &outCode) const; PROJ_DLL std::list<common::IdentifiedObjectNNPtr> createObjectsFromName(const std::string &name, const std::vector<ObjectType> &allowedObjectTypes = std::vector<ObjectType>(), bool approximateMatch = true, size_t limitResultCount = 0) const; PROJ_DLL std::list<std::pair<std::string, std::string>> listAreaOfUseFromName(const std::string &name, bool approximateMatch) const; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL std::list<datum::EllipsoidNNPtr> createEllipsoidFromExisting( const datum::EllipsoidNNPtr &ellipsoid) const; PROJ_INTERNAL std::list<crs::GeodeticCRSNNPtr> createGeodeticCRSFromDatum(const std::string &datum_auth_name, const std::string &datum_code, const std::string &geodetic_crs_type) const; PROJ_INTERNAL std::list<crs::GeodeticCRSNNPtr> createGeodeticCRSFromDatum(const datum::GeodeticReferenceFrameNNPtr &datum, const std::string &preferredAuthName, const std::string &geodetic_crs_type) const; PROJ_INTERNAL std::list<crs::VerticalCRSNNPtr> createVerticalCRSFromDatum(const std::string &datum_auth_name, const std::string &datum_code) const; PROJ_INTERNAL std::list<crs::GeodeticCRSNNPtr> createGeodeticCRSFromEllipsoid(const std::string &ellipsoid_auth_name, const std::string &ellipsoid_code, const std::string &geodetic_crs_type) const; PROJ_INTERNAL std::list<crs::ProjectedCRSNNPtr> createProjectedCRSFromExisting(const crs::ProjectedCRSNNPtr &crs) const; PROJ_INTERNAL std::list<crs::CompoundCRSNNPtr> createCompoundCRSFromExisting(const crs::CompoundCRSNNPtr &crs) const; PROJ_INTERNAL crs::CRSNNPtr createCoordinateReferenceSystem(const std::string &code, bool allowCompound) const; PROJ_INTERNAL std::vector<operation::CoordinateOperationNNPtr> getTransformationsForGeoid(const std::string &geoidName, bool usePROJAlternativeGridNames) const; PROJ_INTERNAL std::vector<operation::CoordinateOperationNNPtr> createBetweenGeodeticCRSWithDatumBasedIntermediates( const crs::CRSNNPtr &sourceCRS, const std::string &sourceCRSAuthName, const std::string &sourceCRSCode, const crs::CRSNNPtr &targetCRS, const std::string &targetCRSAuthName, const std::string &targetCRSCode, bool usePROJAlternativeGridNames, bool discardIfMissingGrid, bool considerKnownGridsAsAvailable, bool discardSuperseded, const std::vector<std::string> &allowedAuthorities, const metadata::ExtentPtr &intersectingExtent1, const metadata::ExtentPtr &intersectingExtent2) const; typedef std::pair<common::IdentifiedObjectNNPtr, std::string> PairObjectName; PROJ_INTERNAL std::list<PairObjectName> createObjectsFromNameEx(const std::string &name, const std::vector<ObjectType> &allowedObjectTypes = std::vector<ObjectType>(), bool approximateMatch = true, size_t limitResultCount = 0) const; PROJ_FOR_TEST std::vector<operation::PointMotionOperationNNPtr> getPointMotionOperationsFor(const crs::GeodeticCRSNNPtr &crs, bool usePROJAlternativeGridNames) const; //! @endcond protected: PROJ_INTERNAL AuthorityFactory(const DatabaseContextNNPtr &context, const std::string &authorityName); PROJ_INTERNAL crs::GeodeticCRSNNPtr createGeodeticCRS(const std::string &code, bool geographicOnly) const; PROJ_INTERNAL operation::CoordinateOperationNNPtr createCoordinateOperation(const std::string &code, bool allowConcatenated, bool usePROJAlternativeGridNames, const std::string &type) const; INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA PROJ_INTERNAL void createGeodeticDatumOrEnsemble(const std::string &code, datum::GeodeticReferenceFramePtr &outDatum, datum::DatumEnsemblePtr &outDatumEnsemble, bool turnEnsembleAsDatum) const; PROJ_INTERNAL void createVerticalDatumOrEnsemble(const std::string &code, datum::VerticalReferenceFramePtr &outDatum, datum::DatumEnsemblePtr &outDatumEnsemble, bool turnEnsembleAsDatum) const; }; // --------------------------------------------------------------------------- /** \brief Exception thrown when a factory can't create an instance of the * requested object. */ class PROJ_GCC_DLL FactoryException : public util::Exception { public: //! @cond Doxygen_Suppress PROJ_DLL explicit FactoryException(const char *message); PROJ_DLL explicit FactoryException(const std::string &message); PROJ_DLL FactoryException(const FactoryException &other); PROJ_DLL ~FactoryException() override; //! @endcond }; // --------------------------------------------------------------------------- /** \brief Exception thrown when an authority factory can't find the requested * authority code. */ class PROJ_GCC_DLL NoSuchAuthorityCodeException : public FactoryException { public: //! @cond Doxygen_Suppress PROJ_DLL explicit NoSuchAuthorityCodeException(const std::string &message, const std::string &authority, const std::string &code); PROJ_DLL NoSuchAuthorityCodeException(const NoSuchAuthorityCodeException &other); PROJ_DLL ~NoSuchAuthorityCodeException() override; //! @endcond PROJ_DLL const std::string &getAuthority() const; PROJ_DLL const std::string &getAuthorityCode() const; private: PROJ_OPAQUE_PRIVATE_DATA }; } // namespace io NS_PROJ_END #endif // IO_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/common.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef COMMON_HH_INCLUDED #define COMMON_HH_INCLUDED #include <memory> #include <string> #include <vector> #include "io.hpp" #include "metadata.hpp" #include "util.hpp" NS_PROJ_START /** osgeo.proj.common namespace * * \brief Common classes. */ namespace common { // --------------------------------------------------------------------------- class UnitOfMeasure; /** Shared pointer of UnitOfMeasure. */ using UnitOfMeasurePtr = std::shared_ptr<UnitOfMeasure>; /** Non-null shared pointer of UnitOfMeasure. */ using UnitOfMeasureNNPtr = util::nn<UnitOfMeasurePtr>; /** \brief Unit of measure. * * This is a mutable object. */ class PROJ_GCC_DLL UnitOfMeasure : public util::BaseObject { public: /** \brief Type of unit of measure. */ enum class PROJ_MSVC_DLL Type { /** Unknown unit of measure */ UNKNOWN, /** No unit of measure */ NONE, /** Angular unit of measure */ ANGULAR, /** Linear unit of measure */ LINEAR, /** Scale unit of measure */ SCALE, /** Time unit of measure */ TIME, /** Parametric unit of measure */ PARAMETRIC, }; PROJ_DLL explicit UnitOfMeasure( const std::string &nameIn = std::string(), double toSIIn = 1.0, Type typeIn = Type::UNKNOWN, const std::string &codeSpaceIn = std::string(), const std::string &codeIn = std::string()); //! @cond Doxygen_Suppress PROJ_DLL UnitOfMeasure(const UnitOfMeasure &other); PROJ_DLL ~UnitOfMeasure() override; PROJ_DLL UnitOfMeasure &operator=(const UnitOfMeasure &other); PROJ_DLL UnitOfMeasure &operator=(UnitOfMeasure &&other); PROJ_INTERNAL static UnitOfMeasureNNPtr create(const UnitOfMeasure &other); //! @endcond PROJ_DLL const std::string &name() PROJ_PURE_DECL; PROJ_DLL double conversionToSI() PROJ_PURE_DECL; PROJ_DLL Type type() PROJ_PURE_DECL; PROJ_DLL const std::string &codeSpace() PROJ_PURE_DECL; PROJ_DLL const std::string &code() PROJ_PURE_DECL; PROJ_DLL bool operator==(const UnitOfMeasure &other) PROJ_PURE_DECL; PROJ_DLL bool operator!=(const UnitOfMeasure &other) PROJ_PURE_DECL; //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter, const std::string &unitType = std::string()) const; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON( io::JSONFormatter *formatter) const; // throw(io::FormattingException) PROJ_INTERNAL std::string exportToPROJString() const; PROJ_INTERNAL bool _isEquivalentTo(const UnitOfMeasure &other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT) const; //! @endcond PROJ_DLL static const UnitOfMeasure NONE; PROJ_DLL static const UnitOfMeasure SCALE_UNITY; PROJ_DLL static const UnitOfMeasure PARTS_PER_MILLION; PROJ_DLL static const UnitOfMeasure PPM_PER_YEAR; PROJ_DLL static const UnitOfMeasure METRE; PROJ_DLL static const UnitOfMeasure METRE_PER_YEAR; PROJ_DLL static const UnitOfMeasure FOOT; PROJ_DLL static const UnitOfMeasure US_FOOT; PROJ_DLL static const UnitOfMeasure RADIAN; PROJ_DLL static const UnitOfMeasure MICRORADIAN; PROJ_DLL static const UnitOfMeasure DEGREE; PROJ_DLL static const UnitOfMeasure ARC_SECOND; PROJ_DLL static const UnitOfMeasure GRAD; PROJ_DLL static const UnitOfMeasure ARC_SECOND_PER_YEAR; PROJ_DLL static const UnitOfMeasure SECOND; PROJ_DLL static const UnitOfMeasure YEAR; private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Numeric value associated with a UnitOfMeasure. */ class Measure : public util::BaseObject { public: // cppcheck-suppress noExplicitConstructor PROJ_DLL Measure(double valueIn = 0.0, const UnitOfMeasure &unitIn = UnitOfMeasure()); //! @cond Doxygen_Suppress PROJ_DLL Measure(const Measure &other); PROJ_DLL ~Measure() override; //! @endcond PROJ_DLL const UnitOfMeasure &unit() PROJ_PURE_DECL; PROJ_DLL double getSIValue() PROJ_PURE_DECL; PROJ_DLL double value() PROJ_PURE_DECL; PROJ_DLL double convertToUnit(const UnitOfMeasure &otherUnit) PROJ_PURE_DECL; PROJ_DLL bool operator==(const Measure &other) PROJ_PURE_DECL; /** Default maximum resulative error. */ static constexpr double DEFAULT_MAX_REL_ERROR = 1e-10; PROJ_INTERNAL bool _isEquivalentTo(const Measure &other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, double maxRelativeError = DEFAULT_MAX_REL_ERROR) const; private: PROJ_OPAQUE_PRIVATE_DATA Measure &operator=(const Measure &) = delete; }; // --------------------------------------------------------------------------- /** \brief Numeric value, without a physical unit of measure. */ class Scale : public Measure { public: PROJ_DLL explicit Scale(double valueIn = 0.0); PROJ_DLL explicit Scale(double valueIn, const UnitOfMeasure &unitIn); //! @cond Doxygen_Suppress explicit Scale(const Measure &other) : Scale(other.value(), other.unit()) {} PROJ_DLL Scale(const Scale &other); PROJ_DLL ~Scale() override; //! @endcond protected: PROJ_FRIEND_OPTIONAL(Scale); Scale &operator=(const Scale &) = delete; }; // --------------------------------------------------------------------------- /** \brief Numeric value, with a angular unit of measure. */ class Angle : public Measure { public: PROJ_DLL explicit Angle(double valueIn = 0.0); PROJ_DLL Angle(double valueIn, const UnitOfMeasure &unitIn); //! @cond Doxygen_Suppress explicit Angle(const Measure &other) : Angle(other.value(), other.unit()) {} PROJ_DLL Angle(const Angle &other); PROJ_DLL ~Angle() override; //! @endcond protected: PROJ_FRIEND_OPTIONAL(Angle); Angle &operator=(const Angle &) = delete; }; // --------------------------------------------------------------------------- /** \brief Numeric value, with a linear unit of measure. */ class Length : public Measure { public: PROJ_DLL explicit Length(double valueIn = 0.0); PROJ_DLL Length(double valueIn, const UnitOfMeasure &unitIn); //! @cond Doxygen_Suppress explicit Length(const Measure &other) : Length(other.value(), other.unit()) {} PROJ_DLL Length(const Length &other); PROJ_DLL ~Length() override; //! @endcond protected: PROJ_FRIEND_OPTIONAL(Length); Length &operator=(const Length &) = delete; }; // --------------------------------------------------------------------------- /** \brief Date-time value, as a ISO:8601 encoded string, or other string * encoding */ class DateTime { public: //! @cond Doxygen_Suppress PROJ_DLL DateTime(const DateTime &other); PROJ_DLL ~DateTime(); //! @endcond PROJ_DLL bool isISO_8601() const; PROJ_DLL std::string toString() const; PROJ_DLL static DateTime create(const std::string &str); // may throw Exception protected: DateTime(); PROJ_FRIEND_OPTIONAL(DateTime); DateTime &operator=(const DateTime &other); private: explicit DateTime(const std::string &str); PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- /** \brief Data epoch */ class DataEpoch { public: //! @cond Doxygen_Suppress PROJ_DLL explicit DataEpoch(const Measure &coordinateEpochIn); PROJ_DLL DataEpoch(const DataEpoch &other); PROJ_DLL ~DataEpoch(); //! @endcond PROJ_DLL const Measure &coordinateEpoch() const; protected: DataEpoch(); PROJ_FRIEND_OPTIONAL(DataEpoch); private: DataEpoch &operator=(const DataEpoch &other) = delete; PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class IdentifiedObject; /** Shared pointer of IdentifiedObject. */ using IdentifiedObjectPtr = std::shared_ptr<IdentifiedObject>; /** Non-null shared pointer of IdentifiedObject. */ using IdentifiedObjectNNPtr = util::nn<IdentifiedObjectPtr>; /** \brief Abstract class representing a CRS-related object that has an * identification. * * \remark Implements IdentifiedObject from \ref ISO_19111_2019 */ class PROJ_GCC_DLL IdentifiedObject : public util::BaseObject, public util::IComparable, public io::IWKTExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~IdentifiedObject() override; //! @endcond PROJ_DLL static const std::string NAME_KEY; PROJ_DLL static const std::string IDENTIFIERS_KEY; PROJ_DLL static const std::string ALIAS_KEY; PROJ_DLL static const std::string REMARKS_KEY; PROJ_DLL static const std::string DEPRECATED_KEY; // in practice only name().description() is used PROJ_DLL const metadata::IdentifierNNPtr &name() PROJ_PURE_DECL; PROJ_DLL const std::string &nameStr() PROJ_PURE_DECL; PROJ_DLL const std::vector<metadata::IdentifierNNPtr> & identifiers() PROJ_PURE_DECL; PROJ_DLL const std::vector<util::GenericNameNNPtr> & aliases() PROJ_PURE_DECL; PROJ_DLL const std::string &remarks() PROJ_PURE_DECL; // from Apache SIS AbstractIdentifiedObject PROJ_DLL bool isDeprecated() PROJ_PURE_DECL; // Non-standard PROJ_DLL std::string alias() PROJ_PURE_DECL; PROJ_DLL int getEPSGCode() PROJ_PURE_DECL; PROJ_PRIVATE : //! @cond Doxygen_Suppress void formatID(io::WKTFormatter *formatter) const; PROJ_INTERNAL void formatID(io::JSONFormatter *formatter) const; PROJ_INTERNAL void formatRemarks(io::WKTFormatter *formatter) const; PROJ_INTERNAL void formatRemarks(io::JSONFormatter *formatter) const; PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL bool _isEquivalentTo( const IdentifiedObject *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) PROJ_PURE_DECL; //! @endcond protected: PROJ_FRIEND_OPTIONAL(IdentifiedObject); INLINED_MAKE_SHARED IdentifiedObject(); IdentifiedObject(const IdentifiedObject &other); void setProperties(const util::PropertyMap &properties); // throw(InvalidValueTypeException) virtual bool hasEquivalentNameToUsingAlias( const IdentifiedObject *other, const io::DatabaseContextPtr &dbContext) const; private: PROJ_OPAQUE_PRIVATE_DATA IdentifiedObject &operator=(const IdentifiedObject &other) = delete; }; // --------------------------------------------------------------------------- class ObjectDomain; /** Shared pointer of ObjectDomain. */ using ObjectDomainPtr = std::shared_ptr<ObjectDomain>; /** Non-null shared pointer of ObjectDomain. */ using ObjectDomainNNPtr = util::nn<ObjectDomainPtr>; /** \brief The scope and validity of a CRS-related object. * * \remark Implements ObjectDomain from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ObjectDomain : public util::BaseObject, public util::IComparable { public: //! @cond Doxygen_Suppress PROJ_DLL ~ObjectDomain() override; //! @endcond // In ISO_19111:2018, scope and domain are compulsory, but in WKT2:2015, // they // are not necessarily both specified PROJ_DLL const util::optional<std::string> &scope() PROJ_PURE_DECL; PROJ_DLL const metadata::ExtentPtr &domainOfValidity() PROJ_PURE_DECL; PROJ_DLL static ObjectDomainNNPtr create(const util::optional<std::string> &scopeIn, const metadata::ExtentPtr &extent); PROJ_PRIVATE : //! @cond Doxygen_Suppress void _exportToWKT(io::WKTFormatter *formatter) const; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON( io::JSONFormatter *formatter) const; // throw(FormattingException) bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: //! @cond Doxygen_Suppress ObjectDomain(const util::optional<std::string> &scopeIn, const metadata::ExtentPtr &extent); //! @endcond ObjectDomain(const ObjectDomain &other); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA ObjectDomain &operator=(const ObjectDomain &other) = delete; }; // --------------------------------------------------------------------------- class ObjectUsage; /** Shared pointer of ObjectUsage. */ using ObjectUsagePtr = std::shared_ptr<ObjectUsage>; /** Non-null shared pointer of ObjectUsage. */ using ObjectUsageNNPtr = util::nn<ObjectUsagePtr>; /** \brief Abstract class of a CRS-related object that has usages. * * \remark Implements ObjectUsage from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ObjectUsage : public IdentifiedObject { public: //! @cond Doxygen_Suppress PROJ_DLL ~ObjectUsage() override; //! @endcond PROJ_DLL const std::vector<ObjectDomainNNPtr> &domains() PROJ_PURE_DECL; PROJ_DLL static const std::string SCOPE_KEY; PROJ_DLL static const std::string DOMAIN_OF_VALIDITY_KEY; PROJ_DLL static const std::string OBJECT_DOMAIN_KEY; //! @cond Doxygen_Suppress bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: ObjectUsage(); ObjectUsage(const ObjectUsage &other); void setProperties(const util::PropertyMap &properties); // throw(InvalidValueTypeException) void baseExportToWKT( io::WKTFormatter *formatter) const; // throw(io::FormattingException) void baseExportToJSON( io::JSONFormatter *formatter) const; // throw(io::FormattingException) private: PROJ_OPAQUE_PRIVATE_DATA ObjectUsage &operator=(const ObjectUsage &other) = delete; }; } // namespace common NS_PROJ_END #endif // COMMON_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/datum.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef DATUM_HH_INCLUDED #define DATUM_HH_INCLUDED #include <memory> #include <string> #include <vector> #include "common.hpp" #include "io.hpp" #include "util.hpp" NS_PROJ_START /** osgeo.proj.datum namespace \brief Datum (the relationship of a coordinate system to the body). */ namespace datum { // --------------------------------------------------------------------------- /** \brief Abstract class of the relationship of a coordinate system to an * object, thus creating a coordinate reference system. * * For geodetic and vertical coordinate reference systems, it relates a * coordinate system to the Earth (or the celestial body considered). With * other types of coordinate reference systems, the datum may relate the * coordinate system to another physical or * virtual object. A datum uses a parameter or set of parameters that determine * the location of the origin of the coordinate reference system. Each datum * subtype can be associated with only specific types of coordinate reference * systems. * * \remark Implements Datum from \ref ISO_19111_2019 */ class PROJ_GCC_DLL Datum : public common::ObjectUsage, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~Datum() override; //! @endcond PROJ_DLL const util::optional<std::string> &anchorDefinition() const; PROJ_DLL const util::optional<common::Measure> &anchorEpoch() const; PROJ_DLL const util::optional<common::DateTime> &publicationDate() const; PROJ_DLL const common::IdentifiedObjectPtr &conventionalRS() const; //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL Datum(); #ifdef DOXYGEN_ENABLED std::string *anchorDefinition_; Date *publicationDate_; common::IdentifiedObject *conventionalRS_; #endif protected: PROJ_INTERNAL void setAnchor(const util::optional<std::string> &anchor); PROJ_INTERNAL void setAnchorEpoch(const util::optional<common::Measure> &anchorEpoch); PROJ_INTERNAL void setProperties(const util::PropertyMap &properties); // throw(InvalidValueTypeException) private: PROJ_OPAQUE_PRIVATE_DATA Datum &operator=(const Datum &other) = delete; Datum(const Datum &other) = delete; }; /** Shared pointer of Datum */ using DatumPtr = std::shared_ptr<Datum>; /** Non-null shared pointer of Datum */ using DatumNNPtr = util::nn<DatumPtr>; // --------------------------------------------------------------------------- class DatumEnsemble; /** Shared pointer of DatumEnsemble */ using DatumEnsemblePtr = std::shared_ptr<DatumEnsemble>; /** Non-null shared pointer of DatumEnsemble */ using DatumEnsembleNNPtr = util::nn<DatumEnsemblePtr>; /** \brief A collection of two or more geodetic or vertical reference frames * (or if not geodetic or vertical reference frame, a collection of two or more * datums) which for all but the highest accuracy requirements may be * considered to be insignificantly different from each other. * * Every frame within the datum ensemble must be a realizations of the same * Terrestrial Reference System or Vertical Reference System. * * \remark Implements DatumEnsemble from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DatumEnsemble final : public common::ObjectUsage, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~DatumEnsemble() override; //! @endcond PROJ_DLL const std::vector<DatumNNPtr> &datums() const; PROJ_DLL const metadata::PositionalAccuracyNNPtr & positionalAccuracy() const; PROJ_DLL static DatumEnsembleNNPtr create( const util::PropertyMap &properties, const std::vector<DatumNNPtr> &datumsIn, const metadata::PositionalAccuracyNNPtr &accuracy); // throw(Exception) //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(io::FormattingException) PROJ_FOR_TEST DatumNNPtr asDatum(const io::DatabaseContextPtr &dbContext) const; //! @endcond protected: #ifdef DOXYGEN_ENABLED Datum datums_[]; PositionalAccuracy positionalAccuracy_; #endif PROJ_INTERNAL DatumEnsemble(const std::vector<DatumNNPtr> &datumsIn, const metadata::PositionalAccuracyNNPtr &accuracy); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA DatumEnsemble(const DatumEnsemble &other) = delete; DatumEnsemble &operator=(const DatumEnsemble &other) = delete; }; // --------------------------------------------------------------------------- class PrimeMeridian; /** Shared pointer of PrimeMeridian */ using PrimeMeridianPtr = std::shared_ptr<PrimeMeridian>; /** Non-null shared pointer of PrimeMeridian */ using PrimeMeridianNNPtr = util::nn<PrimeMeridianPtr>; /** \brief The origin meridian from which longitude values are determined. * * \note The default value for prime meridian name is "Greenwich". When the * default applies, the value for the longitude shall be 0 (degrees). * * \remark Implements PrimeMeridian from \ref ISO_19111_2019 */ class PROJ_GCC_DLL PrimeMeridian final : public common::IdentifiedObject, public io::IPROJStringExportable, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~PrimeMeridian() override; //! @endcond PROJ_DLL const common::Angle &longitude() PROJ_PURE_DECL; // non-standard PROJ_DLL static PrimeMeridianNNPtr create(const util::PropertyMap &properties, const common::Angle &longitudeIn); PROJ_DLL static const PrimeMeridianNNPtr GREENWICH; PROJ_DLL static const PrimeMeridianNNPtr REFERENCE_MERIDIAN; PROJ_DLL static const PrimeMeridianNNPtr PARIS; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL static std::string getPROJStringWellKnownName(const common::Angle &angle); //! @endcond protected: #ifdef DOXYGEN_ENABLED Angle greenwichLongitude_; #endif PROJ_INTERNAL explicit PrimeMeridian( const common::Angle &angle = common::Angle()); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA PrimeMeridian(const PrimeMeridian &other) = delete; PrimeMeridian &operator=(const PrimeMeridian &other) = delete; PROJ_INTERNAL static const PrimeMeridianNNPtr createGREENWICH(); PROJ_INTERNAL static const PrimeMeridianNNPtr createREFERENCE_MERIDIAN(); PROJ_INTERNAL static const PrimeMeridianNNPtr createPARIS(); }; // --------------------------------------------------------------------------- class Ellipsoid; /** Shared pointer of Ellipsoid */ using EllipsoidPtr = std::shared_ptr<Ellipsoid>; /** Non-null shared pointer of Ellipsoid */ using EllipsoidNNPtr = util::nn<EllipsoidPtr>; /** \brief A geometric figure that can be used to describe the approximate * shape of an object. * * For the Earth an oblate biaxial ellipsoid is used: in mathematical terms, * it is a surface formed by the rotation of an ellipse about its minor axis. * * \remark Implements Ellipsoid from \ref ISO_19111_2019 */ class PROJ_GCC_DLL Ellipsoid final : public common::IdentifiedObject, public io::IPROJStringExportable, public io::IJSONExportable { public: //! @cond Doxygen_Suppress PROJ_DLL ~Ellipsoid() override; //! @endcond PROJ_DLL const common::Length &semiMajorAxis() PROJ_PURE_DECL; // Inlined from SecondDefiningParameter union PROJ_DLL const util::optional<common::Scale> & inverseFlattening() PROJ_PURE_DECL; PROJ_DLL const util::optional<common::Length> & semiMinorAxis() PROJ_PURE_DECL; PROJ_DLL bool isSphere() PROJ_PURE_DECL; PROJ_DLL const util::optional<common::Length> & semiMedianAxis() PROJ_PURE_DECL; // non-standard PROJ_DLL double computedInverseFlattening() PROJ_PURE_DECL; PROJ_DLL double squaredEccentricity() PROJ_PURE_DECL; PROJ_DLL common::Length computeSemiMinorAxis() const; PROJ_DLL const std::string &celestialBody() PROJ_PURE_DECL; PROJ_DLL static const std::string EARTH; PROJ_DLL static EllipsoidNNPtr createSphere(const util::PropertyMap &properties, const common::Length &radius, const std::string &celestialBody = EARTH); PROJ_DLL static EllipsoidNNPtr createFlattenedSphere(const util::PropertyMap &properties, const common::Length &semiMajorAxisIn, const common::Scale &invFlattening, const std::string &celestialBody = EARTH); PROJ_DLL static EllipsoidNNPtr createTwoAxis(const util::PropertyMap &properties, const common::Length &semiMajorAxisIn, const common::Length &semiMinorAxisIn, const std::string &celestialBody = EARTH); PROJ_DLL EllipsoidNNPtr identify() const; PROJ_DLL static const EllipsoidNNPtr CLARKE_1866; PROJ_DLL static const EllipsoidNNPtr WGS84; PROJ_DLL static const EllipsoidNNPtr GRS1980; PROJ_PRIVATE : //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL void _exportToPROJString(io::PROJStringFormatter *formatter) const override; // throw(FormattingException) //! @endcond PROJ_INTERNAL static std::string guessBodyName(const io::DatabaseContextPtr &dbContext, double a); PROJ_INTERNAL bool lookForProjWellKnownEllps(std::string &projEllpsName, std::string &ellpsName) const; protected: #ifdef DOXYGEN_ENABLED common::Length semiMajorAxis_; common::Scale *inverseFlattening_; common::Length *semiMinorAxis_; bool isSphere_; common::Length *semiMedianAxis_; #endif PROJ_INTERNAL explicit Ellipsoid(const common::Length &radius, const std::string &celestialBody); PROJ_INTERNAL Ellipsoid(const common::Length &semiMajorAxisIn, const common::Scale &invFlattening, const std::string &celestialBody); PROJ_INTERNAL Ellipsoid(const common::Length &semiMajorAxisIn, const common::Length &semiMinorAxisIn, const std::string &celestialBody); PROJ_INTERNAL Ellipsoid(const Ellipsoid &other); INLINED_MAKE_SHARED PROJ_INTERNAL static const EllipsoidNNPtr createCLARKE_1866(); PROJ_INTERNAL static const EllipsoidNNPtr createWGS84(); PROJ_INTERNAL static const EllipsoidNNPtr createGRS1980(); private: PROJ_OPAQUE_PRIVATE_DATA Ellipsoid &operator=(const Ellipsoid &other) = delete; }; // --------------------------------------------------------------------------- class GeodeticReferenceFrame; /** Shared pointer of GeodeticReferenceFrame */ using GeodeticReferenceFramePtr = std::shared_ptr<GeodeticReferenceFrame>; /** Non-null shared pointer of GeodeticReferenceFrame */ using GeodeticReferenceFrameNNPtr = util::nn<GeodeticReferenceFramePtr>; /** \brief The definition of the position, scale and orientation of a geocentric * Cartesian 3D coordinate system relative to the Earth. * * It may also identify a defined ellipsoid (or sphere) that approximates * the shape of the Earth and which is centred on and aligned to this * geocentric coordinate system. Older geodetic datums define the location and * orientation of a defined ellipsoid (or sphere) that approximates the shape * of the earth. * * \note The terminology "Datum" is often used to mean a GeodeticReferenceFrame. * * \note In \ref ISO_19111_2007, this class was called GeodeticDatum. * * \remark Implements GeodeticReferenceFrame from \ref ISO_19111_2019 */ class PROJ_GCC_DLL GeodeticReferenceFrame : public Datum { public: //! @cond Doxygen_Suppress PROJ_DLL ~GeodeticReferenceFrame() override; //! @endcond PROJ_DLL const PrimeMeridianNNPtr &primeMeridian() PROJ_PURE_DECL; // We constraint more than the standard into which the ellipsoid might // be omitted for a CRS with a non-ellipsoidal CS PROJ_DLL const EllipsoidNNPtr &ellipsoid() PROJ_PURE_DECL; // non-standard PROJ_DLL static GeodeticReferenceFrameNNPtr create(const util::PropertyMap &properties, const EllipsoidNNPtr &ellipsoid, const util::optional<std::string> &anchor, const PrimeMeridianNNPtr &primeMeridian); PROJ_DLL static GeodeticReferenceFrameNNPtr create(const util::PropertyMap &properties, const EllipsoidNNPtr &ellipsoid, const util::optional<std::string> &anchor, const util::optional<common::Measure> &anchorEpoch, const PrimeMeridianNNPtr &primeMeridian); PROJ_DLL static const GeodeticReferenceFrameNNPtr EPSG_6267; // North American Datum 1927 PROJ_DLL static const GeodeticReferenceFrameNNPtr EPSG_6269; // North American Datum 1983 PROJ_DLL static const GeodeticReferenceFrameNNPtr EPSG_6326; // WGS 84 //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL bool isEquivalentToNoExactTypeCheck( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const; //! @endcond protected: #ifdef DOXYGEN_ENABLED PrimeMeridian primeMeridian_; Ellipsoid *ellipsoid_; #endif PROJ_INTERNAL GeodeticReferenceFrame(const EllipsoidNNPtr &ellipsoidIn, const PrimeMeridianNNPtr &primeMeridianIn); INLINED_MAKE_SHARED PROJ_INTERNAL static const GeodeticReferenceFrameNNPtr createEPSG_6267(); PROJ_INTERNAL static const GeodeticReferenceFrameNNPtr createEPSG_6269(); PROJ_INTERNAL static const GeodeticReferenceFrameNNPtr createEPSG_6326(); bool hasEquivalentNameToUsingAlias( const IdentifiedObject *other, const io::DatabaseContextPtr &dbContext) const override; private: PROJ_OPAQUE_PRIVATE_DATA GeodeticReferenceFrame(const GeodeticReferenceFrame &other) = delete; GeodeticReferenceFrame & operator=(const GeodeticReferenceFrame &other) = delete; }; // --------------------------------------------------------------------------- class DynamicGeodeticReferenceFrame; /** Shared pointer of DynamicGeodeticReferenceFrame */ using DynamicGeodeticReferenceFramePtr = std::shared_ptr<DynamicGeodeticReferenceFrame>; /** Non-null shared pointer of DynamicGeodeticReferenceFrame */ using DynamicGeodeticReferenceFrameNNPtr = util::nn<DynamicGeodeticReferenceFramePtr>; /** \brief A geodetic reference frame in which some of the parameters describe * time evolution of defining station coordinates. * * For example defining station coordinates having linear velocities to account * for crustal motion. * * \remark Implements DynamicGeodeticReferenceFrame from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DynamicGeodeticReferenceFrame final : public GeodeticReferenceFrame { public: //! @cond Doxygen_Suppress PROJ_DLL ~DynamicGeodeticReferenceFrame() override; //! @endcond PROJ_DLL const common::Measure &frameReferenceEpoch() const; PROJ_DLL const util::optional<std::string> &deformationModelName() const; // non-standard PROJ_DLL static DynamicGeodeticReferenceFrameNNPtr create(const util::PropertyMap &properties, const EllipsoidNNPtr &ellipsoid, const util::optional<std::string> &anchor, const PrimeMeridianNNPtr &primeMeridian, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn); //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) //! @endcond protected: #ifdef DOXYGEN_ENABLED Measure frameReferenceEpoch_; #endif PROJ_INTERNAL DynamicGeodeticReferenceFrame( const EllipsoidNNPtr &ellipsoidIn, const PrimeMeridianNNPtr &primeMeridianIn, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA DynamicGeodeticReferenceFrame(const DynamicGeodeticReferenceFrame &other) = delete; DynamicGeodeticReferenceFrame & operator=(const DynamicGeodeticReferenceFrame &other) = delete; }; // --------------------------------------------------------------------------- /** \brief The specification of the method by which the vertical reference frame * is realized. * * \remark Implements RealizationMethod from \ref ISO_19111_2019 */ class PROJ_GCC_DLL RealizationMethod : public util::CodeList { public: PROJ_DLL static const RealizationMethod LEVELLING; PROJ_DLL static const RealizationMethod GEOID; PROJ_DLL static const RealizationMethod TIDAL; private: PROJ_FRIEND_OPTIONAL(RealizationMethod); PROJ_DLL explicit RealizationMethod( const std::string &nameIn = std::string()); PROJ_DLL RealizationMethod(const RealizationMethod &other) = default; PROJ_DLL RealizationMethod &operator=(const RealizationMethod &other); }; // --------------------------------------------------------------------------- class VerticalReferenceFrame; /** Shared pointer of VerticalReferenceFrame */ using VerticalReferenceFramePtr = std::shared_ptr<VerticalReferenceFrame>; /** Non-null shared pointer of VerticalReferenceFrame */ using VerticalReferenceFrameNNPtr = util::nn<VerticalReferenceFramePtr>; /** \brief A textual description and/or a set of parameters identifying a * particular reference level surface used as a zero-height or zero-depth * surface, including its position with respect to the Earth. * * \note In \ref ISO_19111_2007, this class was called VerticalDatum. * \remark Implements VerticalReferenceFrame from \ref ISO_19111_2019 */ class PROJ_GCC_DLL VerticalReferenceFrame : public Datum { public: //! @cond Doxygen_Suppress PROJ_DLL ~VerticalReferenceFrame() override; //! @endcond PROJ_DLL const util::optional<RealizationMethod> &realizationMethod() const; // non-standard PROJ_DLL static VerticalReferenceFrameNNPtr create(const util::PropertyMap &properties, const util::optional<std::string> &anchor = util::optional<std::string>(), const util::optional<RealizationMethod> &realizationMethodIn = util::optional<RealizationMethod>()); PROJ_DLL static VerticalReferenceFrameNNPtr create(const util::PropertyMap &properties, const util::optional<std::string> &anchor, const util::optional<common::Measure> &anchorEpoch, const util::optional<RealizationMethod> &realizationMethodIn = util::optional<RealizationMethod>()); //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL bool isEquivalentToNoExactTypeCheck( const util::IComparable *other, util::IComparable::Criterion criterion, const io::DatabaseContextPtr &dbContext) const; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL const std::string &getWKT1DatumType() const; //! @endcond protected: #ifdef DOXYGEN_ENABLED RealizationMethod realizationMethod_; #endif PROJ_INTERNAL explicit VerticalReferenceFrame( const util::optional<RealizationMethod> &realizationMethodIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class DynamicVerticalReferenceFrame; /** Shared pointer of DynamicVerticalReferenceFrame */ using DynamicVerticalReferenceFramePtr = std::shared_ptr<DynamicVerticalReferenceFrame>; /** Non-null shared pointer of DynamicVerticalReferenceFrame */ using DynamicVerticalReferenceFrameNNPtr = util::nn<DynamicVerticalReferenceFramePtr>; /** \brief A vertical reference frame in which some of the defining parameters * have time dependency. * * For example defining station heights have velocity to account for * post-glacial isostatic rebound motion. * * \remark Implements DynamicVerticalReferenceFrame from \ref ISO_19111_2019 */ class PROJ_GCC_DLL DynamicVerticalReferenceFrame final : public VerticalReferenceFrame { public: //! @cond Doxygen_Suppress PROJ_DLL ~DynamicVerticalReferenceFrame() override; //! @endcond PROJ_DLL const common::Measure &frameReferenceEpoch() const; PROJ_DLL const util::optional<std::string> &deformationModelName() const; // non-standard PROJ_DLL static DynamicVerticalReferenceFrameNNPtr create(const util::PropertyMap &properties, const util::optional<std::string> &anchor, const util::optional<RealizationMethod> &realizationMethodIn, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn); //! @cond Doxygen_Suppress PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) //! @endcond protected: #ifdef DOXYGEN_ENABLED Measure frameReferenceEpoch_; #endif PROJ_INTERNAL DynamicVerticalReferenceFrame( const util::optional<RealizationMethod> &realizationMethodIn, const common::Measure &frameReferenceEpochIn, const util::optional<std::string> &deformationModelNameIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA DynamicVerticalReferenceFrame(const DynamicVerticalReferenceFrame &other) = delete; DynamicVerticalReferenceFrame & operator=(const DynamicVerticalReferenceFrame &other) = delete; }; // --------------------------------------------------------------------------- class TemporalDatum; /** Shared pointer of TemporalDatum */ using TemporalDatumPtr = std::shared_ptr<TemporalDatum>; /** Non-null shared pointer of TemporalDatum */ using TemporalDatumNNPtr = util::nn<TemporalDatumPtr>; /** \brief The definition of the relationship of a temporal coordinate system * to an object. The object is normally time on the Earth. * * \remark Implements TemporalDatum from \ref ISO_19111_2019 */ class PROJ_GCC_DLL TemporalDatum final : public Datum { public: //! @cond Doxygen_Suppress PROJ_DLL ~TemporalDatum() override; //! @endcond PROJ_DLL const common::DateTime &temporalOrigin() const; PROJ_DLL const std::string &calendar() const; PROJ_DLL static const std::string CALENDAR_PROLEPTIC_GREGORIAN; // non-standard PROJ_DLL static TemporalDatumNNPtr create(const util::PropertyMap &properties, const common::DateTime &temporalOriginIn, const std::string &calendarIn); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL TemporalDatum(const common::DateTime &temporalOriginIn, const std::string &calendarIn); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class EngineeringDatum; /** Shared pointer of EngineeringDatum */ using EngineeringDatumPtr = std::shared_ptr<EngineeringDatum>; /** Non-null shared pointer of EngineeringDatum */ using EngineeringDatumNNPtr = util::nn<EngineeringDatumPtr>; /** \brief The definition of the origin and orientation of an engineering * coordinate reference system. * * \note The origin can be fixed with respect to the Earth (such as a defined * point at a construction site), or be a defined point on a moving vehicle * (such as on a ship or satellite), or a defined point of an image. * * \remark Implements EngineeringDatum from \ref ISO_19111_2019 */ class PROJ_GCC_DLL EngineeringDatum final : public Datum { public: //! @cond Doxygen_Suppress PROJ_DLL ~EngineeringDatum() override; //! @endcond // non-standard PROJ_DLL static EngineeringDatumNNPtr create(const util::PropertyMap &properties, const util::optional<std::string> &anchor = util::optional<std::string>()); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL EngineeringDatum(); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA }; // --------------------------------------------------------------------------- class ParametricDatum; /** Shared pointer of ParametricDatum */ using ParametricDatumPtr = std::shared_ptr<ParametricDatum>; /** Non-null shared pointer of ParametricDatum */ using ParametricDatumNNPtr = util::nn<ParametricDatumPtr>; /** \brief Textual description and/or a set of parameters identifying a * particular reference surface used as the origin of a parametric coordinate * system, including its position with respect to the Earth. * * \remark Implements ParametricDatum from \ref ISO_19111_2019 */ class PROJ_GCC_DLL ParametricDatum final : public Datum { public: //! @cond Doxygen_Suppress PROJ_DLL ~ParametricDatum() override; //! @endcond // non-standard PROJ_DLL static ParametricDatumNNPtr create(const util::PropertyMap &properties, const util::optional<std::string> &anchor = util::optional<std::string>()); //! @cond Doxygen_Suppress PROJ_INTERNAL void _exportToWKT(io::WKTFormatter *formatter) const override; // throw(io::FormattingException) PROJ_INTERNAL void _exportToJSON(io::JSONFormatter *formatter) const override; // throw(FormattingException) PROJ_INTERNAL bool _isEquivalentTo( const util::IComparable *other, util::IComparable::Criterion criterion = util::IComparable::Criterion::STRICT, const io::DatabaseContextPtr &dbContext = nullptr) const override; //! @endcond protected: PROJ_INTERNAL ParametricDatum(); INLINED_MAKE_SHARED private: PROJ_OPAQUE_PRIVATE_DATA }; } // namespace datum NS_PROJ_END #endif // DATUM_HH_INCLUDED
hpp
PROJ
data/projects/PROJ/include/proj/internal/datum_internal.hpp
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2023, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef FROM_PROJ_CPP #error This file should only be included from a PROJ cpp file #endif #ifndef DATUM_INTERNAL_HH_INCLUDED #define DATUM_INTERNAL_HH_INCLUDED #define UNKNOWN_ENGINEERING_DATUM "Unknown engineering datum" #endif // DATUM_INTERNAL_HH_INCLUDED
hpp