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