1 // Copyright (C) 2006 Mathias Froehlich - Mathias.Froehlich@web.de
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Library General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 # include <simgear_config.h>
26 // These are hard numbers from the WGS84 standard. DON'T MODIFY
27 // unless you want to change the datum.
28 #define _EQURAD 6378137.0
29 #define _FLATTENING 298.257223563
31 // These are derived quantities more useful to the code:
33 #define _SQUASH (1 - 1/_FLATTENING)
34 #define _STRETCH (1/_SQUASH)
35 #define _POLRAD (EQURAD * _SQUASH)
37 // High-precision versions of the above produced with an arbitrary
38 // precision calculator (the compiler might lose a few bits in the FPU
39 // operations). These are specified to 81 bits of mantissa, which is
40 // higher than any FPU known to me:
41 #define _SQUASH 0.9966471893352525192801545
42 #define _STRETCH 1.0033640898209764189003079
43 #define _POLRAD 6356752.3142451794975639668
46 // The constants from the WGS84 standard
47 const double SGGeodesy::EQURAD = _EQURAD;
48 const double SGGeodesy::iFLATTENING = _FLATTENING;
49 const double SGGeodesy::SQUASH = _SQUASH;
50 const double SGGeodesy::STRETCH = _STRETCH;
51 const double SGGeodesy::POLRAD = _POLRAD;
53 // additional derived and precomputable ones
54 // for the geodetic conversion algorithm
56 #define E2 fabs(1 - _SQUASH*_SQUASH)
57 static double a = _EQURAD;
58 static double ra2 = 1/(_EQURAD*_EQURAD);
59 static double e = sqrt(E2);
60 static double e2 = E2;
61 static double e4 = E2*E2;
71 SGGeodesy::SGCartToGeod(const SGVec3<double>& cart, SGGeod& geod)
75 // Direct transformation from geocentric to geodetic ccordinates,
76 // Journal of Geodesy (2002) 76:451-454
80 double XXpYY = X*X+Y*Y;
81 double sqrtXXpYY = sqrt(XXpYY);
83 double q = Z*Z*(1-e2)*ra2;
84 double r = 1/6.0*(p+q-e4);
85 double s = e4*p*q/(4*r*r*r);
86 double t = pow(1+s+sqrt(s*(2+s)), 1/3.0);
87 double u = r*(1+t+1/t);
88 double v = sqrt(u*u+e4*q);
89 double w = e2*(u+v-q)/(2*v);
90 double k = sqrt(u+v+w*w)-w;
91 double D = k*sqrtXXpYY/(k+e2);
92 geod.setLongitudeRad(2*atan2(Y, X+sqrtXXpYY));
93 double sqrtDDpZZ = sqrt(D*D+Z*Z);
94 geod.setLatitudeRad(2*atan2(Z, D+sqrtDDpZZ));
95 geod.setElevationM((k+e2-1)*sqrtDDpZZ/k);
99 SGGeodesy::SGGeodToCart(const SGGeod& geod, SGVec3<double>& cart)
103 // Direct transformation from geocentric to geodetic ccordinates,
104 // Journal of Geodesy (2002) 76:451-454
105 double lambda = geod.getLongitudeRad();
106 double phi = geod.getLatitudeRad();
107 double h = geod.getElevationM();
108 double sphi = sin(phi);
109 double n = a/sqrt(1-e2*sphi*sphi);
110 double cphi = cos(phi);
111 double slambda = sin(lambda);
112 double clambda = cos(lambda);
113 cart(0) = (h+n)*cphi*clambda;
114 cart(1) = (h+n)*cphi*slambda;
115 cart(2) = (h+n-e2*n)*sphi;
119 SGGeodesy::SGGeodToSeaLevelRadius(const SGGeod& geod)
121 // this is just a simplified version of the SGGeodToCart function above,
122 // substitute h = 0, take the 2-norm of the cartesian vector and simplify
123 double phi = geod.getLatitudeRad();
124 double sphi = sin(phi);
125 double sphi2 = sphi*sphi;
126 return a*sqrt((1 + (e4 - 2*e2)*sphi2)/(1 - e2*sphi2));
130 SGGeodesy::SGCartToGeoc(const SGVec3<double>& cart, SGGeoc& geoc)
132 double minVal = SGLimits<double>::min();
133 if (fabs(cart(0)) < minVal && fabs(cart(1)) < minVal)
134 geoc.setLongitudeRad(0);
136 geoc.setLongitudeRad(atan2(cart(1), cart(0)));
138 double nxy = sqrt(cart(0)*cart(0) + cart(1)*cart(1));
139 if (fabs(nxy) < minVal && fabs(cart(2)) < minVal)
140 geoc.setLatitudeRad(0);
142 geoc.setLatitudeRad(atan2(cart(2), nxy));
144 geoc.setRadiusM(norm(cart));
148 SGGeodesy::SGGeocToCart(const SGGeoc& geoc, SGVec3<double>& cart)
150 double lat = geoc.getLatitudeRad();
151 double lon = geoc.getLongitudeRad();
152 double slat = sin(lat);
153 double clat = cos(lat);
154 double slon = sin(lon);
155 double clon = cos(lon);
156 cart = geoc.getRadiusM()*SGVec3<double>(clat*clon, clat*slon, slat);
161 // The XYZ/cartesian coordinate system in use puts the X axis through
162 // zero lat/lon (off west Africa), the Z axis through the north pole,
163 // and the Y axis through 90 degrees longitude (in the Indian Ocean).
165 // All latitude and longitude values are in radians. Altitude is in
166 // meters, with zero on the WGS84 ellipsoid.
168 // The code below makes use of the notion of "squashed" space. This
169 // is a 2D cylindrical coordinate system where the radius from the Z
170 // axis is multiplied by SQUASH; the earth in this space is a perfect
171 // circle with a radius of POLRAD.
173 ////////////////////////////////////////////////////////////////////////
175 // Direct and inverse distance functions
177 // Proceedings of the 7th International Symposium on Geodetic
178 // Computations, 1985
180 // "The Nested Coefficient Method for Accurate Solutions of Direct and
181 // Inverse Geodetic Problems With Any Length"
186 // modified for FlightGear to use WGS84 only -- Norman Vine
188 static inline double M0( double e2 ) {
190 return SGMiscd::pi()*0.5*(1.0 - e2*( 1.0/4.0 + e2*( 3.0/64.0 +
195 // given, lat1, lon1, az1 and distance (s), calculate lat2, lon2
196 // and az2. Lat, lon, and azimuth are in degrees. distance in meters
197 static int _geo_direct_wgs_84 ( double lat1, double lon1, double az1,
198 double s, double *lat2, double *lon2,
201 double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
202 double testv = 1.0E-10;
203 double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
204 double b = a*(1.0-f);
205 double e2 = f*(2.0-f);
206 double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
207 double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
208 double azm1 = SGMiscd::deg2rad(az1);
209 double sinaz1 = sin(azm1), cosaz1 = cos(azm1);
212 if( fabs(s) < 0.01 ) { // distance < centimeter => congruency
216 if( *az2 > 360.0 ) *az2 -= 360.0;
218 } else if( SGLimitsd::min() < fabs(cosphi1) ) { // non-polar origin
219 // u1 is reduced latitude
220 double tanu1 = sqrt(1.0-e2)*sinphi1/cosphi1;
221 double sig1 = atan2(tanu1,cosaz1);
222 double cosu1 = 1.0/sqrt( 1.0 + tanu1*tanu1 ), sinu1 = tanu1*cosu1;
223 double sinaz = cosu1*sinaz1, cos2saz = 1.0-sinaz*sinaz;
224 double us = cos2saz*e2/(1.0-e2);
227 double ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/16384.0,
228 tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0,
231 // FIRST ESTIMATE OF SIGMA (SIG)
232 double first = s/(b*ta); // !!
234 double c2sigm, sinsig,cossig, temp,denom,rnumer, dlams, dlam;
236 c2sigm = cos(2.0*sig1+sig);
237 sinsig = sin(sig); cossig = cos(sig);
240 tb*sinsig*(c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm) -
241 tb*c2sigm*(-3.0+4.0*sinsig*sinsig)
242 *(-3.0+4.0*c2sigm*c2sigm)/6.0)
244 } while( fabs(sig-temp) > testv);
246 // LATITUDE OF POINT 2
247 // DENOMINATOR IN 2 PARTS (TEMP ALSO USED LATER)
248 temp = sinu1*sinsig-cosu1*cossig*cosaz1;
249 denom = (1.0-f)*sqrt(sinaz*sinaz+temp*temp);
252 rnumer = sinu1*cossig+cosu1*sinsig*cosaz1;
253 *lat2 = SGMiscd::rad2deg(atan2(rnumer,denom));
255 // DIFFERENCE IN LONGITUDE ON AUXILARY SPHERE (DLAMS )
256 rnumer = sinsig*sinaz1;
257 denom = cosu1*cossig-sinu1*sinsig*cosaz1;
258 dlams = atan2(rnumer,denom);
261 tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
263 // DIFFERENCE IN LONGITUDE
264 dlam = dlams-(1.0-tc)*f*sinaz*(sig+tc*sinsig*
268 *lon2 = SGMiscd::rad2deg(lam1+dlam);
269 if (*lon2 > 180.0 ) *lon2 -= 360.0;
270 if (*lon2 < -180.0 ) *lon2 += 360.0;
272 // AZIMUTH - FROM NORTH
273 *az2 = SGMiscd::rad2deg(atan2(-sinaz,temp));
274 if ( fabs(*az2) < testv ) *az2 = 0.0;
275 if( *az2 < 0.0) *az2 += 360.0;
277 } else { // phi1 == 90 degrees, polar origin
278 double dM = a*M0(e2) - s;
279 double paz = ( phi1 < 0.0 ? 180.0 : 0.0 );
281 return _geo_direct_wgs_84( zero, lon1, paz, dM, lat2, lon2, az2 );
286 SGGeodesy::direct(const SGGeod& p1, double course1,
287 double distance, SGGeod& p2, double& course2)
290 int ret = _geo_direct_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
291 course1, distance, &lat2, &lon2, &course2);
292 p2.setLatitudeDeg(lat2);
293 p2.setLongitudeDeg(lon2);
298 // given lat1, lon1, lat2, lon2, calculate starting and ending
299 // az1, az2 and distance (s). Lat, lon, and azimuth are in degrees.
300 // distance in meters
301 static int _geo_inverse_wgs_84( double lat1, double lon1, double lat2,
302 double lon2, double *az1, double *az2,
305 double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
307 double testv = 1.0E-10;
308 double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
309 double b = a*(1.0-f);
310 // double e2 = f*(2.0-f); // unused in this routine
311 double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
312 double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
313 double phi2 = SGMiscd::deg2rad(lat2), lam2 = SGMiscd::deg2rad(lon2);
314 double sinphi2 = sin(phi2), cosphi2 = cos(phi2);
316 if( (fabs(lat1-lat2) < testv &&
317 ( fabs(lon1-lon2) < testv) || fabs(lat1-90.0) < testv ) )
319 // TWO STATIONS ARE IDENTICAL : SET DISTANCE & AZIMUTHS TO ZERO */
320 *az1 = 0.0; *az2 = 0.0; *s = 0.0;
322 } else if( fabs(cosphi1) < testv ) {
323 // initial point is polar
324 int k = _geo_inverse_wgs_84( lat2,lon2,lat1,lon1, az1,az2,s );
325 k = k; // avoid compiler error since return result is unused
326 b = *az1; *az1 = *az2; *az2 = b;
328 } else if( fabs(cosphi2) < testv ) {
329 // terminal point is polar
330 double _lon1 = lon1 + 180.0f;
331 int k = _geo_inverse_wgs_84( lat1, lon1, lat1, _lon1,
333 k = k; // avoid compiler error since return result is unused
336 if( *az2 > 360.0 ) *az2 -= 360.0;
338 } else if( (fabs( fabs(lon1-lon2) - 180 ) < testv) &&
339 (fabs(lat1+lat2) < testv) )
341 // Geodesic passes through the pole (antipodal)
343 _geo_inverse_wgs_84( lat1,lon1, lat1,lon2, az1,az2, &s1 );
344 _geo_inverse_wgs_84( lat2,lon2, lat1,lon2, az1,az2, &s2 );
349 // antipodal and polar points don't get here
350 double dlam = lam2 - lam1, dlams = dlam;
351 double sdlams,cdlams, sig,sinsig,cossig, sinaz,
353 double tc,temp, us,rnumer,denom, ta,tb;
354 double cosu1,sinu1, sinu2,cosu2;
357 temp = (1.0-f)*sinphi1/cosphi1;
358 cosu1 = 1.0/sqrt(1.0+temp*temp);
360 temp = (1.0-f)*sinphi2/cosphi2;
361 cosu2 = 1.0/sqrt(1.0+temp*temp);
365 sdlams = sin(dlams), cdlams = cos(dlams);
366 sinsig = sqrt(cosu2*cosu2*sdlams*sdlams+
367 (cosu1*sinu2-sinu1*cosu2*cdlams)*
368 (cosu1*sinu2-sinu1*cosu2*cdlams));
369 cossig = sinu1*sinu2+cosu1*cosu2*cdlams;
371 sig = atan2(sinsig,cossig);
372 sinaz = cosu1*cosu2*sdlams/sinsig;
373 cos2saz = 1.0-sinaz*sinaz;
374 c2sigm = (sinu1 == 0.0 || sinu2 == 0.0 ? cossig :
375 cossig-2.0*sinu1*sinu2/cos2saz);
376 tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
378 dlams = dlam+(1.0-tc)*f*sinaz*
380 (c2sigm+tc*cossig*(-1.0+2.0*c2sigm*c2sigm)));
381 if (fabs(dlams) > SGMiscd::pi() && iter++ > 50) {
384 } while ( fabs(temp-dlams) > testv);
386 us = cos2saz*(a*a-b*b)/(b*b); // !!
387 // BACK AZIMUTH FROM NORTH
388 rnumer = -(cosu1*sdlams);
389 denom = sinu1*cosu2-cosu1*sinu2*cdlams;
390 *az2 = SGMiscd::rad2deg(atan2(rnumer,denom));
391 if( fabs(*az2) < testv ) *az2 = 0.0;
392 if(*az2 < 0.0) *az2 += 360.0;
394 // FORWARD AZIMUTH FROM NORTH
395 rnumer = cosu2*sdlams;
396 denom = cosu1*sinu2-sinu1*cosu2*cdlams;
397 *az1 = SGMiscd::rad2deg(atan2(rnumer,denom));
398 if( fabs(*az1) < testv ) *az1 = 0.0;
399 if(*az1 < 0.0) *az1 += 360.0;
402 ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/
404 tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0;
407 *s = b*ta*(sig-tb*sinsig*
408 (c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm)-tb*
409 c2sigm*(-3.0+4.0*sinsig*sinsig)*
410 (-3.0+4.0*c2sigm*c2sigm)/6.0)/
417 SGGeodesy::inverse(const SGGeod& p1, const SGGeod& p2, double& course1,
418 double& course2, double& distance)
420 int ret = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
421 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
422 &course1, &course2, &distance);
426 /// Geocentric routines
429 SGGeodesy::advanceRadM(const SGGeoc& geoc, double course, double distance,
432 result.setRadiusM(geoc.getRadiusM());
434 // lat=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc))
436 // lon=lon1 // endpoint a pole
438 // lon=mod(lon1-asin(sin(tc)*sin(d)/cos(lat))+pi,2*pi)-pi
441 distance *= SG_METER_TO_NM * SG_NM_TO_RAD;
443 double sinDistance = sin(distance);
444 double cosDistance = cos(distance);
446 double sinLat = sin(geoc.getLatitudeRad()) * cosDistance +
447 cos(geoc.getLatitudeRad()) * sinDistance * cos(course);
448 sinLat = SGMiscd::clip(sinLat, -1, 1);
449 result.setLatitudeRad(asin(sinLat));
450 double cosLat = cos(result.getLatitudeRad());
453 if (cosLat <= SGLimitsd::min()) {
455 result.setLongitudeRad(geoc.getLongitudeRad());
457 double tmp = SGMiscd::clip(sin(course) * sinDistance / cosLat, -1, 1);
458 double lon = SGMiscd::normalizeAngle(geoc.getLongitudeRad() - asin( tmp ));
459 result.setLongitudeRad(lon);
464 SGGeodesy::courseRad(const SGGeoc& from, const SGGeoc& to)
466 double diffLon = to.getLongitudeRad() - from.getLongitudeRad();
468 double sinLatFrom = sin(from.getLatitudeRad());
469 double cosLatFrom = cos(from.getLatitudeRad());
471 double sinLatTo = sin(to.getLatitudeRad());
472 double cosLatTo = cos(to.getLatitudeRad());
474 double x = cosLatTo*sin(diffLon);
475 double y = cosLatFrom*sinLatTo - sinLatFrom*cosLatTo*cos(diffLon);
477 // guard atan2 returning NaN's
478 if (fabs(x) <= SGLimitsd::min() && fabs(y) <= SGLimitsd::min())
481 double c = atan2(x, y);
483 return SGMiscd::twopi() - c;
489 SGGeodesy::distanceM(const SGGeoc& from, const SGGeoc& to)
491 // d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
492 // cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
493 double cosLatFrom = cos(from.getLatitudeRad());
494 double cosLatTo = cos(to.getLatitudeRad());
495 double tmp1 = sin(0.5*(from.getLatitudeRad() - to.getLatitudeRad()));
496 double tmp2 = sin(0.5*(from.getLongitudeRad() - to.getLongitudeRad()));
497 double square = tmp1*tmp1 + cosLatFrom*cosLatTo*tmp2*tmp2;
498 double s = SGMiscd::min(sqrt(SGMiscd::max(square, 0)), 1);
499 return 2 * asin(s) * SG_RAD_TO_NM * SG_NM_TO_METER;