1 // sunpos.cxx (adapted from XEarth)
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.)
10 // Copyright (C) 1989, 1990, 1993, 1994, 1995 Kirk Lauritz Johnson
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>
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
22 // The author makes no representations about the suitability of this
23 // software for any purpose. It is provided "as is" without express or
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.
35 // (Log is kept at end of this file)
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>
58 #include "fg_time.hxx"
61 extern SolarSystem *solarSystem;
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)
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)
76 #define EpochStart (631065600)
77 #define DaysSinceEpoch(secs) (((secs)-EpochStart)*(1.0/(24*3600)))
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:
85 #define RadsPerDay (FG_2PI/365.242191)
88 * details of sun's apparent orbit at epoch 1990.0 (after
89 * duffett-smith, table 6, section 46)
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
96 #define Epsilon_g (279.403303*(FG_2PI/360))
97 #define OmegaBar_g (282.768422*(FG_2PI/360))
98 #define Eccentricity (0.016713)
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)
105 #define MeanObliquity (23.440592*(FG_2PI/360))
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);
114 * solve Kepler's equation via Newton's method
115 * (after duffett-smith, section 47)
118 static double solve_keplers_equation(double M) {
124 delta = E - Eccentricity*sin(E) - M;
125 if (fabs(delta) <= 1e-10) break;
126 E -= delta / (1 - Eccentricity*cos(E));
134 /* compute ecliptic longitude of sun (in radians) (after
135 * duffett-smith, section 47) */
137 static double sun_ecliptic_longitude(time_t ssue) {
138 // time_t ssue; // seconds since unix epoch
143 D = DaysSinceEpoch(ssue);
147 if (N < 0) N += FG_2PI;
149 M_sun = N + Epsilon_g - OmegaBar_g;
150 if (M_sun < 0) M_sun += FG_2PI;
152 E = solve_keplers_equation(M_sun);
153 v = 2 * atan(sqrt((1+Eccentricity)/(1-Eccentricity)) * tan(E/2));
155 return (v + OmegaBar_g);
160 /* convert from ecliptic to equatorial coordinates (after
161 * duffett-smith, section 27) */
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 */
173 sin_e = sin(MeanObliquity);
174 cos_e = cos(MeanObliquity);
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);
183 /* computing julian dates (assuming gregorian calendar, thus this is
184 * only valid for dates of 1582 oct 15 or later) (after duffett-smith,
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 */
195 /* lazy test to ensure gregorian calendar */
197 FG_LOG( FG_EVENT, FG_ALERT,
198 "WHOOPS! Julian dates only valid for 1582 oct 15 or later" );
201 if ((m == 1) || (m == 2)) {
208 C = (int)(365.25 * y);
209 D = (int)(30.6001 * (m + 1));
211 JD = B + C + D + d + 1720994.5;
217 /* compute greenwich mean sidereal time (GST) corresponding to a given
218 * number of seconds since the unix epoch (after duffett-smith,
220 static double GST(time_t ssue) {
221 /* time_t ssue; seconds since unix epoch */
230 JD = julian_date(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday);
231 T = (JD - 2451545) / 36525;
233 T0 = ((T + 2.5862e-5) * T + 2400.051336) * T + 6.697374558;
236 if (T0 < 0) T0 += 24;
238 UT = tm->tm_hour + (tm->tm_min + tm->tm_sec / 60.0) / 60.0;
240 T0 += UT * 1.002737909;
242 if (T0 < 0) T0 += 24;
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 */
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 */
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);
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 ************************************************************************/
278 ecliptic_to_equatorial( SolarSystem::theSolarSystem->getSun()->getLon(),
279 0.0, &alpha, &delta );
280 tmp = alpha - (FG_2PI/24)*GST(ssue);
283 while (tmp < -FG_PI);
284 } else if (tmp > FG_PI) {
286 while (tmp < -FG_PI);
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 */
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 */
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 );
313 // tmp = alpha - (FG_2PI/24)*GST(ssue);
314 tmp = alpha - (FG_2PI/24)*gst;
317 while (tmp < -FG_PI);
318 } else if (tmp > FG_PI) {
320 while (tmp < -FG_PI);
328 // update the cur_time_params structure with the current sun position
329 void fgUpdateSunPos( void ) {
333 MAT3vec nup, nsun, v0, surface_to_sun;
334 Point3D p, rel_sunpos;
335 double dot, east_dot;
336 double sun_gd_lat, sl_radius;
339 l = &cur_light_params;
340 t = &cur_time_params;
343 FG_LOG( FG_EVENT, FG_INFO, " Updating Sun position" );
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);
349 fgGeodToGeoc(sun_gd_lat, 0.0, &sl_radius, &l->sun_gc_lat);
351 p = Point3D( l->sun_lon, l->sun_gc_lat, sl_radius );
352 l->fg_sunpos = fgPolarToCart3d(p);
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 );
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);
366 // make sure these are directional light sources only
368 l->sun_vec_inv[3] = 0.0;
370 // printf(" l->sun_vec = %.2f %.2f %.2f\n", l->sun_vec[0], l->sun_vec[1],
373 // calculate the sun's relative angle to local up
374 MAT3_COPY_VEC(nup, v->get_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);
381 l->sun_angle = acos(MAT3_DOT_PRODUCT(nup, nsun));
382 // printf(" SUN ANGLE relative to current location = %.3f rads.\n",
385 // calculate vector to sun's position on the earth's surface
386 rel_sunpos = l->fg_sunpos - (v->get_view_pos() + scenery.center);
387 v->set_to_sun( rel_sunpos.x(), rel_sunpos.y(), rel_sunpos.z() );
388 // printf( "Vector to sun = %.2f %.2f %.2f\n",
389 // v->to_sun[0], v->to_sun[1], v->to_sun[2]);
391 // make a vector to the current view position
392 Point3D view_pos = v->get_view_pos();
393 MAT3_SET_VEC(v0, view_pos.x(), view_pos.y(), view_pos.z());
395 // Given a vector from the view position to the point on the
396 // earth's surface the sun is directly over, map into onto the
397 // local plane representing "horizontal".
398 map_vec_onto_cur_surface_plane( v->get_local_up(), v0, v->get_to_sun(),
400 MAT3_NORMALIZE_VEC(surface_to_sun, ntmp);
401 v->set_surface_to_sun( surface_to_sun[0], surface_to_sun[1],
403 // printf("Surface direction to sun is %.2f %.2f %.2f\n",
404 // v->surface_to_sun[0], v->surface_to_sun[1], v->surface_to_sun[2]);
405 // printf("Should be close to zero = %.2f\n",
406 // MAT3_DOT_PRODUCT(v->local_up, v->surface_to_sun));
408 // calculate the angle between v->surface_to_sun and
409 // v->surface_east. We do this so we can sort out the acos()
410 // ambiguity. I wish I could think of a more efficient way ... :-(
411 east_dot = MAT3_DOT_PRODUCT( surface_to_sun, v->get_surface_east() );
412 // printf(" East dot product = %.2f\n", east_dot);
414 // calculate the angle between v->surface_to_sun and
415 // v->surface_south. this is how much we have to rotate the sky
416 // for it to align with the sun
417 dot = MAT3_DOT_PRODUCT( surface_to_sun, v->get_surface_south() );
418 // printf(" Dot product = %.2f\n", dot);
419 if ( east_dot >= 0 ) {
420 l->sun_rotation = acos(dot);
422 l->sun_rotation = -acos(dot);
424 // printf(" Sky needs to rotate = %.3f rads = %.1f degrees.\n",
425 // angle, angle * RAD_TO_DEG); */
430 // Revision 1.18 1998/12/09 18:50:36 curt
431 // Converted "class fgVIEW" to "class FGView" and updated to make data
432 // members private and make required accessor functions.
434 // Revision 1.17 1998/11/09 23:41:53 curt
435 // Log message clean ups.
437 // Revision 1.16 1998/11/07 19:07:14 curt
438 // Enable release builds using the --without-logging option to the configure
439 // script. Also a couple log message cleanups, plus some C to C++ comment
442 // Revision 1.15 1998/10/18 01:17:24 curt
445 // Revision 1.14 1998/10/17 01:34:32 curt
448 // Revision 1.13 1998/10/16 00:56:12 curt
449 // Converted to Point3D class.
451 // Revision 1.12 1998/09/15 04:27:50 curt
452 // Changes for new astro code.
454 // Revision 1.11 1998/08/12 21:13:22 curt
455 // Optimizations by Norman Vine.
457 // Revision 1.10 1998/07/22 21:45:39 curt
458 // fg_time.cxx: Removed call to ctime() in a printf() which should be harmless
459 // but seems to be triggering a bug.
460 // light.cxx: Added code to adjust fog color based on sunrise/sunset effects
461 // and view orientation. This is an attempt to match the fog color to the
462 // sky color in the center of the screen. You see discrepancies at the
463 // edges, but what else can be done?
464 // sunpos.cxx: Caculate local direction to sun here. (what compass direction
465 // do we need to face to point directly at sun)
467 // Revision 1.9 1998/07/08 14:48:39 curt
468 // polar3d.h renamed to polar3d.hxx
470 // Revision 1.8 1998/05/02 01:53:18 curt
471 // Fine tuning mktime() support because of varying behavior on different
474 // Revision 1.7 1998/04/30 12:36:05 curt
475 // C++-ifying a couple source files.
477 // Revision 1.6 1998/04/28 01:22:18 curt
478 // Type-ified fgTIME and fgVIEW.
480 // Revision 1.5 1998/04/26 05:10:05 curt
481 // "struct fgLIGHT" -> "fgLIGHT" because fgLIGHT is typedef'd.
483 // Revision 1.4 1998/04/25 22:06:34 curt
484 // Edited cvs log messages in source files ... bad bad bad!
486 // Revision 1.3 1998/04/25 20:24:03 curt
487 // Cleaned up initialization sequence to eliminate interdependencies
488 // between sun position, lighting, and view position. This creates a
489 // valid single pass initialization path.
491 // Revision 1.2 1998/04/24 00:52:31 curt
492 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
494 // Separated out lighting calcs into their own file.
496 // Revision 1.1 1998/04/22 13:24:07 curt
497 // C++ - ifiing the code a bit.
498 // Starting to reorginize some of the lighting calcs to use a table lookup.
500 // Revision 1.27 1998/04/03 22:12:57 curt
501 // Converting to Gnu autoconf system.
502 // Centralized time handling differences.
504 // Revision 1.26 1998/02/23 19:08:00 curt
505 // Incorporated Durk's Astro/ tweaks. Includes unifying the sun position
506 // calculation code between sun display, and other FG sections that use this
507 // for things like lighting.
509 // Revision 1.25 1998/02/09 15:07:53 curt
512 // Revision 1.24 1998/01/27 00:48:07 curt
513 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
514 // system and commandline/config file processing code.
516 // Revision 1.23 1998/01/19 19:27:21 curt
517 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
518 // This should simplify things tremendously.
520 // Revision 1.22 1998/01/19 18:40:40 curt
521 // Tons of little changes to clean up the code and to remove fatal errors
522 // when building with the c++ compiler.
524 // Revision 1.21 1997/12/30 23:10:19 curt
525 // Calculate lighting parameters here.
527 // Revision 1.20 1997/12/30 22:22:43 curt
528 // Further integration of event manager.
530 // Revision 1.19 1997/12/30 20:47:59 curt
531 // Integrated new event manager with subsystem initializations.
533 // Revision 1.18 1997/12/23 04:58:40 curt
534 // Tweaked the sky coloring a bit to build in structures to allow finer rgb
537 // Revision 1.17 1997/12/15 23:55:08 curt
538 // Add xgl wrappers for debugging.
539 // Generate terrain normals on the fly.
541 // Revision 1.16 1997/12/11 04:43:57 curt
542 // Fixed sun vector and lighting problems. I thing the moon is now lit
545 // Revision 1.15 1997/12/10 22:37:55 curt
546 // Prepended "fg" on the name of all global structures that didn't have it yet.
547 // i.e. "struct WEATHER {}" became "struct fgWEATHER {}"
549 // Revision 1.14 1997/12/09 04:25:39 curt
550 // Working on adding a global lighting params structure.
552 // Revision 1.13 1997/11/25 19:25:42 curt
553 // Changes to integrate Durk's moon/sun code updates + clean up.
555 // Revision 1.12 1997/11/15 18:15:39 curt
556 // Reverse direction of sun vector, so object normals can be more normal.
558 // Revision 1.11 1997/10/28 21:07:21 curt
559 // Changed GLUT/ -> Main/
561 // Revision 1.10 1997/09/13 02:00:09 curt
562 // Mostly working on stars and generating sidereal time for accurate star
565 // Revision 1.9 1997/09/05 14:17:31 curt
566 // More tweaking with stars.
568 // Revision 1.8 1997/09/05 01:36:04 curt
569 // Working on getting stars right.
571 // Revision 1.7 1997/09/04 02:17:40 curt
574 // Revision 1.6 1997/08/27 03:30:37 curt
575 // Changed naming scheme of basic shared structures.
577 // Revision 1.5 1997/08/22 21:34:41 curt
578 // Doing a bit of reorganizing and house cleaning.
580 // Revision 1.4 1997/08/19 23:55:09 curt
581 // Worked on better simulating real lighting.
583 // Revision 1.3 1997/08/13 20:23:49 curt
584 // The interface to sunpos now updates a global structure rather than returning
585 // current sun position.
587 // Revision 1.2 1997/08/06 00:24:32 curt
588 // Working on correct real time sun lighting.
590 // Revision 1.1 1997/08/01 15:27:56 curt