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