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