Skip to content

Instantly share code, notes, and snippets.

@blackbone
Last active August 1, 2023 17:47
Show Gist options
  • Save blackbone/bc4c683f6527e2933f2fd6a30efc2cb2 to your computer and use it in GitHub Desktop.
Save blackbone/bc4c683f6527e2933f2fd6a30efc2cb2 to your computer and use it in GitHub Desktop.
Fixed time step loop which gives millisecond precision.
/*
MIT License
Copyright (c) 2023 Dmytro Osipov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
namespace Blackbone.Extensions
{
public static class Extensions
{
public delegate bool TickDelegate(in long time, in double delta, out bool repeat);
public static void RunLoop(this object _, TickDelegate tickDelegate, uint rate, double duration = 0)
{
// prepare variables
var startTime = DateTime.UtcNow;
var nextUpdate = startTime;
double delta = 0;
ulong iterations = 0;
// loop while
while (true)
{
var time = ((DateTimeOffset)nextUpdate).ToUnixTimeMilliseconds();
// net event repeat block
REPEAT:
var run = tickDelegate(time, delta, out var repeat);
if (repeat)
goto REPEAT;
// end of repeatable block
if (!run) break;
// calculate timeout
iterations++;
var passedSeconds = iterations / rate;
var inSecTicks = iterations % rate;
var ne = startTime + TimeSpan.FromSeconds(passedSeconds) + TimeSpan.FromSeconds((double)inSecTicks / rate);
delta = (ne - nextUpdate).TotalMilliseconds;
nextUpdate = ne;
// check timer
if (duration > 0 && passedSeconds > duration)
run = false;
if (!run) break;
// check how much we need to wait
var timeToWait = nextUpdate - DateTime.UtcNow - TimeSpan.FromMilliseconds(delta);
if (timeToWait > TimeSpan.Zero) Thread.Sleep(timeToWait);
else Console.WriteLine("iteration took longer than needed");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment