1 // fg_time.cxx -- data structures and routines for managing time related stuff.
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
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.
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.
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.
28 #include <simgear/compiler.h>
30 #ifdef FG_HAVE_STD_INCLUDES
42 #ifdef HAVE_SYS_TIMEB_H
43 # include <sys/timeb.h> // for ftime() and struct timeb
46 # include <unistd.h> // for gettimeofday()
48 #ifdef HAVE_SYS_TIME_H
49 # include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
52 #include <simgear/constants.h>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/misc/fgpath.hxx>
56 #include <Astro/sky.hxx>
57 #include <Astro/solarsystem.hxx>
58 #include <FDM/flight.hxx>
59 #include <Main/options.hxx>
60 #include <Time/light.hxx>
62 #include "fg_time.hxx"
64 #include "lowleveltime.h"
67 #define DEGHR(x) ((x)/15.)
68 #define RADHR(x) DEGHR(x*RAD_TO_DEG)
71 // #define MK_TIME_IS_GMT 0 // default value
72 // #define TIME_ZONE_OFFSET_WORK 0 // default value
77 if (cur_time_params) {
78 FG_LOG( FG_GENERAL, FG_ALERT,
79 "Error: only one instance of FGTime allowed" );
83 cur_time_params = this;
85 FGPath buffer( current_options.get_fg_root() );
86 buffer.append( "Timezone" );
87 buffer.append( "zone.tab" );
88 FG_LOG( FG_EVENT, FG_INFO, "Reading timezone info from: " << buffer.str() );
89 tzContainer = new TimezoneContainer( buffer.c_str() );
101 void FGTime::updateLocal()
104 f = current_aircraft.fdm_state;
106 time_t aircraftLocalTime;
107 GeoCoord location(RAD_TO_DEG * f->get_Latitude(),
108 RAD_TO_DEG * f->get_Longitude());
109 GeoCoord* nearestTz = tzContainer->getNearest(location);
110 FGPath buffer( current_options.get_fg_root() );
111 buffer.append ("Timezone" );
112 buffer.append ( nearestTz->getDescription() );
115 zonename = strdup(buffer.c_str());
116 currGMT = get_gmt(gmtime(&cur_time));
117 aircraftLocalTime = get_gmt((fgLocaltime(&cur_time, buffer.c_str())));
118 localOffset = aircraftLocalTime - currGMT;
119 // cerr << "Using " << localOffset << " as local time offset Timezone is "
120 // << zonename << endl;
123 // Initialize the time dependent variables (maybe I'll put this in the
124 // constructor later)
125 void FGTime::init(const FGInterface& f)
127 FG_LOG( FG_EVENT, FG_INFO, "Initializing Time" );
129 FG_LOG( FG_EVENT, FG_DEBUG,
130 "time offset = " << current_options.get_time_offset() );
131 time_t timeOffset = current_options.get_time_offset();
132 int offsetType = current_options.get_time_offset_type();
135 time_t systemLocalTime;
136 time_t aircraftLocalTime;
138 // would it be better to put these sanity checks in the options
139 // parsing code? (CLO)
141 cur_time = time(NULL);
143 // printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
144 // printf ("Current local time = %24s", asctime(localtime(&cur_time)));
145 // time_t tmp = cur_time;
146 GeoCoord location(RAD_TO_DEG * f.get_Latitude(),
147 RAD_TO_DEG * f.get_Longitude());
149 GeoCoord* nearestTz = tzContainer->getNearest(location);
151 FGPath buffer( current_options.get_fg_root() );
152 buffer.append( "Timezone" );
153 buffer.append( nearestTz->getDescription() );
155 // printf("Using %s for timezone information\n", buffer);
156 zonename = strdup( buffer.c_str() );
157 //show( buffer.c_str(), cur_time, 1);
158 //printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
159 //printf ("Current local time = %24s", asctime(localtime(&cur_time)));
160 currGMT = get_gmt(gmtime(&cur_time));
161 systemLocalTime = get_gmt(localtime(&cur_time));
162 aircraftLocalTime = get_gmt(fgLocaltime(&cur_time, buffer.c_str()));
163 //printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
164 //printf ("Current local time = %24s", asctime(localtime(&cur_time)));
166 //printf("LT = %d\n", computerLocalTime);
167 // Okay, in principle, this trick allows to calculate the
168 // difference between GMT and localtime, in seconds.
169 // printf("Gmt = %d, SLT = %d, (difference = %d)\n", currGMT, systemLocalTime, (currGMT - systemLocalTime));
170 // printf("Gmt = %d, ALT = %d, (difference = %d)\n", currGMT, aircraftLocalTime, (currGMT - aircraftLocalTime));
172 // Okay, we now have six possible scenarios
175 case fgOPTIONS::FG_TIME_SYS_OFFSET:
178 case fgOPTIONS::FG_TIME_GMT_OFFSET:
179 warp = timeOffset - (currGMT - systemLocalTime);
181 case fgOPTIONS::FG_TIME_LAT_OFFSET:
182 // warp = timeOffset - (currGMT - systemLocalTime +
183 // (currGMT - aircraftLocalTime));
184 warp = timeOffset - (aircraftLocalTime - systemLocalTime);
186 case fgOPTIONS::FG_TIME_SYS_ABSOLUTE:
187 warp = timeOffset - cur_time;
188 //printf("warp = %d\n", warp);
190 case fgOPTIONS::FG_TIME_GMT_ABSOLUTE:
191 warp = timeOffset - (currGMT - systemLocalTime) - cur_time;
193 case fgOPTIONS::FG_TIME_LAT_ABSOLUTE:
194 warp = timeOffset - (aircraftLocalTime - systemLocalTime) -
198 printf("Unsupported type\n");
203 pause = current_options.get_pause();
207 // given a date in months, mn, days, dy, years, yr, return the
208 // modified Julian date (number of days elapsed since 1900 jan 0.5),
209 // mjd. Adapted from Xephem.
211 void FGTime::cal_mjd (int mn, double dy, int yr)
213 //static double last_mjd, last_dy;
215 //static int last_mn, last_yr;
219 if (mn == last_mn && yr == last_yr && dy == last_dy) {
225 y = (yr < 0) ? yr + 1 : yr;
231 if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
240 c = (long)((365.25*y) - 0.75) - 694025L;
242 c = (long)(365.25*y) - 694025L;
245 d = (int)(30.6001*(m+1));
247 mjd = b + c + d + dy - 0.5;
258 // given an mjd, calculate greenwich mean sidereal time, gst
259 void FGTime::utc_gst ()
261 double day = floor(mjd-0.5)+0.5;
262 double hr = (mjd-day)*24.0;
265 T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
266 x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
268 gst = (1.0/SIDRATE)*hr + x;
270 FG_LOG( FG_EVENT, FG_DEBUG, " gst => " << gst );
274 // given Julian Date and Longitude (decimal degrees West) compute
275 // Local Sidereal Time, in decimal hours.
277 // Provided courtesy of ecdowney@noao.edu (Elwood Downey)
279 double FGTime::sidereal_precise (double lng)
283 /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ",
286 // convert to required internal units
289 // compute LST and print
291 lstTmp = gst - RADHR (lng);
292 lstTmp -= 24.0*floor(lstTmp/24.0);
293 // printf ("%7.4f\n", lstTmp);
300 // return a courser but cheaper estimate of sidereal time
301 double FGTime::sidereal_course(double lng)
305 time_t start_gmt, now;
306 double diff, part, days, hours, lstTmp;
312 start_gmt = get_gmt(gmt->tm_year, 2, 21, 12, 0, 0);
314 FG_LOG( FG_EVENT, FG_DEBUG, " COURSE: GMT = " << format_time(gmt, tbuf) );
315 FG_LOG( FG_EVENT, FG_DEBUG, " March 21 noon (GMT) = " << start_gmt );
317 diff = (now - start_gmt) / (3600.0 * 24.0);
319 FG_LOG( FG_EVENT, FG_DEBUG,
320 " Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
322 part = fmod(diff, 1.0);
324 hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
326 lstTmp = (days - lng)/15.0 + hours - 12;
328 while ( lstTmp < 0.0 ) {
332 FG_LOG( FG_EVENT, FG_DEBUG,
333 " days = " << days << " hours = " << hours << " lon = "
334 << lng << " lst = " << lstTmp );
340 // Update time variables such as gmt, julian date, and sidereal time
341 void FGTime::update(const FGInterface& f)
343 double gst_precise, gst_course;
345 FG_LOG( FG_EVENT, FG_DEBUG, "Updating time" );
347 // get current Unix calendar time (in seconds)
349 cur_time = time(NULL) + warp;
350 FG_LOG( FG_EVENT, FG_DEBUG,
351 " Current Unix calendar time = " << cur_time
352 << " warp = " << warp << " delta = " << warp_delta );
355 // time is changing so force an update
356 local_update_sky_and_lighting_params();
359 // get GMT break down for current time
360 gmt = gmtime(&cur_time);
361 FG_LOG( FG_EVENT, FG_DEBUG,
362 " Current GMT = " << gmt->tm_mon+1 << "/"
363 << gmt->tm_mday << "/" << gmt->tm_year << " "
364 << gmt->tm_hour << ":" << gmt->tm_min << ":"
367 // calculate modified Julian date
368 // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday,
369 // (int)(t->gmt->tm_year + 1900));
370 cal_mjd ((int)(gmt->tm_mon+1), (double)gmt->tm_mday,
371 (int)(gmt->tm_year + 1900));
373 // add in partial day
374 mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
375 (gmt->tm_sec / (24.0 * 60.0 * 60.0));
377 // convert "back" to Julian date + partial day (as a fraction of one)
379 FG_LOG( FG_EVENT, FG_DEBUG, " Current Julian Date = " << jd );
381 // printf(" Current Longitude = %.3f\n", FG_Longitude * RAD_TO_DEG);
383 // Calculate local side real time
384 if ( gst_diff < -100.0 ) {
385 // first time through do the expensive calculation & cheap
386 // calculation to get the difference.
387 FG_LOG( FG_EVENT, FG_INFO, " First time, doing precise gst" );
388 gst_precise = gst = sidereal_precise(0.00);
389 gst_course = sidereal_course(0.00);
391 gst_diff = gst_precise - gst_course;
393 lst = sidereal_course(-(f.get_Longitude() * RAD_TO_DEG)) + gst_diff;
395 // course + difference should drift off very slowly
396 gst = sidereal_course( 0.00 ) + gst_diff;
397 lst = sidereal_course( -(f.get_Longitude() * RAD_TO_DEG)) + gst_diff;
399 FG_LOG( FG_EVENT, FG_DEBUG,
400 " Current lon=0.00 Sidereal Time = " << gst );
401 FG_LOG( FG_EVENT, FG_DEBUG,
402 " Current LOCAL Sidereal Time = " << lst << " ("
403 << sidereal_precise(-(f.get_Longitude() * RAD_TO_DEG))
404 << ") (diff = " << gst_diff << ")" );
408 /******************************************************************
409 * The following are some functions that were included as FGTime
410 * members, although they currently don't make use of any of the
411 * class's variables. Maybe this'll change in the future
412 *****************************************************************/
414 // Return time_t for Sat Mar 21 12:00:00 GMT
416 // On many systems it is ambiguous if mktime() assumes the input is in
417 // GMT, or local timezone. To address this, a new function called
418 // timegm() is appearing. It works exactly like mktime() but
419 // explicitely interprets the input as GMT.
421 // timegm() is available and documented under FreeBSD. It is
422 // available, but completely undocumented on my current Debian 2.1
425 // In the absence of timegm() we have to guess what mktime() might do.
427 // Many older BSD style systems have a mktime() that assumes the input
428 // time in GMT. But FreeBSD explicitly states that mktime() assumes
431 // The mktime() on many SYSV style systems (such as Linux) usually
432 // returns its result assuming you have specified the input time in
433 // your local timezone. Therefore, in the absence if timegm() you
434 // have to go to extra trouble to convert back to GMT.
436 // If you are having problems with incorrectly positioned astronomical
437 // bodies, this is a really good place to start looking.
439 time_t FGTime::get_gmt(int year, int month, int day, int hour, int min, int sec)
449 mt.tm_isdst = -1; // let the system determine the proper time zone
451 // For now we assume that if daylight is not defined in
452 // /usr/include/time.h that we have a machine with a mktime() that
453 // assumes input is in GMT ... this only matters if we are
454 // building on a system that does not have timegm()
455 #if !defined(HAVE_DAYLIGHT)
456 # define MK_TIME_IS_GMT 1
459 #if defined( HAVE_TIMEGM )
460 return ( timegm(&mt) );
461 #elif defined( MK_TIME_IS_GMT )
462 return ( mktime(&mt) );
463 #else // ! defined ( MK_TIME_IS_GMT )
465 // timezone seems to work as a proper offset for Linux & Solaris
466 # if defined( __linux__ ) || defined( __sun__ )
467 # define TIMEZONE_OFFSET_WORKS 1
470 long int start = mktime(&mt);
472 FG_LOG( FG_EVENT, FG_DEBUG, "start1 = " << start );
473 // the ctime() call can screw up time progression on some versions
475 // fgPrintf( FG_EVENT, FG_DEBUG, "start2 = %s", ctime(&start));
476 FG_LOG( FG_EVENT, FG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
478 timezone = fix_up_timezone( timezone );
480 # if defined( TIMEZONE_OFFSET_WORKS )
481 FG_LOG( FG_EVENT, FG_DEBUG,
482 "start = " << start << ", timezone = " << timezone );
483 return( start - timezone );
484 # else // ! defined( TIMEZONE_OFFSET_WORKS )
486 daylight = mt.tm_isdst;
487 if ( daylight > 0 ) {
489 } else if ( daylight < 0 ) {
490 FG_LOG( FG_EVENT, FG_WARN,
491 "OOOPS, problem in fg_time.cxx, no daylight savings info." );
494 long int offset = -(timezone / 3600 - daylight);
496 FG_LOG( FG_EVENT, FG_DEBUG, " Raw time zone offset = " << timezone );
497 FG_LOG( FG_EVENT, FG_DEBUG, " Daylight Savings = " << daylight );
498 FG_LOG( FG_EVENT, FG_DEBUG, " Local hours from GMT = " << offset );
500 long int start_gmt = start - timezone + (daylight * 3600);
502 FG_LOG( FG_EVENT, FG_DEBUG, " March 21 noon (CST) = " << start );
504 return ( start_gmt );
505 # endif // ! defined( TIMEZONE_OFFSET_WORKS )
506 #endif // ! defined ( MK_TIME_IS_GMT )
509 // Fix up timezone if using ftime()
510 long int FGTime::fix_up_timezone( long int timezone_orig )
512 #if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
513 // ftime() needs a little extra help finding the current timezone
514 struct timeb current;
516 return( current.timezone * 60 );
518 return( timezone_orig );
523 char* FGTime::format_time( const struct tm* p, char* buf )
525 sprintf( buf, "%d/%d/%2d %d:%02d:%02d",
526 p->tm_mon, p->tm_mday, p->tm_year,
527 p->tm_hour, p->tm_min, p->tm_sec);
532 // Force an update of the sky and lighting parameters
533 void FGTime::local_update_sky_and_lighting_params( void ) {
535 SolarSystem::theSolarSystem->rebuild();
536 cur_light_params.Update();
537 current_sky.repaint( cur_light_params.sky_color,
538 cur_light_params.fog_color,
539 cur_light_params.sun_angle );
543 FGTime* FGTime::cur_time_params = 0;