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