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