Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (109)
games submitted by our members
Games in WIP (536)
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  
  Constant Frame rate and Smooth animation??  (Read 8536 times)
0 Members and 1 Guest are viewing this topic.
Offline neoskunk

Junior Member





« Posted 2010-09-11 10:36:39 »

Is it possible?  I'm having a hell of a time trying to get a constant FPS with Jave2D.  Is this possible and are there alternatives? OpenGL?

I've searched high and low and it doesn't seem like anyone has much luck with Jave2D.  Is that just how it is? 

Also this is for an applet..... if that makes a difference.
Offline Karmington

Senior Member


Medals: 1
Projects: 1


Co-op Freak


« Reply #1 - Posted 2010-09-11 10:54:19 »

It seems it is prone to little hiccups now and then.
Just when you think everything is rolling smoothly, a half sec glitch.
Very annoying, for twitch games unacceptable.
more in this thread
http://www.java-gaming.org/topics/player-sprite-just-doesnt-move-smooth/22762/view.html
Seems like lwjgl is the way to go for steady performance

Offline neoskunk

Junior Member





« Reply #2 - Posted 2010-09-11 11:10:49 »

I've never worked with OpenGL before is it hard to learn?  and in that other thread someone mentioned that if lwjgl is used the applet has to be signed.  Why is that?

Will i have to rewrite all of my graphics code?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline bobjob

JGO Knight


Medals: 10
Projects: 4


David Aaron Muhar


« Reply #3 - Posted 2010-09-11 11:50:46 »

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  
public class Timer {
   
   private long timeThen;
   
   boolean newVersion = true;
   public Timer() {
      if (System.getProperty("java.version").startsWith("1.4")) newVersion = false;
      if (newVersion) timeThen = System.nanoTime();
      else timeThen = System.currentTimeMillis();
     
   }

   public void sync(int fps) {
      Thread.yield();
      if (newVersion) {
         long gapTo = 1000000000L / fps + timeThen;
         long timeNow = System.nanoTime();
         
         try {
            while (gapTo > timeNow) {
               Thread.sleep((gapTo-timeNow) / 2000000L);
               timeNow = System.nanoTime();
            }
         } catch (Exception e) {}

         timeThen = timeNow;
      } else {
         long gapTo = 1000L / fps + timeThen;
         long timeNow = System.currentTimeMillis();
         
         
         while (gapTo > timeNow){
            try { Thread.sleep(1);
            } catch (InterruptedException e) {}
            timeNow = System.currentTimeMillis();
         }
         
         timeThen = timeNow;
      }
   }

   public static void main(String args[]) {
      int framerate = 1;
      System.out.println("Running Timer Test at: " + framerate + " frame per second, should usually be 60");
     
      //create a new timer before starting main loop
     Timer timer = new Timer();
     
      while (true) {
         //Call sync once every game cycle
        timer.sync(framerate);
         System.out.println("tick");
         
      }
   }

}



I pasted this timer class in another thread but I cant find it. Just look at the "main" method to work out how to use it.

This is probably the best you can do with Java2D, otherwise best to use LWJGL

My Projects
Games, Webcam chat, Video screencast, PDF tools.

Javagaming.org with chat room
Offline DzzD
« Reply #4 - Posted 2010-09-11 11:59:24 »

I use this one, still some vsynch error but work nice for applet
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
interval=40; 
lastDraw=0;
while(running)
{
 while(System.currentTimeMillis()-lastDraw<interval)
   Thread.sleep(1);
 
 lastDraw=System.currentTimeMillis();
 this.draw();
 
}

Offline markus.borbely

Junior Member





« Reply #5 - Posted 2010-09-11 14:08:02 »

