]> git.mxchange.org Git - simgear.git/blob - simgear/math/SGGeodesy.cxx
Merge branch 'maint' into next
[simgear.git] / simgear / math / SGGeodesy.cxx
1 // Copyright (C) 2006  Mathias Froehlich - Mathias.Froehlich@web.de
2 //
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.
7 //
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.
12 //
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.
16 //
17
18 #ifdef HAVE_CONFIG_H
19 #  include <simgear_config.h>
20 #endif
21
22 #include <cmath>
23
24 #include <simgear/structure/exception.hxx>
25 #include "SGMath.hxx"
26
27 // These are hard numbers from the WGS84 standard.  DON'T MODIFY
28 // unless you want to change the datum.
29 #define _EQURAD 6378137.0
30 #define _FLATTENING 298.257223563
31
32 // These are derived quantities more useful to the code:
33 #if 0
34 #define _SQUASH (1 - 1/_FLATTENING)
35 #define _STRETCH (1/_SQUASH)
36 #define _POLRAD (EQURAD * _SQUASH)
37 #else
38 // High-precision versions of the above produced with an arbitrary
39 // precision calculator (the compiler might lose a few bits in the FPU
40 // operations).  These are specified to 81 bits of mantissa, which is
41 // higher than any FPU known to me:
42 #define _SQUASH    0.9966471893352525192801545
43 #define _STRETCH   1.0033640898209764189003079
44 #define _POLRAD    6356752.3142451794975639668
45 #endif
46
47 // The constants from the WGS84 standard
48 const double SGGeodesy::EQURAD = _EQURAD;
49 const double SGGeodesy::iFLATTENING = _FLATTENING;
50 const double SGGeodesy::SQUASH = _SQUASH;
51 const double SGGeodesy::STRETCH = _STRETCH;
52 const double SGGeodesy::POLRAD = _POLRAD;
53
54 // additional derived and precomputable ones
55 // for the geodetic conversion algorithm
56
57 #define E2 fabs(1 - _SQUASH*_SQUASH)
58 static double a = _EQURAD;
59 static double ra2 = 1/(_EQURAD*_EQURAD);
60 static double e = sqrt(E2);
61 static double e2 = E2;
62 static double e4 = E2*E2;
63
64 #undef _EQURAD
65 #undef _FLATTENING
66 #undef _SQUASH
67 #undef _STRETCH
68 #undef _POLRAD
69 #undef E2
70
71 void
72 SGGeodesy::SGCartToGeod(const SGVec3<double>& cart, SGGeod& geod)
73 {
74   // according to
75   // H. Vermeille,
76   // Direct transformation from geocentric to geodetic ccordinates,
77   // Journal of Geodesy (2002) 76:451-454
78   double X = cart(0);
79   double Y = cart(1);
80   double Z = cart(2);
81   double XXpYY = X*X+Y*Y;
82   double sqrtXXpYY = sqrt(XXpYY);
83   double p = XXpYY*ra2;
84   double q = Z*Z*(1-e2)*ra2;
85   double r = 1/6.0*(p+q-e4);
86   double s = e4*p*q/(4*r*r*r);
87   double t = pow(1+s+sqrt(s*(2+s)), 1/3.0);
88   double u = r*(1+t+1/t);
89   double v = sqrt(u*u+e4*q);
90   double w = e2*(u+v-q)/(2*v);
91   double k = sqrt(u+v+w*w)-w;
92   double D = k*sqrtXXpYY/(k+e2);
93   geod.setLongitudeRad(2*atan2(Y, X+sqrtXXpYY));
94   double sqrtDDpZZ = sqrt(D*D+Z*Z);
95   geod.setLatitudeRad(2*atan2(Z, D+sqrtDDpZZ));
96   geod.setElevationM((k+e2-1)*sqrtDDpZZ/k);
97 }
98
99 void
100 SGGeodesy::SGGeodToCart(const SGGeod& geod, SGVec3<double>& cart)
101 {
102   // according to
103   // H. Vermeille,
104   // Direct transformation from geocentric to geodetic ccordinates,
105   // Journal of Geodesy (2002) 76:451-454
106   double lambda = geod.getLongitudeRad();
107   double phi = geod.getLatitudeRad();
108   double h = geod.getElevationM();
109   double sphi = sin(phi);
110   double n = a/sqrt(1-e2*sphi*sphi);
111   double cphi = cos(phi);
112   double slambda = sin(lambda);
113   double clambda = cos(lambda);
114   cart(0) = (h+n)*cphi*clambda;
115   cart(1) = (h+n)*cphi*slambda;
116   cart(2) = (h+n-e2*n)*sphi;
117 }
118
119 double
120 SGGeodesy::SGGeodToSeaLevelRadius(const SGGeod& geod)
121 {
122   // this is just a simplified version of the SGGeodToCart function above,
123   // substitute h = 0, take the 2-norm of the cartesian vector and simplify
124   double phi = geod.getLatitudeRad();
125   double sphi = sin(phi);
126   double sphi2 = sphi*sphi;
127   return a*sqrt((1 + (e4 - 2*e2)*sphi2)/(1 - e2*sphi2));
128 }
129
130 void
131 SGGeodesy::SGCartToGeoc(const SGVec3<double>& cart, SGGeoc& geoc)
132 {
133   double minVal = SGLimits<double>::min();
134   if (fabs(cart(0)) < minVal && fabs(cart(1)) < minVal)
135     geoc.setLongitudeRad(0);
136   else
137     geoc.setLongitudeRad(atan2(cart(1), cart(0)));
138
139   double nxy = sqrt(cart(0)*cart(0) + cart(1)*cart(1));
140   if (fabs(nxy) < minVal && fabs(cart(2)) < minVal)
141     geoc.setLatitudeRad(0);
142   else
143     geoc.setLatitudeRad(atan2(cart(2), nxy));
144
145   geoc.setRadiusM(norm(cart));
146 }
147
148 void
149 SGGeodesy::SGGeocToCart(const SGGeoc& geoc, SGVec3<double>& cart)
150 {
151   double lat = geoc.getLatitudeRad();
152   double lon = geoc.getLongitudeRad();
153   double slat = sin(lat);
154   double clat = cos(lat);
155   double slon = sin(lon);
156   double clon = cos(lon);
157   cart = geoc.getRadiusM()*SGVec3<double>(clat*clon, clat*slon, slat);
158 }
159
160 // Notes:
161 //
162 // The XYZ/cartesian coordinate system in use puts the X axis through
163 // zero lat/lon (off west Africa), the Z axis through the north pole,
164 // and the Y axis through 90 degrees longitude (in the Indian Ocean).
165 //
166 // All latitude and longitude values are in radians.  Altitude is in
167 // meters, with zero on the WGS84 ellipsoid.
168 //
169 // The code below makes use of the notion of "squashed" space.  This
170 // is a 2D cylindrical coordinate system where the radius from the Z
171 // axis is multiplied by SQUASH; the earth in this space is a perfect
172 // circle with a radius of POLRAD.
173
174 ////////////////////////////////////////////////////////////////////////
175 //
176 // Direct and inverse distance functions 
177 //
178 // Proceedings of the 7th International Symposium on Geodetic
179 // Computations, 1985
180 //
181 // "The Nested Coefficient Method for Accurate Solutions of Direct and
182 // Inverse Geodetic Problems With Any Length"
183 //
184 // Zhang Xue-Lian
185 // pp 747-763
186 //
187 // modified for FlightGear to use WGS84 only -- Norman Vine
188
189 static inline double M0( double e2 ) {
190     //double e4 = e2*e2;
191   return SGMiscd::pi()*0.5*(1.0 - e2*( 1.0/4.0 + e2*( 3.0/64.0 + 
192                                                   e2*(5.0/256.0) )));
193 }
194
195
196 // given, lat1, lon1, az1 and distance (s), calculate lat2, lon2
197 // and az2.  Lat, lon, and azimuth are in degrees.  distance in meters
198 static int _geo_direct_wgs_84 ( double lat1, double lon1, double az1,
199                         double s, double *lat2, double *lon2,
200                         double *az2 )
201 {
202     double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
203     double testv = 1.0E-10;
204     double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
205     double b = a*(1.0-f);
206     double e2 = f*(2.0-f);
207     double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
208     double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
209     double azm1 = SGMiscd::deg2rad(az1);
210     double sinaz1 = sin(azm1), cosaz1 = cos(azm1);
211         
212         
213     if( fabs(s) < 0.01 ) {      // distance < centimeter => congruency
214         *lat2 = lat1;
215         *lon2 = lon1;
216         *az2 = 180.0 + az1;
217         if( *az2 > 360.0 ) *az2 -= 360.0;
218         return 0;
219     } else if( SGLimitsd::min() < fabs(cosphi1) ) {     // non-polar origin
220         // u1 is reduced latitude
221         double tanu1 = sqrt(1.0-e2)*sinphi1/cosphi1;
222         double sig1 = atan2(tanu1,cosaz1);
223         double cosu1 = 1.0/sqrt( 1.0 + tanu1*tanu1 ), sinu1 = tanu1*cosu1;
224         double sinaz =  cosu1*sinaz1, cos2saz = 1.0-sinaz*sinaz;
225         double us = cos2saz*e2/(1.0-e2);
226
227         // Terms
228         double  ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/16384.0,
229             tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0,
230             tc = 0;
231
232         // FIRST ESTIMATE OF SIGMA (SIG)
233         double first = s/(b*ta);  // !!
234         double sig = first;
235         double c2sigm, sinsig,cossig, temp,denom,rnumer, dlams, dlam;
236         do {
237             c2sigm = cos(2.0*sig1+sig);
238             sinsig = sin(sig); cossig = cos(sig);
239             temp = sig;
240             sig = first + 
241                 tb*sinsig*(c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm) - 
242                                       tb*c2sigm*(-3.0+4.0*sinsig*sinsig)
243                                       *(-3.0+4.0*c2sigm*c2sigm)/6.0)
244                            /4.0);
245         } while( fabs(sig-temp) > testv);
246
247         // LATITUDE OF POINT 2
248         // DENOMINATOR IN 2 PARTS (TEMP ALSO USED LATER)
249         temp = sinu1*sinsig-cosu1*cossig*cosaz1;
250         denom = (1.0-f)*sqrt(sinaz*sinaz+temp*temp);
251
252         // NUMERATOR
253         rnumer = sinu1*cossig+cosu1*sinsig*cosaz1;
254         *lat2 = SGMiscd::rad2deg(atan2(rnumer,denom));
255
256         // DIFFERENCE IN LONGITUDE ON AUXILARY SPHERE (DLAMS )
257         rnumer = sinsig*sinaz1;
258         denom = cosu1*cossig-sinu1*sinsig*cosaz1;
259         dlams = atan2(rnumer,denom);
260
261         // TERM C
262         tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
263
264         // DIFFERENCE IN LONGITUDE
265         dlam = dlams-(1.0-tc)*f*sinaz*(sig+tc*sinsig*
266                                        (c2sigm+
267                                         tc*cossig*(-1.0+2.0*
268                                                    c2sigm*c2sigm)));
269         *lon2 = SGMiscd::rad2deg(lam1+dlam);
270         if (*lon2 > 180.0  ) *lon2 -= 360.0;
271         if (*lon2 < -180.0 ) *lon2 += 360.0;
272
273         // AZIMUTH - FROM NORTH
274         *az2 = SGMiscd::rad2deg(atan2(-sinaz,temp));
275         if ( fabs(*az2) < testv ) *az2 = 0.0;
276         if( *az2 < 0.0) *az2 += 360.0;
277         return 0;
278     } else {                    // phi1 == 90 degrees, polar origin
279         double dM = a*M0(e2) - s;
280         double paz = ( phi1 < 0.0 ? 180.0 : 0.0 );
281         double zero = 0.0f;
282         return _geo_direct_wgs_84( zero, lon1, paz, dM, lat2, lon2, az2 );
283     } 
284 }
285
286 bool
287 SGGeodesy::direct(const SGGeod& p1, double course1,
288                   double distance, SGGeod& p2, double& course2)
289 {
290   double lat2, lon2;
291   int ret = _geo_direct_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
292                                course1, distance, &lat2, &lon2, &course2);
293   p2.setLatitudeDeg(lat2);
294   p2.setLongitudeDeg(lon2);
295   p2.setElevationM(0);
296   return ret == 0;
297 }
298
299 // given lat1, lon1, lat2, lon2, calculate starting and ending
300 // az1, az2 and distance (s).  Lat, lon, and azimuth are in degrees.
301 // distance in meters
302 static int _geo_inverse_wgs_84( double lat1, double lon1, double lat2,
303                         double lon2, double *az1, double *az2,
304                         double *s )
305 {
306     double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
307     int iter=0;
308     double testv = 1.0E-10;
309     double f = ( rf > 0.0 ? 1.0/rf : 0.0 );
310     double b = a*(1.0-f);
311     // double e2 = f*(2.0-f); // unused in this routine
312     double phi1 = SGMiscd::deg2rad(lat1), lam1 = SGMiscd::deg2rad(lon1);
313     double sinphi1 = sin(phi1), cosphi1 = cos(phi1);
314     double phi2 = SGMiscd::deg2rad(lat2), lam2 = SGMiscd::deg2rad(lon2);
315     double sinphi2 = sin(phi2), cosphi2 = cos(phi2);
316         
317     if( (fabs(lat1-lat2) < testv && 
318          ( fabs(lon1-lon2) < testv) || fabs(lat1-90.0) < testv ) )
319     {   
320         // TWO STATIONS ARE IDENTICAL : SET DISTANCE & AZIMUTHS TO ZERO */
321         *az1 = 0.0; *az2 = 0.0; *s = 0.0;
322         return 0;
323     } else if(  fabs(cosphi1) < testv ) {
324         // initial point is polar
325         int k = _geo_inverse_wgs_84( lat2,lon2,lat1,lon1, az1,az2,s );
326         k = k; // avoid compiler error since return result is unused
327         b = *az1; *az1 = *az2; *az2 = b;
328         return 0;
329     } else if( fabs(cosphi2) < testv ) {
330         // terminal point is polar
331         double _lon1 = lon1 + 180.0f;
332         int k = _geo_inverse_wgs_84( lat1, lon1, lat1, _lon1, 
333                                     az1, az2, s );
334         k = k; // avoid compiler error since return result is unused
335         *s /= 2.0;
336         *az2 = *az1 + 180.0;
337         if( *az2 > 360.0 ) *az2 -= 360.0; 
338         return 0;
339     } else if( (fabs( fabs(lon1-lon2) - 180 ) < testv) && 
340                (fabs(lat1+lat2) < testv) ) 
341     {
342         // Geodesic passes through the pole (antipodal)
343         double s1,s2;
344         _geo_inverse_wgs_84( lat1,lon1, lat1,lon2, az1,az2, &s1 );
345         _geo_inverse_wgs_84( lat2,lon2, lat1,lon2, az1,az2, &s2 );
346         *az2 = *az1;
347         *s = s1 + s2;
348         return 0;
349     } else {
350         // antipodal and polar points don't get here
351         double dlam = lam2 - lam1, dlams = dlam;
352         double sdlams,cdlams, sig,sinsig,cossig, sinaz,
353             cos2saz, c2sigm;
354         double tc,temp, us,rnumer,denom, ta,tb;
355         double cosu1,sinu1, sinu2,cosu2;
356
357         // Reduced latitudes
358         temp = (1.0-f)*sinphi1/cosphi1;
359         cosu1 = 1.0/sqrt(1.0+temp*temp);
360         sinu1 = temp*cosu1;
361         temp = (1.0-f)*sinphi2/cosphi2;
362         cosu2 = 1.0/sqrt(1.0+temp*temp);
363         sinu2 = temp*cosu2;
364     
365         do {
366             sdlams = sin(dlams), cdlams = cos(dlams);
367             sinsig = sqrt(cosu2*cosu2*sdlams*sdlams+
368                           (cosu1*sinu2-sinu1*cosu2*cdlams)*
369                           (cosu1*sinu2-sinu1*cosu2*cdlams));
370             cossig = sinu1*sinu2+cosu1*cosu2*cdlams;
371             
372             sig = atan2(sinsig,cossig);
373             sinaz = cosu1*cosu2*sdlams/sinsig;
374             cos2saz = 1.0-sinaz*sinaz;
375             c2sigm = (sinu1 == 0.0 || sinu2 == 0.0 ? cossig : 
376                       cossig-2.0*sinu1*sinu2/cos2saz);
377             tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
378             temp = dlams;
379             dlams = dlam+(1.0-tc)*f*sinaz*
380                 (sig+tc*sinsig*
381                  (c2sigm+tc*cossig*(-1.0+2.0*c2sigm*c2sigm)));
382             if (fabs(dlams) > SGMiscd::pi() && iter++ > 50) {
383                 return iter;
384             }
385         } while ( fabs(temp-dlams) > testv);
386
387         us = cos2saz*(a*a-b*b)/(b*b); // !!
388         // BACK AZIMUTH FROM NORTH
389         rnumer = -(cosu1*sdlams);
390         denom = sinu1*cosu2-cosu1*sinu2*cdlams;
391         *az2 = SGMiscd::rad2deg(atan2(rnumer,denom));
392         if( fabs(*az2) < testv ) *az2 = 0.0;
393         if(*az2 < 0.0) *az2 += 360.0;
394
395         // FORWARD AZIMUTH FROM NORTH
396         rnumer = cosu2*sdlams;
397         denom = cosu1*sinu2-sinu1*cosu2*cdlams;
398         *az1 = SGMiscd::rad2deg(atan2(rnumer,denom));
399         if( fabs(*az1) < testv ) *az1 = 0.0;
400         if(*az1 < 0.0) *az1 += 360.0;
401
402         // Terms a & b
403         ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/
404             16384.0;
405         tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0;
406
407         // GEODETIC DISTANCE
408         *s = b*ta*(sig-tb*sinsig*
409                    (c2sigm+tb*(cossig*(-1.0+2.0*c2sigm*c2sigm)-tb*
410                                c2sigm*(-3.0+4.0*sinsig*sinsig)*
411                                (-3.0+4.0*c2sigm*c2sigm)/6.0)/
412                     4.0));
413         return 0;
414     }
415 }
416
417 bool
418 SGGeodesy::inverse(const SGGeod& p1, const SGGeod& p2, double& course1,
419                    double& course2, double& distance)
420 {
421   int ret = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
422                                 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
423                                 &course1, &course2, &distance);
424   return ret == 0;
425 }
426
427 double
428 SGGeodesy::courseDeg(const SGGeod& p1, const SGGeod& p2)
429 {
430   double course1, course2, distance;
431   int r = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
432                                 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
433                                 &course1, &course2, &distance);
434   if (r != 0) {
435     throw sg_exception("SGGeodesy::courseDeg, unable to compute course");
436   }
437   
438   return course1;
439 }
440
441 double
442 SGGeodesy::distanceM(const SGGeod& p1, const SGGeod& p2)
443 {
444   double course1, course2, distance;
445   int r = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
446                                 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
447                                 &course1, &course2, &distance);
448   if (r != 0) {
449     throw sg_exception("SGGeodesy::distanceM, unable to compute distance");
450   }
451   
452   return distance;
453 }
454
455 double
456 SGGeodesy::distanceNm(const SGGeod& from, const SGGeod& to)
457 {
458   return distanceM(from, to) * SG_METER_TO_NM;
459 }
460
461 /// Geocentric routines
462
463 void
464 SGGeodesy::advanceRadM(const SGGeoc& geoc, double course, double distance,
465                        SGGeoc& result)
466 {
467   result.setRadiusM(geoc.getRadiusM());
468
469   // lat=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc))
470   // IF (cos(lat)=0)
471   //   lon=lon1      // endpoint a pole
472   // ELSE
473   //   lon=mod(lon1-asin(sin(tc)*sin(d)/cos(lat))+pi,2*pi)-pi
474   // ENDIF
475   
476   distance *= SG_METER_TO_NM * SG_NM_TO_RAD;
477   
478   double sinDistance = sin(distance);
479   double cosDistance = cos(distance);
480
481   double sinLat = sin(geoc.getLatitudeRad()) * cosDistance +
482     cos(geoc.getLatitudeRad()) * sinDistance * cos(course);
483   sinLat = SGMiscd::clip(sinLat, -1, 1);
484   result.setLatitudeRad(asin(sinLat));
485   double cosLat = cos(result.getLatitudeRad());
486   
487   
488   if (cosLat <= SGLimitsd::min()) {
489     // endpoint a pole
490     result.setLongitudeRad(geoc.getLongitudeRad());
491   } else {
492     double tmp = SGMiscd::clip(sin(course) * sinDistance / cosLat, -1, 1);
493     double lon = SGMiscd::normalizeAngle(geoc.getLongitudeRad() - asin( tmp ));
494     result.setLongitudeRad(lon);
495   }
496 }
497
498 double
499 SGGeodesy::courseRad(const SGGeoc& from, const SGGeoc& to)
500 {
501   double diffLon = to.getLongitudeRad() - from.getLongitudeRad();
502
503   double sinLatFrom = sin(from.getLatitudeRad());
504   double cosLatFrom = cos(from.getLatitudeRad());
505
506   double sinLatTo = sin(to.getLatitudeRad());
507   double cosLatTo = cos(to.getLatitudeRad());
508
509   double x = cosLatTo*sin(diffLon);
510   double y = cosLatFrom*sinLatTo - sinLatFrom*cosLatTo*cos(diffLon);
511
512   // guard atan2 returning NaN's
513   if (fabs(x) <= SGLimitsd::min() && fabs(y) <= SGLimitsd::min())
514     return 0;
515
516   double c = atan2(x, y);
517   if (c >= 0)
518     return SGMiscd::twopi() - c;
519   else
520     return -c;
521 }
522
523 double
524 SGGeodesy::distanceM(const SGGeoc& from, const SGGeoc& to)
525 {
526   // d = 2*asin(sqrt((sin((lat1-lat2)/2))^2 +
527   //            cos(lat1)*cos(lat2)*(sin((lon1-lon2)/2))^2))
528   double cosLatFrom = cos(from.getLatitudeRad());
529   double cosLatTo = cos(to.getLatitudeRad());
530   double tmp1 = sin(0.5*(from.getLatitudeRad() - to.getLatitudeRad()));
531   double tmp2 = sin(0.5*(from.getLongitudeRad() - to.getLongitudeRad()));
532   double square = tmp1*tmp1 + cosLatFrom*cosLatTo*tmp2*tmp2;
533   double s = SGMiscd::min(sqrt(SGMiscd::max(square, 0)), 1);
534   return 2 * asin(s) * SG_RAD_TO_NM * SG_NM_TO_METER;
535 }