]> git.mxchange.org Git - flightgear.git/blob - Time/sunpos.c
Incorporated Durk's Astro/ tweaks. Includes unifying the sun position
[flightgear.git] / Time / sunpos.c
1 /*
2  * sunpos.c
3  * kirk johnson
4  * july 1993
5  *
6  * code for calculating the position on the earth's surface for which
7  * the sun is directly overhead (adapted from _practical astronomy
8  * with your calculator, third edition_, peter duffett-smith,
9  * cambridge university press, 1988.)
10  *
11  * RCS $Id$
12  *
13  * Copyright (C) 1989, 1990, 1993, 1994, 1995 Kirk Lauritz Johnson
14  *
15  * Parts of the source code (as marked) are:
16  *   Copyright (C) 1989, 1990, 1991 by Jim Frost
17  *   Copyright (C) 1992 by Jamie Zawinski <jwz@lucid.com>
18  *
19  * Permission to use, copy, modify and freely distribute xearth for
20  * non-commercial and not-for-profit purposes is hereby granted
21  * without fee, provided that both the above copyright notice and this
22  * permission notice appear in all copies and in supporting
23  * documentation.
24  *
25  * The author makes no representations about the suitability of this
26  * software for any purpose. It is provided "as is" without express or
27  * implied warranty.
28  *
29  * THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
30  * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS,
31  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT
32  * OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
33  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
34  * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
35  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
36  *
37  * $Id$
38  * (Log is kept at end of this file)
39  */
40
41
42 #include <math.h>
43 #include <stdio.h>
44 #include <time.h>
45
46 #include <Astro/orbits.h>
47 #include <Include/fg_constants.h>
48 #include <Main/views.h>
49 #include <Math/fg_geodesy.h>
50 #include <Math/mat3.h>
51 #include <Math/polar.h>
52 #include <Time/fg_time.h>
53 #include <Time/sunpos.h>
54
55
56 #undef E
57
58
59 /*
60  * the epoch upon which these astronomical calculations are based is
61  * 1990 january 0.0, 631065600 seconds since the beginning of the
62  * "unix epoch" (00:00:00 GMT, Jan. 1, 1970)
63  *
64  * given a number of seconds since the start of the unix epoch,
65  * DaysSinceEpoch() computes the number of days since the start of the
66  * astronomical epoch (1990 january 0.0)
67  */
68
69 #define EpochStart           (631065600)
70 #define DaysSinceEpoch(secs) (((secs)-EpochStart)*(1.0/(24*3600)))
71
72 /*
73  * assuming the apparent orbit of the sun about the earth is circular,
74  * the rate at which the orbit progresses is given by RadsPerDay --
75  * FG_2PI radians per orbit divided by 365.242191 days per year:
76  */
77
78 #define RadsPerDay (FG_2PI/365.242191)
79
80 /*
81  * details of sun's apparent orbit at epoch 1990.0 (after
82  * duffett-smith, table 6, section 46)
83  *
84  * Epsilon_g    (ecliptic longitude at epoch 1990.0) 279.403303 degrees
85  * OmegaBar_g   (ecliptic longitude of perigee)      282.768422 degrees
86  * Eccentricity (eccentricity of orbit)                0.016713
87  */
88
89 #define Epsilon_g    (279.403303*(FG_2PI/360))
90 #define OmegaBar_g   (282.768422*(FG_2PI/360))
91 #define Eccentricity (0.016713)
92
93 /*
94  * MeanObliquity gives the mean obliquity of the earth's axis at epoch
95  * 1990.0 (computed as 23.440592 degrees according to the method given
96  * in duffett-smith, section 27)
97  */
98 #define MeanObliquity (23.440592*(FG_2PI/360))
99
100 /* static double solve_keplers_equation(double); */
101 /* static double sun_ecliptic_longitude(time_t); */
102 static void   ecliptic_to_equatorial(double, double, double *, double *);
103 static double julian_date(int, int, int);
104 static double GST(time_t);
105
106 /*
107  * solve Kepler's equation via Newton's method
108  * (after duffett-smith, section 47)
109  */
110 /*
111 static double solve_keplers_equation(double M) {
112     double E;
113     double delta;
114
115     E = M;
116     while (1) {
117         delta = E - Eccentricity*sin(E) - M;
118         if (fabs(delta) <= 1e-10) break;
119         E -= delta / (1 - Eccentricity*cos(E));
120     }
121
122     return E;
123 }
124 */
125
126
127 /* compute ecliptic longitude of sun (in radians) (after
128  * duffett-smith, section 47) */
129 /*
130 static double sun_ecliptic_longitude(time_t ssue) {
131     // time_t ssue;              //  seconds since unix epoch
132     double D, N;
133     double M_sun, E;
134     double v;
135
136     D = DaysSinceEpoch(ssue);
137
138     N = RadsPerDay * D;
139     N = fmod(N, FG_2PI);
140     if (N < 0) N += FG_2PI;
141
142     M_sun = N + Epsilon_g - OmegaBar_g;
143     if (M_sun < 0) M_sun += FG_2PI;
144
145     E = solve_keplers_equation(M_sun);
146     v = 2 * atan(sqrt((1+Eccentricity)/(1-Eccentricity)) * tan(E/2));
147
148     return (v + OmegaBar_g);
149 }
150 */
151
152
153 /* convert from ecliptic to equatorial coordinates (after
154  * duffett-smith, section 27) */
155
156 static void ecliptic_to_equatorial(double lambda, double beta, 
157                                    double *alpha, double *delta) {
158     /* double  lambda;            ecliptic longitude       */
159     /* double  beta;              ecliptic latitude        */
160     /* double *alpha;             (return) right ascension */
161     /* double *delta;             (return) declination     */
162
163     double sin_e, cos_e;
164
165     sin_e = sin(MeanObliquity);
166     cos_e = cos(MeanObliquity);
167
168     *alpha = atan2(sin(lambda)*cos_e - tan(beta)*sin_e, cos(lambda));
169     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin(lambda));
170 }
171
172
173 /* computing julian dates (assuming gregorian calendar, thus this is
174  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
175  * section 4) */
176
177 static double julian_date(int y, int m, int d) {
178     /* int y;                    year (e.g. 19xx)          */
179     /* int m;                    month (jan=1, feb=2, ...) */
180     /* int d;                    day of month              */
181
182     int    A, B, C, D;
183     double JD;
184
185     /* lazy test to ensure gregorian calendar */
186     if (y < 1583) {
187         printf("WHOOPS! Julian dates only valid for 1582 oct 15 or later\n");
188     }
189
190     if ((m == 1) || (m == 2)) {
191         y -= 1;
192         m += 12;
193     }
194
195     A = y / 100;
196     B = 2 - A + (A / 4);
197     C = (int)(365.25 * y);
198     D = (int)(30.6001 * (m + 1));
199
200     JD = B + C + D + d + 1720994.5;
201
202     return JD;
203 }
204
205
206 /* compute greenwich mean sidereal time (GST) corresponding to a given
207  * number of seconds since the unix epoch (after duffett-smith,
208  * section 12) */
209 static double GST(time_t ssue) {
210     /* time_t ssue;           seconds since unix epoch */
211
212     double     JD;
213     double     T, T0;
214     double     UT;
215     struct tm *tm;
216
217     tm = gmtime(&ssue);
218
219     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
220     T  = (JD - 2451545) / 36525;
221
222     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
223
224     T0 = fmod(T0, 24.0);
225     if (T0 < 0) T0 += 24;
226
227     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
228
229     T0 += UT * 1.002737909;
230     T0 = fmod(T0, 24.0);
231     if (T0 < 0) T0 += 24;
232
233     return T0;
234 }
235
236
237 /* given a particular time (expressed in seconds since the unix
238  * epoch), compute position on the earth (lat, lon) such that sun is
239  * directly overhead.  (lat, lon are reported in radians */
240
241 void fgSunPosition(time_t ssue, double *lon, double *lat) {
242     /* time_t  ssue;           seconds since unix epoch */
243     /* double *lat;            (return) latitude        */
244     /* double *lon;            (return) longitude       */
245
246     /* double lambda; */
247     double alpha, delta;
248     double tmp;
249
250     /* lambda = sun_ecliptic_longitude(ssue); */
251     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
252     ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
253
254     tmp = alpha - (FG_2PI/24)*GST(ssue);
255     if (tmp < -FG_PI) {
256         do tmp += FG_2PI;
257         while (tmp < -FG_PI);
258     } else if (tmp > FG_PI) {
259         do tmp -= FG_2PI;
260         while (tmp < -FG_PI);
261     }
262
263     *lon = tmp;
264     *lat = delta;
265 }
266
267
268 /* update the cur_time_params structure with the current sun position */
269 void fgUpdateSunPos( void ) {
270     struct fgLIGHT *l;
271     struct fgTIME *t;
272     struct fgVIEW *v;
273     MAT3vec nup, nsun;
274     /* if the 4th field is 0.0, this specifies a direction ... */
275     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
276     /* base sky color */
277     GLfloat base_sky_color[4] =        {0.60, 0.60, 0.90, 1.0};
278     /* base fog color */
279     GLfloat base_fog_color[4] = {0.70, 0.70, 0.70, 1.0};
280     double sun_gd_lat, sl_radius, temp;
281     double x_2, x_4, x_8, x_10;
282     double light, ambient, diffuse, sky_brightness;
283     static int time_warp = 0;
284
285     l = &cur_light_params;
286     t = &cur_time_params;
287     v = &current_view;
288
289     printf("  Updating Sun position\n");
290
291     time_warp += 0; /* increase this to make the world spin real fast */
292
293     fgSunPosition(t->cur_time + time_warp, &l->sun_lon, &sun_gd_lat);
294
295     fgGeodToGeoc(sun_gd_lat, 0.0, &sl_radius, &l->sun_gc_lat);
296
297     l->fg_sunpos = fgPolarToCart(l->sun_lon, l->sun_gc_lat, sl_radius);
298
299     /* printf("  Geodetic lat = %.5f Geocentric lat = %.5f\n", sun_gd_lat,
300        t->sun_gc_lat); */
301
302     /* FALSE! (?> the sun position has to be translated just like
303      * everything else */
304     /* l->sun_vec_inv[0] = l->fg_sunpos.x - scenery_center.x;  */
305     /* l->sun_vec_inv[1] = l->fg_sunpos.y - scenery_center.y; */
306     /* l->sun_vec_inv[2] = l->fg_sunpos.z - scenery_center.z; */
307     /* MAT3_SCALE_VEC(l->sun_vec, l->sun_vec_inv, -1.0); */
308
309     /* I think this will work better for generating the sun light vector */
310     l->sun_vec[0] = l->fg_sunpos.x;
311     l->sun_vec[1] = l->fg_sunpos.y;
312     l->sun_vec[2] = l->fg_sunpos.z;
313     MAT3_NORMALIZE_VEC(l->sun_vec, temp);
314     MAT3_SCALE_VEC(l->sun_vec_inv, l->sun_vec, -1.0);
315
316     /* make these are directional light sources only */
317     l->sun_vec[3] = 0.0;
318     l->sun_vec_inv[3] = 0.0;
319
320     printf("  l->sun_vec = %.2f %.2f %.2f\n", l->sun_vec[0], l->sun_vec[1],
321            l->sun_vec[2]);
322
323     /* calculate the sun's relative angle to local up */
324     MAT3_COPY_VEC(nup, v->local_up);
325     nsun[0] = l->fg_sunpos.x; 
326     nsun[1] = l->fg_sunpos.y;
327     nsun[2] = l->fg_sunpos.z;
328     MAT3_NORMALIZE_VEC(nup, temp);
329     MAT3_NORMALIZE_VEC(nsun, temp);
330
331     l->sun_angle = acos(MAT3_DOT_PRODUCT(nup, nsun));
332     printf("  SUN ANGLE relative to current location = %.3f rads.\n", 
333            l->sun_angle);
334
335     /* calculate lighting parameters based on sun's relative angle to
336      * local up */
337     /* ya kind'a have to plot this to see how it works */
338
339     /* x = t->sun_angle^8 */
340     x_2 = l->sun_angle * l->sun_angle;
341     x_4 = x_2 * x_2;
342     x_8 = x_4 * x_4;
343     x_10 = x_8 * x_2;
344
345     light = pow(1.1, -x_10 / 30.0);
346     ambient = 0.2 * light;
347     diffuse = 0.9 * light;
348
349     sky_brightness = 0.85 * pow(1.2, -x_8 / 20.0) + 0.15;
350
351     /* sky_brightness = 0.15; */ /* to force a dark sky (for testing) */
352
353     if ( ambient < 0.02 ) { ambient = 0.02; }
354     if ( diffuse < 0.0 ) { diffuse = 0.0; }
355
356     if ( sky_brightness < 0.1 ) { sky_brightness = 0.1; }
357
358     l->scene_ambient[0] = white[0] * ambient;
359     l->scene_ambient[1] = white[1] * ambient;
360     l->scene_ambient[2] = white[2] * ambient;
361
362     l->scene_diffuse[0] = white[0] * diffuse;
363     l->scene_diffuse[1] = white[1] * diffuse;
364     l->scene_diffuse[2] = white[2] * diffuse;
365
366     /* set fog color */
367     l->fog_color[0] = base_fog_color[0] * (ambient + diffuse);
368     l->fog_color[1] = base_fog_color[1] * (ambient + diffuse);
369     l->fog_color[2] = base_fog_color[2] * (ambient + diffuse);
370     l->fog_color[3] = base_fog_color[3];
371
372     /* set sky color */
373     l->sky_color[0] = base_sky_color[0] * sky_brightness;
374     l->sky_color[1] = base_sky_color[1] * sky_brightness;
375     l->sky_color[2] = base_sky_color[2] * sky_brightness;
376     l->sky_color[3] = base_sky_color[3];
377 }
378
379
380 /* $Log$
381 /* Revision 1.26  1998/02/23 19:08:00  curt
382 /* Incorporated Durk's Astro/ tweaks.  Includes unifying the sun position
383 /* calculation code between sun display, and other FG sections that use this
384 /* for things like lighting.
385 /*
386  * Revision 1.25  1998/02/09 15:07:53  curt
387  * Minor tweaks.
388  *
389  * Revision 1.24  1998/01/27 00:48:07  curt
390  * Incorporated Paul Bleisch's <bleisch@chromatic.com> new debug message
391  * system and commandline/config file processing code.
392  *
393  * Revision 1.23  1998/01/19 19:27:21  curt
394  * Merged in make system changes from Bob Kuehne <rpk@sgi.com>
395  * This should simplify things tremendously.
396  *
397  * Revision 1.22  1998/01/19 18:40:40  curt
398  * Tons of little changes to clean up the code and to remove fatal errors
399  * when building with the c++ compiler.
400  *
401  * Revision 1.21  1997/12/30 23:10:19  curt
402  * Calculate lighting parameters here.
403  *
404  * Revision 1.20  1997/12/30 22:22:43  curt
405  * Further integration of event manager.
406  *
407  * Revision 1.19  1997/12/30 20:47:59  curt
408  * Integrated new event manager with subsystem initializations.
409  *
410  * Revision 1.18  1997/12/23 04:58:40  curt
411  * Tweaked the sky coloring a bit to build in structures to allow finer rgb
412  * control.
413  *
414  * Revision 1.17  1997/12/15 23:55:08  curt
415  * Add xgl wrappers for debugging.
416  * Generate terrain normals on the fly.
417  *
418  * Revision 1.16  1997/12/11 04:43:57  curt
419  * Fixed sun vector and lighting problems.  I thing the moon is now lit
420  * correctly.
421  *
422  * Revision 1.15  1997/12/10 22:37:55  curt
423  * Prepended "fg" on the name of all global structures that didn't have it yet.
424  * i.e. "struct WEATHER {}" became "struct fgWEATHER {}"
425  *
426  * Revision 1.14  1997/12/09 04:25:39  curt
427  * Working on adding a global lighting params structure.
428  *
429  * Revision 1.13  1997/11/25 19:25:42  curt
430  * Changes to integrate Durk's moon/sun code updates + clean up.
431  *
432  * Revision 1.12  1997/11/15 18:15:39  curt
433  * Reverse direction of sun vector, so object normals can be more normal.
434  *
435  * Revision 1.11  1997/10/28 21:07:21  curt
436  * Changed GLUT/ -> Main/
437  *
438  * Revision 1.10  1997/09/13 02:00:09  curt
439  * Mostly working on stars and generating sidereal time for accurate star
440  * placement.
441  *
442  * Revision 1.9  1997/09/05 14:17:31  curt
443  * More tweaking with stars.
444  *
445  * Revision 1.8  1997/09/05 01:36:04  curt
446  * Working on getting stars right.
447  *
448  * Revision 1.7  1997/09/04 02:17:40  curt
449  * Shufflin' stuff.
450  *
451  * Revision 1.6  1997/08/27 03:30:37  curt
452  * Changed naming scheme of basic shared structures.
453  *
454  * Revision 1.5  1997/08/22 21:34:41  curt
455  * Doing a bit of reorganizing and house cleaning.
456  *
457  * Revision 1.4  1997/08/19 23:55:09  curt
458  * Worked on better simulating real lighting.
459  *
460  * Revision 1.3  1997/08/13 20:23:49  curt
461  * The interface to sunpos now updates a global structure rather than returning
462  * current sun position.
463  *
464  * Revision 1.2  1997/08/06 00:24:32  curt
465  * Working on correct real time sun lighting.
466  *
467  * Revision 1.1  1997/08/01 15:27:56  curt
468  * Initial revision.
469  *
470  */