Search code examples
haxekha

How to display the real frame rate in kha?


I started experimenting with kha on haxe, and compiled a sample project for my aged iPad2.

Now I wonder how to display the actual framerate on screen.

As a starting point I found this repo:

https://github.com/lewislepton/kha-tutorial-series/blob/master/007_fontText

It loads a font and displays some text on screen. It also sets the framerate to 60fps.

So now I just need to calulate the fps and display it via drawString.

But how to calculate it?

EDIT:

Thanks to @RobDangerous this seems to work:

package;

import kha.Framebuffer;
import kha.Color;
import kha.Assets;
import kha.input.Surface;
import kha.Font;
import kha.Scheduler;
import Std;


class Project {

    public var font:Font;

    public var previousRealTime:Float;
    public var realTime:Float;

    public function new() {
        font             = Assets.fonts.OpenSans;

        previousRealTime = 0.0;
        realTime         = 0.0;

        Surface.get().notify(onTouchDown, onTouchUp, onTouchMove);
    }

    public function update():Void {
        previousRealTime = realTime;
        realTime = Scheduler.realTime();
    }

    public function render(framebuffer:Framebuffer):Void {
        var graphics = framebuffer.g2;
        graphics.begin();

        var fps = 1.0 / ( realTime - previousRealTime );
        graphics.font = font;
        graphics.fontSize = 32;
        graphics.color = Color.White;
        graphics.drawString(Std.string(fps), 10, 10);

        graphics.end();
    }

    // ...
}

Solution

  • You can use Scheduler.realTime to get the actual, real time (Scheduler.time in contrast is a smoothed time value optimized for fluid animations). You can put realTime into a variable in one frame (aka in a render callback) and subtract it from realTime in the next frame to get your frame time in seconds. Invert it to get your fps.