Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (521)
Games in Android Showcase (127)
games submitted by our members
Games in WIP (589)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Calculating and displaying FPS accurately and efficiently  (Read 6129 times)
0 Members and 1 Guest are viewing this topic.
Offline CoryG89

Senior Newbie





« Posted 2011-01-05 02:21:31 »

I was wondering if anyone could show me any code where they have used a JPanel
with double buffering and active rendering using a thread and was able to accurately and effectively calculate and display their FPS.

Here is my code:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
   /**
    * Implements the Runnable interface. Responsible
    * for updates, rendering, and sleeping the thread.
    */

   @Override
   public void run()
   {
      bRunning = true;   // Keep flag set
      long beforeTime, deltaTime, sleepTime;
   
      beforeTime = System.currentTimeMillis();
     
      initRender();
     
      // Repeat update/animation loop, sleeping a bit
      while (bRunning)
      {
         
         try
         {
            updateBoard();
         } catch (IOException e)
         { System.err.println("Error: IO Failure"); }
         
         renderBoard();
         paintBoard();
         
         deltaTime = System.currentTimeMillis() - beforeTime;
         sleepTime = PERIOD - deltaTime;
         
         if (sleepTime < 0)
         {
            timeOver = (-1) * (int) sleepTime;
            sleepTime = 0;
           
         }
         
         try
         {
            Thread.sleep(sleepTime);
         }
         catch(InterruptedException ie)
         {
            System.err.println("Error: Thread exception!");
         }
         beforeTime = System.currentTimeMillis();
      }
     
      System.exit(0);   // end of run
   }



1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
   /**
    * Renders the resulting output frame to
    * an Image buffer. Off-screen rendering.
    */

   private void renderBoard()
   {
     
      // Draw background, using correct coordinates
      gDevice.drawImage(background, bX[0], 0, null);
      gDevice.drawImage(background, bX[1], 0, null);
      gDevice.drawImage(background, bX[2], 0, null);
      gDevice.drawImage(background, bX[3], 0, null);
     
      // Draw characters and all sprites
      gChar.draw(gDevice);
     
      //  Test debug flags and take explicit action here
      if (bFPSDebug)
         calcAndDisplayFPS();
   }


1  
2  
3  
4  
5  
6  
7  
8  
   /**
    * Used to calculate and paint the FPS on the GameBoard.
    */

   private void calcAndDisplayFPS()
   {
      FPS = 1000 / ((Double) PERIOD + timeOver);
      gDevice.drawString("FPS: " + String.valueOf(FPS), 20, 20);
   }



This doesn't seem to work as my output is constantly either 62.0 or 66.0. This is with a const PERIOD of 10 milliseconds. This means as long as my computer can handle it I should be sleeping for 10 milliseconds which should give me 1000/10 = 100 FPS cap. Apparently I am not achieving this.

Does anyone know if what I am doing is sufficient to get an accurate FPS count.  And also is calculating and drawing to the screen every loop like this going to be a performance hit in itself?

If the
Offline avm1979
« Reply #1 - Posted 2011-01-05 03:44:59 »

Hmm... for one, your timeOver seems to be updated only if you go over budget, so that'll skew your computation if you dip over just once - since that value will be retained for the subsequent loops where you don't go over.

Offline CoryG89

Senior Newbie





« Reply #2 - Posted 2011-01-05 05:40:17 »

Oh yes, I had timeOver as a class variable when it should have had a local scope. Now I have a constant 100.0 FPS. I don't guess I should have any fluctuation at all?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Mads

JGO Ninja


Medals: 26
Projects: 3
Exp: 6 years


One for all!


« Reply #3 - Posted 2011-01-13 17:00:11 »

Heres some code from Killer Game Programming in Java, that has all of your concerns.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
331  
332  
333  
334  
335  
336  
337  
338  
339  
340  
341  
342  
343  
344  
345  
346  
347  
348  
import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;


public class TilePanel extends JPanel implements Runnable
{
  private static final int PWIDTH = 500;   // size of panel
  private static final int PHEIGHT = 400;

  private static long MAX_STATS_INTERVAL = 1000000000L;
  // private static long MAX_STATS_INTERVAL = 1000L;
    // record stats every 1 second (roughly)

  private static final int NO_DELAYS_PER_YIELD = 16;
  /* Number of frames with a delay of 0 ms before the animation thread yields
     to other running threads. */


  private static int MAX_FRAME_SKIPS = 5;   // was 2;
    // no. of frames that can be skipped in any one animation loop
    // i.e the games state is updated but not rendered

  private static int NUM_FPS = 10;
     // number of FPS values stored to get an average


  // used for gathering statistics
  private long statsInterval = 0L;    // in ns
  private long prevStatsTime;  
  private long totalElapsedTime = 0L;
  private long gameStartTime;
  private int timeSpentInGame = 0;    // in seconds

  private long frameCount = 0;
  private double fpsStore[];
  private long statsCount = 0;
  private double averageFPS = 0.0;

