]> git.mxchange.org Git - flightgear.git/blob - src/Time/TimeManager.cxx
use http_proxy environment variable
[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   _adjustWarpOnUnfreeze = false;
62   
63   _maxDtPerFrame = fgGetNode("/sim/max-simtime-per-frame", true);
64   _clockFreeze = fgGetNode("/sim/freeze/clock", true);
65   _timeOverride = fgGetNode("/sim/time/cur-time-override", true);
66   _warp = fgGetNode("/sim/time/warp", true);
67   _warp->addChangeListener(this);
68   
69   _warpDelta = fgGetNode("/sim/time/warp-delta", true);
70   
71   _longitudeDeg = fgGetNode("/position/longitude-deg", true);
72   _latitudeDeg = fgGetNode("/position/latitude-deg", true);
73   
74   SGPath zone(globals->get_fg_root());
75   zone.append("Timezone");
76   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
77   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
78   
79   _impl = new SGTime(lon, lat, zone.str(), _timeOverride->getLongValue());
80   
81   _warpDelta->setIntValue(0);
82   
83   globals->get_event_mgr()->addTask("updateLocalTime", this,
84                             &TimeManager::updateLocalTime, 30*60 );
85   updateLocalTime();
86   
87   _impl->update(lon, lat, _timeOverride->getLongValue(),
88                _warp->getIntValue());
89   globals->set_time_params(_impl);
90     
91 // frame/update-rate counters
92   _frameRate = fgGetNode("/sim/frame-rate", true);
93   _lastFrameTime = 0;
94   _frameCount = 0;
95 }
96
97 void TimeManager::postinit()
98 {
99   initTimeOffset();
100 }
101
102 void TimeManager::reinit()
103 {
104   shutdown();
105   init();
106   postinit();
107 }
108
109 void TimeManager::shutdown()
110 {
111   _warp->removeChangeListener(this);
112   
113   globals->set_time_params(NULL);
114   delete _impl;
115   _impl = NULL;
116   _inited = false;
117   globals->get_event_mgr()->removeTask("updateLocalTime");
118 }
119
120 void TimeManager::valueChanged(SGPropertyNode* aProp)
121 {
122   if (aProp == _warp) {
123     if (_clockFreeze->getBoolValue()) {
124     // if the warp is changed manually while frozen, don't modify it when
125     // un-freezing - the user wants to unfreeze with exactly the warp
126     // they specified.
127       _adjustWarpOnUnfreeze = false;
128     }
129     
130     double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
131     double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
132     _impl->update(lon, lat,
133                    _timeOverride->getLongValue(),
134                    _warp->getIntValue());
135   }
136 }
137
138 void TimeManager::computeTimeDeltas(double& simDt, double& realDt)
139 {
140   // Update the elapsed time.
141   if (_firstUpdate) {
142     _lastStamp.stamp();
143     _firstUpdate = false;
144     _lastClockFreeze = _clockFreeze->getBoolValue();
145   }
146
147   bool scenery_loaded = fgGetBool("sim/sceneryloaded");
148   bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
149   
150   if (!wait_for_scenery) {
151     throttleUpdateRate();
152   }
153   else
154   {
155       // suppress framerate while initial scenery isn't loaded yet (splash screen still active) 
156       _lastFrameTime=0;
157       _frameCount = 0;
158   }
159   
160   SGTimeStamp currentStamp;
161   currentStamp.stamp();
162   double dt = (currentStamp - _lastStamp).toSecs();
163   
164 // Limit the time we need to spend in simulation loops
165 // That means, if the /sim/max-simtime-per-frame value is strictly positive
166 // you can limit the maximum amount of time you will do simulations for
167 // one frame to display. The cpu time spent in simulations code is roughly
168 // at least O(real_delta_time_sec). If this is (due to running debug
169 // builds or valgrind or something different blowing up execution times)
170 // larger than the real time you will no longer get any response
171 // from flightgear. This limits that effect. Just set to property from
172 // your .fgfsrc or commandline ...
173   double dtMax = _maxDtPerFrame->getDoubleValue();
174   if (0 < dtMax && dtMax < dt) {
175     dt = dtMax;
176   }
177   
178   int model_hz = fgGetInt("/sim/model-hz");
179   
180   SGSubsystemGroup* fdmGroup = 
181     globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
182   fdmGroup->set_fixed_update_time(1.0 / model_hz);
183   
184 // round the real time down to a multiple of 1/model-hz.
185 // this way all systems are updated the _same_ amount of dt.
186   dt += _dtRemainder;
187   int multiLoop = long(floor(dt * model_hz));
188   multiLoop = SGMisc<long>::max(0, multiLoop);
189   _dtRemainder = dt - double(multiLoop)/double(model_hz);
190   dt = double(multiLoop)/double(model_hz);
191
192   realDt = dt;
193   if (_clockFreeze->getBoolValue() || wait_for_scenery) {
194     simDt = 0;
195   } else {
196     simDt = dt;
197   }
198   
199   _lastStamp = currentStamp;
200   globals->inc_sim_time_sec(simDt);
201
202 // These are useful, especially for Nasal scripts.
203   fgSetDouble("/sim/time/delta-realtime-sec", realDt);
204   fgSetDouble("/sim/time/delta-sec", simDt);
205 }
206
207 void TimeManager::update(double dt)
208 {
209   bool freeze = _clockFreeze->getBoolValue();
210   time_t now = time(NULL);
211   
212   if (freeze) {
213     // clock freeze requested
214     if (_timeOverride->getLongValue() == 0) {
215       _timeOverride->setLongValue(now);
216       _adjustWarpOnUnfreeze = true;
217     }
218   } else {
219     // no clock freeze requested
220     if (_lastClockFreeze) {
221       if (_adjustWarpOnUnfreeze) {
222       // clock just unfroze, let's set warp as the difference
223       // between frozen time and current time so we don't get a
224       // time jump (and corresponding sky object and lighting
225       // jump.)
226         int adjust = _timeOverride->getLongValue() - now;
227         SG_LOG(SG_GENERAL, SG_INFO, "adjusting on un-freeze:" << adjust);
228         _warp->setIntValue(_warp->getIntValue() + adjust);
229       }
230       _timeOverride->setLongValue(0);
231     }
232     
233     int warpDelta = _warpDelta->getIntValue();
234     if (warpDelta != 0) {
235       _warp->setIntValue(_warp->getIntValue() + warpDelta);
236     }
237   }
238
239   _lastClockFreeze = freeze;
240   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
241   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
242   _impl->update(lon, lat,
243                _timeOverride->getLongValue(),
244                _warp->getIntValue());
245
246   computeFrameRate();
247 }
248
249 void TimeManager::computeFrameRate()
250 {
251   // Calculate frame rate average
252   if ((_impl->get_cur_time() != _lastFrameTime)) {
253     _frameRate->setIntValue(_frameCount);
254     _frameCount = 0;
255   }
256   
257   _lastFrameTime = _impl->get_cur_time();
258   ++_frameCount;
259 }
260
261 void TimeManager::throttleUpdateRate()
262 {
263   double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
264   SGTimeStamp currentStamp;
265   
266   // common case, no throttle requested
267   if (throttle_hz <= 0.0) {
268     return; // no-op
269   }
270   
271   double frame_us = 1000000.0 / throttle_hz;
272 #define FG_SLEEP_BASED_TIMING 1
273 #if defined(FG_SLEEP_BASED_TIMING)
274   // sleep based timing loop.
275   //
276   // Calling sleep, even usleep() on linux is less accurate than
277   // we like, but it does free up the cpu for other tasks during
278   // the sleep so it is desirable.  Because of the way sleep()
279   // is implemented in consumer operating systems like windows
280   // and linux, you almost always sleep a little longer than the
281   // requested amount.
282   //
283   // To combat the problem of sleeping too long, we calculate the
284   // desired wait time and shorten it by 2000us (2ms) to avoid
285   // [hopefully] over-sleep'ing.  The 2ms value was arrived at
286   // via experimentation.  We follow this up at the end with a
287   // simple busy-wait loop to get the final pause timing exactly
288   // right.
289   //
290   // Assuming we don't oversleep by more than 2000us, this
291   // should be a reasonable compromise between sleep based
292   // waiting, and busy waiting.
293
294   // sleep() will always overshoot by a bit so undersleep by
295   // 2000us in the hopes of never oversleeping.
296   frame_us -= 2000.0;
297   if ( frame_us < 0.0 ) {
298       frame_us = 0.0;
299   }
300   
301   currentStamp.stamp();
302
303   double elapsed_us = (currentStamp - _lastStamp).toUSecs();
304   if ( elapsed_us < frame_us ) {
305     double requested_us = frame_us - elapsed_us;
306  
307 #ifdef _WIN32
308     Sleep ((int)(requested_us / 1000.0)) ;
309 #else
310     usleep(requested_us) ;
311 #endif
312   }
313 #endif
314
315   // busy wait timing loop.
316   //
317   // This yields the most accurate timing.  If the previous
318   // ulMilliSecondSleep() call is omitted this will peg the cpu
319   // (which is just fine if FG is the only app you care about.)
320   currentStamp.stamp();
321   SGTimeStamp next_time_stamp = _lastStamp;
322   next_time_stamp += SGTimeStamp::fromSec(1e-6*frame_us);
323   while ( currentStamp < next_time_stamp ) {
324       currentStamp.stamp();
325   }
326 }
327
328 // periodic time updater wrapper
329 void TimeManager::updateLocalTime() 
330 {
331   SGPath zone(globals->get_fg_root());
332   zone.append("Timezone");
333   
334   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
335   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
336   
337   SG_LOG(SG_GENERAL, SG_INFO, "updateLocal(" << lon << ", " << lat << ", " << zone.str() << ")");
338   _impl->updateLocal(lon, lat, zone.str());
339 }
340
341 void TimeManager::initTimeOffset()
342 {
343   // Handle potential user specified time offsets
344   int orig_warp = _warp->getIntValue();
345   time_t cur_time = _impl->get_cur_time();
346   time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
347   time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
348   time_t aircraftLocalTime = 
349       sgTimeGetGMT( fgLocaltime(&cur_time, _impl->get_zonename() ) );
350     
351   // Okay, we now have several possible scenarios
352   int offset = fgGetInt("/sim/startup/time-offset");
353   string offset_type = fgGetString("/sim/startup/time-offset-type");
354   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
355   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
356   int warp = 0;
357   
358   if ( offset_type == "real" ) {
359       warp = 0;
360   } else if ( offset_type == "dawn" ) {
361       warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, true ); 
362   } else if ( offset_type == "morning" ) {
363      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, true ); 
364   } else if ( offset_type == "noon" ) {
365      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 0.0, true ); 
366   } else if ( offset_type == "afternoon" ) {
367     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 60.0, false );  
368   } else if ( offset_type == "dusk" ) {
369     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, false );
370   } else if ( offset_type == "evening" ) {
371     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 100.0, false );
372   } else if ( offset_type == "midnight" ) {
373     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 180.0, false );
374   } else if ( offset_type == "system-offset" ) {
375     warp = offset;
376     orig_warp = 0;
377   } else if ( offset_type == "gmt-offset" ) {
378     warp = offset - (currGMT - systemLocalTime);
379     orig_warp = 0;
380   } else if ( offset_type == "latitude-offset" ) {
381     warp = offset - (aircraftLocalTime - systemLocalTime);
382     orig_warp = 0;
383   } else if ( offset_type == "system" ) {
384     warp = offset - (systemLocalTime - currGMT) - cur_time;
385   } else if ( offset_type == "gmt" ) {
386       warp = offset - cur_time;
387   } else if ( offset_type == "latitude" ) {
388       warp = offset - (aircraftLocalTime - currGMT)- cur_time; 
389   } else {
390     SG_LOG( SG_GENERAL, SG_ALERT,
391           "TimeManager::initTimeOffset: unsupported offset: " << offset_type );
392      warp = 0;
393   }
394   
395   _warp->setIntValue( orig_warp + warp );
396
397   SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
398             << _warp->getIntValue() );
399 }