Yes, it is possible. At least on my machine (a five year old laptop with graphics that wasn't good at that time, but hey it runs Heroes of Might and Magic 2).

Can you show us something that is not working?

This is my timer loop (I think it is from Killer game programming, slightly modified). It will give you a constant update pace and as much framerate as you computer can handle (maximum same as update).

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  
while (!end) {
            update();
            paintScreen();

            afterTime = System.nanoTime();
            timeDiff = afterTime - beforeTime;
            sleepTime = period - timeDiff - overSleepTime;

            if (sleepTime > 0) {
                try {
                    Thread.sleep(sleepTime/1000000);
                } catch (InterruptedException e) { }

                overSleepTime = System.nanoTime() - afterTime - sleepTime;
            } else {
                excess -= sleepTime;
                overSleepTime = 0;
                Thread.yield();
            }

            beforeTime = System.nanoTime();

            int skips = 0;
            while (excess > period && skips < 5) {
                excess -= period;
                update();
                skips++;
            }
            excess = excess > period ? 0 : excess;
        }
Offline DzzD
« Reply #6 - Posted 2010-09-11 22:13:02 »

I also often use constant logic using as much FPS than requiered (up to max FPS) but prefer the following solution wich look less complex and have always worked fine for me.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
try
{
  int logicInterval=40;
  long lastLogicTime=System.currentTimeMillis();
  while(this.run)
  {
    long time=System.currentTimeMillis();
   
    int nbLogic=(int)((time-lastLogicTime)/logicInterval);
    for(int n=0;n<nbLogic;n++)
      this.logic();
    lastLogicTime+=nbLogic*logicInterval;
   
    //no need to draw anything if no logic was perfomed (nothing changed => so no visible change)
   if(nbLogic!=0)
      this.draw();
    else
      Thread.sleep(1);
  }
}
catch(InterruptedException ie)
{
  //game thread interrupted
}


with this one logic calls will be perfectly constant while FPS will be adjusted

(as I can remember System.nanoTime may be weird sometime, especially on AMD dual core but never experience such problem)

Offline neoskunk

Junior Member





« Reply #7 - Posted 2010-09-11 23:04:30 »

wow thanks for all the replies.  I'm going to give some of your suggestions a try.  This is what I was doing...

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  
   public void run()
   {
      long frameTime, renderTime;
      long beforeTime, timeDiff, sleepTime;
      beforeTime = System.nanoTime();
      frameTime = System.nanoTime();

      while(showing)
      {
         update();
         draw();
         controller.paintScreen(buffer);

         timeDiff = System.nanoTime() - beforeTime;
         renderTime = System.nanoTime() - frameTime;
         sleepTime = speed - timeDiff/1000000L;

         if(renderTime >= 1000000000)
         {
            frameTime = System.nanoTime();
            FPS = counter;
            counter = 0;
         }
         else
            counter++;

         if(sleepTime > 0)
         {
            try
            {
               Thread.sleep(sleepTime);
            }
            catch (InterruptedException ex)
            {
               ex.printStackTrace();
            }
         }
         else
            Thread.yield();

         beforeTime = System.nanoTime();
      }
   }


However,  I was getting very inconsistent FPS.  Also can someone address the LWJGL and signing thing.  To sign an applet and use LWJGL do you have to buy an actual certificate?
Offline neoskunk

Junior Member





« Reply #8 - Posted 2010-09-12 06:21:09 »

Ok i have had all i can take of Java2D.  Can someone give me a quick tutorial on what LWJGL is/how to implement it?  Is it going to be hard to convert my current graphics method to that?  All i'm currently using java2D for is to manipulate .gif images.
Offline markus.borbely

Junior Member





« Reply #9 - Posted 2010-09-12 06:55:09 »

Ok i have had all i can take of Java2D.  Can someone give me a quick tutorial on what LWJGL is/how to implement it?  Is it going to be hard to convert my current graphics method to that?  All i'm currently using java2D for is to manipulate .gif images.

I'm not going to do more than point you to slick, a 2D game engine that uses lwjgl.
http://slick.cokeandcode.com/

But... I hope you are not painting the images directly from the gifs?Huh?
You have to create an image that is the same mode as the screen, paint the gif onto it and then discard the gif.

Some old code I wrote to do this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
            ImageIcon icon = new ImageIcon(path);
            if (icon.getImage() != null && icon.getImage().getHeight(null) > 0) {
                Image temp = icon.getImage();
                BufferedImage dest = GameWindow.createCompatibleImage(temp.getWidth(null), temp.getHeight(null));
                Graphics g = dest.getGraphics();
                g.drawImage(temp, 0, 0, null);
                g.dispose();
            }
            //now, dest have the image you want to use

    public static BufferedImage createCompatibleImage(int width, int height) {
        if (gd == null) {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            gd = ge.getDefaultScreenDevice();
        }
        return gd.getDefaultConfiguration().createCompatibleImage(width,height,Transparency.TRANSLUCENT);
    }


Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline neoskunk

Junior Member





« Reply #10 - Posted 2010-09-12 07:52:39 »

currently I am loading the gif via this method:

1  
2  
3  
Image city;
city = getImage(getDocumentBase(), "images/city.gif");
      appletTracker.addImage(city,105);


you are saying i should create an image that is 800,600 (my applet size) that is all translucent other than the actual gif???


That seems to me like it would take even longer given that each image is now huge....

is slick easy to use?  and can someone please explain to me why using any of these engines (LWJGL, slick, etc...) i need to sign the applet?
Offline CommanderKeith
« Reply #11 - Posted 2010-09-12 08:47:46 »


is slick easy to use?  and can someone please explain to me why using any of these engines (LWJGL, slick, etc...) i need to sign the applet?


It's because they use native code - dll files (for windows). Slick uses lwjgl under the hood

Offline neoskunk

Junior Member





« Reply #12 - Posted 2010-09-12 08:59:59 »

so what all does signing involve?  do i have to pay hundreds of dollar for verisign or thawte??
Offline CommanderKeith
« Reply #13 - Posted 2010-09-12 09:09:32 »

No since the LWJGL devs kindly sign sign their jars etc with their certificate.

To use non-LWJGL native stuff then yes you need to pay hundreds for a cert.

Offline kappa
« League of Dukes »

JGO Kernel


Medals: 75
Projects: 15


★★★★★


« Reply #14 - Posted 2010-09-12 12:00:23 »

If you buy a proper certificate to sign your jars then you will get a nicer dialog when your applet is run.

However you don't need to buy a certificate, you can just sign your own jars using a self signed certificate which is free. However the dialog at run time is not as pretty.

Also as mentioned above LWJGL provides pre-signed jars with a proper certificate so you can just use that.
Offline markus.borbely

Junior Member





« Reply #15 - Posted 2010-09-12 13:57:30 »

Quote
you are saying i should create an image that is 800,600 (my applet size) that is all translucent other than the actual gif???

ok, to start from the beginning. Images need to be accelerated for them to be fast. Otherwise, they are slow. Smiley
The method createCompatibleImage creates an accelerated image for you. I will be completely blank and support translucency.
If you load an image that is 32x32 you should create an accelerated image that is 32x32.

If you read my code it is this line: (see that i set the loaded images dimensions as parameters).
1  
                BufferedImage dest = GameWindow.createCompatibleImage(temp.getWidth(null), temp.getHeight(null));


Then paint the loaded image onto the acclerated one.
Discard the loaded image and use the accelerated.

Of course, this does not guarantee that your game will run smooth. It also depends on other things, like you main loop, your AI, physics etc.
Offline markus.borbely

Junior Member





« Reply #16 - Posted 2010-09-12 14:02:38 »

so what all does signing involve?  do i have to pay hundreds of dollar for verisign or thawte??

Its pretty easy to set up ant to create your certificate and sign all your jars for you.

Ant target for creating certificate. Call this once.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
    <target name="Gen key">
        <delete file="yourname.ks"/>
        <genkey alias="YourAlias" keyalg="RSA" storepass="yourpass" keypass="yourkeypass" keystore="yourname.ks" validity="1000" >
            <dname>
                <param name="CN" value="Your Name"/>
                <param name="OU" value="Game Name"/>
                <param name="O" value="Your Organisation Name"/>
                <param name="C" value="Your Country"/>
            </dname>
        </genkey>
    </target>


Then, when you have created your jar. Use this antcall to sign it.
1  
        <signjar keystore="yourname.ks" jar="nameofjar.jar" alias="YourAlias" storepass="yourpass" />

Offline DzzD
« Reply #17 - Posted 2010-09-12 14:18:37 »

NB:

be carfefull with sleep method like the following :

1  
Thread.sleep(sleepTime);


if you got other thread running Thread.sleep(15) may sleep for 50 ms for example

Thread.sleep(10) does not mean thread will sleep for 10 ms, this a very inacurrate method

and be carefull with System.nanoTime too

Quote
the result of nanoTime is jumping forward and backward in
time, depending on which cpu the thread is currently running

Offline neoskunk

Junior Member





« Reply #18 - Posted 2010-09-12 21:30:14 »

thanks for all the replies yall have been very helpful.  last question I think.  Does LWJGL have the pitfalls that Java2D has?  for instance the inaccuracy of sleep or does it have some other way to increment FPS and UPS? (ie. what is the general game loop look like for LWJGL, is it still update, render, sleep?)  Is the difference between LWJGL and java2D a drastic one or am i splitting hairs by moving to it?

oh and thanks markus,  I might give that a try and see if it speeds things up.
Offline kappa
« League of Dukes »

JGO Kernel


Medals: 75
Projects: 15


★★★★★


« Reply #19 - Posted 2010-09-12 21:36:13 »

Does LWJGL have the pitfalls that Java2D has?  for instance the inaccuracy of sleep or does it have some other way to increment FPS and UPS?

LWJGL has its own high resolution timer so has much more accurate timing.

Is the difference between LWJGL and java2D a drastic one or am i splitting hairs by moving to it?

You can't really compare LWJGL with Java2D, you can however compare Slick2D with Java2D and yes the difference is pretty drastic. Also slick provides you with a pretty accurate delta time every frame which can be used for all your game timing, so you don't need to worry about creating your own timer.
Offline neoskunk

Junior Member





« Reply #20 - Posted 2010-09-12 21:52:01 »


You can't really compare LWJGL with Java2D, you can however compare Slick2D with Java2D and yes the difference is pretty drastic.

doesn't slick2D use LWJGL? So essentially they are the same?  now you have got me confused....should I use LWJGL or use Slick2D?  My game is purely 2D but if LWJGL is better why not just use that?
Offline kappa
« League of Dukes »

JGO Kernel


Medals: 75
Projects: 15


★★★★★


« Reply #21 - Posted 2010-09-12 22:00:57 »

doesn't slick2D use LWJGL? So essentially they are the same?  now you have got me confused....should I use LWJGL or use Slick2D?  My game is purely 2D but if LWJGL is better why not just use that?

yes Slick2D uses LWJGL, however LWJGL is much more closer to the metal and essentially just a minimal layer to OpenGL, OpenAL, etc. You will have to write a lot of code to clone an api similar to Java2D.

Slick2D however is a small library which wraps LWJGL to give you an API very similar to Java2D and does all the hard work for you like loading textures, sounds, basic game framework, timers, fonts, etc (which you would have to write code for manually if you used LWJGL directly). So using it will save you alot of time and at the same time be much easier to pick up if you already know Java2D.
Offline neoskunk

Junior Member





« Reply #22 - Posted 2010-09-12 22:38:00 »

alright cool so looks like I will try and use Slick2D.  thanks kapta Smiley
Offline oNyx

JGO Coder


Medals: 1


pixels! :x


« Reply #23 - Posted 2010-09-13 04:51:35 »

>LWJGL has its own high resolution timer so has much more accurate timing.

It got a resolution of 1msec, which you can't really call "high resolution". However, a 1msec resolution is all you need for games. All Quake engine based games used such a timer for example.

A temporal 0-0.5msec jitter just isn't noticeable for humans. We can't even tell the difference between 100 and 120fps (vsynced @100/120hz respectively) and that's a much bigger difference.

What I also like about those 1msec timers is their robustness. They always work perfectly on any hardware which doesn't predate Windows 95.

弾幕 ☆ @mahonnaiseblog
Offline neoskunk

Junior Member





« Reply #24 - Posted 2010-09-13 06:28:20 »

ok i been looking at Slick2D.  question though...is ALL rendering in slick2D done with LWJGL or is it done with Java2D unless i tell it to use LWJGL?
Offline kappa
« League of Dukes »

JGO Kernel


Medals: 75
Projects: 15


★★★★★


« Reply #25 - Posted 2010-09-13 11:26:00 »

ok i been looking at Slick2D.  question though...is ALL rendering in slick2D done with LWJGL or is it done with Java2D unless i tell it to use LWJGL?

Its all done with LWJGL.
Offline neoskunk

Junior Member





« Reply #26 - Posted 2010-09-13 16:37:04 »

awesome! just looking through the javadocs slick looks amazing.  simplifies everything about making a game. wish i had found it sooner!
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.

CogWheelz (18 views)
2014-07-30 21:08:39

Riven (25 views)
2014-07-29 18:09:19

Riven (15 views)
2014-07-29 18:08:52

Dwinin (13 views)
2014-07-29 10:59:34

E.R. Fleming (33 views)
2014-07-29 03:07:13

E.R. Fleming (12 views)
2014-07-29 03:06:25

pw (43 views)
2014-07-24 01:59:36

Riven (44 views)
2014-07-23 21:16:32

Riven (30 views)
2014-07-23 21:07:15

Riven (31 views)
2014-07-23 20:56:16
List of Learning Resources
by SilverTiger
2014-07-31 18:29:50

List of Learning Resources
by SilverTiger
2014-07-31 18:26:06

List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54
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!