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