]> git.mxchange.org Git - flightgear.git/blob - Time/sunpos.cxx
Log message clean ups.
[flightgear.git] / 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 // (Log is kept at end of this file)
36
37
38 #ifdef HAVE_CONFIG_H
39 #  include <config.h>
40 #endif
41
42 #include <math.h>
43 #include <stdio.h>
44 #include <time.h>
45
46 //#include <Astro/orbits.hxx>
47 #include <Astro/solarsystem.hxx>
48 #include <Debug/logstream.hxx>
49 #include <Include/fg_constants.h>
50 #include <Main/views.hxx>
51 #include <Math/fg_geodesy.hxx>
52 #include <Math/mat3.h>
53 #include <Math/point3d.hxx>
54 #include <Math/polar3d.hxx>
55 #include <Math/vector.hxx>
56 #include <Scenery/scenery.hxx>
57
58 #include "fg_time.hxx"
59 #include "sunpos.hxx"
60
61 extern SolarSystem *solarSystem;
62
63 #undef E
64
65
66 /*
67  * the epoch upon which these astronomical calculations are based is
68  * 1990 january 0.0, 631065600 seconds since the beginning of the
69  * "unix epoch" (00:00:00 GMT, Jan. 1, 1970)
70  *
71  * given a number of seconds since the start of the unix epoch,
72  * DaysSinceEpoch() computes the number of days since the start of the
73  * astronomical epoch (1990 january 0.0)
74  */
75
76 #define EpochStart           (631065600)
77 #define DaysSinceEpoch(secs) (((secs)-EpochStart)*(1.0/(24*3600)))
78
79 /*
80  * assuming the apparent orbit of the sun about the earth is circular,
81  * the rate at which the orbit progresses is given by RadsPerDay --
82  * FG_2PI radians per orbit divided by 365.242191 days per year:
83  */
84
85 #define RadsPerDay (FG_2PI/365.242191)
86
87 /*
88  * details of sun's apparent orbit at epoch 1990.0 (after
89  * duffett-smith, table 6, section 46)
90  *
91  * Epsilon_g    (ecliptic longitude at epoch 1990.0) 279.403303 degrees
92  * OmegaBar_g   (ecliptic longitude of perigee)      282.768422 degrees
93  * Eccentricity (eccentricity of orbit)                0.016713
94  */
95
96 #define Epsilon_g    (279.403303*(FG_2PI/360))
97 #define OmegaBar_g   (282.768422*(FG_2PI/360))
98 #define Eccentricity (0.016713)
99
100 /*
101  * MeanObliquity gives the mean obliquity of the earth's axis at epoch
102  * 1990.0 (computed as 23.440592 degrees according to the method given
103  * in duffett-smith, section 27)
104  */
105 #define MeanObliquity (23.440592*(FG_2PI/360))
106
107 /* static double solve_keplers_equation(double); */
108 /* static double sun_ecliptic_longitude(time_t); */
109 static void   ecliptic_to_equatorial(double, double, double *, double *);
110 static double julian_date(int, int, int);
111 static double GST(time_t);
112
113 /*
114  * solve Kepler's equation via Newton's method
115  * (after duffett-smith, section 47)
116  */
117 /*
118 static double solve_keplers_equation(double M) {
119     double E;
120     double delta;
121
122     E = M;
123     while (1) {
124         delta = E - Eccentricity*sin(E) - M;
125         if (fabs(delta) <= 1e-10) break;
126         E -= delta / (1 - Eccentricity*cos(E));
127     }
128
129     return E;
130 }
131 */
132
133
134 /* compute ecliptic longitude of sun (in radians) (after
135  * duffett-smith, section 47) */
136 /*
137 static double sun_ecliptic_longitude(time_t ssue) {
138     // time_t ssue;              //  seconds since unix epoch
139     double D, N;
140     double M_sun, E;
141     double v;
142
143     D = DaysSinceEpoch(ssue);
144
145     N = RadsPerDay * D;
146     N = fmod(N, FG_2PI);
147     if (N < 0) N += FG_2PI;
148
149     M_sun = N + Epsilon_g - OmegaBar_g;
150     if (M_sun < 0) M_sun += FG_2PI;
151
152     E = solve_keplers_equation(M_sun);
153     v = 2 * atan(sqrt((1+Eccentricity)/(1-Eccentricity)) * tan(E/2));
154
155     return (v + OmegaBar_g);
156 }
157 */
158
159
160 /* convert from ecliptic to equatorial coordinates (after
161  * duffett-smith, section 27) */
162
163 static void ecliptic_to_equatorial(double lambda, double beta, 
164                                    double *alpha, double *delta) {
165     /* double  lambda;            ecliptic longitude       */
166     /* double  beta;              ecliptic latitude        */
167     /* double *alpha;             (return) right ascension */
168     /* double *delta;             (return) declination     */
169
170     double sin_e, cos_e;
171     double sin_l, cos_l;
172
173     sin_e = sin(MeanObliquity);
174     cos_e = cos(MeanObliquity);
175     sin_l = sin(lambda);
176     cos_l = cos(lambda);
177
178     *alpha = atan2(sin_l*cos_e - tan(beta)*sin_e, cos_l);
179     *delta = asin(sin(beta)*cos_e + cos(beta)*sin_e*sin_l);
180 }
181
182
183 /* computing julian dates (assuming gregorian calendar, thus this is
184  * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
185  * section 4) */
186
187 static double julian_date(int y, int m, int d) {
188     /* int y;                    year (e.g. 19xx)          */
189     /* int m;                    month (jan=1, feb=2, ...) */
190     /* int d;                    day of month              */
191
192     int    A, B, C, D;
193     double JD;
194
195     /* lazy test to ensure gregorian calendar */
196     if (y < 1583) {
197         FG_LOG( FG_EVENT, FG_ALERT, 
198                 "WHOOPS! Julian dates only valid for 1582 oct 15 or later" );
199     }
200
201     if ((m == 1) || (m == 2)) {
202         y -= 1;
203         m += 12;
204     }
205
206     A = y / 100;
207     B = 2 - A + (A / 4);
208     C = (int)(365.25 * y);
209     D = (int)(30.6001 * (m + 1));
210
211     JD = B + C + D + d + 1720994.5;
212
213     return JD;
214 }
215
216
217 /* compute greenwich mean sidereal time (GST) corresponding to a given
218  * number of seconds since the unix epoch (after duffett-smith,
219  * section 12) */
220 static double GST(time_t ssue) {
221     /* time_t ssue;           seconds since unix epoch */
222
223     double     JD;
224     double     T, T0;
225     double     UT;
226     struct tm *tm;
227
228     tm = gmtime(&ssue);
229
230     JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
231     T  = (JD - 2451545) / 36525;
232
233     T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
234
235     T0 = fmod(T0, 24.0);
236     if (T0 < 0) T0 += 24;
237
238     UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
239
240     T0 += UT * 1.002737909;
241     T0 = fmod(T0, 24.0);
242     if (T0 < 0) T0 += 24;
243
244     return T0;
245 }
246
247
248 /* given a particular time (expressed in seconds since the unix
249  * epoch), compute position on the earth (lat, lon) such that sun is
250  * directly overhead.  (lat, lon are reported in radians */
251
252 void fgSunPosition(time_t ssue, double *lon, double *lat) {
253     /* time_t  ssue;           seconds since unix epoch */
254     /* double *lat;            (return) latitude        */
255     /* double *lon;            (return) longitude       */
256
257     /* double lambda; */
258     double alpha, delta;
259     double tmp;
260
261     /* lambda = sun_ecliptic_longitude(ssue); */
262     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
263     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
264     
265     /* ********************************************************************** 
266      * NOTE: in the next function, each time the sun's position is updated, the
267      * the sun's longitude is returned from solarSystem->sun. Note that the 
268      * sun's position is updated at a much higher frequency than the rate at 
269      * which the solar system's rebuilds occur. This is not a problem, however,
270      * because the fgSunPosition we're talking about here concerns the changing
271      * position of the sun due to the daily rotation of the earth.
272      * The ecliptic longitude, however, represents the position of the sun with
273      * respect to the stars, and completes just one cycle over the course of a 
274      * year. Its therefore pretty safe to update the sun's longitude only once
275      * every ten minutes. (Comment added by Durk Talsma).
276      ************************************************************************/
277
278     ecliptic_to_equatorial( SolarSystem::theSolarSystem->getSun()->getLon(),
279                             0.0, &alpha, &delta );
280     tmp = alpha - (FG_2PI/24)*GST(ssue);
281     if (tmp < -FG_PI) {
282         do tmp += FG_2PI;
283         while (tmp < -FG_PI);
284     } else if (tmp > FG_PI) {
285         do tmp -= FG_2PI;
286         while (tmp < -FG_PI);
287     }
288
289     *lon = tmp;
290     *lat = delta;
291 }
292
293
294 /* given a particular time expressed in side real time at prime
295  * meridian (GST), compute position on the earth (lat, lon) such that
296  * sun is directly overhead.  (lat, lon are reported in radians */
297
298 static void fgSunPositionGST(double gst, double *lon, double *lat) {
299     /* time_t  ssue;           seconds since unix epoch */
300     /* double *lat;            (return) latitude        */
301     /* double *lon;            (return) longitude       */
302
303     /* double lambda; */
304     double alpha, delta;
305     double tmp;
306
307     /* lambda = sun_ecliptic_longitude(ssue); */
308     /* ecliptic_to_equatorial(lambda, 0.0, &alpha, &delta); */
309     //ecliptic_to_equatorial (solarPosition.lonSun, 0.0, &alpha, &delta);
310     ecliptic_to_equatorial( SolarSystem::theSolarSystem->getSun()->getLon(),
311                             0.0, &alpha,  &delta );
312
313 //    tmp = alpha - (FG_2PI/24)*GST(ssue);
314     tmp = alpha - (FG_2PI/24)*gst;      
315     if (tmp < -FG_PI) {
316         do tmp += FG_2PI;
317         while (tmp < -FG_PI);
318     } else if (tmp > FG_PI) {
319         do tmp -= FG_2PI;
320         while (tmp < -FG_PI);
321     }
322
323     *lon = tmp;
324     *lat = delta;
325 }
326
327
328 // update the cur_time_params structure with the current sun position
329 void fgUpdateSunPos( void ) {
330     fgLIGHT *l;
331     fgTIME *t;
332     fgVIEW *v;
333     MAT3vec nup, nsun, v0;
334     Point3D p, rel_sunpos;
335     double dot, east_dot;
336     double sun_gd_lat, sl_radius;
337     double ntmp;
338
339     l = &cur_light_params;
340     t = &cur_time_params;
341     v = &current_view;
342
343     FG_LOG( FG_EVENT, FG_INFO, "  Updating Sun position" );
344
345     // (not sure why there was two)
346     // fgSunPosition(t->cur_time, &l->sun_lon, &sun_gd_lat);
347     fgSunPositionGST(t->gst, &l->sun_lon, &sun_gd_lat);
348
349     fgGeodToGeoc(sun_gd_lat, 0.0, &sl_radius, &l->sun_gc_lat);
350
351     p = Point3D( l->sun_lon, l->sun_gc_lat, sl_radius );
352     l->fg_sunpos = fgPolarToCart3d(p);
353
354     FG_LOG( FG_EVENT, FG_INFO, "    t->cur_time = " << t->cur_time );
355     FG_LOG( FG_EVENT, FG_INFO, 
356             "    Sun Geodetic lat = " << sun_gd_lat
357             << " Geocentric lat = " << l->sun_gc_lat );
358
359     // I think this will work better for generating the sun light vector
360     l->sun_vec[0] = l->fg_sunpos.x();
361     l->sun_vec[1] = l->fg_sunpos.y();
362     l->sun_vec[2] = l->fg_sunpos.z();
363     MAT3_NORMALIZE_VEC(l->sun_vec, ntmp);
364     MAT3_SCALE_VEC(l->sun_vec_inv, l->sun_vec, -1.0);
365
366     // make sure these are directional light sources only
367     l->sun_vec[3] = 0.0;
368     l->sun_vec_inv[3] = 0.0;
369
370     // printf("  l->sun_vec = %.2f %.2f %.2f\n", l->sun_vec[0], l->sun_vec[1],
371     //        l->sun_vec[2]);
372
373     // calculate the sun's relative angle to local up
374     MAT3_COPY_VEC(nup, v->local_up);
375     nsun[0] = l->fg_sunpos.x(); 
376     nsun[1] = l->fg_sunpos.y();
377     nsun[2] = l->fg_sunpos.z();
378     MAT3_NORMALIZE_VEC(nup, ntmp);
379     MAT3_NORMALIZE_VEC(nsun, ntmp);
380
381     l->sun_angle = acos(MAT3_DOT_PRODUCT(nup, nsun));
382     // printf("  SUN ANGLE relative to current location = %.3f rads.\n", 
383     //        l->sun_angle);
384     
385     // calculate vector to sun's position on the earth's surface
386     rel_sunpos = l->fg_sunpos - (v->view_pos + scenery.center);
387     v->to_sun[0] = rel_sunpos.x();
388     v->to_sun[1] = rel_sunpos.y();
389     v->to_sun[2] = rel_sunpos.z();
390     // printf( "Vector to sun = %.2f %.2f %.2f\n",
391     //         v->to_sun[0], v->to_sun[1], v->to_sun[2]);
392
393     // make a vector to the current view position
394     MAT3_SET_VEC(v0, v->view_pos.x(), v->view_pos.y(), v->view_pos.z());
395
396     // Given a vector from the view position to the point on the
397     // earth's surface the sun is directly over, map into onto the
398     // local plane representing "horizontal".
399     map_vec_onto_cur_surface_plane(v->local_up, v0, v->to_sun, 
400                                    v->surface_to_sun);
401     MAT3_NORMALIZE_VEC(v->surface_to_sun, ntmp);
402     // printf("Surface direction to sun is %.2f %.2f %.2f\n",
403     //        v->surface_to_sun[0], v->surface_to_sun[1], v->surface_to_sun[2]);
404     // printf("Should be close to zero = %.2f\n", 
405     //        MAT3_DOT_PRODUCT(v->local_up, v->surface_to_sun));
406
407     // calculate the angle between v->surface_to_sun and
408     // v->surface_east.  We do this so we can sort out the acos()
409     // ambiguity.  I wish I could think of a more efficient way ... :-(
410     east_dot = MAT3_DOT_PRODUCT(v->surface_to_sun, v->surface_east);
411     // printf("  East dot product = %.2f\n", east_dot);
412
413     // calculate the angle between v->surface_to_sun and
414     // v->surface_south.  this is how much we have to rotate the sky
415     // for it to align with the sun
416     dot = MAT3_DOT_PRODUCT(v->surface_to_sun, v->surface_south);
417     // printf("  Dot product = %.2f\n", dot);
418     if ( east_dot >= 0 ) {
419         l->sun_rotation = acos(dot);
420     } else {
421         l->sun_rotation = -acos(dot);
422     }
423     // printf("  Sky needs to rotate = %.3f rads = %.1f degrees.\n", 
424     //        angle, angle * RAD_TO_DEG); */
425 }
426
427
428 // $Log$
429 // Revision 1.17  1998/11/09 23:41:53  curt
430 // Log message clean ups.
431 //
432 // Revision 1.16  1998/11/07 19:07:14  curt
433 // Enable release builds using the --without-logging option to the configure
434 // script.  Also a couple log message cleanups, plus some C to C++ comment
435 // conversion.
436 //
437 // Revision 1.15  1998/10/18 01:17:24  curt
438 // Point3D tweaks.
439 //
440 // Revision 1.14  1998/10/17 01:34:32  curt
441 // C++ ifying ...
442 //
443 // Revision 1.13  1998/10/16 00:56:12  curt
444 // Converted to Point3D class.
445 //
446 // Revision 1.12  1998/09/15 04:27:50  curt
447 // Changes for new astro code.
448 //
449 // Revision 1.11  1998/08/12 21:13:22  curt
450 // Optimizations by Norman Vine.
451 //
452 // Revision 1.10  1998/07/22 21:45:39  curt
453 // fg_time.cxx: Removed call to ctime() in a printf() which should be harmless
454 //   but seems to be triggering a bug.
455 // light.cxx: Added code to adjust fog color based on sunrise/sunset effects
456 //   and view orientation.  This is an attempt to match the fog color to the
457 //   sky color in the center of the screen.  You see discrepancies at the
458 //   edges, but what else can be done?
459 // sunpos.cxx: Caculate local direction to sun here.  (what compass direction
460 //   do we need to face to point directly at sun)
461 //
462 // Revision 1.9  1998/07/08 14:48:39  curt
463 // polar3d.h renamed to polar3d.hxx
464 //
465 // Revision 1.8  1998/05/02 01:53:18  curt
466 // Fine tuning mktime() support because of varying behavior on different
467 // platforms.
468 //
469 // Revision 1.7  1998/04/30 12:36:05  curt
470 // C++-ifying a couple source files.
471 //
472 // Revision 1.6  1998/04/28 01:22:18  curt
473 // Type-ified fgTIME and fgVIEW.
474 //
475 // Revision 1.5  1998/04/26 05:10:05  curt
476 // "struct fgLIGHT" -> "fgLIGHT" because fgLIGHT is typedef'd.
477 //
478 // Revision 1.4  1998/04/25 22:06:34  curt
479 // Edited cvs log messages in source files ... bad bad bad!
480 //
481 // Revision 1.3  1998/04/25 20:24:03  curt
482 // Cleaned up initialization sequence to eliminate interdependencies
483 // between sun position, lighting, and view position.  This creates a
484 // valid single pass initialization path.
485 //
486 // Revision 1.2  1998/04/24 00:52:31  curt
487 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
488 // Fog color fixes.
489 // Separated out lighting calcs into their own file.
490 //
491 // Revision 1.1  1998/04/22 13:24:07  curt
492 // C++ - ifiing the code a bit.
493 // Starting to reorginize some of the lighting calcs to use a table lookup.
494 //
495 // Revision 1.27  1998/04/03 22:12:57  curt
496 // Converting to Gnu autoconf system.
497 // Centralized time handling differences.
498 //
499 // Revision 1.26  1998/02/23 19:08:00  curt
500 // Incorporated Durk's Astro/ tweaks.  Includes unifying the sun position
501 // calculation code between sun display, and other FG sections that use this
502 // for things like lighting.
503 //
504 // Revision 1.25  1998/02/09 15:07:53  curt
505 // Minor tweaks.
506 //
507 // Revision 1.24  1998/01/27 00:48:07  curt
508 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
509 // system and commandline/config file processing code.
510 //
511 // Revision 1.23  1998/01/19 19:27:21  curt
512 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
513 // This should simplify things tremendously.
514 //
515 // Revision 1.22  1998/01/19 18:40:40  curt
516 // Tons of little changes to clean up the code and to remove fatal errors
517 // when building with the c++ compiler.
518 //
519 // Revision 1.21  1997/12/30 23:10:19  curt
520 // Calculate lighting parameters here.
521 //
522 // Revision 1.20  1997/12/30 22:22:43  curt
523 // Further integration of event manager.
524 //
525 // Revision 1.19  1997/12/30 20:47:59  curt
526 // Integrated new event manager with subsystem initializations.
527 //
528 // Revision 1.18  1997/12/23 04:58:40  curt
529 // Tweaked the sky coloring a bit to build in structures to allow finer rgb
530 // control.
531 //
532 // Revision 1.17  1997/12/15 23:55:08  curt
533 // Add xgl wrappers for debugging.
534 // Generate terrain normals on the fly.
535 //
536 // Revision 1.16  1997/12/11 04:43:57  curt
537 // Fixed sun vector and lighting problems.  I thing the moon is now lit
538 // correctly.
539 //
540 // Revision 1.15  1997/12/10 22:37:55  curt
541 // Prepended "fg" on the name of all global structures that didn't have it yet.
542 // i.e. "struct WEATHER {}" became "struct fgWEATHER {}"
543 //
544 // Revision 1.14  1997/12/09 04:25:39  curt
545 // Working on adding a global lighting params structure.
546 //
547 // Revision 1.13  1997/11/25 19:25:42  curt
548 // Changes to integrate Durk's moon/sun code updates + clean up.
549 //
550 // Revision 1.12  1997/11/15 18:15:39  curt
551 // Reverse direction of sun vector, so object normals can be more normal.
552 //
553 // Revision 1.11  1997/10/28 21:07:21  curt
554 // Changed GLUT/ -> Main/
555 //
556 // Revision 1.10  1997/09/13 02:00:09  curt
557 // Mostly working on stars and generating sidereal time for accurate star
558 // placement.
559 //
560 // Revision 1.9  1997/09/05 14:17:31  curt
561 // More tweaking with stars.
562 //
563 // Revision 1.8  1997/09/05 01:36:04  curt
564 // Working on getting stars right.
565 //
566 // Revision 1.7  1997/09/04 02:17:40  curt
567 // Shufflin' stuff.
568 //
569 // Revision 1.6  1997/08/27 03:30:37  curt
570 // Changed naming scheme of basic shared structures.
571 //
572 // Revision 1.5  1997/08/22 21:34:41  curt
573 // Doing a bit of reorganizing and house cleaning.
574 //
575 // Revision 1.4  1997/08/19 23:55:09  curt
576 // Worked on better simulating real lighting.
577 //
578 // Revision 1.3  1997/08/13 20:23:49  curt
579 // The interface to sunpos now updates a global structure rather than returning
580 // current sun position.
581 //
582 // Revision 1.2  1997/08/06 00:24:32  curt
583 // Working on correct real time sun lighting.
584 //
585 // Revision 1.1  1997/08/01 15:27:56  curt
586 // Initial revision.
587 //