summaryrefslogtreecommitdiff
path: root/frame_counter.py
diff options
context:
space:
mode:
authordavidovski <david@sendula.com>2023-01-05 11:35:28 +0000
committerdavidovski <david@sendula.com>2023-01-05 11:35:28 +0000
commitb99dbb396c313f4b3130b566c0df42c10eec6084 (patch)
treeffd2bbebe47f66fd1c21000b371ebc897ef84e34 /frame_counter.py
Initial CommitHEADmain
Diffstat (limited to 'frame_counter.py')
-rw-r--r--frame_counter.py41
1 files changed, 41 insertions, 0 deletions
diff --git a/frame_counter.py b/frame_counter.py
new file mode 100644
index 0000000..a71f915
--- /dev/null
+++ b/frame_counter.py
@@ -0,0 +1,41 @@
+from sys import stderr
+from time import time
+
+
+class FrameCounter:
+ """Creates a main loop and ensures that the framerate is static"""
+
+ def __init__(self, canvas, target_fps):
+ """Initialise the frame counter
+
+ :param canvas: The canvas which to call after on
+ :param target_fps: The fps to aim to achieve
+ """
+ self.canvas = canvas
+ self.fps = target_fps
+ self.frame_time = 1 / target_fps
+ self.last_frame = time()
+
+ self.current_fps = 1
+
+ def next_frame(self, callback):
+ """Calculate when the next frame should be called
+
+ :param callback: function to call for the next frame
+ """
+ t = time()
+ ft = t - self.last_frame
+
+ delay = 0
+
+ if ft > self.frame_time:
+ if ft - self.frame_time > self.frame_time / 5:
+ print(
+ f"Help! Running {ft - self.frame_time} seconds behind!",
+ file=stderr)
+ else:
+ delay = self.frame_time - ft
+
+ self.canvas.after(int(delay*1000), callback)
+ self.current_fps = 1 / (delay+ft)
+ self.last_frame = t