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