A version of lwjgl.util.Timer with game tick support

Started by Matthias, June 10, 2006, 17:55:32

Previous topic - Next topic

Matthias

Hi,

I've created a class similar to org.lwjgl.util.Timer that also reports how many game ticks have passed since last frame.

If some wants to use it, or even include it into lwjgl (in parts or complete) feel free to do so.

public class TimeBase {
    
    private static int fps = 60;
    
    private static long startTime;
    private static long lastTime;
    private static int deltaMs;
    private static int deltaTicks;
    private static double absTime;
    private static float deltaTime;
    private static boolean paused;
    private static boolean lag;
    
    private TimeBase() {
    }
    
    public static void setFPS(int fps) {
        TimeBase.fps = fps;
    }
    
    public static int getFPS() {
        return fps;
    }
    
    public static double getAbsoluteTime() {
        return absTime;
    }
    
    public static float getDeltaTime() {
        return deltaTime;
    }
    
    public static long getDeltaMilis() {
        return deltaMs;
    }
    
    public static int getDeltaTicks() {
        return deltaTicks;
    }
    
    public static boolean isLag() {
        return lag;
    }
    
    public static void tick() {
        if(paused) {
            deltaMs = 0;
            deltaTicks = 0;
            deltaTime = 0;
            return;
        }
        
        long now = Sys.getTime();
        long res = Sys.getTimerResolution();
        long dif = now - lastTime;
        
        deltaMs = limit((dif * 1000) / res);
        deltaTicks = limit((dif * fps) / res);
        deltaTime = (float)((double)dif / (double)res);
        absTime = (double)(now - startTime) / (double)res;
        lastTime += deltaTicks * res / fps;
        
        if(lag=(deltaTicks > fps)) {
            // LAG
            deltaMs = 0;
            deltaTicks = 0;
            deltaTime = 0;
            lastTime = now;
        }
    }
    
    public static void pause() {
        paused = true;
    }
    
    public static void unpause() {
        if(paused) {
            paused = false;
            long now = Sys.getTime();
            startTime += now - lastTime;
            lastTime = now;
        }
    }
    
    public static void togglePause() {
        if(paused) {
            unpause();
        } else {
            pause();
        }
    }
    
    public static boolean isPaused() {
        return paused;
    }
    
    private static int limit(long value) {
        if(value > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        return (int)value;
    }
}



Matthias