  private long framesSkipped = 0L;
  private long totalFramesSkipped = 0L;
  private double upsStore[];
  private double averageUPS = 0.0;


  private DecimalFormat df = new DecimalFormat("0.##");  // 2 dp
  private DecimalFormat timedf = new DecimalFormat("0.####");  // 4 dp


  private Thread animator;           // the thread that performs the animation
  private boolean running = false;   // used to stop the animation thread
  private boolean isPaused = false;

  private long period;                // period between drawing in _nanosecs_


  private Initialize ini;
  private TileMap tileMap;


  // used at game termination
  private boolean gameOver = false;
  private int score = 0;
  private Font font;
  private FontMetrics metrics;

  // off screen rendering
  private Graphics dbg;
  private Image dbImage = null;



  public TilePanel(Initialize ini, long period)
  {
    this.ini = ini;
    this.period = period;

    setBackground(Color.white);
    setPreferredSize( new Dimension(PWIDTH, PHEIGHT));

    tileMap = new TileMap();

    // set up message font
    font = new Font("SansSerif", Font.BOLD, 10);
    metrics = this.getFontMetrics(font);

    // initialise timing elements
    fpsStore = new double[NUM_FPS];
    upsStore = new double[NUM_FPS];
    for (int i=0; i < NUM_FPS; i++) {
      fpsStore[i] = 0.0;
      upsStore[i] = 0.0;
    }
  }  // end of WormPanel()


  @Override
  public void addNotify()
  // wait for the JPanel to be added to the JFrame before starting
  { super.addNotify();   // creates the peer
    startGame();         // start the thread
  }


  private void startGame()
  // initialise and start the thread
  {
    if (animator == null || !running) {
      animator = new Thread(this);
     animator.start();
    }
  } // end of startGame()
   

  // ------------- game life cycle methods ------------
  // called by the JFrame's window listener methods


  public void resumeGame()
  // called when the JFrame is activated / deiconified
  {  isPaused = false;  }


  public void pauseGame()
  // called when the JFrame is deactivated / iconified
  { isPaused = true;   }


  public void stopGame()
  // called when the JFrame is closing
  {  running = false;   }

  // ----------------------------------------------


  public void run()
  /* The frames of the animation are drawn inside the while loop. */
  {
    long beforeTime, afterTime, timeDiff, sleepTime;
    long overSleepTime = 0L;
    int noDelays = 0;
    long excess = 0L;

    gameStartTime = Timer.getValue();
    prevStatsTime = gameStartTime;
    beforeTime = gameStartTime;

   running = true;

   while(running) {
     gameUpdate();
      gameRender();
      paintScreen();

      afterTime = Timer.getValue();
      timeDiff = afterTime - beforeTime;
      sleepTime = (period - timeDiff) - overSleepTime;  

      if (sleepTime > 0) {   // some time left in this cycle
        try {
          Thread.sleep(sleepTime/1000000L);  // nano -> ms
        }
        catch(InterruptedException ex){}
        overSleepTime = (Timer.getValue() - afterTime) - sleepTime;
      }
      else {    // sleepTime <= 0; the frame took longer than the period
        excess -= sleepTime;  // store excess time value
        overSleepTime = 0L;

        if (++noDelays >= NO_DELAYS_PER_YIELD) {
          Thread.yield();   // give another thread a chance to run
          noDelays = 0;
        }
      }

      beforeTime = Timer.getValue();

      /* If frame animation is taking too long, update the game state
         without rendering it, to get the updates/sec nearer to
         the required FPS. */

      int skips = 0;
      while((excess > period) && (skips < MAX_FRAME_SKIPS)) {
        excess -= period;
       gameUpdate();    // update state but don't render
        skips++;
      }
      framesSkipped += skips;

      storeStats();
   }

    printStats();
    System.exit(0);   // so window disappears
  } // end of run()


  private void gameUpdate() {
    if (!isPaused && !gameOver) {
    }
  }  // end of gameUpdate()


  private void gameRender()
  {
    if (dbImage == null){
      dbImage = createImage(PWIDTH, PHEIGHT);
      if (dbImage == null) {
        System.out.println("dbImage is null");
        return;
      }
      else
        dbg = dbImage.getGraphics();
    }

    // clear the background
    dbg.setColor(Color.white);
    dbg.fillRect (0, 0, PWIDTH, PHEIGHT);

    dbg.setColor(Color.black);

    // draw game elements
    tileMap.draw(dbg);

    dbg.setColor(Color.blue);
    dbg.setFont(font);

    // report frame count & average FPS and UPS at top left
    // dbg.drawString("Frame Count " + frameCount, 10, 25);
    dbg.drawString("Average FPS/UPS: " + df.format(averageFPS) + ", " +
    df.format(averageUPS), 10, 10);  // was (10,55)

    if (gameOver)
      gameOverMessage(dbg);
  }  // end of gameRender()


