]> git.mxchange.org Git - simgear.git/blob - simgear/timing/sg_time.cxx
5d462725798050f216dada389771a4ba12292bb5
[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 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.
11 //
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.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #ifdef FG_HAVE_STD_INCLUDES
31 #  include <cmath>
32 #  include <cstdio>
33 #  include <cstdlib>
34 #  include <ctime>
35 #else
36 #  include <math.h>
37 #  include <stdio.h>
38 #  include <stdlib.h>
39 #  include <time.h>
40 #endif
41
42 #ifdef HAVE_SYS_TIMEB_H
43 #  include <sys/timeb.h> // for ftime() and struct timeb
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #  include <unistd.h>    // for gettimeofday()
47 #endif
48 #ifdef HAVE_SYS_TIME_H
49 #  include <sys/time.h>  // for get/setitimer, gettimeofday, struct timeval
50 #endif
51
52 #include <simgear/constants.h>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/misc/fgpath.hxx>
55
56 #include "sg_time.hxx"
57 #include "timezone.h"
58 #include "lowleveltime.h"
59
60
61 #define DEGHR(x)        ((x)/15.)
62 #define RADHR(x)        DEGHR(x*RAD_TO_DEG)
63
64
65 SGTime::SGTime( const string& root )
66 {
67     if (cur_time_params) {
68         FG_LOG( FG_GENERAL, FG_ALERT, 
69                 "Error: only one instance of SGTime allowed" );
70         exit(-1);
71     }
72
73     cur_time_params = this;
74
75     FGPath zone( root );
76     zone.append( "Timezone" );
77     zone.append( "zone.tab" );
78
79     FG_LOG( FG_EVENT, FG_INFO, "Reading timezone info from: " << zone.str() );
80     tzContainer = new TimezoneContainer( zone.c_str() );
81     // warp=0;
82     // warp_delta=0;
83 }
84
85
86 SGTime::~SGTime()
87 {
88     delete tzContainer;
89     delete zonename;
90 }
91
92 void SGTime::updateLocal( double lon, double lat, const string& root )
93 {
94   time_t currGMT;
95   time_t aircraftLocalTime;
96   GeoCoord location( RAD_TO_DEG * lat, RAD_TO_DEG * lon );
97   GeoCoord* nearestTz = tzContainer->getNearest(location);
98   FGPath zone( root );
99   zone.append ("Timezone" );
100   zone.append ( nearestTz->getDescription() );
101   if ( zonename ) {
102       delete zonename;
103   }
104   zonename = strdup( zone.c_str() );
105   currGMT = get_gmt( gmtime(&cur_time) );
106   aircraftLocalTime = get_gmt( (fgLocaltime(&cur_time, zone.c_str())) );
107   local_offset = aircraftLocalTime - currGMT;
108   cout << "Using " << local_offset << " as local time offset Timezone is " 
109        << zonename << endl;
110 }
111
112 // Initialize the time dependent variables (maybe I'll put this in the
113 // constructor later)
114 void SGTime::init( double lon, double lat, const string& root )
115 // time_t timeOffset, sgTimingOffsetType offsetType )
116 {
117     FG_LOG( FG_EVENT, FG_INFO, "Initializing Time" );
118     gst_diff = -9999.0;
119
120     time_t currGMT;
121     time_t systemLocalTime;
122     time_t aircraftLocalTime;
123
124     // would it be better to put these sanity checks in the options
125     // parsing code? (CLO)
126
127     cur_time = time(NULL); 
128
129     // printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
130     // printf ("Current local time          = %24s", asctime(localtime(&cur_time)));
131     // time_t tmp = cur_time;
132     GeoCoord location( RAD_TO_DEG * lat, RAD_TO_DEG * lon );
133
134     GeoCoord* nearestTz = tzContainer->getNearest(location);
135
136     FGPath zone( root );
137     zone.append( "Timezone" );
138     zone.append( nearestTz->getDescription() );
139
140     cout << "Using " << zone.str() << " for timezone information" << endl;
141     zonename = strdup( zone.c_str() );
142     cout << "zonename = " << zonename << endl;
143     //show( buffer.c_str(), cur_time, 1); 
144     //printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
145     //printf ("Current local time          = %24s", asctime(localtime(&cur_time)));
146     currGMT = get_gmt( gmtime(&cur_time) );
147     cout << "currGMT = " << currGMT << endl;
148
149     systemLocalTime = get_gmt( localtime(&cur_time) );
150     cout << "systemLocalTime = " << systemLocalTime << endl;
151
152     aircraftLocalTime = get_gmt( fgLocaltime(&cur_time, zone.c_str()) ); 
153     //printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
154     //printf ("Current local time          = %24s", asctime(localtime(&cur_time)));
155
156     //printf("LT  = %d\n", computerLocalTime);
157     // Okay, in principle, this trick allows to calculate the
158     // difference between GMT and localtime, in seconds.
159     // printf("Gmt = %d, SLT = %d, (difference = %d)\n", currGMT, systemLocalTime,   (currGMT - systemLocalTime));
160     // printf("Gmt = %d, ALT = %d, (difference = %d)\n", currGMT, aircraftLocalTime, (currGMT - aircraftLocalTime));
161     // exit(1);
162
163 #if 0
164     // Okay, we now have six possible scenarios
165     switch (offsetType)
166         {
167         case SG_TIME_SYS_OFFSET:
168             warp = timeOffset;
169             break;
170         case SG_TIME_GMT_OFFSET:
171             warp = timeOffset - (currGMT - systemLocalTime);
172             break;
173         case SG_TIME_LAT_OFFSET:
174             // warp = timeOffset - (currGMT - systemLocalTime + 
175             //        (currGMT - aircraftLocalTime));
176             warp = timeOffset - (aircraftLocalTime - systemLocalTime); 
177             break;
178         case SG_TIME_SYS_ABSOLUTE:
179             warp = timeOffset - cur_time;
180             //printf("warp = %d\n", warp); 
181             break;
182         case SG_TIME_GMT_ABSOLUTE:
183             warp = timeOffset - currGMT;
184             break;
185         case SG_TIME_LAT_ABSOLUTE:
186             warp = timeOffset - (aircraftLocalTime - systemLocalTime) - 
187                 cur_time; 
188             break;
189         default:
190             printf("Unsupported type\n");
191             exit(1);
192         }
193
194     warp_delta = 0;
195     // pause = current_options.get_pause();
196 #endif
197
198 }
199
200
201 // given a date in months, mn, days, dy, years, yr, return the
202 // modified Julian date (number of days elapsed since 1900 jan 0.5),
203 // mjd.  Adapted from Xephem.
204
205 void SGTime::cal_mjd (int mn, double dy, int yr) 
206 {
207     //static double last_mjd, last_dy;
208     //double mjd;
209     //static int last_mn, last_yr;
210     int b, d, m, y;
211     long c;
212   
213     if (mn == last_mn && yr == last_yr && dy == last_dy) {
214         mjd = last_mjd;
215     }
216   
217     m = mn;
218     y = (yr < 0) ? yr + 1 : yr;
219     if (mn < 3) {
220         m += 12;
221         y -= 1;
222     }
223   
224     if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
225         b = 0;
226     } else {
227         int a;
228         a = y/100;
229         b = 2 - a + a/4;
230     }
231   
232     if (y < 0) {
233         c = (long)((365.25*y) - 0.75) - 694025L;
234     } else {
235         c = (long)(365.25*y) - 694025L;
236     }
237   
238     d = (int)(30.6001*(m+1));
239   
240     mjd = b + c + d + dy - 0.5;
241   
242     last_mn = mn;
243     last_dy = dy;
244     last_yr = yr;
245     last_mjd = mjd;
246 }
247
248
249 // given an mjd, calculate greenwich mean sidereal time, gst
250 void SGTime::utc_gst () 
251 {
252     double day = floor(mjd-0.5)+0.5;
253     double hr = (mjd-day)*24.0;
254     double T, x;
255
256     T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
257     x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
258     x /= 3600.0;
259     gst = (1.0/SIDRATE)*hr + x;
260
261     FG_LOG( FG_EVENT, FG_INFO, "  gst => " << gst );
262 }
263
264
265 // given Julian Date and Longitude (decimal degrees West) compute
266 // Local Sidereal Time, in decimal hours.
267 //
268 // Provided courtesy of ecdowney@noao.edu (Elwood Downey) 
269
270 double SGTime::sidereal_precise (double lng) 
271 {
272     double lstTmp;
273
274     /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ", 
275        mjd + MJD0, lng); */
276
277     // convert to required internal units
278     lng *= DEG_TO_RAD;
279
280     // compute LST and print
281     utc_gst();
282     lstTmp = gst - RADHR (lng);
283     lstTmp -= 24.0*floor(lstTmp/24.0);
284     // printf ("%7.4f\n", lstTmp);
285
286     // that's all
287     return (lstTmp);
288 }
289
290
291 // return a courser but cheaper estimate of sidereal time
292 double SGTime::sidereal_course(double lng) 
293 {
294     //struct tm *gmt;
295     //double lstTmp;
296     time_t start_gmt, now;
297     double diff, part, days, hours, lstTmp;
298     char tbuf[64];
299   
300     //gmt = t->gmt;
301     //now = t->cur_time;
302     now = cur_time;
303     start_gmt = get_gmt(gmt->tm_year, 2, 21, 12, 0, 0);
304   
305     FG_LOG( FG_EVENT, FG_DEBUG, "  COURSE: GMT = " << format_time(gmt, tbuf) );
306     FG_LOG( FG_EVENT, FG_DEBUG, "  March 21 noon (GMT) = " << start_gmt );
307   
308     diff = (now - start_gmt) / (3600.0 * 24.0);
309   
310     FG_LOG( FG_EVENT, FG_DEBUG, 
311             "  Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
312   
313     part = fmod(diff, 1.0);
314     days = diff - part;
315     hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
316   
317     lstTmp = (days - lng)/15.0 + hours - 12;
318   
319     while ( lstTmp < 0.0 ) {
320         lstTmp += 24.0;
321     }
322   
323     FG_LOG( FG_EVENT, FG_DEBUG,
324             "  days = " << days << "  hours = " << hours << "  lon = " 
325             << lng << "  lst = " << lstTmp );
326   
327     return(lstTmp);
328 }
329
330
331 // Update time variables such as gmt, julian date, and sidereal time
332 void SGTime::update( double lon, double lat, double alt_m, long int warp ) {
333     double gst_precise, gst_course;
334
335     FG_LOG( FG_EVENT, FG_INFO, "Updating time" );
336
337     // get current Unix calendar time (in seconds)
338     // warp += warp_delta;
339     cur_time = time(NULL) + warp;
340     FG_LOG( FG_EVENT, FG_INFO, 
341             "  Current Unix calendar time = " << cur_time 
342             << "  warp = " << warp );
343
344     // get GMT break down for current time
345     gmt = gmtime(&cur_time);
346     FG_LOG( FG_EVENT, FG_INFO, 
347             "  Current GMT = " << gmt->tm_mon+1 << "/" 
348             << gmt->tm_mday << "/" << gmt->tm_year << " "
349             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
350             << gmt->tm_sec );
351
352     // calculate modified Julian date
353     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
354     //     (int)(t->gmt->tm_year + 1900));
355     cal_mjd ((int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
356              (int)(gmt->tm_year + 1900));
357
358     // add in partial day
359     mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
360         (gmt->tm_sec / (24.0 * 60.0 * 60.0));
361
362     // convert "back" to Julian date + partial day (as a fraction of one)
363     jd = mjd + MJD0;
364     FG_LOG( FG_EVENT, FG_INFO, "  Current Julian Date = " << jd );
365
366     // printf("  Current Longitude = %.3f\n", FG_Longitude * RAD_TO_DEG);
367
368     // Calculate local side real time
369     if ( gst_diff < -100.0 ) {
370         // first time through do the expensive calculation & cheap
371         // calculation to get the difference.
372         FG_LOG( FG_EVENT, FG_INFO, "  First time, doing precise gst" );
373         gst_precise = gst = sidereal_precise(0.00);
374         gst_course = sidereal_course(0.00);
375       
376         gst_diff = gst_precise - gst_course;
377
378         lst = sidereal_course(-(lon * RAD_TO_DEG)) + gst_diff;
379     } else {
380         // course + difference should drift off very slowly
381         gst = sidereal_course( 0.00 ) + gst_diff;
382         lst = sidereal_course( -(lon * RAD_TO_DEG)) + gst_diff;
383     }
384
385     FG_LOG( FG_EVENT, FG_INFO,
386             "  Current lon=0.00 Sidereal Time = " << gst );
387     FG_LOG( FG_EVENT, FG_INFO,
388             "  Current LOCAL Sidereal Time = " << lst << " (" 
389             << sidereal_precise(-(lon * RAD_TO_DEG)) 
390             << ") (diff = " << gst_diff << ")" );
391 }
392
393
394 /******************************************************************
395  * The following are some functions that were included as SGTime
396  * members, although they currently don't make use of any of the
397  * class's variables. Maybe this'll change in the future
398  *****************************************************************/
399
400 // Return time_t for Sat Mar 21 12:00:00 GMT
401 //
402 // On many systems it is ambiguous if mktime() assumes the input is in
403 // GMT, or local timezone.  To address this, a new function called
404 // timegm() is appearing.  It works exactly like mktime() but
405 // explicitely interprets the input as GMT.
406 //
407 // timegm() is available and documented under FreeBSD.  It is
408 // available, but completely undocumented on my current Debian 2.1
409 // distribution.
410 //
411 // In the absence of timegm() we have to guess what mktime() might do.
412 //
413 // Many older BSD style systems have a mktime() that assumes the input
414 // time in GMT.  But FreeBSD explicitly states that mktime() assumes
415 // local time zone
416 //
417 // The mktime() on many SYSV style systems (such as Linux) usually
418 // returns its result assuming you have specified the input time in
419 // your local timezone.  Therefore, in the absence if timegm() you
420 // have to go to extra trouble to convert back to GMT.
421 //
422 // If you are having problems with incorrectly positioned astronomical
423 // bodies, this is a really good place to start looking.
424
425 time_t SGTime::get_gmt(int year, int month, int day, int hour, int min, int sec)
426 {
427     struct tm mt;
428
429     mt.tm_mon = month;
430     mt.tm_mday = day;
431     mt.tm_year = year;
432     mt.tm_hour = hour;
433     mt.tm_min = min;
434     mt.tm_sec = sec;
435     mt.tm_isdst = -1; // let the system determine the proper time zone
436
437     // For now we assume that if daylight is not defined in
438     // /usr/include/time.h that we have a machine with a mktime() that
439     // assumes input is in GMT ... this only matters if we are
440     // building on a system that does not have timegm()
441 #if !defined(HAVE_DAYLIGHT)
442 #  define MK_TIME_IS_GMT 1
443 #endif
444
445 #if defined( HAVE_TIMEGM ) 
446     return ( timegm(&mt) );
447 #elif defined( MK_TIME_IS_GMT )
448     return ( mktime(&mt) );
449 #else // ! defined ( MK_TIME_IS_GMT )
450
451     // timezone seems to work as a proper offset for Linux & Solaris
452 #   if defined( __linux__ ) || defined( __sun__ ) 
453 #       define TIMEZONE_OFFSET_WORKS 1
454 #   endif
455
456     long int start = mktime(&mt);
457
458     FG_LOG( FG_EVENT, FG_DEBUG, "start1 = " << start );
459     // the ctime() call can screw up time progression on some versions
460     // of Linux
461     // fgPrintf( FG_EVENT, FG_DEBUG, "start2 = %s", ctime(&start));
462     FG_LOG( FG_EVENT, FG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
463
464     timezone = fix_up_timezone( timezone );
465
466 #  if defined( TIMEZONE_OFFSET_WORKS )
467     FG_LOG( FG_EVENT, FG_DEBUG, 
468             "start = " << start << ", timezone = " << timezone );
469     return( start - timezone );
470 #  else // ! defined( TIMEZONE_OFFSET_WORKS )
471
472     daylight = mt.tm_isdst;
473     if ( daylight > 0 ) {
474         daylight = 1;
475     } else if ( daylight < 0 ) {
476         FG_LOG( FG_EVENT, FG_WARN, 
477                 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
478     }
479
480     long int offset = -(timezone / 3600 - daylight);
481
482     FG_LOG( FG_EVENT, FG_DEBUG, "  Raw time zone offset = " << timezone );
483     FG_LOG( FG_EVENT, FG_DEBUG, "  Daylight Savings = " << daylight );
484     FG_LOG( FG_EVENT, FG_DEBUG, "  Local hours from GMT = " << offset );
485     
486     long int start_gmt = start - timezone + (daylight * 3600);
487     
488     FG_LOG( FG_EVENT, FG_DEBUG, "  March 21 noon (CST) = " << start );
489
490     return ( start_gmt );
491 #  endif // ! defined( TIMEZONE_OFFSET_WORKS )
492 #endif // ! defined ( MK_TIME_IS_GMT )
493 }
494
495 // Fix up timezone if using ftime()
496 long int SGTime::fix_up_timezone( long int timezone_orig ) 
497 {
498 #if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
499     // ftime() needs a little extra help finding the current timezone
500     struct timeb current;
501     ftime(&current);
502     return( current.timezone * 60 );
503 #else
504     return( timezone_orig );
505 #endif
506 }
507
508
509 char* SGTime::format_time( const struct tm* p, char* buf )
510 {
511     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
512              p->tm_mon, p->tm_mday, p->tm_year,
513              p->tm_hour, p->tm_min, p->tm_sec);
514     return buf;
515 }
516
517
518 SGTime* SGTime::cur_time_params = 0;