From: Jean Privat Date: Mon, 16 Jun 2014 15:42:11 +0000 (-0400) Subject: lib/mnit: introduce mnit_fps so each app does not need to play with clocks X-Git-Tag: v0.6.6~5^2~12 X-Git-Url: http://nitlanguage.org lib/mnit: introduce mnit_fps so each app does not need to play with clocks Signed-off-by: Jean Privat --- diff --git a/lib/mnit/mnit.nit b/lib/mnit/mnit.nit index 3e313d4..53c4681 100644 --- a/lib/mnit/mnit.nit +++ b/lib/mnit/mnit.nit @@ -21,3 +21,4 @@ import mnit_app import opengles1 import assets import numbers +import mnit_fps diff --git a/lib/mnit/mnit_fps.nit b/lib/mnit/mnit_fps.nit new file mode 100644 index 0000000..38f0d48 --- /dev/null +++ b/lib/mnit/mnit_fps.nit @@ -0,0 +1,54 @@ +# This file is part of NIT ( http://www.nitlanguage.org ). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Frame-rate control for applications +module mnit_fps + +import mnit_app +private import realtime + +redef class App + # Limit the frame-rate to a given frequency + # This basically limits how much `frame_core` is called per second. + # Zero (or a negative value) means no limit. + # + # Applications can modify this value even during the main-loop. + var maximum_fps writable = 60 + + redef fun full_frame + do + super + limit_fps + end + + # The clock for limit_fps + private var clock = new Clock + + # Check and sleep to maitain a frame-rate bellow `maximum_fps` + # Is automatically called at the end of `full_frame`. + fun limit_fps + do + var mfps = maximum_fps + if mfps <= 0 then return + var dt = clock.lapse + var target_dt = 1000000000 / mfps + var sec = dt.sec + var nanosec = dt.nanosec + if sec == 0 and nanosec < target_dt then + var sleep_t = target_dt - nanosec + sys.nanosleep(0, sleep_t) + dt = clock.lapse + end + end +end