]> git.mxchange.org Git - flightgear.git/blob - src/Time/fg_time.cxx
Changes to begin incorporating plib support for managing and rendering the
[flightgear.git] / src / Time / fg_time.cxx
1 // fg_time.cxx -- data structures and routines for managing time related stuff.
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <Include/compiler.h>
29
30 #ifdef FG_HAVE_STD_INCLUDES
31 #  include <cmath>
32 #  include <cstdio>
33 #  include <cstdlib>
34 #  include <ctime>
35 #else
36 #  include <math.h>
37 #  include <stdio.h>
38 #  include <stdlib.h>
39 #  include <time.h>
40 #endif
41
42 #ifdef HAVE_SYS_TIMEB_H
43 #  include <sys/timeb.h> // for ftime() and struct timeb
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #  include <unistd.h>    // for gettimeofday()
47 #endif
48 #ifdef HAVE_SYS_TIME_H
49 #  include <sys/time.h>  // for get/setitimer, gettimeofday, struct timeval
50 #endif
51
52 #include <Debug/logstream.hxx>
53 #include <Astro/sky.hxx>
54 #include <Astro/solarsystem.hxx>
55 #include <FDM/flight.hxx>
56 #include <Include/fg_constants.h>
57 #include <Main/options.hxx>
58 #include <Time/light.hxx>
59
60 #include "fg_time.hxx"
61
62
63 #define DEGHR(x)        ((x)/15.)
64 #define RADHR(x)        DEGHR(x*RAD_TO_DEG)
65
66
67 // #define MK_TIME_IS_GMT 0         // default value
68 // #define TIME_ZONE_OFFSET_WORK 0  // default value
69
70
71 FGTime::FGTime()
72 {
73     if (cur_time_params) {
74         FG_LOG( FG_GENERAL, FG_ALERT, 
75                 "Error: only one instance of FGTime allowed" );
76         exit(-1);
77     }
78
79     cur_time_params = this;
80 }
81
82
83 FGTime::~FGTime()
84 {
85 }
86
87
88 // Initialize the time dependent variables (maybe I'll put this in the
89 // constructor later)
90 void FGTime::init() 
91 {
92     FG_LOG( FG_EVENT, FG_INFO, "Initializing Time" );
93     gst_diff = -9999.0;
94     FG_LOG( FG_EVENT, FG_DEBUG, 
95             "time offset = " << current_options.get_time_offset() );
96     time_t timeOffset = current_options.get_time_offset();
97     time_t gstStart = current_options.get_start_gst();
98     time_t lstStart = current_options.get_start_lst();
99
100     // would it be better to put these sanity checks in the options
101     // parsing code? (CLO)
102     if (timeOffset && gstStart)
103         {
104             FG_LOG( FG_EVENT, FG_ALERT, "Error: you specified both a time offset and a gst. Confused now!" );
105             current_options.usage();
106             exit(1);
107         }
108     if (timeOffset && lstStart)
109         {
110             FG_LOG( FG_EVENT, FG_ALERT, "Error: you specified both a time offset and a lst. Confused now!" );
111             current_options.usage();
112             exit(1);
113         }
114     if (gstStart && lstStart)
115         {
116             FG_LOG( FG_EVENT, FG_ALERT, "Error: you specified both a time offset and a lst. Confused now!" );
117             current_options.usage();
118             exit(1);
119         }
120     cur_time = time(NULL); 
121     if (gstStart)
122         warp = gstStart - cur_time;
123     else if (lstStart) // I need to use the time zone info for this one, but I'll do that later.
124         // Until then, Gst and LST are the same 
125         {
126             warp = lstStart - cur_time;
127         }
128     else if (timeOffset)
129         {
130             warp = timeOffset;
131         }
132     else
133         {
134             warp = 0;
135         }
136     warp_delta = 0;
137     pause = current_options.get_pause();
138 }
139
140
141 // given a date in months, mn, days, dy, years, yr, return the
142 // modified Julian date (number of days elapsed since 1900 jan 0.5),
143 // mjd.  Adapted from Xephem.
144
145 void FGTime::cal_mjd (int mn, double dy, int yr) 
146 {
147     //static double last_mjd, last_dy;
148     //double mjd;
149     //static int last_mn, last_yr;
150     int b, d, m, y;
151     long c;
152   
153     if (mn == last_mn && yr == last_yr && dy == last_dy) {
154         mjd = last_mjd;
155         //return(mjd);
156     }
157   
158     m = mn;
159     y = (yr < 0) ? yr + 1 : yr;
160     if (mn < 3) {
161         m += 12;
162         y -= 1;
163     }
164   
165     if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
166         b = 0;
167     } else {
168         int a;
169         a = y/100;
170         b = 2 - a + a/4;
171     }
172   
173     if (y < 0) {
174         c = (long)((365.25*y) - 0.75) - 694025L;
175     } else {
176         c = (long)(365.25*y) - 694025L;
177     }
178   
179     d = (int)(30.6001*(m+1));
180   
181     mjd = b + c + d + dy - 0.5;
182   
183     last_mn = mn;
184     last_dy = dy;
185     last_yr = yr;
186     last_mjd = mjd;
187   
188     //return(mjd);
189 }
190
191
192 // given an mjd, calculate greenwich mean sidereal time, gst
193 void FGTime::utc_gst () 
194 {
195     double day = floor(mjd-0.5)+0.5;
196     double hr = (mjd-day)*24.0;
197     double T, x;
198
199     T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
200     x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
201     x /= 3600.0;
202     gst = (1.0/SIDRATE)*hr + x;
203
204     FG_LOG( FG_EVENT, FG_DEBUG, "  gst => " << gst );
205 }
206
207
208 // given Julian Date and Longitude (decimal degrees West) compute
209 // Local Sidereal Time, in decimal hours.
210 //
211 // Provided courtesy of ecdowney@noao.edu (Elwood Downey) 
212
213 double FGTime::sidereal_precise (double lng) 
214 {
215     double lstTmp;
216
217     /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ", 
218        mjd + MJD0, lng); */
219
220     // convert to required internal units
221     lng *= DEG_TO_RAD;
222
223     // compute LST and print
224     utc_gst();
225     lstTmp = gst - RADHR (lng);
226     lstTmp -= 24.0*floor(lstTmp/24.0);
227     // printf ("%7.4f\n", lstTmp);
228
229     // that's all
230     return (lstTmp);
231 }
232
233
234 // return a courser but cheaper estimate of sidereal time
235 double FGTime::sidereal_course(double lng) 
236 {
237     //struct tm *gmt;
238     //double lstTmp;
239     time_t start_gmt, now;
240     double diff, part, days, hours, lstTmp;
241     char tbuf[64];
242   
243     //gmt = t->gmt;
244     //now = t->cur_time;
245     now = cur_time;
246     start_gmt = get_gmt(gmt->tm_year, 2, 21, 12, 0, 0);
247   
248     FG_LOG( FG_EVENT, FG_DEBUG, "  COURSE: GMT = " << format_time(gmt, tbuf) );
249     FG_LOG( FG_EVENT, FG_DEBUG, "  March 21 noon (GMT) = " << start_gmt );
250   
251     diff = (now - start_gmt) / (3600.0 * 24.0);
252   
253     FG_LOG( FG_EVENT, FG_DEBUG, 
254             "  Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
255   
256     part = fmod(diff, 1.0);
257     days = diff - part;
258     hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
259   
260     lstTmp = (days - lng)/15.0 + hours - 12;
261   
262     while ( lstTmp < 0.0 ) {
263         lstTmp += 24.0;
264     }
265   
266     FG_LOG( FG_EVENT, FG_DEBUG,
267             "  days = " << days << "  hours = " << hours << "  lon = " 
268             << lng << "  lst = " << lstTmp );
269   
270     return(lstTmp);
271 }
272
273
274 // Update time variables such as gmt, julian date, and sidereal time
275 void FGTime::update(FGInterface *f) 
276 {
277     double gst_precise, gst_course;
278
279     FG_LOG( FG_EVENT, FG_DEBUG, "Updating time" );
280
281     // get current Unix calendar time (in seconds)
282     warp += warp_delta;
283     cur_time = time(NULL) + warp;
284     FG_LOG( FG_EVENT, FG_DEBUG, 
285             "  Current Unix calendar time = " << cur_time 
286             << "  warp = " << warp << "  delta = " << warp_delta );
287
288     if ( warp_delta ) {
289         // time is changing so force an update
290         local_update_sky_and_lighting_params();
291     }
292
293     // get GMT break down for current time
294     gmt = gmtime(&cur_time);
295     FG_LOG( FG_EVENT, FG_DEBUG, 
296             "  Current GMT = " << gmt->tm_mon+1 << "/" 
297             << gmt->tm_mday << "/" << gmt->tm_year << " "
298             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
299             << gmt->tm_sec );
300
301     // calculate modified Julian date
302     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
303     //     (int)(t->gmt->tm_year + 1900));
304     cal_mjd ((int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
305              (int)(gmt->tm_year + 1900));
306
307     // add in partial day
308     mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
309         (gmt->tm_sec / (24.0 * 60.0 * 60.0));
310
311     // convert "back" to Julian date + partial day (as a fraction of one)
312     jd = mjd + MJD0;
313     FG_LOG( FG_EVENT, FG_DEBUG, "  Current Julian Date = " << jd );
314
315     // printf("  Current Longitude = %.3f\n", FG_Longitude * RAD_TO_DEG);
316
317     // Calculate local side real time
318     if ( gst_diff < -100.0 ) {
319         // first time through do the expensive calculation & cheap
320         // calculation to get the difference.
321         FG_LOG( FG_EVENT, FG_INFO, "  First time, doing precise gst" );
322         gst_precise = gst = sidereal_precise(0.00);
323         gst_course = sidereal_course(0.00);
324       
325         gst_diff = gst_precise - gst_course;
326
327         lst = sidereal_course(-(f->get_Longitude() * RAD_TO_DEG)) + gst_diff;
328     } else {
329         // course + difference should drift off very slowly
330         gst = sidereal_course( 0.00                              ) + gst_diff;
331         lst = sidereal_course( -(f->get_Longitude() * RAD_TO_DEG)) + gst_diff;
332     }
333     FG_LOG( FG_EVENT, FG_DEBUG,
334             "  Current lon=0.00 Sidereal Time = " << gst );
335     FG_LOG( FG_EVENT, FG_DEBUG,
336             "  Current LOCAL Sidereal Time = " << lst << " (" 
337             << sidereal_precise(-(f->get_Longitude() * RAD_TO_DEG)) 
338             << ") (diff = " << gst_diff << ")" );
339 }
340
341
342 /******************************************************************
343  * The following are some functions that were included as FGTime
344  * members, although they currently don't make used of any of the
345  * class's variables. Maybe this'll change in the future
346  *****************************************************************/
347
348 // Return time_t for Sat Mar 21 12:00:00 GMT
349 //
350 // I believe the mktime() has a SYSV vs. BSD behavior difference.
351 //
352 // The BSD style mktime() is nice because it returns its result
353 // assuming you have specified the input time in GMT
354 //
355 // The SYSV style mktime() is a pain because it returns its result
356 // assuming you have specified the input time in your local timezone.
357 // Therefore you have to go to extra trouble to convert back to GMT.
358 //
359 // If you are having problems with incorrectly positioned astronomical
360 // bodies, this is a really good place to start looking.
361
362 time_t FGTime::get_gmt(int year, int month, int day, int hour, int min, int sec)
363 {
364     struct tm mt;
365
366     // For now we assume that if daylight is not defined in
367     // /usr/include/time.h that we have a machine with a BSD behaving
368     // mktime()
369 #   if !defined(HAVE_DAYLIGHT)
370 #       define MK_TIME_IS_GMT 1
371 #   endif
372
373     // timezone seems to work as a proper offset for Linux & Solaris
374 #   if defined( __linux__ ) || defined( __sun__ ) 
375 #       define TIMEZONE_OFFSET_WORKS 1
376 #   endif
377
378     mt.tm_mon = month;
379     mt.tm_mday = day;
380     mt.tm_year = year;
381     mt.tm_hour = hour;
382     mt.tm_min = min;
383     mt.tm_sec = sec;
384     mt.tm_isdst = -1; // let the system determine the proper time zone
385
386 #   if defined( MK_TIME_IS_GMT )
387     return ( mktime(&mt) );
388 #   else // ! defined ( MK_TIME_IS_GMT )
389
390     long int start = mktime(&mt);
391
392     FG_LOG( FG_EVENT, FG_DEBUG, "start1 = " << start );
393     // the ctime() call can screw up time progression on some versions
394     // of Linux
395     // fgPrintf( FG_EVENT, FG_DEBUG, "start2 = %s", ctime(&start));
396     FG_LOG( FG_EVENT, FG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
397
398     timezone = fix_up_timezone( timezone );
399
400 #   if defined( TIMEZONE_OFFSET_WORKS )
401     FG_LOG( FG_EVENT, FG_DEBUG, 
402             "start = " << start << ", timezone = " << timezone );
403     return( start - timezone );
404 #   else // ! defined( TIMEZONE_OFFSET_WORKS )
405
406     daylight = mt.tm_isdst;
407     if ( daylight > 0 ) {
408         daylight = 1;
409     } else if ( daylight < 0 ) {
410         FG_LOG( FG_EVENT, FG_WARN, 
411                 "OOOPS, problem in fg_time.cxx, no daylight savings info." );
412     }
413
414     long int offset = -(timezone / 3600 - daylight);
415
416     FG_LOG( FG_EVENT, FG_DEBUG, "  Raw time zone offset = " << timezone );
417     FG_LOG( FG_EVENT, FG_DEBUG, "  Daylight Savings = " << daylight );
418     FG_LOG( FG_EVENT, FG_DEBUG, "  Local hours from GMT = " << offset );
419     
420     long int start_gmt = start - timezone + (daylight * 3600);
421     
422     FG_LOG( FG_EVENT, FG_DEBUG, "  March 21 noon (CST) = " << start );
423
424     return ( start_gmt );
425 #   endif // ! defined( TIMEZONE_OFFSET_WORKS )
426 #   endif // ! defined ( MK_TIME_IS_GMT )
427 }
428
429 // Fix up timezone if using ftime()
430 long int FGTime::fix_up_timezone( long int timezone_orig ) 
431 {
432 #if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
433     // ftime() needs a little extra help finding the current timezone
434     struct timeb current;
435     ftime(&current);
436     return( current.timezone * 60 );
437 #else
438     return( timezone_orig );
439 #endif
440 }
441
442
443 char* FGTime::format_time( const struct tm* p, char* buf )
444 {
445     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
446              p->tm_mon, p->tm_mday, p->tm_year,
447              p->tm_hour, p->tm_min, p->tm_sec);
448     return buf;
449 }
450
451
452 // Force an update of the sky and lighting parameters
453 void FGTime::local_update_sky_and_lighting_params( void ) {
454     // fgSunInit();
455     SolarSystem::theSolarSystem->rebuild();
456     cur_light_params.Update();
457     fgSkyColorsInit();
458 }
459
460
461 FGTime* FGTime::cur_time_params = 0;