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