cd30e83c74dabdbbd22d581a41f210d0d044a924
[nit.git] / lib / mnit / mnit_fps.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Frame-rate control for applications
16 module mnit_fps
17
18 import mnit_app
19 private import realtime
20
21 redef class App
22 # Limit the frame-rate to a given frequency
23 # This basically limits how much `frame_core` is called per second.
24 # Zero (or a negative value) means no limit.
25 #
26 # Applications can modify this value even during the main-loop.
27 var maximum_fps writable = 60
28
29 # Current frame-rate
30 # Updated each 5 seconds.
31 var current_fps = 0.0
32
33 redef fun full_frame
34 do
35 super
36 limit_fps
37 end
38
39 # The clock for limit_fps
40 private var clock = new Clock
41
42 # Number of frames since the last deadline
43 # Used tocompute `current_fps`.
44 private var frame_count = 0
45
46 # Deadline used to compute `current_fps`
47 private var frame_count_deadline = 0
48
49 # Check and sleep to maitain a frame-rate bellow `maximum_fps`
50 # Also periodically uptate `current_fps`
51 # Is automatically called at the end of `full_frame`.
52 fun limit_fps
53 do
54 var t = clock.total.sec
55 if t >= frame_count_deadline then
56 var cfps = frame_count_deadline.to_f / 5.0
57 self.current_fps = cfps
58 frame_count = 0
59 frame_count_deadline = t + 5
60 end
61 frame_count += 1
62
63 var mfps = maximum_fps
64 if mfps <= 0 then return
65 var dt = clock.lapse
66 var target_dt = 1000000000 / mfps
67 var sec = dt.sec
68 var nanosec = dt.nanosec
69 if sec == 0 and nanosec < target_dt then
70 var sleep_t = target_dt - nanosec
71 sys.nanosleep(0, sleep_t)
72 dt = clock.lapse
73 end
74 end
75 end