  private void gameOverMessage(Graphics g)
  // center the game-over message in the panel
  {
    String msg = "Game Over. Your Score: " + score;
   int x = (PWIDTH - metrics.stringWidth(msg))/2;
   int y = (PHEIGHT - metrics.getHeight())/2;
   g.setColor(Color.red);
    g.setFont(font);
   g.drawString(msg, x, y);
  }  // end of gameOverMessage()


  private void paintScreen()
  // use active rendering to put the buffered image on-screen
  {
    Graphics g;
    try {
      g = this.getGraphics();
      if ((g != null) && (dbImage != null))
        g.drawImage(dbImage, 0, 0, null);
      g.dispose();
    }
    catch (Exception e)
    { System.out.println("Graphics context error: " + e);  }
  } // end of paintScreen()


  private void storeStats()
  /* The statistics:
       - the summed periods for all the iterations in this interval
         (period is the amount of time a single frame iteration should take),
         the actual elapsed time in this interval,
         the error between these two numbers;

       - the total frame count, which is the total number of calls to run();

       - the frames skipped in this interval, the total number of frames
         skipped. A frame skip is a game update without a corresponding render;

       - the FPS (frames/sec) and UPS (updates/sec) for this interval,
         the average FPS & UPS over the last NUM_FPSs intervals.

     The data is collected every MAX_STATS_INTERVAL  (1 sec).
  */

  {
    frameCount++;
    statsInterval += period;

    if (statsInterval >= MAX_STATS_INTERVAL) {     // record stats every MAX_STATS_INTERVAL
      long timeNow = Timer.getValue();
      timeSpentInGame = (int) ((timeNow - gameStartTime)/1000000000L);  // ns --> secs

      long realElapsedTime = timeNow - prevStatsTime;   // time since last stats collection
      totalElapsedTime += realElapsedTime;

      double timingError =
         ((double)(realElapsedTime - statsInterval) / statsInterval) * 100.0;

      totalFramesSkipped += framesSkipped;

      double actualFPS = 0;     // calculate the latest FPS and UPS
      double actualUPS = 0;
      if (totalElapsedTime > 0) {
        actualFPS = (((double)frameCount / totalElapsedTime) * 1000000000L);
        actualUPS = (((double)(frameCount + totalFramesSkipped) / totalElapsedTime)
                                                             * 1000000000L);
      }

      // store the latest FPS and UPS
      fpsStore[ (int)statsCount%NUM_FPS ] = actualFPS;
      upsStore[ (int)statsCount%NUM_FPS ] = actualUPS;
      statsCount = statsCount+1;

      double totalFPS = 0.0;     // total the stored FPSs and UPSs
      double totalUPS = 0.0;
      for (int i=0; i < NUM_FPS; i++) {
        totalFPS += fpsStore[i];
        totalUPS += upsStore[i];
      }

      if (statsCount < NUM_FPS) { // obtain the average FPS and UPS
        averageFPS = totalFPS/statsCount;
        averageUPS = totalUPS/statsCount;
      }
      else {
        averageFPS = totalFPS/NUM_FPS;
        averageUPS = totalUPS/NUM_FPS;
      }
/*
      System.out.println(timedf.format( (double) statsInterval/1000000000L) + " " +
                    timedf.format((double) realElapsedTime/1000000000L) + "s " +
                 df.format(timingError) + "% " +
                    frameCount + "c " +
                    framesSkipped + "/" + totalFramesSkipped + " skip; " +
                    df.format(actualFPS) + " " + df.format(averageFPS) + " afps; " +
                    df.format(actualUPS) + " " + df.format(averageUPS) + " aups" );
*/

      framesSkipped = 0;
      prevStatsTime = timeNow;
      statsInterval = 0L;   // reset
    }
  }  // end of storeStats()


  private void printStats()
  {
    System.out.println("Frame Count/Loss: " + frameCount + " / " + totalFramesSkipped);
   System.out.println("Average FPS: " + df.format(averageFPS));
   System.out.println("Average UPS: " + df.format(averageUPS));
    System.out.println("Time Spent: " + timeSpentInGame + " secs");
  }  // end of printStats()

}  // end of WormPanel class


I just copied it from an early project of mine, so you're to do some edits and removing unused code.
All Timer.getVariable() calls, can be replaced with System.nanoTime() for the exact same effect.

Cheers!

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xFryIx (58 views)
2014-11-13 12:34:49

digdugdiggy (37 views)
2014-11-12 21:11:50

digdugdiggy (30 views)
2014-11-12 21:10:15

digdugdiggy (26 views)
2014-11-12 21:09:33

kovacsa (48 views)
2014-11-07 19:57:14

TehJavaDev (51 views)
2014-11-03 22:04:50

BurntPizza (51 views)
2014-11-03 18:54:52

moogie (66 views)
2014-11-03 06:22:04

CopyableCougar4 (65 views)
2014-11-01 23:36:41

DarkCart (150 views)
2014-11-01 14:51:03
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!