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