1 module d2d.core.fpslimiter; 2 3 import core.thread; 4 import std.datetime; 5 6 /** 7 * Class for limiting your FPS. 8 * Examples: 9 * --- 10 * FPSLimiter limiter = new FPSLimiter(25); 11 * while(window.open) 12 * { 13 * window.clear(); 14 * // Draw and Update stuff 15 * window.display(); 16 * limiter.wait(); 17 * } 18 * --- 19 */ 20 class FPSLimiter 21 { 22 protected: 23 int _fps = 0; 24 int _skiphns = 0; 25 ulong _next = 0; 26 long _sleep = 0; 27 28 public: 29 /// Creates a new FPS Limiter instance with specified max FPS. 30 this(int maxFPS) 31 { 32 _fps = maxFPS; 33 _skiphns = 10_000_000 / _fps; 34 _next = Clock.currStdTime(); 35 } 36 37 /// Calculates how long to wait and then waits that amount of time to ensure the target FPS. 38 void wait() 39 { 40 _next += _skiphns; 41 _sleep = _next - Clock.currStdTime(); 42 if (_sleep > 0) 43 { 44 Thread.sleep(dur!("hnsecs")(_sleep)); 45 } 46 } 47 }