]> git.mxchange.org Git - flightgear.git/blob - src/Time/moonpos.cxx
e32df4ac1ed7a50714c3106e2fefc8bc74ed68b1
[flightgear.git] / src / Time / moonpos.cxx
1 // moonpos.cxx (basically, this is a slightly modified version of the 'sunpos.cxx' file, adapted from XEarth)
2
3 // kirk johnson
4 // july 1993
5 //
6 // code for calculating the position on the earth's surface for which
7 // the moon is directly overhead (adapted from _practical astronomy
8 // with your calculator, third edition_, peter duffett-smith,
9 // cambridge university press, 1988.)
10 //
11 // Copyright (C) 1989, 1990, 1993, 1994, 1995 Kirk Lauritz Johnson
12 //
13 // Parts of the source code (as marked) are:
14 //   Copyright (C) 1989, 1990, 1991 by Jim Frost
15 //   Copyright (C) 1992 by Jamie Zawinski <jwz@lucid.com>
16 //
17 // Permission to use, copy, modify and freely distribute xearth for
18 // non-commercial and not-for-profit purposes is hereby granted
19 // without fee, provided that both the above copyright notice and this
20 // permission notice appear in all copies and in supporting
21 // documentation.
22 //
23 // The author makes no representations about the suitability of this
24 // software for any purpose. It is provided "as is" without express or
25 // implied warranty.
26 //
27 // THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
28 // INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
29 // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT
30 // OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
31 // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
32 // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
33 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
34 //
35 // $Id$
36
37
38 #ifdef HAVE_CONFIG_H
39 #  include <config.h>
40 #endif
41
42 #include "Include/compiler.h"
43 #ifdef FG_HAVE_STD_INCLUDES
44 #  include <cmath>
45 #  include <cstdio>
46 #  include <ctime>
47 #else
48 #  include <math.h>
49 #  include <stdio.h>
50 #  include <time.h>
51 #endif
52
53
54 #include <Debug/logstream.hxx>
55 #include <Astro/solarsystem.hxx>
56 #include <Include/fg_constants.h>
57 #include <Main/views.hxx>
58 #include <Math/fg_geodesy.hxx>
59 #include <Math/mat3.h>
60 #include <Math/point3d.hxx>
61 #include <Math/polar3d.hxx>
62 #include <Math/vector.hxx>
63 #include <Scenery/scenery.hxx>
64
65 #include "fg_time.hxx"
66 #include "moonpos.hxx"
67
68 extern SolarSystem *solarSystem;
69
70 #undef E
71
72
73 /*
74  * the epoch upon which these astronomical calculations are based is
75  * 1990 january 0.0, 631065600 seconds since the beginning of the
76  * "unix epoch" (00:00:00 GMT, Jan. 1, 1970)
77  *
78  * given a number of seconds since the start of the unix epoch,
79  * DaysSinceEpoch() computes the number of days since the start of the
80  * astronomical epoch (1990 january 0.0)
81  */
82
83 #define EpochStart           (631065600)
84 #define DaysSinceEpoch(secs) (((secs)-EpochStart)*(1.0/(24*3600)))
85
86 /*
87  * assuming the apparent orbit of the moon about the earth is circular,
88  * the rate at which the orbit progresses is given by RadsPerDay --
89  * FG_2PI radians per orbit divided by 365.242191 days per year:
90  */
91
92 #define RadsPerDay (FG_2PI/365.242191)
93
94 /*
95  * details of moon's apparent orbit at epoch 1990.0 (after
96  * duffett-smith, table 6, section 46)
97  *
98  * Epsilon_g    (ecliptic longitude at epoch 1990.0) 279.403303 degrees
99  * OmegaBar_g   (ecliptic longitude of perigee)      282.768422 degrees
100  * Eccentricity (eccentricity of orbit)                0.016713
101  */
102
103 #define Epsilon_g    (279.403303*(FG_2PI/360))
104 #define OmegaBar_g   (282.768422*(FG_2PI/360))
105 #define Eccentricity (0.016713)
106
107 /*
108  * MeanObliquity gives the mean obliquity of the earth's axis at epoch
109  * 1990.0 (computed as 23.440592 degrees according to the method given
110  * in duffett-smith, section 27)
111  */
112 #define MeanObliquity (23.440592*(FG_2PI/360))
113
114 /* static double solve_keplers_equation(double); */
115 /* static double moon_ecliptic_longitude(time_t); */
116 static void   ecliptic_to_equatorial(double, double, double *, double *);
117 static double julian_date(int, int, int);
118 static double GST(time_t);
119
120 /*
121  * solve Kepler's equation via Newton's method
122  * (after duffett-smith, section 47)
123  */
124 /*
125 static double solve_keplers_equation(double M) {
126     double E;
127     double delta;
128
129     E = M;
130     while (1) {
131         delta = E - Eccentricity*sin(E) - M;
132         if (fabs(delta) <= 1e-10) break;
133         E -= delta / (1 - Eccentricity*cos(E));
134     }
135
136     return E;
137 }
138 */
139
140
141 /* compute ecliptic longitude of moon (in radians) (after
142  * duffett-smith, section 47) */
143 /*
144 static double moon_ecliptic_longitude(time_t ssue) {
145     // time_t ssue;              //  seconds since unix epoch
146     double D, N;
147     double M_moon, E;
148     double v;
149
150     D = DaysSinceEpoch(ssue);
151
152     N = RadsPerDay * D;
153     N = fmod(N, FG_2PI);
154     if (N < 0) N += FG_2PI;
155
156     M_moon = N + Epsilon_g - OmegaBar_g;
157     if (M_moon < 0) M_moon += FG_2PI;
158
159     E = solve_keplers_equation(M_moon);
160     v = 2 * atan(sqrt((1+Eccentricity)/(1-Eccentricity)) * tan(E/2));
161
162     return (v + OmegaBar_g);
163 }
164 */
165
166
167 /* convert from ecliptic to equatorial coordinates (after
168  * duffett-smith, section 27) */
169
170 static void ecliptic_to_equatorial(double lambda, double beta, 
171                                    double *alpha, double *delta) {
172     /* double  lambda;            ecliptic longitude       */
173     /* double  beta;              ecliptic latitude        */
174     /* double *alpha;             (return) right ascension */
175     /* double *delta;             (return) declination     */
176
177     double sin_e, cos_e;
178     double sin_l, cos_l;
179
180     sin_e = sin(MeanObliquity);
181     cos_e = cos(MeanObliquity);
182     sin_l = sin(lambda);
183     cos_l = cos(lambda);
184
185     *alpha = atan2(sin_l*cos_e - tan(beta)*sin_e, cos_l);
186     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin_l);
187 }
188
189
190 /* computing julian dates (assuming gregorian calendar, thus this is
191  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
192  * section 4) */
193
194 static double julian_date(int y, int m, int d) {
195     /* int y;                    year (e.g. 19xx)          */
196     /* int m;                    month (jan=1, feb=2, ...) */
197     /* int d;                    day of month              */
198
199     int    A, B, C, D;
200     double JD;
201
202     /* lazy test to ensure gregorian calendar */
203     if (y < 1583) {
204         FG_LOG( FG_EVENT, FG_ALERT, 
205                 "WHOOPS! Julian dates only valid for 1582 oct 15 or later" );
206     }
207
208     if ((m == 1) || (m == 2)) {
209         y -= 1;
210         m += 12;
211     }
212
213     A = y / 100;
214     B = 2 - A + (A / 4);
215     C = (int)(365.25 * y);
216     D = (int)(30.6001 * (m + 1));
217
218     JD = B + C + D + d + 1720994.5;
219
220     return JD;
221 }
222
223
224 /* compute greenwich mean sidereal time (GST) corresponding to a given
225  * number of seconds since the unix epoch (after duffett-smith,
226  * section 12) */
227 static double GST(time_t ssue) {
228     /* time_t ssue;           seconds since unix epoch */
229
230     double     JD;
231     double     T, T0;
232     double     UT;
233     struct tm *tm;
234
235     tm = gmtime(&ssue);
236
237     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
238     T  = (JD - 2451545) / 36525;
239
240     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
241
242     T0 = fmod(T0, 24.0);
243     if (T0 < 0) T0 += 24;
244
245     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
246
247     T0 += UT * 1.002737909;
248     T0 = fmod(T0, 24.0);
249     if (T0 < 0) T0 += 24;
250
251     return T0;
252 }
253
254
255 /* given a particular time (expressed in seconds since the unix
256  * epoch), compute position on the earth (lat, lon) such that moon is
257  * directly overhead.  (lat, lon are reported in radians */
258
259 void fgMoonPosition(time_t ssue, double *lon, double *lat) {
260     /* time_t  ssue;           seconds since unix epoch */
261     /* double *lat;            (return) latitude        */
262     /* double *lon;            (return) longitude       */
263
264     /* double lambda; */
265     double alpha, delta;
266     double tmp;
267
268     /* lambda = moon_ecliptic_longitude(ssue); */
269     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
270     //ecliptic_to_equatorial (solarPosition.lonMoon, 0.0, &alpha, &delta);
271     
272     /* ********************************************************************** 
273      * NOTE: in the next function, each time the moon's position is updated, the
274      * the moon's longitude is returned from solarSystem->moon. Note that the 
275      * moon's position is updated at a much higher frequency than the rate at 
276      * which the solar system's rebuilds occur. This is not a problem, however,
277      * because the fgMoonPosition we're talking about here concerns the changing
278      * position of the moon due to the daily rotation of the earth.
279      * The ecliptic longitude, however, represents the position of the moon with
280      * respect to the stars, and completes just one cycle over the course of a 
281      * year. Its therefore pretty safe to update the moon's longitude only once
282      * every ten minutes. (Comment added by Durk Talsma).
283      ************************************************************************/
284
285     ecliptic_to_equatorial( SolarSystem::theSolarSystem->getMoon()->getLon(),
286                             0.0, &alpha, &delta );
287     tmp = alpha - (FG_2PI/24)*GST(ssue);
288     if (tmp < -FG_PI) {
289         do tmp += FG_2PI;
290         while (tmp < -FG_PI);
291     } else if (tmp > FG_PI) {
292         do tmp -= FG_2PI;
293         while (tmp < -FG_PI);
294     }
295
296     *lon = tmp;
297     *lat = delta;
298 }
299
300
301 /* given a particular time expressed in side real time at prime
302  * meridian (GST), compute position on the earth (lat, lon) such that
303  * moon is directly overhead.  (lat, lon are reported in radians */
304
305 static void fgMoonPositionGST(double gst, double *lon, double *lat) {
306     /* time_t  ssue;           seconds since unix epoch */
307     /* double *lat;            (return) latitude        */
308     /* double *lon;            (return) longitude       */
309
310     /* double lambda; */
311     double alpha, delta;
312     double tmp;
313
314     /* lambda = moon_ecliptic_longitude(ssue); */
315     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
316     //ecliptic_to_equatorial (solarPosition.lonMoon, 0.0, &alpha, &delta);
317     ecliptic_to_equatorial( SolarSystem::theSolarSystem->getMoon()->getLon(),
318                             SolarSystem::theSolarSystem->getMoon()->getLat(), 
319                             &alpha,  &delta );
320
321 //    tmp = alpha - (FG_2PI/24)*GST(ssue);
322     tmp = alpha - (FG_2PI/24)*gst;      
323     if (tmp < -FG_PI) {
324         do tmp += FG_2PI;
325         while (tmp < -FG_PI);
326     } else if (tmp > FG_PI) {
327         do tmp -= FG_2PI;
328         while (tmp < -FG_PI);
329     }
330
331     *lon = tmp;
332     *lat = delta;
333 }
334
335
336 // update the cur_time_params structure with the current moon position
337 void fgUpdateMoonPos( void ) {
338     fgLIGHT *l;
339     FGTime *t;
340     FGView *v;
341     sgVec3 nup, nmoon, v0, surface_to_moon;
342     Point3D p, rel_moonpos;
343     double dot, east_dot;
344     double moon_gd_lat, sl_radius;
345
346     l = &cur_light_params;
347     t = FGTime::cur_time_params;
348     v = &current_view;
349
350     FG_LOG( FG_EVENT, FG_INFO, "  Updating Moon position" );
351
352     // (not sure why there was two)
353     // fgMoonPosition(t->cur_time, &l->moon_lon, &moon_gd_lat);
354     fgMoonPositionGST(t->getGst(), &l->moon_lon, &moon_gd_lat);
355
356     fgGeodToGeoc(moon_gd_lat, 0.0, &sl_radius, &l->moon_gc_lat);
357
358     p = Point3D( l->moon_lon, l->moon_gc_lat, sl_radius );
359     l->fg_moonpos = fgPolarToCart3d(p);
360
361     FG_LOG( FG_EVENT, FG_INFO, "    t->cur_time = " << t->get_cur_time() );
362     FG_LOG( FG_EVENT, FG_INFO, 
363             "    Moon Geodetic lat = " << moon_gd_lat
364             << " Geocentric lat = " << l->moon_gc_lat );
365
366     // update the sun light vector
367     sgSetVec4( l->moon_vec,
368                l->fg_moonpos.x(), l->fg_moonpos.y(), l->fg_moonpos.z(), 0.0 );
369     sgNormalizeVec4( l->moon_vec );
370     sgCopyVec4( l->moon_vec_inv, l->moon_vec );
371     sgNegateVec4( l->moon_vec_inv );
372
373     // make sure these are directional light sources only
374     l->moon_vec[3] = l->moon_vec_inv[3] = 0.0;
375     // cout << "  l->moon_vec = " << l->moon_vec[0] << "," << l->moon_vec[1]
376     //      << ","<< l->moon_vec[2] << endl;
377
378     // calculate the moon's relative angle to local up
379     sgCopyVec3( nup, v->get_local_up() );
380     sgSetVec3( nmoon, l->fg_moonpos.x(), l->fg_moonpos.y(), l->fg_moonpos.z() );
381     sgNormalizeVec3(nup);
382     sgNormalizeVec3(nmoon);
383     // cout << "nup = " << nup[0] << "," << nup[1] << "," 
384     //      << nup[2] << endl;
385     // cout << "nmoon = " << nmoon[0] << "," << nmoon[1] << "," 
386     //      << nmoon[2] << endl;
387
388     l->moon_angle = acos( sgScalarProductVec3( nup, nmoon ) );
389     cout << "moon angle relative to current location = " 
390          << l->moon_angle << endl;
391     
392     // calculate vector to moon's position on the earth's surface
393     rel_moonpos = l->fg_moonpos - (v->get_view_pos() + scenery.center);
394     v->set_to_moon( rel_moonpos.x(), rel_moonpos.y(), rel_moonpos.z() );
395     // printf( "Vector to moon = %.2f %.2f %.2f\n",
396     //         v->to_moon[0], v->to_moon[1], v->to_moon[2]);
397
398     // make a vector to the current view position
399     Point3D view_pos = v->get_view_pos();
400     sgSetVec3( v0, view_pos.x(), view_pos.y(), view_pos.z() );
401
402     // Given a vector from the view position to the point on the
403     // earth's surface the moon is directly over, map into onto the
404     // local plane representing "horizontal".
405
406     sgmap_vec_onto_cur_surface_plane( v->get_local_up(), v0, 
407                                       v->get_to_moon(), surface_to_moon );
408     sgNormalizeVec3(surface_to_moon);
409     v->set_surface_to_moon( surface_to_moon[0], surface_to_moon[1], 
410                             surface_to_moon[2] );
411     // cout << "(sg) Surface direction to moon is "
412     //   << surface_to_moon[0] << "," 
413     //   << surface_to_moon[1] << ","
414     //   << surface_to_moon[2] << endl;
415     // cout << "Should be close to zero = " 
416     //   << sgScalarProductVec3(nup, surface_to_moon) << endl;
417
418     // calculate the angle between v->surface_to_moon and
419     // v->surface_east.  We do this so we can sort out the acos()
420     // ambiguity.  I wish I could think of a more efficient way ... :-(
421     east_dot = sgScalarProductVec3( surface_to_moon, v->get_surface_east() );
422    // cout << "  East dot product = " << east_dot << endl;
423
424     // calculate the angle between v->surface_to_moon and
425     // v->surface_south.  this is how much we have to rotate the sky
426     // for it to align with the moon
427     dot = sgScalarProductVec3( surface_to_moon, v->get_surface_south() );
428     // cout << "  Dot product = " << dot << endl;
429
430     if ( east_dot >= 0 ) {
431         l->moon_rotation = acos(dot);
432     } else {
433         l->moon_rotation = -acos(dot);
434     }
435     // cout << "  Sky needs to rotate = " << angle << " rads = "
436     //      << angle * RAD_TO_DEG << " degrees." << endl;
437 }
438
439