Migrating timing support routines over to SimGear.

This commit is contained in:
curt
2000-07-05 00:25:30 +00:00
parent a46163bcd7
commit 1b07b25ad2
9 changed files with 2417 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
includedir = @includedir@/timing
lib_LIBRARIES = libsgtiming.a
include_HEADERS = \
fg_time.hxx \
geocoord.h \
timezone.h
libsgtiming_a_SOURCES = \
fg_time.cxx \
geocoord.cxx \
lowleveltime.cxx lowleveltime.h \
timezone.cxx \
# event.cxx event.hxx \
# fg_timer.cxx fg_timer.hxx \
# light.cxx light.hxx \
# moonpos.cxx moonpos.hxx \
# sunpos.cxx sunpos.hxx \
# timestamp.hxx
INCLUDES += -I$(top_builddir)

544
simgear/timing/fg_time.cxx Normal file
View File

@@ -0,0 +1,544 @@
// fg_time.cxx -- data structures and routines for managing time related stuff.
//
// Written by Curtis Olson, started August 1997.
//
// Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <simgear/compiler.h>
#ifdef FG_HAVE_STD_INCLUDES
# include <cmath>
# include <cstdio>
# include <cstdlib>
# include <ctime>
#else
# include <math.h>
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
#endif
#ifdef HAVE_SYS_TIMEB_H
# include <sys/timeb.h> // for ftime() and struct timeb
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h> // for gettimeofday()
#endif
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
#endif
#include <simgear/constants.h>
#include <simgear/debug/logstream.hxx>
// #include <simgear/magvar/magvar.hxx>
#include <simgear/misc/fgpath.hxx>
// #include <FDM/flight.hxx>
// #include <Main/options.hxx>
// #include <Time/light.hxx>
#include "fg_time.hxx"
#include "timezone.h"
#include "lowleveltime.h"
// #include "moonpos.hxx"
// #include "sunpos.hxx"
#define DEGHR(x) ((x)/15.)
#define RADHR(x) DEGHR(x*RAD_TO_DEG)
// #define MK_TIME_IS_GMT 0 // default value
// #define TIME_ZONE_OFFSET_WORK 0 // default value
FGTime::FGTime( const string& root )
{
if (cur_time_params) {
FG_LOG( FG_GENERAL, FG_ALERT,
"Error: only one instance of FGTime allowed" );
exit(-1);
}
cur_time_params = this;
FGPath zone( root );
zone.append( "Timezone" );
zone.append( "zone.tab" );
FG_LOG( FG_EVENT, FG_INFO, "Reading timezone info from: " << zone.str() );
tzContainer = new TimezoneContainer( zone.c_str() );
warp=0;
warp_delta=0;
}
FGTime::~FGTime()
{
delete tzContainer;
delete zonename;
}
void FGTime::updateLocal( double lon, double lat, const string& root )
{
time_t currGMT;
time_t aircraftLocalTime;
GeoCoord location( RAD_TO_DEG * lat, RAD_TO_DEG * lon );
GeoCoord* nearestTz = tzContainer->getNearest(location);
FGPath zone( root );
zone.append ("Timezone" );
zone.append ( nearestTz->getDescription() );
if ( zonename ) {
delete zonename;
}
zonename = strdup( zone.c_str() );
currGMT = get_gmt( gmtime(&cur_time) );
aircraftLocalTime = get_gmt( (fgLocaltime(&cur_time, zone.c_str())) );
localOffset = aircraftLocalTime - currGMT;
// cerr << "Using " << localOffset << " as local time offset Timezone is "
// << zonename << endl;
}
// Initialize the time dependent variables (maybe I'll put this in the
// constructor later)
void FGTime::init( double lon, double lat, const string& root,
time_t timeOffset, sgTimingOffsetType offsetType )
{
FG_LOG( FG_EVENT, FG_INFO, "Initializing Time" );
gst_diff = -9999.0;
FG_LOG( FG_EVENT, FG_DEBUG,
"time offset = " << timeOffset );
// time_t timeOffset = current_options.get_time_offset();
// int offsetType = current_options.get_time_offset_type();
time_t currGMT;
time_t systemLocalTime;
time_t aircraftLocalTime;
// would it be better to put these sanity checks in the options
// parsing code? (CLO)
cur_time = time(NULL);
// printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
// printf ("Current local time = %24s", asctime(localtime(&cur_time)));
// time_t tmp = cur_time;
GeoCoord location( RAD_TO_DEG * lat, RAD_TO_DEG * lon );
GeoCoord* nearestTz = tzContainer->getNearest(location);
FGPath zone( root );
zone.append( "Timezone" );
zone.append( nearestTz->getDescription() );
// printf("Using %s for timezone information\n", buffer);
zonename = strdup( zone.c_str() );
//show( buffer.c_str(), cur_time, 1);
//printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
//printf ("Current local time = %24s", asctime(localtime(&cur_time)));
currGMT = get_gmt( gmtime(&cur_time) );
systemLocalTime = get_gmt( localtime(&cur_time) );
aircraftLocalTime = get_gmt( fgLocaltime(&cur_time, zone.c_str()) );
//printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
//printf ("Current local time = %24s", asctime(localtime(&cur_time)));
//printf("LT = %d\n", computerLocalTime);
// Okay, in principle, this trick allows to calculate the
// difference between GMT and localtime, in seconds.
// printf("Gmt = %d, SLT = %d, (difference = %d)\n", currGMT, systemLocalTime, (currGMT - systemLocalTime));
// printf("Gmt = %d, ALT = %d, (difference = %d)\n", currGMT, aircraftLocalTime, (currGMT - aircraftLocalTime));
// exit(1);
// Okay, we now have six possible scenarios
switch (offsetType)
{
case SG_TIME_SYS_OFFSET:
warp = timeOffset;
break;
case SG_TIME_GMT_OFFSET:
warp = timeOffset - (currGMT - systemLocalTime);
break;
case SG_TIME_LAT_OFFSET:
// warp = timeOffset - (currGMT - systemLocalTime +
// (currGMT - aircraftLocalTime));
warp = timeOffset - (aircraftLocalTime - systemLocalTime);
break;
case SG_TIME_SYS_ABSOLUTE:
warp = timeOffset - cur_time;
//printf("warp = %d\n", warp);
break;
case SG_TIME_GMT_ABSOLUTE:
warp = timeOffset - currGMT;
break;
case SG_TIME_LAT_ABSOLUTE:
warp = timeOffset - (aircraftLocalTime - systemLocalTime) -
cur_time;
break;
default:
printf("Unsupported type\n");
exit(1);
}
warp_delta = 0;
// pause = current_options.get_pause();
}
// given a date in months, mn, days, dy, years, yr, return the
// modified Julian date (number of days elapsed since 1900 jan 0.5),
// mjd. Adapted from Xephem.
void FGTime::cal_mjd (int mn, double dy, int yr)
{
//static double last_mjd, last_dy;
//double mjd;
//static int last_mn, last_yr;
int b, d, m, y;
long c;
if (mn == last_mn && yr == last_yr && dy == last_dy) {
mjd = last_mjd;
//return(mjd);
}
m = mn;
y = (yr < 0) ? yr + 1 : yr;
if (mn < 3) {
m += 12;
y -= 1;
}
if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
b = 0;
} else {
int a;
a = y/100;
b = 2 - a + a/4;
}
if (y < 0) {
c = (long)((365.25*y) - 0.75) - 694025L;
} else {
c = (long)(365.25*y) - 694025L;
}
d = (int)(30.6001*(m+1));
mjd = b + c + d + dy - 0.5;
last_mn = mn;
last_dy = dy;
last_yr = yr;
last_mjd = mjd;
//return(mjd);
}
// given an mjd, calculate greenwich mean sidereal time, gst
void FGTime::utc_gst ()
{
double day = floor(mjd-0.5)+0.5;
double hr = (mjd-day)*24.0;
double T, x;
T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
x /= 3600.0;
gst = (1.0/SIDRATE)*hr + x;
FG_LOG( FG_EVENT, FG_DEBUG, " gst => " << gst );
}
// given Julian Date and Longitude (decimal degrees West) compute
// Local Sidereal Time, in decimal hours.
//
// Provided courtesy of ecdowney@noao.edu (Elwood Downey)
double FGTime::sidereal_precise (double lng)
{
double lstTmp;
/* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ",
mjd + MJD0, lng); */
// convert to required internal units
lng *= DEG_TO_RAD;
// compute LST and print
utc_gst();
lstTmp = gst - RADHR (lng);
lstTmp -= 24.0*floor(lstTmp/24.0);
// printf ("%7.4f\n", lstTmp);
// that's all
return (lstTmp);
}
// return a courser but cheaper estimate of sidereal time
double FGTime::sidereal_course(double lng)
{
//struct tm *gmt;
//double lstTmp;
time_t start_gmt, now;
double diff, part, days, hours, lstTmp;
char tbuf[64];
//gmt = t->gmt;
//now = t->cur_time;
now = cur_time;
start_gmt = get_gmt(gmt->tm_year, 2, 21, 12, 0, 0);
FG_LOG( FG_EVENT, FG_DEBUG, " COURSE: GMT = " << format_time(gmt, tbuf) );
FG_LOG( FG_EVENT, FG_DEBUG, " March 21 noon (GMT) = " << start_gmt );
diff = (now - start_gmt) / (3600.0 * 24.0);
FG_LOG( FG_EVENT, FG_DEBUG,
" Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
part = fmod(diff, 1.0);
days = diff - part;
hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
lstTmp = (days - lng)/15.0 + hours - 12;
while ( lstTmp < 0.0 ) {
lstTmp += 24.0;
}
FG_LOG( FG_EVENT, FG_DEBUG,
" days = " << days << " hours = " << hours << " lon = "
<< lng << " lst = " << lstTmp );
return(lstTmp);
}
// Update time variables such as gmt, julian date, and sidereal time
void FGTime::update( double lon, double lat, double alt_m ) {
double gst_precise, gst_course;
FG_LOG( FG_EVENT, FG_DEBUG, "Updating time" );
// get current Unix calendar time (in seconds)
warp += warp_delta;
cur_time = time(NULL) + warp;
FG_LOG( FG_EVENT, FG_DEBUG,
" Current Unix calendar time = " << cur_time
<< " warp = " << warp << " delta = " << warp_delta );
#if 0
if ( warp_delta ) {
// time is changing so force an update
local_update_sky_and_lighting_params();
}
#endif
// get GMT break down for current time
gmt = gmtime(&cur_time);
FG_LOG( FG_EVENT, FG_DEBUG,
" Current GMT = " << gmt->tm_mon+1 << "/"
<< gmt->tm_mday << "/" << gmt->tm_year << " "
<< gmt->tm_hour << ":" << gmt->tm_min << ":"
<< gmt->tm_sec );
// calculate modified Julian date
// t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday,
// (int)(t->gmt->tm_year + 1900));
cal_mjd ((int)(gmt->tm_mon+1), (double)gmt->tm_mday,
(int)(gmt->tm_year + 1900));
// add in partial day
mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
(gmt->tm_sec / (24.0 * 60.0 * 60.0));
// convert "back" to Julian date + partial day (as a fraction of one)
jd = mjd + MJD0;
FG_LOG( FG_EVENT, FG_DEBUG, " Current Julian Date = " << jd );
// printf(" Current Longitude = %.3f\n", FG_Longitude * RAD_TO_DEG);
// Calculate local side real time
if ( gst_diff < -100.0 ) {
// first time through do the expensive calculation & cheap
// calculation to get the difference.
FG_LOG( FG_EVENT, FG_INFO, " First time, doing precise gst" );
gst_precise = gst = sidereal_precise(0.00);
gst_course = sidereal_course(0.00);
gst_diff = gst_precise - gst_course;
lst = sidereal_course(-(lon * RAD_TO_DEG)) + gst_diff;
} else {
// course + difference should drift off very slowly
gst = sidereal_course( 0.00 ) + gst_diff;
lst = sidereal_course( -(lon * RAD_TO_DEG)) + gst_diff;
}
FG_LOG( FG_EVENT, FG_DEBUG,
" Current lon=0.00 Sidereal Time = " << gst );
FG_LOG( FG_EVENT, FG_DEBUG,
" Current LOCAL Sidereal Time = " << lst << " ("
<< sidereal_precise(-(lon * RAD_TO_DEG))
<< ") (diff = " << gst_diff << ")" );
}
/******************************************************************
* The following are some functions that were included as FGTime
* members, although they currently don't make use of any of the
* class's variables. Maybe this'll change in the future
*****************************************************************/
// Return time_t for Sat Mar 21 12:00:00 GMT
//
// On many systems it is ambiguous if mktime() assumes the input is in
// GMT, or local timezone. To address this, a new function called
// timegm() is appearing. It works exactly like mktime() but
// explicitely interprets the input as GMT.
//
// timegm() is available and documented under FreeBSD. It is
// available, but completely undocumented on my current Debian 2.1
// distribution.
//
// In the absence of timegm() we have to guess what mktime() might do.
//
// Many older BSD style systems have a mktime() that assumes the input
// time in GMT. But FreeBSD explicitly states that mktime() assumes
// local time zone
//
// The mktime() on many SYSV style systems (such as Linux) usually
// returns its result assuming you have specified the input time in
// your local timezone. Therefore, in the absence if timegm() you
// have to go to extra trouble to convert back to GMT.
//
// If you are having problems with incorrectly positioned astronomical
// bodies, this is a really good place to start looking.
time_t FGTime::get_gmt(int year, int month, int day, int hour, int min, int sec)
{
struct tm mt;
mt.tm_mon = month;
mt.tm_mday = day;
mt.tm_year = year;
mt.tm_hour = hour;
mt.tm_min = min;
mt.tm_sec = sec;
mt.tm_isdst = -1; // let the system determine the proper time zone
// For now we assume that if daylight is not defined in
// /usr/include/time.h that we have a machine with a mktime() that
// assumes input is in GMT ... this only matters if we are
// building on a system that does not have timegm()
#if !defined(HAVE_DAYLIGHT)
# define MK_TIME_IS_GMT 1
#endif
#if defined( HAVE_TIMEGM )
return ( timegm(&mt) );
#elif defined( MK_TIME_IS_GMT )
return ( mktime(&mt) );
#else // ! defined ( MK_TIME_IS_GMT )
// timezone seems to work as a proper offset for Linux & Solaris
# if defined( __linux__ ) || defined( __sun__ )
# define TIMEZONE_OFFSET_WORKS 1
# endif
long int start = mktime(&mt);
FG_LOG( FG_EVENT, FG_DEBUG, "start1 = " << start );
// the ctime() call can screw up time progression on some versions
// of Linux
// fgPrintf( FG_EVENT, FG_DEBUG, "start2 = %s", ctime(&start));
FG_LOG( FG_EVENT, FG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
timezone = fix_up_timezone( timezone );
# if defined( TIMEZONE_OFFSET_WORKS )
FG_LOG( FG_EVENT, FG_DEBUG,
"start = " << start << ", timezone = " << timezone );
return( start - timezone );
# else // ! defined( TIMEZONE_OFFSET_WORKS )
daylight = mt.tm_isdst;
if ( daylight > 0 ) {
daylight = 1;
} else if ( daylight < 0 ) {
FG_LOG( FG_EVENT, FG_WARN,
"OOOPS, problem in fg_time.cxx, no daylight savings info." );
}
long int offset = -(timezone / 3600 - daylight);
FG_LOG( FG_EVENT, FG_DEBUG, " Raw time zone offset = " << timezone );
FG_LOG( FG_EVENT, FG_DEBUG, " Daylight Savings = " << daylight );
FG_LOG( FG_EVENT, FG_DEBUG, " Local hours from GMT = " << offset );
long int start_gmt = start - timezone + (daylight * 3600);
FG_LOG( FG_EVENT, FG_DEBUG, " March 21 noon (CST) = " << start );
return ( start_gmt );
# endif // ! defined( TIMEZONE_OFFSET_WORKS )
#endif // ! defined ( MK_TIME_IS_GMT )
}
// Fix up timezone if using ftime()
long int FGTime::fix_up_timezone( long int timezone_orig )
{
#if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
// ftime() needs a little extra help finding the current timezone
struct timeb current;
ftime(&current);
return( current.timezone * 60 );
#else
return( timezone_orig );
#endif
}
char* FGTime::format_time( const struct tm* p, char* buf )
{
sprintf( buf, "%d/%d/%2d %d:%02d:%02d",
p->tm_mon, p->tm_mday, p->tm_year,
p->tm_hour, p->tm_min, p->tm_sec);
return buf;
}
#if 0
// Force an update of the sky and lighting parameters
void FGTime::local_update_sky_and_lighting_params( void ) {
fgUpdateSunPos();
fgUpdateMoonPos();
cur_light_params.Update();
}
#endif
FGTime* FGTime::cur_time_params = 0;

169
simgear/timing/fg_time.hxx Normal file
View File

@@ -0,0 +1,169 @@
// fg_time.hxx -- data structures and routines for managing time related stuff.
//
// Written by Curtis Olson, started August 1997.
//
// Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$
#ifndef _FG_TIME_HXX
#define _FG_TIME_HXX
#ifndef __cplusplus
# error This library requires C++
#endif
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifdef HAVE_WINDOWS_H
# include <windows.h>
#endif
#include <GL/glut.h>
#include <simgear/compiler.h>
#ifdef FG_HAVE_STD_INCLUDES
# include <ctime>
#else
# include <time.h>
#endif
// #include <FDM/flight.hxx>
#include "timezone.h"
// #include "lowleveltime.h"
enum sgTimingOffsetType {
SG_TIME_SYS_OFFSET = 0,
SG_TIME_GMT_OFFSET = 1,
SG_TIME_LAT_OFFSET = 2,
SG_TIME_SYS_ABSOLUTE = 3,
SG_TIME_GMT_ABSOLUTE = 4,
SG_TIME_LAT_ABSOLUTE = 5
};
// Define a structure containing time parameters
class FGTime {
private:
// tzContainer stores all the current Timezone control points/
TimezoneContainer* tzContainer;
//Store the current local timezone name;
char *zonename;
// Unix "calendar" time in seconds
time_t cur_time;
// Break down of GMT time
struct tm *gmt;
// Julian date
double jd;
// modified Julian date
double mjd;
double last_mjd, last_dy;
int last_mn, last_yr;
// side real time at prime meridian
double gst;
// local sidereal time
double lst;
// local offset to GMT
time_t localOffset;
// the difference between the precise sidereal time algorithm
// result and the course result. course + diff has good accuracy
// for the short term
double gst_diff;
// An offset in seconds from the true time. Allows us to adjust
// the effective time of day.
long int warp;
// How much to change the value of warp each iteration. Allows us
// to make time progress faster than normal.
long int warp_delta;
public:
FGTime( const string& root );
~FGTime();
inline double getJD() const { return jd; };
inline double getMjd() const { return mjd; };
inline double getLst() const { return lst; };
inline double getGst() const { return gst; };
inline time_t get_cur_time() const { return cur_time; };
inline struct tm* getGmt()const { return gmt; };
void adjust_warp(int val) { warp += val; };
void adjust_warp_delta(int val) { warp_delta += val; };
// Initialize the time dependent variables
void init( double lon, double lat, const string& root,
time_t timeOffset, sgTimingOffsetType offsetType );
// Update the time dependent variables
void update( double lon, double lat, double alt_m );
void updateLocal( double lon, double lat, const string& root );
void cal_mjd (int mn, double dy, int yr);
void utc_gst();
double sidereal_precise (double lng);
double sidereal_course(double lng);
static FGTime *cur_time_params;
// Some other stuff which were changed to FGTime members on
// questionable grounds -:)
// time_t get_start_gmt(int year);
time_t get_gmt(int year, int month, int day,
int hour, int minute, int second);
time_t get_gmt(struct tm* the_time);
char* format_time( const struct tm* p, char* buf );
long int fix_up_timezone( long int timezone_orig );
inline int get_warp_delta() const { return warp_delta; }
};
inline time_t FGTime::get_gmt(struct tm* the_time) // this is just a wrapper
{
//printf("Using: %24s as input\n", asctime(the_time));
return get_gmt(the_time->tm_year,
the_time->tm_mon,
the_time->tm_mday,
the_time->tm_hour,
the_time->tm_min,
the_time->tm_sec);
}
#endif // _FG_TIME_HXX

102
simgear/timing/geocoord.cxx Normal file
View File

@@ -0,0 +1,102 @@
/* -*- Mode: C++ -*- *****************************************************
* geocoord.h
* Written by Durk Talsma. Started March 1998.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
**************************************************************************/
/*************************************************************************
*
* This file defines a small and simple class to store geocentric
* coordinates. Basically, class GeoCoord is intended as a base class for
* any kind of of object, that can be categorized according to its
* location on earth, be it navaids, or aircraft. This class for originally
* written for FlightGear, in order to store Timezone control points.
*
************************************************************************/
#include "geocoord.h"
#include <plib/sg.h>
GeoCoord::GeoCoord(const GeoCoord& other)
{
lat = other.lat;
lon = other.lon;
}
// double GeoCoord::getAngle(const GeoCoord& other) const
// {
// Vector first( getX(), getY(), getZ());
// Vector secnd(other.getX(), other.getY(), other.getZ());
// double
// dot = VecDot(first, secnd),
// len1 = first.VecLen(),
// len2 = secnd.VecLen(),
// len = len1 * len2,
// angle = 0;
// //printf ("Dot: %f, len1: %f len2: %f\n", dot, len1, len2);
// /*Vector pPos = prevPos - Reference->prevPos;
// Vector pVel = prevVel - Reference->prevVel;*/
// if ( ( (dot / len) < 1) && (dot / len > -1) && len )
// angle = acos(dot / len);
// return angle;
// }
// GeoCoord* GeoCoordContainer::getNearest(const GeoCoord& ref) const
// {
// float angle, maxAngle = 180;
// GeoCoordVectorConstIterator i, nearest;
// for (i = data.begin(); i != data.end(); i++)
// {
// angle = RAD_TO_DEG * (*i)->getAngle(ref);
// if (angle < maxAngle)
// {
// maxAngle = angle;
// nearest = i;
// }
// }
// return *nearest;
// }
GeoCoord* GeoCoordContainer::getNearest(const GeoCoord& ref) const
{
sgVec3 first, secnd;
float dist, maxDist=SG_MAX;
sgSetVec3( first, ref.getX(), ref.getY(), ref.getZ());
GeoCoordVectorConstIterator i, nearest;
for (i = data.begin(); i != data.end(); i++)
{
sgSetVec3(secnd, (*i)->getX(), (*i)->getY(), (*i)->getZ());
dist = sgDistanceSquaredVec3(first, secnd);
if (dist < maxDist)
{
maxDist = dist;
nearest = i;
}
}
return *nearest;
}
GeoCoordContainer::~GeoCoordContainer()
{
GeoCoordVectorIterator i = data.begin();
while (i != data.end())
delete *i++;
}

98
simgear/timing/geocoord.h Normal file
View File

@@ -0,0 +1,98 @@
/* -*- Mode: C++ -*- *****************************************************
* geocoord.h
* Written by Durk Talsma. Started July 1999.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
**************************************************************************/
/*************************************************************************
*
* This file defines a small and simple class to store geocentric
* coordinates. Basically, class GeoCoord is intended as a base class for
* any kind of of object, that can be categorized according to its
* location on earth, be it navaids, or aircraft. This class for originally
* written for FlightGear, in order to store Timezone control points.
*
************************************************************************/
#ifndef _GEOCOORD_H_
#define _GEOCOORD_H_
#include <simgear/compiler.h>
#include <math.h>
#include <string>
#include STL_IOSTREAM
//#include <streambuf> // looks like streambuf does not exist on linux.
// But it looks like it isn't used anyways -:)
#include <vector>
FG_USING_NAMESPACE(std);
#include <simgear/constants.h>
class GeoCoord
{
protected:
float lat;
float lon;
public:
GeoCoord() { lat = 0.0; lon = 0.0;};
GeoCoord(float la, float lo) { lat = la; lon = lo;};
GeoCoord(const GeoCoord& other);
virtual ~GeoCoord() {};
void set(float la, float lo) { lat = la; lon = lo; };
float getLat() const { return lat; };
float getLon() const { return lon; };
float getX() const { return cos(DEG_TO_RAD*lat) * cos(DEG_TO_RAD*lon); };
float getY() const { return cos(DEG_TO_RAD*lat) * sin(DEG_TO_RAD*lon); };
float getZ() const { return sin(DEG_TO_RAD*lat); };
//double getAngle(const GeoCoord& other) const;
virtual void print() {} ;
virtual char *getDescription() {return 0;};
};
typedef vector<GeoCoord*> GeoCoordVector;
typedef vector<GeoCoord*>::iterator GeoCoordVectorIterator;
typedef vector<GeoCoord*>::const_iterator GeoCoordVectorConstIterator;
/************************************************************************
* GeoCoordContainer is a simple container class, that stores objects
* derived from GeoCoord. Basically, it is a wrapper around an STL vector,
* with some added functionality
***********************************************************************/
class GeoCoordContainer
{
protected:
GeoCoordVector data;
public:
GeoCoordContainer() {};
virtual ~GeoCoordContainer();
const GeoCoordVector& getData() const { return data; };
GeoCoord* getNearest(const GeoCoord& ref) const;
};
#endif // _GEO_COORD_H_

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,128 @@
/* -*- Mode: C++ -*- *****************************************************
* lowleveltime.h
* Written by various people (I"ll look up the exact credits later)
* Modified by Durk Talsma, July 1999 for use in FlightGear
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
**************************************************************************/
/********************************************************************
* This file redefines some low-level Unix-like time functions for *
* use with FlightGear. Most notably, localtime() is adapted to use *
* a custom timezone, in order to get the 'local' time for a given *
* aircraft's position, and not only for the current location of the*
* computer running the sim. *
* *
* Software adapted from glibc functions, by Durk Talsma. Started *
* July, 17, 1999. *
********************************************************************/
#ifndef _LOWLEVELTIME_H_
#define _LOWLEVELTIME_H_
#include <time.h>
/* adapted from zdump.c */
void show (const char *zone, time_t t, int v);
/* adapted from <time.h> */
struct tm * fgLocaltime (const time_t *t, const char *tzName);
/* Prototype for the internal function to get information based on TZ. */
extern struct tm *fgtz_convert (const time_t *t, int use_localtime,
struct tm *tp, const char *tzName);
/* This structure contains all the information about a
timezone given in the POSIX standard TZ envariable. */
typedef struct
{
const char *name;
/* When to change. */
enum { J0, J1, M } type; /* Interpretation of: */
unsigned short int m, n, d; /* Month, week, day. */
unsigned int secs; /* Time of day. */
long int offset; /* Seconds east of GMT (west if < 0). */
/* We cache the computed time of change for a
given year so we don't have to recompute it. */
time_t change; /* When to change to this zone. */
int computed_for; /* Year above is computed for. */
} fgtz_rule;
struct tzhead {
char tzh_magic[4]; /* TZ_MAGIC */
char tzh_reserved[16]; /* reserved for future use */
char tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */
char tzh_ttisstdcnt[4]; /* coded number of trans. time flags */
char tzh_leapcnt[4]; /* coded number of leap seconds */
char tzh_timecnt[4]; /* coded number of transition times */
char tzh_typecnt[4]; /* coded number of local time types */
char tzh_charcnt[4]; /* coded number of abbr. chars */
};
/* Defined in mktime.c. */
extern const unsigned short int mon_yday[2][13];
#ifndef TZDIR
#define TZDIR "/usr/local/etc/zoneinfo" /* Time zone object file directory */
#endif /* !defined TZDIR */
#ifndef TZDEFAULT
#define TZDEFAULT "localtime"
#endif /* !defined TZDEFAULT */
#define SECSPERMIN 60
#define MINSPERHOUR 60
#define HOURSPERDAY 24
#define DAYSPERWEEK 7
#define DAYSPERNYEAR 365
#define DAYSPERLYEAR 366
#define SECSPERHOUR (SECSPERMIN * MINSPERHOUR)
#define SECSPERDAY ((long) SECSPERHOUR * HOURSPERDAY)
#define MONSPERYEAR 12
#define TM_SUNDAY 0
#define TM_MONDAY 1
#define TM_TUESDAY 2
#define TM_WEDNESDAY 3
#define TM_THURSDAY 4
#define TM_FRIDAY 5
#define TM_SATURDAY 6
#define TM_JANUARY 0
#define TM_FEBRUARY 1
#define TM_MARCH 2
#define TM_APRIL 3
#define TM_MAY 4
#define TM_JUNE 5
#define TM_JULY 6
#define TM_AUGUST 7
#define TM_SEPTEMBER 8
#define TM_OCTOBER 9
#define TM_NOVEMBER 10
#define TM_DECEMBER 11
#define TM_YEAR_BASE 1900
#define EPOCH_YEAR 1970
#define EPOCH_WDAY TM_THURSDAY
#endif

147
simgear/timing/timezone.cxx Normal file
View File

@@ -0,0 +1,147 @@
/* -*- Mode: C++ -*- *****************************************************
* timezone.cc
* Written by Durk Talsma. Started July 1999.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
**************************************************************************/
/*************************************************************************
*
* Timezone is derived from geocoord, and stores the timezone centerpoint,
* as well as the countrycode and the timezone descriptor. The latter is
* used in order to get the local time.
*
************************************************************************/
#include <stdio.h>
#include "timezone.h"
Timezone::Timezone(float la, float lo, char* cc, char* desc) :
GeoCoord(la, lo)
{
countryCode = strdup(cc);
descriptor = strdup(desc);
}
/* Build a timezone object from a textline in zone.tab */
Timezone::Timezone(const char *infoString) :
GeoCoord()
{
int i = 0;
while (infoString[i] != '\t')
i++;
char buffer[128];
char latlon[128];
strncpy(buffer, infoString, i);
buffer[i] = 0;
countryCode = strdup(buffer);
i ++;
int start = i;
while (infoString[i] != '\t')
i++;
int size = i - start;
strncpy(latlon, (&infoString[start]), size);
latlon[size] = 0;
char sign;
sign = latlon[0];
strncpy(buffer, &latlon[1], 2);
lat = atof(buffer);
strncpy(buffer, &latlon[3], 2);
lat += (atof(buffer) / 60);
int nextPos;
if (strlen(latlon) > 12)
{
nextPos = 7;
strncpy(buffer, &latlon[5], 2);
lat += (atof(buffer) / 3600.0);
}
else
nextPos = 5;
if (sign == '-')
lat = -lat;
sign = latlon[nextPos];
nextPos++;
strncpy(buffer, &latlon[nextPos], 3);
lon = atof(buffer);
nextPos += 3;
strncpy(buffer, &latlon[nextPos], 2);
buffer[2] = 0;
lon += (atof(buffer) / 60);
if (strlen(latlon) > 12)
{
nextPos += 2;
strncpy(buffer, &latlon[nextPos], 2);
lon += (atof (buffer) / 3600.00);
}
if (sign == '-')
lon = -lon;
i ++;
start = i;
while (!((infoString[i] == '\t') || (infoString[i] == '\n')))
i++;
size = i - start;
strncpy(buffer, (&infoString[start]), size);
buffer[size] = 0;
descriptor = strdup(buffer);
}
/* the copy constructor */
Timezone::Timezone(const Timezone& other)
{
lat = other.getLat();
lon = other.getLon();
countryCode = strdup(other.countryCode);
descriptor = strdup(other.descriptor);
}
/********* Member functions for TimezoneContainer class ********/
TimezoneContainer::TimezoneContainer(const char *filename)
{
char buffer[256];
FILE* infile = fopen(filename, "r");
if (!(infile))
{
fprintf(stderr, "Unable to open file %s\n", filename);
exit(1);
}
else
{
while (1)
{
fgets(buffer, 256, infile);
if (feof(infile))
break;
for (int i = 0; i < 256; i++)
{
if (buffer[i] == '#')
buffer[i] = 0;
}
if (buffer[0])
{
data.push_back(new Timezone(buffer));
}
}
}
}
TimezoneContainer::~TimezoneContainer()
{
}

72
simgear/timing/timezone.h Normal file
View File

@@ -0,0 +1,72 @@
/* -*- Mode: C++ -*- *****************************************************
* timezone.h
* Written by Durk Talsma. Started July 1999.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
**************************************************************************/
/*************************************************************************
*
* Timezone is derived from geocoord, and stores the timezone centerpoint,
* as well as the countrycode and the timezone descriptor. The latter is
* used in order to get the local time.
*
************************************************************************/
#ifndef _TIMEZONE_H_
#define _TIMEZONE_H_
#include "geocoord.h"
#include <stdio.h>
class Timezone : public GeoCoord
{
private:
char* countryCode;
char* descriptor;
public:
Timezone() :
GeoCoord()
{
countryCode = 0;
descriptor = 0;
};
Timezone(float la, float lo, char* cc, char* desc);
Timezone(const char *infoString);
Timezone(const Timezone &other);
virtual ~Timezone() { delete [] countryCode; delete [] descriptor; };
virtual void print() { printf("%s", descriptor);};
virtual char * getDescription() { return descriptor; };
};
/************************************************************************
* Timezone container is derived from GeoCoordContainer, and has some
* added functionality.
************************************************************************/
class TimezoneContainer : public GeoCoordContainer
{
public:
TimezoneContainer(const char *filename);
virtual ~TimezoneContainer();
};
#endif // _TIMEZONE_H_