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