@@ -188,30 +188,25 @@ void WbSimulationWorld::step() {
188188 if (WbSimulationState::instance ()->isRealTime ()) {
189189 const int elapsed = mRealTimeTimer .restart ();
190190
191- // computing the mean of an history of several elapsedTime
192- // improves significantly the stability of the algorithm
193- // in case of simulations where elapsedTime oscillates often
194- // above and below basicTimeStep.
191+ // How long should we have slept to be in real-time?
192+ double idealSleepTime = timeStep - (elapsed - mSleepRealTime );
193+ // Limit to timeStep to avoid weird behavior on large pauses (e.g., on startup)
194+ if (idealSleepTime > timeStep)
195+ idealSleepTime = timeStep;
196+ // computing the mean of an history of several time values
197+ // improves significantly the stability of the algorithm.
195198 // Moreover it improves the stability of simulations where
196199 // basicTimeStep contains significant decimals
197- mElapsedTimeHistory .append (elapsed );
198- if (mElapsedTimeHistory .size () > qMax (4.0 , 128.0 / timeStep)) // history size found empirically
199- mElapsedTimeHistory .pop_front ();
200+ mIdealSleepTimeHistory .append (idealSleepTime );
201+ if (mIdealSleepTimeHistory .size () > qMax (4.0 , 128.0 / timeStep)) // history size found empirically
202+ mIdealSleepTimeHistory .pop_front ();
200203 double mean = 0.0 ;
201- foreach (const int &v, mElapsedTimeHistory )
204+ foreach (const double &v, mIdealSleepTimeHistory )
202205 mean += v;
203- mean /= mElapsedTimeHistory .size ();
204-
205- // useful hack: uncomment to run Webots at 90% of the real-time
206- // (if the real-time mode is enabled, of course)
207- // mean *= 0.90;
208-
209- if (mean > timeStep && mSleepRealTime > 0.0 ) {
210- mSleepRealTime -= 0.03 * timeStep;
211- if (mSleepRealTime < 0 )
212- mSleepRealTime = 0.0 ;
213- } else if (mean < timeStep)
214- mSleepRealTime += 0.03 * timeStep;
206+ mean /= mIdealSleepTimeHistory .size ();
207+ mSleepRealTime = mean;
208+ if (mSleepRealTime < 0.0 )
209+ mSleepRealTime = 0.0 ;
215210
216211 mTimer ->start (mSleepRealTime );
217212 }
0 commit comments