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