]> git.mxchange.org Git - flightgear.git/blob - src/Time/TimeManager.cxx
Merge commit 'refs/merge-requests/1551' of git://gitorious.org/fg/flightgear into...
[flightgear.git] / src / Time / TimeManager.cxx
1 // TimeManager.cxx -- simulation-wide time management
2 //
3 // Written by James Turner, started July 2010.
4 //
5 // Copyright (C) 2010  Curtis L. Olson  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 # include "config.h"
23 #endif
24
25 #include "TimeManager.hxx"
26
27 #ifdef _WIN32
28 #  define WIN32_LEAN_AND_MEAN
29 #  include <windows.h> // for Sleep()
30 #else
31 #  include <unistd.h> // for usleep()
32 #endif
33
34 #include <simgear/timing/sg_time.hxx>
35 #include <simgear/structure/event_mgr.hxx>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/timing/lowleveltime.h>
38
39 #include <Main/fg_props.hxx>
40 #include <Main/globals.hxx>
41 #include <Time/sunsolver.hxx>
42
43 TimeManager::TimeManager() :
44   _inited(false),
45   _impl(NULL)
46 {
47   
48 }
49
50 void TimeManager::init()
51 {
52   if (_inited) {
53     // time manager has to be initialised early, so needs to be defensive
54     // about multiple initialisation 
55     return; 
56   }
57   
58   _firstUpdate = true;
59   _inited = true;
60   _dtRemainder = 0.0;
61   
62   _maxDtPerFrame = fgGetNode("/sim/max-simtime-per-frame", true);
63   _clockFreeze = fgGetNode("/sim/freeze/clock", true);
64   _timeOverride = fgGetNode("/sim/time/cur-time-override", true);
65   
66   _longitudeDeg = fgGetNode("/position/longitude-deg", true);
67   _latitudeDeg = fgGetNode("/position/latitude-deg", true);
68   
69   SGPath zone(globals->get_fg_root());
70   zone.append("Timezone");
71   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
72   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
73   _impl = new SGTime(lon, lat, zone.str(), _timeOverride->getLongValue());
74   
75   globals->set_warp_delta(0);
76   
77   globals->get_event_mgr()->addTask("updateLocalTime", this,
78                             &TimeManager::updateLocalTime, 30*60 );
79   updateLocalTime();
80   
81   _impl->update(lon, lat, _timeOverride->getLongValue(),
82                globals->get_warp());
83   globals->set_time_params(_impl);
84     
85 // frame/update-rate counters
86   _frameRate = fgGetNode("/sim/frame-rate", true);
87   _lastFrameTime = _impl->get_cur_time();
88   _frameCount = 0;
89 }
90
91 void TimeManager::postinit()
92 {
93   initTimeOffset();
94 }
95
96 void TimeManager::reinit()
97 {
98   globals->set_time_params(NULL);
99   delete _impl;
100   _inited = false;
101   globals->get_event_mgr()->removeTask("updateLocalTime");
102   
103   init();
104   postinit();
105 }
106
107 void TimeManager::computeTimeDeltas(double& simDt, double& realDt)
108 {
109   // Update the elapsed time.
110   if (_firstUpdate) {
111     _lastStamp.stamp();
112     _firstUpdate = false;
113     _lastClockFreeze = _clockFreeze->getBoolValue();
114   }
115
116   bool scenery_loaded = fgGetBool("sim/sceneryloaded");
117   bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
118   
119   if (!wait_for_scenery) {
120     throttleUpdateRate();
121   }
122   
123   SGTimeStamp currentStamp;
124   currentStamp.stamp();
125   double dt = (currentStamp - _lastStamp).toSecs();
126   
127 // Limit the time we need to spend in simulation loops
128 // That means, if the /sim/max-simtime-per-frame value is strictly positive
129 // you can limit the maximum amount of time you will do simulations for
130 // one frame to display. The cpu time spent in simulations code is roughly
131 // at least O(real_delta_time_sec). If this is (due to running debug
132 // builds or valgrind or something different blowing up execution times)
133 // larger than the real time you will no longer get any response
134 // from flightgear. This limits that effect. Just set to property from
135 // your .fgfsrc or commandline ...
136   double dtMax = _maxDtPerFrame->getDoubleValue();
137   if (0 < dtMax && dtMax < dt) {
138     dt = dtMax;
139   }
140   
141   int model_hz = fgGetInt("/sim/model-hz");
142   
143   SGSubsystemGroup* fdmGroup = 
144     globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
145   fdmGroup->set_fixed_update_time(1.0 / model_hz);
146   
147 // round the real time down to a multiple of 1/model-hz.
148 // this way all systems are updated the _same_ amount of dt.
149   dt += _dtRemainder;
150   int multiLoop = long(floor(dt * model_hz));
151   multiLoop = SGMisc<long>::max(0, multiLoop);
152   _dtRemainder = dt - double(multiLoop)/double(model_hz);
153   dt = double(multiLoop)/double(model_hz);
154
155   realDt = dt;
156   if (_clockFreeze->getBoolValue() || wait_for_scenery) {
157     simDt = 0;
158   } else {
159     simDt = dt;
160   }
161   
162   _lastStamp = currentStamp;
163   globals->inc_sim_time_sec(simDt);
164
165 // These are useful, especially for Nasal scripts.
166   fgSetDouble("/sim/time/delta-realtime-sec", realDt);
167   fgSetDouble("/sim/time/delta-sec", simDt);
168 }
169
170 void TimeManager::update(double dt)
171 {
172   bool freeze = _clockFreeze->getBoolValue();
173   if (freeze) {
174     // clock freeze requested
175     if (_timeOverride->getLongValue() == 0) {
176       fgSetLong( "/sim/time/cur-time-override", _impl->get_cur_time());
177       globals->set_warp(0);
178     }
179   } else {
180     // no clock freeze requested
181     if (_lastClockFreeze) {
182     // clock just unfroze, let's set warp as the difference
183     // between frozen time and current time so we don't get a
184     // time jump (and corresponding sky object and lighting
185     // jump.)
186       globals->set_warp(_timeOverride->getLongValue() - time(NULL));
187       fgSetLong( "/sim/time/cur-time-override", 0 );
188     }
189     
190     if ( globals->get_warp_delta() != 0 ) {
191       globals->inc_warp( globals->get_warp_delta() );
192     }
193   }
194
195   _lastClockFreeze = freeze;
196   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
197   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
198   _impl->update(lon, lat,
199                _timeOverride->getLongValue(),
200                globals->get_warp());
201
202   computeFrameRate();
203 }
204
205 void TimeManager::computeFrameRate()
206 {
207   // Calculate frame rate average
208   if ((_impl->get_cur_time() != _lastFrameTime) && (_lastFrameTime > 0)) {
209     _frameRate->setIntValue(_frameCount);
210     _frameCount = 0;
211   }
212   
213   _lastFrameTime = _impl->get_cur_time();
214   ++_frameCount;
215 }
216
217 void TimeManager::throttleUpdateRate()
218 {
219   double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
220   SGTimeStamp currentStamp;
221   
222   // common case, no throttle requested
223   if (throttle_hz <= 0.0) {
224     return; // no-op
225   }
226   
227   double frame_us = 1000000.0 / throttle_hz;
228 #define FG_SLEEP_BASED_TIMING 1
229 #if defined(FG_SLEEP_BASED_TIMING)
230   // sleep based timing loop.
231   //
232   // Calling sleep, even usleep() on linux is less accurate than
233   // we like, but it does free up the cpu for other tasks during
234   // the sleep so it is desirable.  Because of the way sleep()
235   // is implemented in consumer operating systems like windows
236   // and linux, you almost always sleep a little longer than the
237   // requested amount.
238   //
239   // To combat the problem of sleeping too long, we calculate the
240   // desired wait time and shorten it by 2000us (2ms) to avoid
241   // [hopefully] over-sleep'ing.  The 2ms value was arrived at
242   // via experimentation.  We follow this up at the end with a
243   // simple busy-wait loop to get the final pause timing exactly
244   // right.
245   //
246   // Assuming we don't oversleep by more than 2000us, this
247   // should be a reasonable compromise between sleep based
248   // waiting, and busy waiting.
249
250   // sleep() will always overshoot by a bit so undersleep by
251   // 2000us in the hopes of never oversleeping.
252   frame_us -= 2000.0;
253   if ( frame_us < 0.0 ) {
254       frame_us = 0.0;
255   }
256   
257   currentStamp.stamp();
258
259   double elapsed_us = (currentStamp - _lastStamp).toUSecs();
260   if ( elapsed_us < frame_us ) {
261     double requested_us = frame_us - elapsed_us;
262  
263 #ifdef _WIN32
264     Sleep ((int)(requested_us / 1000.0)) ;
265 #else
266     usleep(requested_us) ;
267 #endif
268   }
269 #endif
270
271   // busy wait timing loop.
272   //
273   // This yields the most accurate timing.  If the previous
274   // ulMilliSecondSleep() call is omitted this will peg the cpu
275   // (which is just fine if FG is the only app you care about.)
276   currentStamp.stamp();
277   SGTimeStamp next_time_stamp = _lastStamp;
278   next_time_stamp += SGTimeStamp::fromSec(1e-6*frame_us);
279   while ( currentStamp < next_time_stamp ) {
280       currentStamp.stamp();
281   }
282 }
283
284 // periodic time updater wrapper
285 void TimeManager::updateLocalTime() 
286 {
287   SGPath zone(globals->get_fg_root());
288   zone.append("Timezone");
289   
290   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
291   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
292   
293   SG_LOG(SG_GENERAL, SG_INFO, "updateLocal(" << lon << ", " << lat << ", " << zone.str() << ")");
294   _impl->updateLocal(lon, lat, zone.str());
295 }
296
297 void TimeManager::initTimeOffset()
298 {
299   // Handle potential user specified time offsets
300   int orig_warp = globals->get_warp();
301   time_t cur_time = _impl->get_cur_time();
302   time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
303   time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
304   time_t aircraftLocalTime = 
305       sgTimeGetGMT( fgLocaltime(&cur_time, _impl->get_zonename() ) );
306     
307   // Okay, we now have several possible scenarios
308   int offset = fgGetInt("/sim/startup/time-offset");
309   string offset_type = fgGetString("/sim/startup/time-offset-type");
310   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
311   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
312   int warp = 0;
313   
314   if ( offset_type == "real" ) {
315       warp = 0;
316   } else if ( offset_type == "dawn" ) {
317       warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, true ); 
318   } else if ( offset_type == "morning" ) {
319      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, true ); 
320   } else if ( offset_type == "noon" ) {
321      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 0.0, true ); 
322   } else if ( offset_type == "afternoon" ) {
323     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 60.0, false );  
324   } else if ( offset_type == "dusk" ) {
325     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, false );
326   } else if ( offset_type == "evening" ) {
327     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 100.0, false );
328   } else if ( offset_type == "midnight" ) {
329     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 180.0, false );
330   } else if ( offset_type == "system-offset" ) {
331     warp = offset;
332     orig_warp = 0;
333   } else if ( offset_type == "gmt-offset" ) {
334     warp = offset - (currGMT - systemLocalTime);
335     orig_warp = 0;
336   } else if ( offset_type == "latitude-offset" ) {
337     warp = offset - (aircraftLocalTime - systemLocalTime);
338     orig_warp = 0;
339   } else if ( offset_type == "system" ) {
340     warp = offset - (systemLocalTime - currGMT) - cur_time;
341   } else if ( offset_type == "gmt" ) {
342       warp = offset - cur_time;
343   } else if ( offset_type == "latitude" ) {
344       warp = offset - (aircraftLocalTime - currGMT)- cur_time; 
345   } else {
346     SG_LOG( SG_GENERAL, SG_ALERT,
347           "TimeManager::initTimeOffset: unsupported offset: " << offset_type );
348      warp = 0;
349   }
350   
351   globals->set_warp( orig_warp + warp );
352   _impl->update(lon, lat, _timeOverride->getLongValue(),
353                globals->get_warp() );
354
355   SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
356             << globals->get_warp() );
357 }