]> git.mxchange.org Git - flightgear.git/blob - src/Time/sunpos.cxx
Check for less than -1.0 also.
[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 #include <simgear/timing/sg_time.hxx>
64
65 #include <Main/globals.hxx>
66 #include <Main/viewer.hxx>
67 #include <Scenery/scenery.hxx>
68 #include <Time/light.hxx>
69
70 #include "sunpos.hxx"
71
72 // #undef E // should no longer be needed
73 #define MeanObliquity (23.440592*(SGD_2PI/360))
74
75 static void   ecliptic_to_equatorial(double, double, double *, double *);
76 static double julian_date(int, int, int);
77 static double GST(time_t);
78
79 static void ecliptic_to_equatorial(double lambda, double beta, 
80                                    double *alpha, double *delta) {
81     /* double  lambda;            ecliptic longitude       */
82     /* double  beta;              ecliptic latitude        */
83     /* double *alpha;             (return) right ascension */
84     /* double *delta;             (return) declination     */
85
86     double sin_e, cos_e;
87     double sin_l, cos_l;
88
89     sin_e = sin(MeanObliquity);
90     cos_e = cos(MeanObliquity);
91     sin_l = sin(lambda);
92     cos_l = cos(lambda);
93
94     *alpha = atan2(sin_l*cos_e - tan(beta)*sin_e, cos_l);
95     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin_l);
96 }
97
98
99 /* computing julian dates (assuming gregorian calendar, thus this is
100  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
101  * section 4) */
102
103 static double julian_date(int y, int m, int d) {
104     /* int y;                    year (e.g. 19xx)          */
105     /* int m;                    month (jan=1, feb=2, ...) */
106     /* int d;                    day of month              */
107
108     int    A, B, C, D;
109     double JD;
110
111     /* lazy test to ensure gregorian calendar */
112     if (y < 1583) {
113         SG_LOG( SG_EVENT, SG_ALERT, 
114                 "WHOOPS! Julian dates only valid for 1582 oct 15 or later" );
115     }
116
117     if ((m == 1) || (m == 2)) {
118         y -= 1;
119         m += 12;
120     }
121
122     A = y / 100;
123     B = 2 - A + (A / 4);
124     C = (int)(365.25 * y);
125     D = (int)(30.6001 * (m + 1));
126
127     JD = B + C + D + d + 1720994.5;
128
129     return JD;
130 }
131
132
133 /* compute greenwich mean sidereal time (GST) corresponding to a given
134  * number of seconds since the unix epoch (after duffett-smith,
135  * section 12) */
136 static double GST(time_t ssue) {
137     /* time_t ssue;           seconds since unix epoch */
138
139     double     JD;
140     double     T, T0;
141     double     UT;
142     struct tm *tm;
143
144     tm = gmtime(&ssue);
145
146     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
147     T  = (JD - 2451545) / 36525;
148
149     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
150
151     T0 = fmod(T0, 24.0);
152     if (T0 < 0) T0 += 24;
153
154     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
155
156     T0 += UT * 1.002737909;
157     T0 = fmod(T0, 24.0);
158     if (T0 < 0) T0 += 24;
159
160     return T0;
161 }
162
163
164 /* given a particular time (expressed in seconds since the unix
165  * epoch), compute position on the earth (lat, lon) such that sun is
166  * directly overhead.  (lat, lon are reported in radians */
167
168 void fgSunPosition(time_t ssue, double *lon, double *lat) {
169     /* time_t  ssue;           seconds since unix epoch */
170     /* double *lat;            (return) latitude        */
171     /* double *lon;            (return) longitude       */
172
173     /* double lambda; */
174     double alpha, delta;
175     double tmp;
176
177     /* lambda = sun_ecliptic_longitude(ssue); */
178     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
179     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
180     
181     /* ********************************************************************** 
182      * NOTE: in the next function, each time the sun's position is updated, the
183      * the sun's longitude is returned from solarSystem->sun. Note that the 
184      * sun's position is updated at a much higher frequency than the rate at 
185      * which the solar system's rebuilds occur. This is not a problem, however,
186      * because the fgSunPosition we're talking about here concerns the changing
187      * position of the sun due to the daily rotation of the earth.
188      * The ecliptic longitude, however, represents the position of the sun with
189      * respect to the stars, and completes just one cycle over the course of a 
190      * year. Its therefore pretty safe to update the sun's longitude only once
191      * every ten minutes. (Comment added by Durk Talsma).
192      ************************************************************************/
193
194     ecliptic_to_equatorial( globals->get_ephem()->get_sun()->getLon(),
195                             0.0, &alpha, &delta );
196     tmp = alpha - (SGD_2PI/24)*GST(ssue);
197     if (tmp < -SGD_PI) {
198         do tmp += SGD_2PI;
199         while (tmp < -SGD_PI);
200     } else if (tmp > SGD_PI) {
201         do tmp -= SGD_2PI;
202         while (tmp < -SGD_PI);
203     }
204
205     *lon = tmp;
206     *lat = delta;
207 }
208
209
210 /* given a particular time expressed in side real time at prime
211  * meridian (GST), compute position on the earth (lat, lon) such that
212  * sun is directly overhead.  (lat, lon are reported in radians */
213
214 void fgSunPositionGST(double gst, double *lon, double *lat) {
215     /* time_t  ssue;           seconds since unix epoch */
216     /* double *lat;            (return) latitude        */
217     /* double *lon;            (return) longitude       */
218
219     /* double lambda; */
220     double alpha, delta;
221     double tmp;
222
223     /* lambda = sun_ecliptic_longitude(ssue); */
224     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
225     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
226     ecliptic_to_equatorial( globals->get_ephem()->get_sun()->getLon(),
227                             globals->get_ephem()->get_sun()->getLat(),
228                             &alpha, &delta );
229
230     // tmp = alpha - (SGD_2PI/24)*GST(ssue);
231     tmp = alpha - (SGD_2PI/24)*gst;     
232     if (tmp < -SGD_PI) {
233         do tmp += SGD_2PI;
234         while (tmp < -SGD_PI);
235     } else if (tmp > SGD_PI) {
236         do tmp -= SGD_2PI;
237         while (tmp < -SGD_PI);
238     }
239
240     *lon = tmp;
241     *lat = delta;
242 }
243
244
245 // update the cur_time_params structure with the current sun position
246 void fgUpdateSunPos( void ) {
247     sgVec3 nup, nsun;
248     Point3D rel_sunpos;
249     double dot, east_dot;
250     double sun_gd_lat, sl_radius;
251
252     // vector in cartesian coordinates from current position to the
253     // postion on the earth's surface the sun is directly over
254     sgVec3 to_sun;
255
256     // surface direction to go to head towards sun
257     sgVec3 surface_to_sun;
258
259     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
260     SGTime *t = globals->get_time_params();
261     FGViewer *v = globals->get_current_view();
262
263     SG_LOG( SG_EVENT, SG_INFO, "  Updating Sun position" );
264     SG_LOG( SG_EVENT, SG_INFO, "  Gst = " << t->getGst() );
265
266     double sun_l;
267     fgSunPositionGST(t->getGst(), &sun_l, &sun_gd_lat);
268     l->set_sun_lon(sun_l);
269
270     sgGeodToGeoc(sun_gd_lat, 0.0, &sl_radius, &sun_l);
271     l->set_sun_gc_lat(sun_l);
272
273     Point3D p = Point3D( l->get_sun_lon(), l->get_sun_gc_lat(), sl_radius );
274     l->set_sunpos( sgPolarToCart3d(p) );
275
276     SG_LOG( SG_EVENT, SG_INFO, "    t->cur_time = " << t->get_cur_time() );
277     SG_LOG( SG_EVENT, SG_INFO, 
278             "    Sun Geodetic lat = " << sun_gd_lat
279             << " Geocentric lat = " << l->get_sun_gc_lat() );
280
281     // update the sun light vector
282     sgSetVec4( l->sun_vec(), l->get_sunpos().x(),
283                l->get_sunpos().y(), l->get_sunpos().z(), 0.0 );
284     sgNormalizeVec4( l->sun_vec() );
285     sgCopyVec4( l->sun_vec_inv(), l->sun_vec() );
286     sgNegateVec4( l->sun_vec_inv() );
287
288     // make sure these are directional light sources only
289     l->sun_vec()[3] = l->sun_vec_inv()[3] = 0.0;
290     // cout << "  l->sun_vec = " << l->sun_vec[0] << "," << l->sun_vec[1]
291     //      << ","<< l->sun_vec[2] << endl;
292
293     // calculate the sun's relative angle to local up
294     sgCopyVec3( nup, v->get_world_up() );
295     sgSetVec3( nsun, l->get_sunpos().x(),
296                l->get_sunpos().y(), l->get_sunpos().z() );
297     sgNormalizeVec3(nup);
298     sgNormalizeVec3(nsun);
299     // cout << "nup = " << nup[0] << "," << nup[1] << "," 
300     //      << nup[2] << endl;
301     // cout << "nsun = " << nsun[0] << "," << nsun[1] << "," 
302     //      << nsun[2] << endl;
303
304     l->set_sun_angle( acos( sgScalarProductVec3 ( nup, nsun ) ) );
305     SG_LOG( SG_EVENT, SG_INFO, "sun angle relative to current location = "
306             << l->get_sun_angle() );
307     
308     // calculate vector to sun's position on the earth's surface
309     Point3D vp( v->get_view_pos()[0],
310                 v->get_view_pos()[1],
311                 v->get_view_pos()[2] );
312     rel_sunpos = l->get_sunpos() - (vp + globals->get_scenery()->get_center());
313     sgSetVec3( to_sun, rel_sunpos.x(), rel_sunpos.y(), rel_sunpos.z() );
314     // printf( "Vector to sun = %.2f %.2f %.2f\n",
315     //         v->to_sun[0], v->to_sun[1], v->to_sun[2]);
316
317     // Given a vector from the view position to the point on the
318     // earth's surface the sun is directly over, map into onto the
319     // local plane representing "horizontal".
320
321     sgmap_vec_onto_cur_surface_plane( v->get_world_up(), v->get_view_pos(),
322                                       to_sun, surface_to_sun );
323     sgNormalizeVec3(surface_to_sun);
324     // cout << "(sg) Surface direction to sun is "
325     //   << surface_to_sun[0] << "," 
326     //   << surface_to_sun[1] << ","
327     //   << surface_to_sun[2] << endl;
328     // cout << "Should be close to zero = " 
329     //   << sgScalarProductVec3(nup, surface_to_sun) << endl;
330
331     // calculate the angle between surface_to_sun and
332     // v->get_surface_east().  We do this so we can sort out the
333     // acos() ambiguity.  I wish I could think of a more efficient
334     // way. :-(
335     east_dot = sgScalarProductVec3( surface_to_sun, v->get_surface_east() );
336     // cout << "  East dot product = " << east_dot << endl;
337
338     // calculate the angle between v->surface_to_sun and
339     // v->surface_south.  this is how much we have to rotate the sky
340     // for it to align with the sun
341     dot = sgScalarProductVec3( surface_to_sun, v->get_surface_south() );
342     // cout << "  Dot product = " << dot << endl;
343
344     if (dot > 1.0) {
345         SG_LOG( SG_ASTRO, SG_WARN,
346                 "Dot product  = " << dot << " is greater than 1.0" );
347         dot = 1.0;
348     }
349     else if (dot < -1.0) {
350          SG_LOG( SG_ASTRO, SG_WARN,
351                  "Dot product  = " << dot << " is less than -1.0" );
352          dot = -1.0;
353      }
354
355     if ( east_dot >= 0 ) {
356         l->set_sun_rotation( acos(dot) );
357     } else {
358         l->set_sun_rotation( -acos(dot) );
359     }
360     // cout << "  Sky needs to rotate = " << angle << " rads = "
361     //      << angle * SGD_RADIANS_TO_DEGREES << " degrees." << endl;
362 }
363
364