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