]> git.mxchange.org Git - simgear.git/blob - simgear/math/SGGeodesy.cxx
MINGW patch by Csaba Halasz
[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 "SGMath.hxx"
25
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
30
31 // These are derived quantities more useful to the code:
32 #if 0
33 #define _SQUASH (1 - 1/_FLATTENING)
34 #define _STRETCH (1/_SQUASH)
35 #define _POLRAD (EQURAD * _SQUASH)
36 #else
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
44 #endif
45
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;
52
53 // additional derived and precomputable ones
54 // for the geodetic conversion algorithm
55
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;
62
63 #undef _EQURAD
64 #undef _FLATTENING
65 #undef _SQUASH
66 #undef _STRETCH
67 #undef _POLRAD
68 #undef E2
69
70 void
71 SGGeodesy::SGCartToGeod(const SGVec3<double>& cart, SGGeod& geod)
72 {
73   // according to
74   // H. Vermeille,
75   // Direct transformation from geocentric to geodetic ccordinates,
76   // Journal of Geodesy (2002) 76:451-454
77   double X = cart(0);
78   double Y = cart(1);
79   double Z = cart(2);
80   double XXpYY = X*X+Y*Y;
81   double sqrtXXpYY = sqrt(XXpYY);
82   double p = XXpYY*ra2;
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);
96 }
97
98 void
99 SGGeodesy::SGGeodToCart(const SGGeod& geod, SGVec3<double>& cart)
100 {
101   // according to
102   // H. Vermeille,
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;
116 }
117
118 double
119 SGGeodesy::SGGeodToSeaLevelRadius(const SGGeod& geod)
120 {
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));
127 }
128
129 void
130 SGGeodesy::SGCartToGeoc(const SGVec3<double>& cart, SGGeoc& geoc)
131 {
132   double minVal = SGLimits<double>::min();
133   if (fabs(cart(0)) < minVal && fabs(cart(1)) < minVal)
134     geoc.setLongitudeRad(0);
135   else
136     geoc.setLongitudeRad(atan2(cart(1), cart(0)));
137
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);
141   else
142     geoc.setLatitudeRad(atan2(cart(2), nxy));
143
144   geoc.setRadiusM(norm(cart));
145 }
146
147 void
148 SGGeodesy::SGGeocToCart(const SGGeoc& geoc, SGVec3<double>& cart)
149 {
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);
157 }
158
159 // Notes:
160 //
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).
164 //
165 // All latitude and longitude values are in radians.  Altitude is in
166 // meters, with zero on the WGS84 ellipsoid.
167 //
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.
172
173 ////////////////////////////////////////////////////////////////////////
174 //
175 // Direct and inverse distance functions 
176 //
177 // Proceedings of the 7th International Symposium on Geodetic
178 // Computations, 1985
179 //
180 // "The Nested Coefficient Method for Accurate Solutions of Direct and
181 // Inverse Geodetic Problems With Any Length"
182 //
183 // Zhang Xue-Lian
184 // pp 747-763
185 //
186 // modified for FlightGear to use WGS84 only -- Norman Vine
187
188 static inline double M0( double e2 ) {
189     //double e4 = e2*e2;
190   return SGMiscd::pi()*0.5*(1.0 - e2*( 1.0/4.0 + e2*( 3.0/64.0 + 
191                                                   e2*(5.0/256.0) )));
192 }
193
194
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,
199                         double *az2 )
200 {
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);
210         
211         
212     if( fabs(s) < 0.01 ) {      // distance < centimeter => congruency
213         *lat2 = lat1;
214         *lon2 = lon1;
215         *az2 = 180.0 + az1;
216         if( *az2 > 360.0 ) *az2 -= 360.0;
217         return 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);
225
226         // Terms
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,
229             tc = 0;
230
231         // FIRST ESTIMATE OF SIGMA (SIG)
232         double first = s/(b*ta);  // !!
233         double sig = first;
234         double c2sigm, sinsig,cossig, temp,denom,rnumer, dlams, dlam;
235         do {
236             c2sigm = cos(2.0*sig1+sig);
237             sinsig = sin(sig); cossig = cos(sig);
238             temp = sig;
239             sig = first + 
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)
243                            /4.0);
244         } while( fabs(sig-temp) > testv);
245
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);
250
251         // NUMERATOR
252         rnumer = sinu1*cossig+cosu1*sinsig*cosaz1;
253         *lat2 = SGMiscd::rad2deg(atan2(rnumer,denom));
254
255         // DIFFERENCE IN LONGITUDE ON AUXILARY SPHERE (DLAMS )
256         rnumer = sinsig*sinaz1;
257         denom = cosu1*cossig-sinu1*sinsig*cosaz1;
258         dlams = atan2(rnumer,denom);
259
260         // TERM C
261         tc = f*cos2saz*(4.0+f*(4.0-3.0*cos2saz))/16.0;
262
263         // DIFFERENCE IN LONGITUDE
264         dlam = dlams-(1.0-tc)*f*sinaz*(sig+tc*sinsig*
265                                        (c2sigm+
266                                         tc*cossig*(-1.0+2.0*
267                                                    c2sigm*c2sigm)));
268         *lon2 = SGMiscd::rad2deg(lam1+dlam);
269         if (*lon2 > 180.0  ) *lon2 -= 360.0;
270         if (*lon2 < -180.0 ) *lon2 += 360.0;
271
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;
276         return 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 );
280         double zero = 0.0f;
281         return _geo_direct_wgs_84( zero, lon1, paz, dM, lat2, lon2, az2 );
282     } 
283 }
284
285 bool
286 SGGeodesy::direct(const SGGeod& p1, double course1,
287                   double distance, SGGeod& p2, double& course2)
288 {
289   double lat2, lon2;
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);
294   p2.setElevationM(0);
295   return ret == 0;
296 }
297
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,
303                         double *s )
304 {
305     double a = SGGeodesy::EQURAD, rf = SGGeodesy::iFLATTENING;
306     int iter=0;
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);
315         
316     if( (fabs(lat1-lat2) < testv && 
317          ( fabs(lon1-lon2) < testv) || fabs(lat1-90.0) < testv ) )
318     {   
319         // TWO STATIONS ARE IDENTICAL : SET DISTANCE & AZIMUTHS TO ZERO */
320         *az1 = 0.0; *az2 = 0.0; *s = 0.0;
321         return 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;
327         return 0;
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, 
332                                     az1, az2, s );
333         k = k; // avoid compiler error since return result is unused
334         *s /= 2.0;
335         *az2 = *az1 + 180.0;
336         if( *az2 > 360.0 ) *az2 -= 360.0; 
337         return 0;
338     } else if( (fabs( fabs(lon1-lon2) - 180 ) < testv) && 
339                (fabs(lat1+lat2) < testv) ) 
340     {
341         // Geodesic passes through the pole (antipodal)
342         double s1,s2;
343         _geo_inverse_wgs_84( lat1,lon1, lat1,lon2, az1,az2, &s1 );
344         _geo_inverse_wgs_84( lat2,lon2, lat1,lon2, az1,az2, &s2 );
345         *az2 = *az1;
346         *s = s1 + s2;
347         return 0;
348     } else {
349         // antipodal and polar points don't get here
350         double dlam = lam2 - lam1, dlams = dlam;
351         double sdlams,cdlams, sig,sinsig,cossig, sinaz,
352             cos2saz, c2sigm;
353         double tc,temp, us,rnumer,denom, ta,tb;
354         double cosu1,sinu1, sinu2,cosu2;
355
356         // Reduced latitudes
357         temp = (1.0-f)*sinphi1/cosphi1;
358         cosu1 = 1.0/sqrt(1.0+temp*temp);
359         sinu1 = temp*cosu1;
360         temp = (1.0-f)*sinphi2/cosphi2;
361         cosu2 = 1.0/sqrt(1.0+temp*temp);
362         sinu2 = temp*cosu2;
363     
364         do {
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;
370             
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;
377             temp = dlams;
378             dlams = dlam+(1.0-tc)*f*sinaz*
379                 (sig+tc*sinsig*
380                  (c2sigm+tc*cossig*(-1.0+2.0*c2sigm*c2sigm)));
381             if (fabs(dlams) > SGMiscd::pi() && iter++ > 50) {
382                 return iter;
383             }
384         } while ( fabs(temp-dlams) > testv);
385
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;
393
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;
400
401         // Terms a & b
402         ta = 1.0+us*(4096.0+us*(-768.0+us*(320.0-175.0*us)))/
403             16384.0;
404         tb = us*(256.0+us*(-128.0+us*(74.0-47.0*us)))/1024.0;
405
406         // GEODETIC DISTANCE
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)/
411                     4.0));
412         return 0;
413     }
414 }
415
416 bool
417 SGGeodesy::inverse(const SGGeod& p1, const SGGeod& p2, double& course1,
418                    double& course2, double& distance)
419 {
420   int ret = _geo_inverse_wgs_84(p1.getLatitudeDeg(), p1.getLongitudeDeg(),
421                                 p2.getLatitudeDeg(), p2.getLongitudeDeg(),
422                                 &course1, &course2, &distance);
423   return ret == 0;
424 }
425
426 /// Geocentric routines
427
428 void
429 SGGeodesy::advanceRadM(const SGGeoc& geoc, double course, double distance,
430                        SGGeoc& result)
431 {
432   result.setRadiusM(geoc.getRadiusM());
433
434   // lat=asin(sin(lat1)*cos(d)+cos(lat1)*sin(d)*cos(tc))
435   // IF (cos(lat)=0)
436   //   lon=lon1      // endpoint a pole
437   // ELSE
438   //   lon=mod(lon1-asin(sin(tc)*sin(d)/cos(lat))+pi,2*pi)-pi
439   // ENDIF
440   
441   distance *= SG_METER_TO_NM * SG_NM_TO_RAD;
442   
443   double sinDistance = sin(distance);
444   double cosDistance = cos(distance);
445
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());
451   
452   
453   if (cosLat <= SGLimitsd::min()) {
454     // endpoint a pole
455     result.setLongitudeRad(geoc.getLongitudeRad());
456   } else {
457     double tmp = SGMiscd::clip(sin(course) * sinDistance / cosLat, -1, 1);
458     double lon = SGMiscd::normalizeAngle(geoc.getLongitudeRad() - asin( tmp ));
459     result.setLongitudeRad(lon);
460   }
461 }
462
463 double
464 SGGeodesy::courseRad(const SGGeoc& from, const SGGeoc& to)
465 {
466   double diffLon = to.getLongitudeRad() - from.getLongitudeRad();
467
468   double sinLatFrom = sin(from.getLatitudeRad());
469   double cosLatFrom = cos(from.getLatitudeRad());
470
471   double sinLatTo = sin(to.getLatitudeRad());
472   double cosLatTo = cos(to.getLatitudeRad());
473
474   double x = cosLatTo*sin(diffLon);
475   double y = cosLatFrom*sinLatTo - sinLatFrom*cosLatTo*cos(diffLon);
476
477   // guard atan2 returning NaN's
478   if (fabs(x) <= SGLimitsd::min() && fabs(y) <= SGLimitsd::min())
479     return 0;
480
481   double c = atan2(x, y);
482   if (c >= 0)
483     return SGMiscd::twopi() - c;
484   else
485     return -c;
486 }
487
488 double
489 SGGeodesy::distanceM(const SGGeoc& from, const SGGeoc& to)
490 {
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;
500 }