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