/*автор GOAR*/

public class Lib_fps {

    public static int fps = 0;

    private static long lastTime = System.currentTimeMillis();
    private static float smoothedFps = 0.0f;
    private static long frameStart = System.currentTimeMillis();

    public static void count() {
        long currentTime = System.currentTimeMillis();
        long deltaTime = currentTime - lastTime;
        lastTime = currentTime;

        if (deltaTime > 0) {
            float instantFps = 1000.0f / deltaTime;

            if (smoothedFps == 0.0f) {
                smoothedFps = instantFps;
            } else {
                smoothedFps += (instantFps - smoothedFps) * 0.2f;
            }

            fps = (int) smoothedFps;
        }
    }

    public static void reset() {
        fps = 0;
        smoothedFps = 0.0f;
        lastTime = System.currentTimeMillis();
        frameStart = System.currentTimeMillis();
    }

    public static int countfps() {
        return fps;
    }

    public static void limit(int targetFps) {
        if (targetFps <= 0) return;
        long targetTime = 1000 / targetFps;
        long currentTime = System.currentTimeMillis();
        long elapsed = currentTime - frameStart;
        long sleepTime = targetTime - elapsed;

        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
            }
        }
        frameStart = System.currentTimeMillis();
    }
}
