]> git.mxchange.org Git - simgear.git/blob - simgear/timing/sg_time.cxx
Manage OSG object cache explicitly
[simgear.git] / simgear / timing / sg_time.cxx
1 // sg_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  - http://www.flightgear.org/~curt
6 //
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Library General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // Library 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <simgear_config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <errno.h>              // for errno
31
32 #ifdef SG_HAVE_STD_INCLUDES
33 #  include <cstdio>
34 #  include <cstdlib>
35 #  include <ctime>
36 #else
37 #  include <math.h>
38 #  include <stdio.h>
39 #  include <stdlib.h>
40 #endif
41
42 #include <string>
43
44 #ifdef HAVE_SYS_TIME_H
45 #  include <sys/time.h>  // for get/setitimer, gettimeofday, struct timeval
46 #endif
47 #ifdef HAVE_SYS_TIMEB_H
48 #  include <sys/timeb.h> // for ftime() and struct timeb
49 #endif
50 #ifdef HAVE_UNISTD_H
51 #  include <unistd.h>    // for gettimeofday()
52 #endif
53
54 #include <math.h>        // for NAN
55
56 #include <simgear/constants.h>
57 #include <simgear/debug/logstream.hxx>
58 #include <simgear/misc/sg_path.hxx>
59
60 #include "sg_time.hxx"
61 #include "timezone.h"
62 #include "lowleveltime.h"
63
64 #define DEGHR(x)        ((x)/15.)
65 #define RADHR(x)        DEGHR(x*SGD_RADIANS_TO_DEGREES)
66
67
68 static const double MJD0    = 2415020.0;
69 static const double J2000   = 2451545.0 - MJD0;
70 static const double SIDRATE = 0.9972695677;
71
72
73 void SGTime::init( double lon_rad, double lat_rad,
74                    const string& root, time_t init_time )
75 {
76     SG_LOG( SG_EVENT, SG_INFO, "Initializing Time" );
77
78     gst_diff = -9999.0;
79
80     if ( init_time ) {
81         cur_time = init_time;
82     } else {
83         cur_time = time(NULL); 
84     }
85
86     SG_LOG( SG_EVENT, SG_INFO,
87                 "Current greenwich mean time = " << asctime(gmtime(&cur_time)));
88     SG_LOG( SG_EVENT, SG_INFO,
89              "Current local time          = " << asctime(localtime(&cur_time)));
90
91     if ( !root.empty()) {
92         SGPath zone( root );
93         zone.append( "zone.tab" );
94         SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
95                 << zone.str() );
96         tzContainer = new SGTimeZoneContainer( zone.c_str() );
97
98         SGGeoCoord location( SGD_RADIANS_TO_DEGREES * lat_rad, SGD_RADIANS_TO_DEGREES * lon_rad );
99         SGGeoCoord* nearestTz = tzContainer->getNearest(location);
100
101         SGPath name( root );
102         name.append( nearestTz->getDescription() );
103         zonename = name.str();
104         SG_LOG( SG_EVENT, SG_INFO, "Using zonename = " << zonename );
105     } else {
106         SG_LOG( SG_EVENT, SG_INFO, "*** NO TIME ZONE NAME ***" );
107         tzContainer = NULL;
108         zonename.erase();
109     }
110 }
111
112 SGTime::SGTime( double lon_rad, double lat_rad, const string& root,
113                 time_t init_time )
114 {
115     init( lon_rad, lat_rad, root, init_time );
116 }
117
118
119 SGTime::SGTime( const string& root ) {
120     init( 0.0, 0.0, root, 0 );
121 }
122
123
124 SGTime::SGTime() {
125     init( 0.0, 0.0, "", 0 );
126 }
127
128
129 SGTime::~SGTime()
130 {
131     if ( tzContainer != NULL ) {
132         SGTimeZoneContainer *tmp = tzContainer;
133         tzContainer = NULL;
134         delete tmp;
135     }
136 }
137
138
139 // given Julian Date and Longitude (decimal degrees West) compute
140 // Local Sidereal Time, in decimal hours.
141 //
142 // Provided courtesy of ecdowney@noao.edu (Elwood Downey) 
143 static double sidereal_precise( double mjd, double lng )
144 {
145     /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ", 
146        mjd + MJD0, lng); */
147
148     // convert to required internal units
149     lng *= SGD_DEGREES_TO_RADIANS;
150
151     // compute LST and print
152     double gst = sgTimeCalcGST( mjd );
153     double lst = gst - RADHR( lng );
154     lst -= 24.0 * floor( lst / 24.0 );
155     // printf ("%7.4f\n", lstTmp);
156
157     return lst;
158 }
159
160
161 // return a courser but cheaper estimate of sidereal time
162 static double sidereal_course( time_t cur_time, const struct tm *gmt, double lng )
163 {
164     time_t start_gmt, now;
165     double diff, part, days, hours, lstTmp;
166     char tbuf[64];
167   
168     now = cur_time;
169     start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
170   
171     SG_LOG( SG_EVENT, SG_DEBUG, "  COURSE: GMT = "
172             << sgTimeFormatTime(gmt, tbuf) );
173     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (GMT) = " << start_gmt );
174   
175     diff = (now - start_gmt) / (3600.0 * 24.0);
176   
177     SG_LOG( SG_EVENT, SG_DEBUG, 
178             "  Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
179   
180     part = fmod(diff, 1.0);
181     days = diff - part;
182     hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
183   
184     lstTmp = (days - lng)/15.0 + hours - 12;
185   
186     while ( lstTmp < 0.0 ) {
187         lstTmp += 24.0;
188     }
189   
190     SG_LOG( SG_EVENT, SG_DEBUG,
191             "  days = " << days << "  hours = " << hours << "  lon = " 
192             << lng << "  lst = " << lstTmp );
193   
194     return lstTmp;
195 }
196
197
198 // Update the time related variables
199 void SGTime::update( double lon_rad, double lat_rad,
200                      time_t ct, long int warp )
201 {
202     double gst_precise, gst_course;
203
204 #if defined(_MSC_VER) || defined(__MINGW32__)
205     tm * gmt = &m_gmt;
206 #endif
207
208     SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
209
210     // get current Unix calendar time (in seconds)
211     // warp += warp_delta;
212     if ( ct ) {
213         cur_time = ct + warp;
214     } else {
215         cur_time = time(NULL) + warp;
216     }
217     SG_LOG( SG_EVENT, SG_DEBUG, 
218             "  Current Unix calendar time = " << cur_time 
219             << "  warp = " << warp );
220
221     // get GMT break down for current time
222 #if defined(_MSC_VER) || defined(__MINGW32__)
223     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
224 #else
225     gmt = gmtime(&cur_time);
226 #endif
227     SG_LOG( SG_EVENT, SG_DEBUG, 
228             "  Current GMT = " << gmt->tm_mon+1 << "/" 
229             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
230             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
231             << gmt->tm_sec );
232
233     // calculate modified Julian date starting with current
234     mjd = sgTimeCurrentMJD( ct, warp );
235
236     // add in partial day
237     mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
238         (gmt->tm_sec / (24.0 * 60.0 * 60.0));
239
240     // convert "back" to Julian date + partial day (as a fraction of one)
241     jd = mjd + MJD0;
242     SG_LOG( SG_EVENT, SG_DEBUG, "  Current Julian Date = " << jd );
243
244     // printf("  Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
245
246     // Calculate local side real time
247     if ( gst_diff < -100.0 ) {
248         // first time through do the expensive calculation & cheap
249         // calculation to get the difference.
250         SG_LOG( SG_EVENT, SG_INFO, "  First time, doing precise gst" );
251         gst_precise = gst = sidereal_precise( mjd, 0.00 );
252         gst_course = sidereal_course( cur_time, gmt, 0.00 );
253       
254         gst_diff = gst_precise - gst_course;
255
256         lst = sidereal_course( cur_time, gmt,
257                                -(lon_rad * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
258     } else {
259         // course + difference should drift off very slowly
260         gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
261         lst = sidereal_course( cur_time, gmt,
262                                -(lon_rad * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
263     }
264
265     SG_LOG( SG_EVENT, SG_DEBUG,
266             "  Current lon=0.00 Sidereal Time = " << gst );
267     SG_LOG( SG_EVENT, SG_DEBUG,
268             "  Current LOCAL Sidereal Time = " << lst << " (" 
269             << sidereal_precise( mjd, -(lon_rad * SGD_RADIANS_TO_DEGREES) ) 
270             << ") (diff = " << gst_diff << ")" );
271 }
272
273
274 // Given lon/lat, update timezone information and local_offset
275 void SGTime::updateLocal( double lon_rad, double lat_rad, const string& root ) {
276     // sanity checking
277     if ( lon_rad < -SGD_PI || lon_rad> SGD_PI ) {
278         // not within -180 ... 180
279         lon_rad = 0.0;
280     }
281     if ( lat_rad < -SGD_PI_2 || lat_rad > SGD_PI_2 ) {
282         // not within -90 ... 90
283         lat_rad = 0.0;
284     }
285     if ( lon_rad != lon_rad ) {
286         // only true if lon_rad == nan
287         SG_LOG( SG_EVENT, SG_ALERT,
288                 "  Detected lon_rad == nan, resetting to 0.0" );
289         lon_rad = 0.0;
290     }
291     if ( lat_rad != lat_rad ) {
292         // only true if lat_rad == nan
293         SG_LOG( SG_EVENT, SG_ALERT,
294                 "  Detected lat_rad == nan, resetting to 0.0" );
295         lat_rad = 0.0;
296     }
297     time_t currGMT;
298     time_t aircraftLocalTime;
299     SGGeoCoord location( SGD_RADIANS_TO_DEGREES * lat_rad,
300                          SGD_RADIANS_TO_DEGREES * lon_rad );
301     SGGeoCoord* nearestTz = tzContainer->getNearest(location);
302     SGPath zone( root );
303     zone.append ( nearestTz->getDescription() );
304     zonename = zone.str();
305
306     //Avoid troubles when zone.tab hasn't got the right line endings
307     if (zonename[zonename.size()-1] == '\r')
308     {
309       zonename[zonename.size()-1]=0;
310       zone.set( zonename );
311     }
312
313     currGMT = sgTimeGetGMT( gmtime(&cur_time) );
314     aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
315     local_offset = aircraftLocalTime - currGMT;
316     // cout << "Using " << local_offset << " as local time offset Timezone is " 
317     //      << zonename << endl;
318 }
319
320
321 // given a date in months, mn, days, dy, years, yr, return the
322 // modified Julian date (number of days elapsed since 1900 jan 0.5),
323 // mjd.  Adapted from Xephem.
324 double sgTimeCalcMJD(int mn, double dy, int yr) {
325     double mjd;
326
327     // internal book keeping data
328     static double last_mjd, last_dy;
329     static int last_mn, last_yr;
330
331     int b, d, m, y;
332     long c;
333   
334     if (mn == last_mn && yr == last_yr && dy == last_dy) {
335         mjd = last_mjd;
336     }
337   
338     m = mn;
339     y = (yr < 0) ? yr + 1 : yr;
340     if (mn < 3) {
341         m += 12;
342         y -= 1;
343     }
344   
345     if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
346         b = 0;
347     } else {
348         int a;
349         a = y/100;
350         b = 2 - a + a/4;
351     }
352   
353     if (y < 0) {
354         c = (long)((365.25*y) - 0.75) - 694025L;
355     } else {
356         c = (long)(365.25*y) - 694025L;
357     }
358   
359     d = (int)(30.6001*(m+1));
360   
361     mjd = b + c + d + dy - 0.5;
362   
363     last_mn = mn;
364     last_dy = dy;
365     last_yr = yr;
366     last_mjd = mjd;
367
368     return mjd;
369 }
370
371
372 // return the current modified Julian date (number of days elapsed
373 // since 1900 jan 0.5), mjd.
374 double sgTimeCurrentMJD( time_t ct, long int warp ) {
375
376 #if defined(_MSC_VER) || defined(__MINGW32__)
377     struct tm m_gmt;    // copy of system gmtime(&time_t) structure
378     struct tm *gmt = &m_gmt;
379 #else
380     struct tm *gmt;
381 #endif
382
383     // get current Unix calendar time (in seconds)
384     // warp += warp_delta;
385     time_t cur_time;
386     if ( ct ) {
387         cur_time = ct + warp;
388     } else {
389         cur_time = time(NULL) + warp;
390     }
391     SG_LOG( SG_EVENT, SG_DEBUG, 
392             "  Current Unix calendar time = " << cur_time 
393             << "  warp = " << warp );
394
395     // get GMT break down for current time
396 #if defined(_MSC_VER) || defined(__MINGW32__)
397     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
398 #else
399     gmt = gmtime(&cur_time);
400 #endif
401     SG_LOG( SG_EVENT, SG_DEBUG, 
402             "  Current GMT = " << gmt->tm_mon+1 << "/" 
403             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
404             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
405             << gmt->tm_sec );
406
407     // calculate modified Julian date
408     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
409     //     (int)(t->gmt->tm_year + 1900));
410     double mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
411                                 (int)(gmt->tm_year + 1900) );
412
413     return mjd;
414 }
415
416
417 // given an mjd, calculate greenwich mean sidereal time, gst
418 double sgTimeCalcGST( double mjd ) {
419     double gst;
420
421     double day = floor(mjd-0.5)+0.5;
422     double hr = (mjd-day)*24.0;
423     double T, x;
424
425     T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
426     x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
427     x /= 3600.0;
428     gst = (1.0/SIDRATE)*hr + x;
429
430     SG_LOG( SG_EVENT, SG_DEBUG, "  gst => " << gst );
431
432     return gst;
433 }
434
435
436 #if defined( HAVE_TIMEGM ) 
437     // ignore this function
438 #elif defined( MK_TIME_IS_GMT )
439     // ignore this function
440 #else // ! defined ( MK_TIME_IS_GMT )
441
442     // Fix up timezone if using ftime()
443     static long int fix_up_timezone( long int timezone_orig ) {
444 #   if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
445         // ftime() needs a little extra help finding the current timezone
446         struct timeb current;
447         ftime(&current);
448         return( current.timezone * 60 );
449 #   else
450         return( timezone_orig );
451 #   endif
452     }
453 #endif
454
455
456 /******************************************************************
457  * The following are some functions that were included as SGTime
458  * members, although they currently don't make use of any of the
459  * class's variables. Maybe this'll change in the future
460  *****************************************************************/
461
462 // Return time_t for Sat Mar 21 12:00:00 GMT
463 //
464 // On many systems it is ambiguous if mktime() assumes the input is in
465 // GMT, or local timezone.  To address this, a new function called
466 // timegm() is appearing.  It works exactly like mktime() but
467 // explicitely interprets the input as GMT.
468 //
469 // timegm() is available and documented under FreeBSD.  It is
470 // available, but completely undocumented on my current Debian 2.1
471 // distribution.
472 //
473 // In the absence of timegm() we have to guess what mktime() might do.
474 //
475 // Many older BSD style systems have a mktime() that assumes the input
476 // time in GMT.  But FreeBSD explicitly states that mktime() assumes
477 // local time zone
478 //
479 // The mktime() on many SYSV style systems (such as Linux) usually
480 // returns its result assuming you have specified the input time in
481 // your local timezone.  Therefore, in the absence if timegm() you
482 // have to go to extra trouble to convert back to GMT.
483 //
484 // If you are having problems with incorrectly positioned astronomical
485 // bodies, this is a really good place to start looking.
486
487 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
488 {
489     struct tm mt;
490
491     mt.tm_mon = month;
492     mt.tm_mday = day;
493     mt.tm_year = year;
494     mt.tm_hour = hour;
495     mt.tm_min = min;
496     mt.tm_sec = sec;
497     mt.tm_isdst = -1; // let the system determine the proper time zone
498
499     // For now we assume that if daylight is not defined in
500     // /usr/include/time.h that we have a machine with a mktime() that
501     // assumes input is in GMT ... this only matters if we are
502     // building on a system that does not have timegm()
503 #if !defined(HAVE_DAYLIGHT)
504 #  define MK_TIME_IS_GMT 1
505 #endif
506
507 #if defined( HAVE_TIMEGM )
508     return ( timegm(&mt) );
509 #elif defined( MK_TIME_IS_GMT )
510     time_t ret = mktime(&mt);
511
512 #ifdef __CYGWIN__
513         ret -= _timezone;
514 #endif
515
516     // This is necessary as some mktime() calls may
517     // try to access the system timezone files
518     // if this open fails errno is set to 2
519     // CYGWIN for one does this
520     // if ( errno ) {
521     //     perror( "sgTimeGetGMT()" );
522     //     errno = 0;
523     // }
524
525     // reset errno in any event.
526     errno = 0;
527
528     return ret;
529 #else // ! defined ( MK_TIME_IS_GMT )
530
531     // timezone seems to work as a proper offset for Linux & Solaris
532 #   if defined( __linux__ ) || defined(__sun) ||defined(__CYGWIN__)
533 #       define TIMEZONE_OFFSET_WORKS 1
534 #   endif
535
536 #if defined(__CYGWIN__)
537 #define TIMEZONE _timezone
538 #else
539 #define TIMEZONE timezone
540 #endif
541         
542     time_t start = mktime(&mt);
543
544     SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
545     // the ctime() call can screw up time progression on some versions
546     // of Linux
547     // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
548     SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
549
550     TIMEZONE = fix_up_timezone( TIMEZONE );
551
552 #  if defined( TIMEZONE_OFFSET_WORKS )
553     SG_LOG( SG_EVENT, SG_DEBUG,
554             "start = " << start << ", timezone = " << TIMEZONE );
555     return( start - TIMEZONE );
556 #  else // ! defined( TIMEZONE_OFFSET_WORKS )
557
558     daylight = mt.tm_isdst;
559     if ( daylight > 0 ) {
560         daylight = 1;
561     } else if ( daylight < 0 ) {
562         SG_LOG( SG_EVENT, FG_WARN, 
563                 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
564     }
565
566     long int offset = -(TIMEZONE / 3600 - daylight);
567
568     SG_LOG( SG_EVENT, SG_DEBUG, "  Raw time zone offset = " << TIMEZONE );
569     SG_LOG( SG_EVENT, SG_DEBUG, "  Daylight Savings = " << daylight );
570     SG_LOG( SG_EVENT, SG_DEBUG, "  Local hours from GMT = " << offset );
571     
572     long int start_gmt = start - TIMEZONE + (daylight * 3600);
573     
574     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (CST) = " << start );
575
576     return ( start_gmt );
577 #  endif // ! defined( TIMEZONE_OFFSET_WORKS )
578 #endif // ! defined ( MK_TIME_IS_GMT )
579 }
580
581
582 // format time
583 char* sgTimeFormatTime( const struct tm* p, char* buf )
584 {
585     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
586              p->tm_mon, p->tm_mday, p->tm_year,
587              p->tm_hour, p->tm_min, p->tm_sec);
588     return buf;
589 }