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