]> git.mxchange.org Git - flightgear.git/blob - src/Time/sunpos.cxx
Substantial rewrite of FGNewMat, the material class. Most of the
[flightgear.git] / src / Time / sunpos.cxx
1 // sunpos.cxx (adapted from XEarth)
2 // kirk johnson
3 // july 1993
4 //
5 // code for calculating the position on the earth's surface for which
6 // the sun is directly overhead (adapted from _practical astronomy
7 // with your calculator, third edition_, peter duffett-smith,
8 // cambridge university press, 1988.)
9 //
10 // Copyright (C) 1989, 1990, 1993, 1994, 1995 Kirk Lauritz Johnson
11 //
12 // Parts of the source code (as marked) are:
13 //   Copyright (C) 1989, 1990, 1991 by Jim Frost
14 //   Copyright (C) 1992 by Jamie Zawinski <jwz@lucid.com>
15 //
16 // Permission to use, copy, modify and freely distribute xearth for
17 // non-commercial and not-for-profit purposes is hereby granted
18 // without fee, provided that both the above copyright notice and this
19 // permission notice appear in all copies and in supporting
20 // documentation.
21 //
22 // The author makes no representations about the suitability of this
23 // software for any purpose. It is provided "as is" without express or
24 // implied warranty.
25 //
26 // THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
27 // INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
28 // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT
29 // OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
30 // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
31 // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
32 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
33 //
34 // $Id$
35
36
37 #ifdef HAVE_CONFIG_H
38 #  include <config.h>
39 #endif
40
41 #include <simgear/compiler.h>
42
43 #ifdef SG_HAVE_STD_INCLUDES
44 #  include <cmath>
45 #  include <cstdio>
46 #  include <ctime>
47 #  ifdef macintosh
48      SG_USING_STD(time_t);
49 #  endif
50 #else
51 #  include <math.h>
52 #  include <stdio.h>
53 #  include <time.h>
54 #endif
55
56 #include <simgear/constants.h>
57 #include <simgear/debug/logstream.hxx>
58 #include <simgear/ephemeris/ephemeris.hxx>
59 #include <simgear/math/point3d.hxx>
60 #include <simgear/math/polar3d.hxx>
61 #include <simgear/math/sg_geodesy.hxx>
62 #include <simgear/math/vector.hxx>
63
64 #include <Main/globals.hxx>
65 #include <Main/viewer.hxx>
66 #include <Scenery/scenery.hxx>
67 #include <Time/light.hxx>
68
69 #include "sunpos.hxx"
70
71 // #undef E // should no longer be needed
72 #define MeanObliquity (23.440592*(SGD_2PI/360))
73
74 static void   ecliptic_to_equatorial(double, double, double *, double *);
75 static double julian_date(int, int, int);
76 static double GST(time_t);
77
78 static void ecliptic_to_equatorial(double lambda, double beta, 
79                                    double *alpha, double *delta) {
80     /* double  lambda;            ecliptic longitude       */
81     /* double  beta;              ecliptic latitude        */
82     /* double *alpha;             (return) right ascension */
83     /* double *delta;             (return) declination     */
84
85     double sin_e, cos_e;
86     double sin_l, cos_l;
87
88     sin_e = sin(MeanObliquity);
89     cos_e = cos(MeanObliquity);
90     sin_l = sin(lambda);
91     cos_l = cos(lambda);
92
93     *alpha = atan2(sin_l*cos_e - tan(beta)*sin_e, cos_l);
94     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin_l);
95 }
96
97
98 /* computing julian dates (assuming gregorian calendar, thus this is
99  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
100  * section 4) */
101
102 static double julian_date(int y, int m, int d) {
103     /* int y;                    year (e.g. 19xx)          */
104     /* int m;                    month (jan=1, feb=2, ...) */
105     /* int d;                    day of month              */
106
107     int    A, B, C, D;
108     double JD;
109
110     /* lazy test to ensure gregorian calendar */
111     if (y < 1583) {
112         SG_LOG( SG_EVENT, SG_ALERT, 
113                 "WHOOPS! Julian dates only valid for 1582 oct 15 or later" );
114     }
115
116     if ((m == 1) || (m == 2)) {
117         y -= 1;
118         m += 12;
119     }
120
121     A = y / 100;
122     B = 2 - A + (A / 4);
123     C = (int)(365.25 * y);
124     D = (int)(30.6001 * (m + 1));
125
126     JD = B + C + D + d + 1720994.5;
127
128     return JD;
129 }
130
131
132 /* compute greenwich mean sidereal time (GST) corresponding to a given
133  * number of seconds since the unix epoch (after duffett-smith,
134  * section 12) */
135 static double GST(time_t ssue) {
136     /* time_t ssue;           seconds since unix epoch */
137
138     double     JD;
139     double     T, T0;
140     double     UT;
141     struct tm *tm;
142
143     tm = gmtime(&ssue);
144
145     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
146     T  = (JD - 2451545) / 36525;
147
148     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
149
150     T0 = fmod(T0, 24.0);
151     if (T0 < 0) T0 += 24;
152
153     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
154
155     T0 += UT * 1.002737909;
156     T0 = fmod(T0, 24.0);
157     if (T0 < 0) T0 += 24;
158
159     return T0;
160 }
161
162
163 /* given a particular time (expressed in seconds since the unix
164  * epoch), compute position on the earth (lat, lon) such that sun is
165  * directly overhead.  (lat, lon are reported in radians */
166
167 void fgSunPosition(time_t ssue, double *lon, double *lat) {
168     /* time_t  ssue;           seconds since unix epoch */
169     /* double *lat;            (return) latitude        */
170     /* double *lon;            (return) longitude       */
171
172     /* double lambda; */
173     double alpha, delta;
174     double tmp;
175
176     /* lambda = sun_ecliptic_longitude(ssue); */
177     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
178     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
179     
180     /* ********************************************************************** 
181      * NOTE: in the next function, each time the sun's position is updated, the
182      * the sun's longitude is returned from solarSystem->sun. Note that the 
183      * sun's position is updated at a much higher frequency than the rate at 
184      * which the solar system's rebuilds occur. This is not a problem, however,
185      * because the fgSunPosition we're talking about here concerns the changing
186      * position of the sun due to the daily rotation of the earth.
187      * The ecliptic longitude, however, represents the position of the sun with
188      * respect to the stars, and completes just one cycle over the course of a 
189      * year. Its therefore pretty safe to update the sun's longitude only once
190      * every ten minutes. (Comment added by Durk Talsma).
191      ************************************************************************/
192
193     ecliptic_to_equatorial( globals->get_ephem()->get_sun()->getLon(),
194                             0.0, &alpha, &delta );
195     tmp = alpha - (SGD_2PI/24)*GST(ssue);
196     if (tmp < -SGD_PI) {
197         do tmp += SGD_2PI;
198         while (tmp < -SGD_PI);
199     } else if (tmp > SGD_PI) {
200         do tmp -= SGD_2PI;
201         while (tmp < -SGD_PI);
202     }
203
204     *lon = tmp;
205     *lat = delta;
206 }
207
208
209 /* given a particular time expressed in side real time at prime
210  * meridian (GST), compute position on the earth (lat, lon) such that
211  * sun is directly overhead.  (lat, lon are reported in radians */
212
213 static void fgSunPositionGST(double gst, double *lon, double *lat) {
214     /* time_t  ssue;           seconds since unix epoch */
215     /* double *lat;            (return) latitude        */
216     /* double *lon;            (return) longitude       */
217
218     /* double lambda; */
219     double alpha, delta;
220     double tmp;
221
222     /* lambda = sun_ecliptic_longitude(ssue); */
223     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
224     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
225     ecliptic_to_equatorial( globals->get_ephem()->get_sun()->getLon(),
226                             globals->get_ephem()->get_sun()->getLat(),
227                             &alpha, &delta );
228
229 //    tmp = alpha - (SGD_2PI/24)*GST(ssue);
230     tmp = alpha - (SGD_2PI/24)*gst;     
231     if (tmp < -SGD_PI) {
232         do tmp += SGD_2PI;
233         while (tmp < -SGD_PI);
234     } else if (tmp > SGD_PI) {
235         do tmp -= SGD_2PI;
236         while (tmp < -SGD_PI);
237     }
238
239     *lon = tmp;
240     *lat = delta;
241 }
242
243
244 // update the cur_time_params structure with the current sun position
245 void fgUpdateSunPos( void ) {
246     fgLIGHT *l;
247     FGViewer *v;
248     sgVec3 nup, nsun;
249     Point3D p, rel_sunpos;
250     double dot, east_dot;
251     double sun_gd_lat, sl_radius;
252
253     // vector in cartesian coordinates from current position to the
254     // postion on the earth's surface the sun is directly over
255     sgVec3 to_sun;
256
257     // surface direction to go to head towards sun
258     sgVec3 surface_to_sun;
259
260     l = &cur_light_params;
261     SGTime *t = globals->get_time_params();
262     v = globals->get_current_view();
263
264     SG_LOG( SG_EVENT, SG_INFO, "  Updating Sun position" );
265     SG_LOG( SG_EVENT, SG_INFO, "  Gst = " << t->getGst() );
266
267     fgSunPositionGST(t->getGst(), &l->sun_lon, &sun_gd_lat);
268
269     sgGeodToGeoc(sun_gd_lat, 0.0, &sl_radius, &l->sun_gc_lat);
270
271     p = Point3D( l->sun_lon, l->sun_gc_lat, sl_radius );
272     l->fg_sunpos = sgPolarToCart3d(p);
273
274     SG_LOG( SG_EVENT, SG_INFO, "    t->cur_time = " << t->get_cur_time() );
275     SG_LOG( SG_EVENT, SG_INFO, 
276             "    Sun Geodetic lat = " << sun_gd_lat
277             << " Geocentric lat = " << l->sun_gc_lat );
278
279     // update the sun light vector
280     sgSetVec4( l->sun_vec, 
281                l->fg_sunpos.x(), l->fg_sunpos.y(), l->fg_sunpos.z(), 0.0 );
282     sgNormalizeVec4( l->sun_vec );
283     sgCopyVec4( l->sun_vec_inv, l->sun_vec );
284     sgNegateVec4( l->sun_vec_inv );
285
286     // make sure these are directional light sources only
287     l->sun_vec[3] = l->sun_vec_inv[3] = 0.0;
288     // cout << "  l->sun_vec = " << l->sun_vec[0] << "," << l->sun_vec[1]
289     //      << ","<< l->sun_vec[2] << endl;
290
291     // calculate the sun's relative angle to local up
292     sgCopyVec3( nup, v->get_world_up() );
293     sgSetVec3( nsun, l->fg_sunpos.x(), l->fg_sunpos.y(), l->fg_sunpos.z() );
294     sgNormalizeVec3(nup);
295     sgNormalizeVec3(nsun);
296     // cout << "nup = " << nup[0] << "," << nup[1] << "," 
297     //      << nup[2] << endl;
298     // cout << "nsun = " << nsun[0] << "," << nsun[1] << "," 
299     //      << nsun[2] << endl;
300
301     l->sun_angle = acos( sgScalarProductVec3 ( nup, nsun ) );
302     SG_LOG( SG_EVENT, SG_INFO, "sun angle relative to current location = "
303             << l->sun_angle );
304     
305     // calculate vector to sun's position on the earth's surface
306     Point3D vp( v->get_view_pos()[0],
307                 v->get_view_pos()[1],
308                 v->get_view_pos()[2] );
309     rel_sunpos = l->fg_sunpos - ( vp + scenery.get_center() );
310     sgSetVec3( to_sun, rel_sunpos.x(), rel_sunpos.y(), rel_sunpos.z() );
311     // printf( "Vector to sun = %.2f %.2f %.2f\n",
312     //         v->to_sun[0], v->to_sun[1], v->to_sun[2]);
313
314     // Given a vector from the view position to the point on the
315     // earth's surface the sun is directly over, map into onto the
316     // local plane representing "horizontal".
317
318     sgmap_vec_onto_cur_surface_plane( v->get_world_up(), v->get_view_pos(),
319                                       to_sun, surface_to_sun );
320     sgNormalizeVec3(surface_to_sun);
321     // cout << "(sg) Surface direction to sun is "
322     //   << surface_to_sun[0] << "," 
323     //   << surface_to_sun[1] << ","
324     //   << surface_to_sun[2] << endl;
325     // cout << "Should be close to zero = " 
326     //   << sgScalarProductVec3(nup, surface_to_sun) << endl;
327
328     // calculate the angle between surface_to_sun and
329     // v->get_surface_east().  We do this so we can sort out the
330     // acos() ambiguity.  I wish I could think of a more efficient
331     // way. :-(
332     east_dot = sgScalarProductVec3( surface_to_sun, v->get_surface_east() );
333     // cout << "  East dot product = " << east_dot << endl;
334
335     // calculate the angle between v->surface_to_sun and
336     // v->surface_south.  this is how much we have to rotate the sky
337     // for it to align with the sun
338     dot = sgScalarProductVec3( surface_to_sun, v->get_surface_south() );
339     // cout << "  Dot product = " << dot << endl;
340
341     if ( east_dot >= 0 ) {
342         l->sun_rotation = acos(dot);
343     } else {
344         l->sun_rotation = -acos(dot);
345     }
346     // cout << "  Sky needs to rotate = " << angle << " rads = "
347     //      << angle * SGD_RADIANS_TO_DEGREES << " degrees." << endl;
348 }
349
350