]> git.mxchange.org Git - flightgear.git/blob - src/Time/TimeManager.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[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 #include <simgear/timing/sg_time.hxx>
28 #include <simgear/structure/event_mgr.hxx>
29 #include <simgear/misc/sg_path.hxx>
30 #include <simgear/timing/lowleveltime.h>
31 #include <simgear/structure/commands.hxx>
32
33 #include <Main/fg_props.hxx>
34 #include <Main/globals.hxx>
35 #include <Time/sunsolver.hxx>
36
37 using std::string;
38
39 static bool do_timeofday (const SGPropertyNode * arg)
40 {
41     const string &offset_type = arg->getStringValue("timeofday", "noon");
42     int offset = arg->getIntValue("offset", 0);
43     TimeManager* self = (TimeManager*) globals->get_subsystem("time");
44     if (offset_type == "real") {
45     // without this, setting 'real' time is a no-op, since the current
46     // wrap value (orig_warp) is retained in setTimeOffset. Ick.
47         fgSetInt("/sim/time/warp", 0);
48     }
49     
50     self->setTimeOffset(offset_type, offset);
51     return true;
52 }
53
54 TimeManager::TimeManager() :
55   _inited(false),
56   _impl(NULL)
57 {
58   SGCommandMgr::instance()->addCommand("timeofday", do_timeofday);
59 }
60
61 void TimeManager::init()
62 {
63   if (_inited) {
64     // time manager has to be initialised early, so needs to be defensive
65     // about multiple initialisation 
66     return; 
67   }
68   
69   _firstUpdate = true;
70   _inited = true;
71   _dtRemainder = 0.0;
72   _adjustWarpOnUnfreeze = false;
73   
74   _maxDtPerFrame = fgGetNode("/sim/max-simtime-per-frame", true);
75   _clockFreeze = fgGetNode("/sim/freeze/clock", true);
76   _timeOverride = fgGetNode("/sim/time/cur-time-override", true);
77   _warp = fgGetNode("/sim/time/warp", true);
78   _warp->addChangeListener(this);
79   
80   _warpDelta = fgGetNode("/sim/time/warp-delta", true);
81   
82   _longitudeDeg = fgGetNode("/position/longitude-deg", true);
83   _latitudeDeg = fgGetNode("/position/latitude-deg", true);
84   
85   SGPath zone(globals->get_fg_root());
86   zone.append("Timezone");
87   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
88   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
89   
90   _impl = new SGTime(lon, lat, zone.str(), _timeOverride->getLongValue());
91   
92   _warpDelta->setIntValue(0);
93   
94   globals->get_event_mgr()->addTask("updateLocalTime", this,
95                             &TimeManager::updateLocalTime, 30*60 );
96   updateLocalTime();
97   
98   _impl->update(lon, lat, _timeOverride->getLongValue(),
99                _warp->getIntValue());
100   globals->set_time_params(_impl);
101     
102   // frame-rate / worst-case latency / update-rate counters
103   _frameRate = fgGetNode("/sim/frame-rate", true);
104   _frameLatency = fgGetNode("/sim/frame-latency-max-ms", true);
105   _lastFrameTime = 0;
106   _frameLatencyMax = 0.0;
107   _frameCount = 0;
108 }
109
110 void TimeManager::postinit()
111 {
112   initTimeOffset();
113 }
114
115 void TimeManager::reinit()
116 {
117   shutdown();
118   init();
119   postinit();
120 }
121
122 void TimeManager::shutdown()
123 {
124   _warp->removeChangeListener(this);
125   
126   globals->set_time_params(NULL);
127   delete _impl;
128   _impl = NULL;
129   _inited = false;
130   globals->get_event_mgr()->removeTask("updateLocalTime");
131 }
132
133 void TimeManager::valueChanged(SGPropertyNode* aProp)
134 {
135   if (aProp == _warp) {
136     if (_clockFreeze->getBoolValue()) {
137     // if the warp is changed manually while frozen, don't modify it when
138     // un-freezing - the user wants to unfreeze with exactly the warp
139     // they specified.
140       _adjustWarpOnUnfreeze = false;
141     }
142     
143     double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
144     double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
145     _impl->update(lon, lat,
146                    _timeOverride->getLongValue(),
147                    _warp->getIntValue());
148   }
149 }
150
151 void TimeManager::computeTimeDeltas(double& simDt, double& realDt)
152 {
153   // Update the elapsed time.
154   if (_firstUpdate) {
155     _lastStamp.stamp();
156     _firstUpdate = false;
157     _lastClockFreeze = _clockFreeze->getBoolValue();
158   }
159
160   bool scenery_loaded = fgGetBool("sim/sceneryloaded");
161   bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
162   
163   if (!wait_for_scenery) {
164     throttleUpdateRate();
165   }
166   else
167   {
168       // suppress framerate while initial scenery isn't loaded yet (splash screen still active) 
169       _lastFrameTime=0;
170       _frameCount = 0;
171   }
172   
173   SGTimeStamp currentStamp;
174   currentStamp.stamp();
175   double dt = (currentStamp - _lastStamp).toSecs();
176   if (dt > _frameLatencyMax)
177       _frameLatencyMax = dt;
178
179 // Limit the time we need to spend in simulation loops
180 // That means, if the /sim/max-simtime-per-frame value is strictly positive
181 // you can limit the maximum amount of time you will do simulations for
182 // one frame to display. The cpu time spent in simulations code is roughly
183 // at least O(real_delta_time_sec). If this is (due to running debug
184 // builds or valgrind or something different blowing up execution times)
185 // larger than the real time you will no longer get any response
186 // from flightgear. This limits that effect. Just set to property from
187 // your .fgfsrc or commandline ...
188   double dtMax = _maxDtPerFrame->getDoubleValue();
189   if (0 < dtMax && dtMax < dt) {
190     dt = dtMax;
191   }
192   
193   int model_hz = fgGetInt("/sim/model-hz");
194   
195   SGSubsystemGroup* fdmGroup = 
196     globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
197   fdmGroup->set_fixed_update_time(1.0 / model_hz);
198   
199 // round the real time down to a multiple of 1/model-hz.
200 // this way all systems are updated the _same_ amount of dt.
201   dt += _dtRemainder;
202   int multiLoop = long(floor(dt * model_hz));
203   multiLoop = SGMisc<long>::max(0, multiLoop);
204   _dtRemainder = dt - double(multiLoop)/double(model_hz);
205   dt = double(multiLoop)/double(model_hz);
206
207   realDt = dt;
208   if (_clockFreeze->getBoolValue() || wait_for_scenery) {
209     simDt = 0;
210   } else {
211     simDt = dt;
212   }
213   
214   _lastStamp = currentStamp;
215   globals->inc_sim_time_sec(simDt);
216
217 // These are useful, especially for Nasal scripts.
218   fgSetDouble("/sim/time/delta-realtime-sec", realDt);
219   fgSetDouble("/sim/time/delta-sec", simDt);
220 }
221
222 void TimeManager::update(double dt)
223 {
224   bool freeze = _clockFreeze->getBoolValue();
225   time_t now = time(NULL);
226   
227   if (freeze) {
228     // clock freeze requested
229     if (_timeOverride->getLongValue() == 0) {
230       _timeOverride->setLongValue(now);
231       _adjustWarpOnUnfreeze = true;
232     }
233   } else {
234     // no clock freeze requested
235     if (_lastClockFreeze) {
236       if (_adjustWarpOnUnfreeze) {
237       // clock just unfroze, let's set warp as the difference
238       // between frozen time and current time so we don't get a
239       // time jump (and corresponding sky object and lighting
240       // jump.)
241         int adjust = _timeOverride->getLongValue() - now;
242         SG_LOG(SG_GENERAL, SG_INFO, "adjusting on un-freeze:" << adjust);
243         _warp->setIntValue(_warp->getIntValue() + adjust);
244       }
245       _timeOverride->setLongValue(0);
246     }
247     
248     int warpDelta = _warpDelta->getIntValue();
249     if (warpDelta != 0) {
250       _warp->setIntValue(_warp->getIntValue() + warpDelta);
251     }
252   }
253
254   _lastClockFreeze = freeze;
255   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
256   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
257   _impl->update(lon, lat,
258                _timeOverride->getLongValue(),
259                _warp->getIntValue());
260
261   computeFrameRate();
262 }
263
264 void TimeManager::computeFrameRate()
265 {
266   // Calculate frame rate average
267   if ((_impl->get_cur_time() != _lastFrameTime)) {
268     _frameRate->setIntValue(_frameCount);
269     _frameLatency->setDoubleValue(_frameLatencyMax*1000);
270     _frameCount = 0;
271     _frameLatencyMax = 0.0;
272   }
273   
274   _lastFrameTime = _impl->get_cur_time();
275   ++_frameCount;
276 }
277
278 void TimeManager::throttleUpdateRate()
279 {
280   // common case, no throttle requested
281   double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
282   if (throttle_hz <= 0)
283     return; // no-op
284
285   // sleep for exactly 1/hz seconds relative to the past valid timestamp
286   SGTimeStamp::sleepUntil(_lastStamp + SGTimeStamp::fromSec(1/throttle_hz));
287 }
288
289 // periodic time updater wrapper
290 void TimeManager::updateLocalTime() 
291 {
292   SGPath zone(globals->get_fg_root());
293   zone.append("Timezone");
294   
295   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
296   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
297   
298   SG_LOG(SG_GENERAL, SG_INFO, "updateLocal(" << lon << ", " << lat << ", " << zone.str() << ")");
299   _impl->updateLocal(lon, lat, zone.str());
300 }
301
302 void TimeManager::initTimeOffset()
303 {
304
305   long int offset = fgGetLong("/sim/startup/time-offset");
306   string offset_type = fgGetString("/sim/startup/time-offset-type");
307   setTimeOffset(offset_type, offset);
308 }
309
310 void TimeManager::setTimeOffset(const std::string& offset_type, long int offset)
311 {
312   // Handle potential user specified time offsets
313   int orig_warp = _warp->getIntValue();
314   time_t cur_time = _impl->get_cur_time();
315   time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
316   time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
317   time_t aircraftLocalTime = 
318       sgTimeGetGMT( fgLocaltime(&cur_time, _impl->get_zonename() ) );
319     
320   // Okay, we now have several possible scenarios
321   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
322   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
323   int warp = 0;
324   
325   if ( offset_type == "real" ) {
326       warp = 0;
327   } else if ( offset_type == "dawn" ) {
328       warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, true ); 
329   } else if ( offset_type == "morning" ) {
330      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, true ); 
331   } else if ( offset_type == "noon" ) {
332      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 0.0, true ); 
333   } else if ( offset_type == "afternoon" ) {
334     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, false );  
335   } else if ( offset_type == "dusk" ) {
336     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, false );
337   } else if ( offset_type == "evening" ) {
338     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 100.0, false );
339   } else if ( offset_type == "midnight" ) {
340     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 180.0, false );
341   } else if ( offset_type == "system-offset" ) {
342     warp = offset;
343     orig_warp = 0;
344   } else if ( offset_type == "gmt-offset" ) {
345     warp = offset - (currGMT - systemLocalTime);
346     orig_warp = 0;
347   } else if ( offset_type == "latitude-offset" ) {
348     warp = offset - (aircraftLocalTime - systemLocalTime);
349     orig_warp = 0;
350   } else if ( offset_type == "system" ) {
351     warp = offset - (systemLocalTime - currGMT) - cur_time;
352   } else if ( offset_type == "gmt" ) {
353       warp = offset - cur_time;
354   } else if ( offset_type == "latitude" ) {
355       warp = offset - (aircraftLocalTime - currGMT)- cur_time; 
356   } else {
357     SG_LOG( SG_GENERAL, SG_ALERT,
358           "TimeManager::setTimeOffset: unsupported offset: " << offset_type );
359      warp = 0;
360   }
361   
362   _warp->setIntValue( orig_warp + warp );
363
364   SG_LOG( SG_GENERAL, SG_INFO, "After TimeManager::setTimeOffset(): warp = " 
365             << _warp->getIntValue() );
366 }