PageRenderTime 56ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/src/sprites/base/Clock.java

https://bitbucket.org/salbeira/jsprites-gl
Java | 114 lines | 78 code | 21 blank | 15 comment | 11 complexity | 970133357e11889a6759eec3f001eb84 MD5 | raw file
  1. package sprites.base;
  2. import com.jogamp.newt.opengl.GLWindow;
  3. import sprites.LogicCallback;
  4. public class Clock extends Thread{
  5. public static final int FRAME_SKIP = 10;
  6. private boolean running;
  7. private boolean paused;
  8. private LogicCallback logic;
  9. private Renderer renderer;
  10. private long FPS;
  11. private long TPS;
  12. public Clock(LogicCallback logic, Renderer renderer , long FPS, long TPS) {
  13. this.running = true;
  14. this.paused = logic == null;
  15. this.logic = logic;
  16. this.renderer = renderer;
  17. this.FPS = FPS;
  18. this.TPS = TPS;
  19. Runtime.getRuntime().addShutdownHook(new Thread(){
  20. @Override
  21. public void run(){
  22. running = false;
  23. }
  24. });
  25. }
  26. @Override
  27. public void run() {
  28. this.running = true;
  29. long tickDelay = 1000 / this.TPS;
  30. long frameDelay = 1000 / this.FPS;
  31. long lastTick = System.currentTimeMillis();
  32. long lastFrame = lastTick;
  33. long nextTick = lastTick + tickDelay;
  34. long nextFrame = lastFrame + frameDelay;
  35. long now;
  36. int skips;
  37. /*
  38. * The idea for this came from:
  39. * http://www.koonsolo.com/news/dewitters-gameloop/ I implemented this
  40. * to see how it runs - though I still don't feel that "threading" is a
  41. * bad idea ...
  42. */
  43. while (this.running) {
  44. if(this.logic == null){
  45. now = System.currentTimeMillis();
  46. if (now > nextFrame) {
  47. if(this.renderer != null){
  48. this.renderer.render();
  49. }
  50. nextFrame += frameDelay;
  51. }
  52. continue;
  53. }
  54. skips = 0;
  55. now = System.currentTimeMillis();
  56. while (now > nextTick && skips < FRAME_SKIP) {
  57. if (!this.paused) {
  58. this.logic.tick(now - lastTick);
  59. lastTick = now;
  60. }
  61. nextTick += tickDelay;
  62. skips++;
  63. now = System.currentTimeMillis();
  64. }
  65. now = System.currentTimeMillis();
  66. if (now > nextFrame) {
  67. this.renderer.render();
  68. nextFrame += frameDelay;
  69. }
  70. }
  71. }
  72. /**
  73. * Stops execution of the clock - this thread will need to be restarted when calling this!
  74. */
  75. public void halt() {
  76. this.running = false;
  77. }
  78. /**
  79. * Pauses the game logic so no ticks happen, but rendering will still happen.
  80. */
  81. public void pause() {
  82. this.paused = true;
  83. }
  84. /**
  85. * Un-pauses the game logic.
  86. */
  87. public void unpause(){
  88. this.paused = false;
  89. }
  90. public void setLogicCallback(LogicCallback logic){
  91. this.logic = logic;
  92. }
  93. }