/src/sprites/base/Clock.java
Java | 114 lines | 78 code | 21 blank | 15 comment | 11 complexity | 970133357e11889a6759eec3f001eb84 MD5 | raw file
- package sprites.base;
-
- import com.jogamp.newt.opengl.GLWindow;
-
- import sprites.LogicCallback;
-
- public class Clock extends Thread{
-
- public static final int FRAME_SKIP = 10;
-
- private boolean running;
- private boolean paused;
-
- private LogicCallback logic;
- private Renderer renderer;
-
- private long FPS;
- private long TPS;
-
- public Clock(LogicCallback logic, Renderer renderer , long FPS, long TPS) {
- this.running = true;
- this.paused = logic == null;
- this.logic = logic;
- this.renderer = renderer;
- this.FPS = FPS;
- this.TPS = TPS;
- Runtime.getRuntime().addShutdownHook(new Thread(){
- @Override
- public void run(){
- running = false;
- }
- });
- }
-
- @Override
- public void run() {
-
- this.running = true;
-
- long tickDelay = 1000 / this.TPS;
- long frameDelay = 1000 / this.FPS;
-
- long lastTick = System.currentTimeMillis();
- long lastFrame = lastTick;
- long nextTick = lastTick + tickDelay;
- long nextFrame = lastFrame + frameDelay;
-
- long now;
- int skips;
-
- /*
- * The idea for this came from:
- * http://www.koonsolo.com/news/dewitters-gameloop/ I implemented this
- * to see how it runs - though I still don't feel that "threading" is a
- * bad idea ...
- */
-
- while (this.running) {
-
- if(this.logic == null){
- now = System.currentTimeMillis();
- if (now > nextFrame) {
- if(this.renderer != null){
- this.renderer.render();
- }
- nextFrame += frameDelay;
- }
- continue;
- }
-
- skips = 0;
- now = System.currentTimeMillis();
- while (now > nextTick && skips < FRAME_SKIP) {
- if (!this.paused) {
- this.logic.tick(now - lastTick);
- lastTick = now;
- }
- nextTick += tickDelay;
- skips++;
- now = System.currentTimeMillis();
- }
- now = System.currentTimeMillis();
- if (now > nextFrame) {
- this.renderer.render();
- nextFrame += frameDelay;
- }
- }
- }
-
- /**
- * Stops execution of the clock - this thread will need to be restarted when calling this!
- */
- public void halt() {
- this.running = false;
- }
-
- /**
- * Pauses the game logic so no ticks happen, but rendering will still happen.
- */
- public void pause() {
- this.paused = true;
- }
-
- /**
- * Un-pauses the game logic.
- */
- public void unpause(){
- this.paused = false;
- }
-
- public void setLogicCallback(LogicCallback logic){
- this.logic = logic;
- }
- }