Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (579)
games submitted by our members
Games in WIP (500)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1] 2
1  Game Development / Shared Code / Re: Smooth scroll on: 2010-03-27 22:16:33
A tutorial!? I'd have to go back to square one, fifteen years ago sitting in a comp sci. computer room drumming my fingers on the desk waiting for the download link for The Java Programming Language to appear.  Cheesy

Believe it or not, the smooth scroll code above is very nearly fifteen years old. Because of it's age it is extremely reliable. The most recent change was made when Javasofct released the system nanotimer. But since then the code has remained largely unchanged.

IMO the best tutorials are those that just show the code interspersed with a few comments. I never read most of the verbiage on the Java tutorial site, I normally go straiight for the section of code I am interested in and copy and paste the chunk into whatever piece of software I happen to be working on.

Oh, just one rather big thing to point out about the smooth scroll code: I've never written a full game in Java and released it so feel free to shoot me down in flames.

--Mario
2  Game Development / Shared Code / Smooth scroll on: 2010-03-27 11:51:57
Thought I'd share the code for my smooth scrolling game loop:



import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.event.KeyListener;

/**
 * Main.java - A smooth scrolling game loop.
 *
 * @author Mario Gianota
 */
public class Main implements KeyListener {
   /*
    * Colour palette
    */
    private static Color[] COLORS = new Color[] {
        Color.red, Color.blue, Color.green, Color.white, Color.black,
        Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
        Color.magenta, Color.orange, Color.darkGray };
   
    Frame mainFrame;
    long lastTime;
    int fps;
    int frameCounter;
    long elapsedTime;
    long delayTime = 0;
    Rectangle rect;
   
    public Main(GraphicsDevice device) {
        try {
            // Setup the frame
            GraphicsConfiguration gc = device.getDefaultConfiguration();
           
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated(true);
            mainFrame.setIgnoreRepaint(true);
            mainFrame.setVisible(true);
            mainFrame.setSize(640, 480);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.createBufferStrategy(3);
            mainFrame.addKeyListener(this);
           
            // Cache the buffer strategy and create a rectangle to move
            BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
            rect = new Rectangle(0, 100, 50, 50);
           
            // Main loop

            while(true) {
                long time = System.nanoTime();
                calculateFramesPerSecond();
               
                // Update rectangle co'ords
                rect.x+=4;
               
                if( rect.x > mainFrame.getWidth() )
                    rect.x = -rect.width;
               
                // Draw
                Graphics g = bufferStrategy.getDrawGraphics();
                drawScreen(g);
                g.dispose();
               
                // Flip the buffer
                if( ! bufferStrategy.contentsLost() )
                    bufferStrategy.show();

                // Delay for a period of time equal to 1/60th of a
                // second minus the elapsed time
                elapsedTime = System.nanoTime() - time;
                delayTime = 1000000000L/60 - elapsedTime;
                time = System.nanoTime();
                while( System.nanoTime() - time <= delayTime)
                    ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
       
    }
    private void drawScreen(Graphics g) {
        g.setColor(COLORS[1]);
        g.fillRect(0, 0, 640, 480);
        g.setColor(COLORS[3]);
        g.drawString("FPS: "+ fps, 0, 17);
        g.setColor(COLORS[0]);
        g.fillRect(rect.x, rect.y, rect.width, rect.height);
    }
    private void calculateFramesPerSecond() {
        long time = System.nanoTime();
        if( time - lastTime >= 1000000000L ) {
            fps = frameCounter;
            lastTime = time;
            frameCounter = 0;
        }
        frameCounter++;
    }
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
            System.exit(0);
        }
    }
    public void keyReleased(KeyEvent e) {
       
    }
    public void keyTyped(KeyEvent e) {
       
    }
    public static void main(String[] args) {
        try {
            GraphicsEnvironment env = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            Main test = new Main(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Have fun.

--Mario
3  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-17 11:55:21
Hmm... I have enjoyed my time on this forum immensely, it is populated by very intelligent programmers. However, the real world beckons and I have a game to produce which I would have liked to have produced in Java but cannot because of the performance. I have seen the eminently capable LWJGL library though I am unwilling to opt for using OpenGL over DirectX. It is a shame that he used OpenGL 'cos I quite liked the screenshots for Puppygames and was disappointed that I couldn't play them. BTW IMO David Brackeen's Pulpcore is grr-eat. And JOGL is well... JOGL reminds me of that horse that is running around outside of a closed stable door.

I still have strong reservations about using Java exclusively for writing games and I simply don't believe it is up to the job. But I am not going to spend anymore time prodding at your hearts and minds by advocating C++ because it is obvious you have your souls set on Java. So I shall bid the forum a fond farewell and depart back to Microsoft land, where everything is bright and whizzy and explodes for no apparent reason. Grin Sanity beckons. As a parting shot, I'll leave you with a reference to a picture of a truly great language designer: http://www.research.att.com/~bs/

I shall return when I am equipped with OpenGL... Hell, maybe I'll write a Java SDL wrapper and return bearing a whizzy thin Java library. Who knows.

TTFN

--Mario
4  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-17 05:52:54
This thread has taken a number of diversions away from its intended purpose but I can't say that I am unsurprised to see a discussion  of JNI. My feeling on Java now after having spent a week or so with the language is that it is mean-spirited. Let me explain. I was initially bemused as to why Java does not include so much of the C/C++ syntax which gives that programming language so much of its power and flexibility, but understanding dawned when I read this article: http://www.eweek.com/c/a/IT-Management/Father-of-Java-Has-His-Eye-on-Jackpot/.

I wish you the best of luck with your Java creations but I cannot help but feel that you are being led up the garden path with a watered down version of C++ by a very clever man that has deliberately forbidden vital syntactical constructs and programming idioms because the inclusion of those constructs would fight his ability to create tools that produce "semantic models of the application", not because the use of those constructs and idioms are representative of bad programming practice. What he means by semantic models of course is a model of a program that is amenable to algebraic manipulation.

Finally, to sum up. I read comments from one young man who proclaimed that, "Java is a language that your grandfather uses.". I'm inclined to agree; it is safe and doesn't allow you to do anything "dangerous". For dangerous, read "truly useful".

--Mario
5  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-16 09:41:05
That code is broken through too much hacking. Below is the code I'm currently using. It is based upon feedback from Mr_Light and it is better than my original version but it still stutters. BTW it is not true that Thread.sleep() is innacurate. The method has a resolution of 1 millisecond and it seems to sleep for exactly that length of time.

If you're interested in this problem, here's the current test 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  
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  
package gameloop;

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferStrategy;

/**
 * A basic game loop.
 *
 * @author Mario
 */

public class GameLoop implements KeyListener {
    /*
     * The display window
     */

    Frame mainFrame;
   
    /*
     * Saves the time in nanos at which the last frame was drawn
     */

    long lastFrameDrawn;
   
    /*
     * The frame rate cap. Set to 60 fps here as a default.
     */

    long fpsLimit = 60;
   
    /*
     * Stores the frames per second.
     */

    long fps;
   
    /*
     * Saves the last time we looked at the clock.
     */

    long lastTime;
   
    /*
     * Saves a count of the number of frames drawn per 1 sec interval.
     */

    long frameCounter;
   
    /*
     * Saves the elapsed time in nanos.
     */

    long elapsedTime;
   
    /*
     * A rectangle to use as a basic game object to move
     * around on screen.
     */

    Rectangle2D rect;
   
    /**
     * Create a new GameLoop that will use the specified GraphicsDevice.
     *
     * @param device
     */

    public GameLoop(GraphicsDevice device) {
        try {
            // Setup the frame
           GraphicsConfiguration gc = device.getDefaultConfiguration();
           
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated(true);
            mainFrame.setIgnoreRepaint(true);
            mainFrame.setVisible(true);
            mainFrame.setSize(640, 480);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.createBufferStrategy(2);
            mainFrame.addKeyListener(this);
            // Uncomment this code if you want to see the game loop run full
           // screen. Running in full screen will enable the buffer strategy's
           // vertical retrace lock which should result in smoother animation.
           //device.setDisplayMode(new DisplayMode(640,480,8,DisplayMode.REFRESH_RATE_UNKNOWN));
           //device.setFullScreenWindow(mainFrame);
           
            // Cache the buffer strategy and create a rectangle to move
           BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
            rect = new Rectangle2D.Float(0,100,64,64);
           
            // Main loop
           
            while(true) {
                long time = System.nanoTime();
                elapsedTime = System.nanoTime() - time;
               
                updateWorld(elapsedTime);
               
                // Draw
               Graphics g = bufferStrategy.getDrawGraphics();
                drawScreen(g);
                g.dispose();
               
                // Flip the buffer
               if( ! bufferStrategy.contentsLost() )
                    bufferStrategy.show();
               
                // Synchronise with the display hardware. Note that on
               // Windows Vista this method may cause your screen to flash.
               // If that bothers you, just comment it out.
               Toolkit.getDefaultToolkit().sync();
               
                yield();
                calculateFramesPerSecond();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
       
    }
    private void updateWorld(long elapsedTime) {
       
        //double xMov = 0.001 * elapsedTime;
       double xMov = 2.0;
        rect.setRect(rect.getX() + xMov, 100, 64, 64);
       
        if( rect.getX() > mainFrame.getWidth() )
            rect.setRect(-rect.getWidth(), 100, 64, 64);
       
    }
   
    private void drawScreen(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, mainFrame.getWidth(), mainFrame.getHeight());
        g.setColor(Color.WHITE);
        g.drawString("FPS: "+ fps, 0, 17);
       
        g.setColor(Color.RED);
        g.fillRect((int)rect.getX(), (int)rect.getY(), (int)rect.getWidth(), (int)rect.getHeight());
    }

    protected void yield() throws InterruptedException {
      long delayTime = 1000000000L/fpsLimit  - (System.nanoTime() - lastFrameDrawn);
      if(delayTime > 0) Thread.sleep(delayTime/1000000);
      lastFrameDrawn = System.nanoTime();
   }
   
    private void calculateFramesPerSecond() {
        long time = System.nanoTime();
        if( time - lastTime >= 1000000000L ) {
            fps = frameCounter;
            lastTime = time;
            frameCounter = 0;
        }
        frameCounter++;
    }
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
            System.exit(0);
        }
    }
    public void keyReleased(KeyEvent e) {
       
    }
    public void keyTyped(KeyEvent e) {
       
    }

    public static void main(String[] args) {
        try {
            GraphicsEnvironment env = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            new GameLoop(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


--Mario
6  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-16 08:34:14
Hmm... You can't do a Thread.yield() in your delay section as it will peg the CPU. It is better just to put the thread to sleep for the length of the delay time. Additionally, the AWT thread is running at a higher priority than your game thread so you don't need code that gives it a chance to run. As far as I am aware, the only time you need to use yield is when you have a thread running at maximum priority and you need to give lower priority threads a chance to run.

I really want to get this stutter problem sorted out but I'm beginning to think that it is impossible.

--Mario
7  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-16 03:31:49
I know how to write a game loop with a fixed time step, a variable time step and move objects in discrete increments and I know the benefits of these aproaches. I also know how to compensate for variable time step physics simulations by decoupling the physics update from the framerate and using an alpha blending approach to cope with any remainder problems. In short I know how the mathematics for game loops work. Cool Your comments are simply unfair.

Anyway, it still stutters regardless of whether you use a fixed, or variable time step. The C code doesn't, which is strange because the JVM writers have access to the exact same C libraries that I do. If you write games in pure Java they stutter. I'm sorry but I think I'm correct, Java is not a good language for games development. Or more accurately, the JVM is not a good platform upon which to build a game.

If you use a native lib to do your graphics, input and sound then you might as well continue writing the game in C. At least in C you can synchronize the main loop properly. I think it is Java's shortcomings in the timing and synchronization arena that you are attempting to vainly support (it is obviously inadequate) and that you're just making excuses for Java's stuttery, laggy games performance by pointing the finger at my coding errors which were Java specific and based upon lack of experience in Java. It isn't fair to dismiss me as having made basic fundamental errors simply because I am new to Java. Let's face it, the code that I posted was pretty simple stuff and it was a fair translation of how you implement a simple game loop. Works in C, doesn't work in Java. Hmm... why not? That was the basis from which I approached the problem.

Why is it that Java games require a native library to handle the graphics & input in a satisfactory manner? Is it because pure Java simply sucks from a games development point of view? I think so. And it is obvious that others do too otherwise they wouldn't need the native libs.


--Mario
8  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-16 02:33:49
@Mr_Light: It still stutters on my machine --I didn't run your code for long enough to see the stuttering effect the first time. It is as if something is throttling the execution thread, slowing it down and then speeding it up.

The *reason* you don't see stuttering as bad with your example is that you are not updating the game objects inline with elapsed time, you just tick them forward a fixed increment at a time. That's why your example looks smoother even though the game objects are actually moving at a variable rate. My game needs physics and that means integrating values over an elapsed time period.

I need to think about this issue some more. Something in the JVM or in the OS is throttling the execution thread.

--Mario
9  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 23:30:45
@Mr_Light: Gosh, that was well written. It also runs smoothly.

Thanks for the lesson. That's me told. I consider myself spanked.

--Mario
10  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 22:39:45
Ever figured the problem could be between the screen and the chair?

Frequently  Grin
Quote
your code stutters here too, I've added an adaptation of your original code that works smooth here. it also consumes a fraction of my cpu-time compared to yours.

ps. I won't be handing out cookies for the obvious memory leak that's in there.  Tongue

That's not fair, I'm a C programmer not a Java programmer, you have way more experience. Undecided Are you just going to sit on the mod'd code without telling me what you've done?


--Mario
11  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 10:35:20
Look, when I write the same code in C it works flawlessly with no stutter and no lag. When I write the code in Java there is stutter and lag. The problem is not my hardware, the problem is Java. Angry

--Mario
12  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 10:06:58
'Course you can, yeah. Bu-ut, the main game loop stutters and lags if you use pure Java. That is what this thread is currently about.

--Mario
13  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 09:47:14
LWJGL doesn't work on all systems. To run LWJGL code you must either have a graphics card plus drivers that support OpenGL, or a software OpenGL emulation layer. A lot of people out there simply will not be able to run your game.

As soon as you include native libs like LWJGL you effectively reduce the portability of your code to people who have compatible hardware. Cas has already said that he doesn't really use much OpenGL code, all he does is blit quads and draw lines. If that's all then you might as well use Windows GDI and DirectDraw and your game will work on every Windows machine.

I think now that if you're going to write games in Java, then for maximum portability you should stick to pure Java. But so far it looks as though pure Java isn't up to the job of managing a simple game loop.  Shocked

--Mario
14  Java Game APIs & Engines / Java 3D / Re: im looking an sofware accelerated 3D engine for my Applets. on: 2008-11-15 07:00:10
http://www.jpct.net/

--Mario
15  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 04:30:53
We've gotten way off topic here...

Yup. The thread is about reasons why Java should not be used for games writing.

To bring the thread back on track I thought I'd post the updated test code I'm using. It is a physics based main loop and the physics update code is decoupled from the framerate with a fixed time step --quite groovy really. But it is still jerky, despite the addition of a call to synchronize with the display adapter. Recall from previous posts that the stuttering and lag is a major reason for saying no to using Java for writing games. It needs a bit of a clean-up because I've hacked about with it a bit but there is no reason I can think of why this code should produce a stuttering animation.

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  
package gameloop;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;

/**
 *
 * @author Mario
 */

public class Main implements KeyListener {
    private static Color[] COLORS = new Color[] {
        Color.red, Color.blue, Color.green, Color.white, Color.black,
        Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
        Color.magenta, Color.orange, Color.darkGray };
    Frame mainFrame;
    /*
     * Saves the last time the frame counter looked at the clock
     */

    long lastTime;
    /*
     * Stores the calculated frames per second
     */

    int fps;
    /*
     * Stores a count of the number of frames that have been issued
     * within 1 second
     */

    int frameCounter;
    /*
     * Saves the elapsed time in nanoseconds
     */

    long elapsedTime;
    /*
     * Stores the calculated time to delay at the bottom of the main loop
     */

    double delayTime;
    /*
     * Total game time in nano seconds
     */

    float gameTime;
    /*
     * Fixed time step in seconds
     */

    float dt = 0.01f;
    /*
     * elapsed time accumulator in seconds
     */

    float accumulator;
    /*
     * Desired frame rate
     */

    double frameRate = (double)1000000000L/(double)60;
   
    Rectangle2D rect;
   
    public Main(GraphicsDevice device) {
        try {
            // Setup the frame
           GraphicsConfiguration gc = device.getDefaultConfiguration();
           
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated(true);
            mainFrame.setIgnoreRepaint(true);
            mainFrame.setVisible(true);
            mainFrame.setSize(640, 480);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.createBufferStrategy(3);
            mainFrame.addKeyListener(this);
            //device.setDisplayMode(new DisplayMode(640,480,8,DisplayMode.REFRESH_RATE_UNKNOWN));
           //device.setFullScreenWindow(mainFrame);
           // Cache the buffer strategy and create a rectangle to move
           BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
            rect = new Rectangle2D.Float(0,100,64,64);
           
            // Main loop
           
            while(true) {
                long time = System.nanoTime();
                calculateFramesPerSecond();
               
                // Add the elapsed time in seconds to the accumulator
               accumulator += (float)elapsedTime/(float)1000000000;
                // For each dt in the accumulator, update the physics
               while( accumulator >= dt ) {
                    // Update world
                   updateWorld(dt);
                    gameTime += dt;
                    accumulator -= dt;
                }
               
                // Draw
               Graphics g = bufferStrategy.getDrawGraphics();
                drawScreen(g);
                g.dispose();
               
                // Flip the buffer
               if( ! bufferStrategy.contentsLost() )
                    bufferStrategy.show();
               
                // Synchronise with the display hardware
               Toolkit.getDefaultToolkit().sync();
               
                // Delay for a period of time equal to 1/60th of a
               // second minus the elapsed time
               elapsedTime = System.nanoTime() - time;
                delayTime = frameRate - (double)elapsedTime;
                time = System.nanoTime();
                while( System.nanoTime() - time <= delayTime)
                    Thread.yield();
               
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
       
    }

    private void updateWorld(float deltaTime) {
       
        rect.setRect(rect.getX() + 240*deltaTime, 100, 64, 64);
       
        if( rect.getX() > mainFrame.getWidth() )
            rect.setRect(-rect.getWidth(), 100, 64, 64);
       
    }
    private void drawScreen(Graphics g) {
        g.setColor(COLORS[0]);
        g.fillRect(0, 0, mainFrame.getWidth(), mainFrame.getHeight());
        g.setColor(COLORS[3]);
        g.drawString("FPS: "+ fps, 0, 17);
        g.drawString("Game time: " + gameTime, 0, 34);
        g.setColor(COLORS[1]);
        g.fillRect((int)rect.getX(), (int)rect.getY(), (int)rect.getWidth(), (int)rect.getHeight());
    }
    private void calculateFramesPerSecond() {
        long time = System.nanoTime();
        if( time - lastTime >= 1000000000L ) {
            fps = frameCounter;
            lastTime = time;
            frameCounter = 0;
        }
        frameCounter++;
    }
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
            System.exit(0);
        }
    }
    public void keyReleased(KeyEvent e) {
       
    }
    public void keyTyped(KeyEvent e) {
       
    }
    public static void main(String[] args) {
        try {
            GraphicsEnvironment env = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            new Main(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


I realize that many of you use LWJGL because of the performance hit, but I actually can't see the point of including native libraries with a Java program. When a Java program calls for native support I automatically reach for my C/C++ compiler. Once I'm in the C/C++ environment I'm reluctant to leave it to go back into Java as it just feels as though I'm creating a DLL for scripting purposes. I might as well stay in the C/C++ IDE and write the whole thing in C and then I don't have to concern myself with producing JNI interfaces. So-o, I want to write pure Java games without native support.

--Mario
16  Discussions / General Discussions / Re: Java Applets. Problems? What problems? on: 2008-11-15 02:54:44
I have the ATI Radeon Xpress 1100 chipset with a DirectX 7 driver. Unfortunately, the card doesn't seem to support OpenGL: the driver software says that OpenGL is unavailable. It is the latest driver software package from AMD for my card too.

The machine is a laptop so I can't just go out and buy an NVidia card. I guess I'll have to buy a proper machine.

--Mario
17  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 02:41:11
Damn. Graphics card doesn't support OpenGL. I wanted to download and try the Puppy Games too.

--Mario
18  Discussions / General Discussions / Re: Java Applets. Problems? What problems? on: 2008-11-15 02:00:43
Have a look at this:

http://www.puppygames.net/applets/test/

It's big right now - haven't optimised it for applets, should be able to cut out another 3mb or so - and it misbehaves a bit on shutdown and seems not to work properly in Chrome. But it's nearly there!

Cas Smiley

I can't play it. Undecided The screen shots for your games look really good too. That's why I want to write pure Java because the native libraries fail on some machines.

I wish someone would write a good shooter in pure Java so that I could see what can be done. Attack of the Meeplings wasn't bad, but it didn't really have much in the way of effects to make it more interesting.

--Mario
19  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 01:28:18
The installer for the newest graphics drivers from AMD fails to execute properly on my machine. Windows Vista notifies me with a "this program has stopped working" dialog. I think the installer wasn't tested on Windows Vista. Undecided So, I can't update the drivers to run LWJGL code until AMD get around to fixing their installer to work with Vista. Cry

--Mario
20  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-15 00:25:21
Maybe I'm missing something, but I seriously don't know how you can call that 'Unpredictable as Hell'  Huh
Given that Thread.sleep() has a precision of 1ms, 9998757ns IS exactly the amount of time you intended to sleep, so your example just demonstrates that Thread.sleep() works as advertised and your code to report a failure is wrong.
...

Since when was 9998757ns ever equal to 10ms? Okay, it is close to 10ms but it is not exact.

This thread is about why Java is not a good language for game development and the sample code which attempts to synchronize a main loop to 60fps clearly doesn't work properly on my machine (a reasonably well spec'd one) which is why I am investigating Java's timing abilities. A jerky screen update is a major reason for abandoning Java as a games development language.

Here's some timer test code written by David Brackeen that shows the problem. He's already stated in a PM to me that he believes it to be a thread scheduling problem. When you execute it you should get no jumps forward.

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  
import static java.lang.System.out;


public class TimerTest implements Runnable {

    long testLength = 10L * 1000 * 1000 * 1000; // 60 seconds
   long iterations = 0;
    long jumpsForward = 0;
    long jumpsBackward = 0;
    boolean lastWasAJump = false;
    long firstTime = System.nanoTime();
    long lastTime = firstTime;

    public void run() {
        while (true) {
            Thread.yield();
            long time = System.nanoTime();
            if (time < lastTime) {
                out.println("Backwards by: " + ((lastTime - time) / 1000000.0f) + "ms");
                lastWasAJump = true;
                jumpsBackward++;
            } else if (time >= lastTime + 1000 * 1000 * 10) { // 10ms
               out.println("Large jump by: " + ((time - lastTime) / 1000000.0f) + "ms");
                lastWasAJump = true;
                jumpsForward++;
            } else if (lastWasAJump) {
                out.println("Back to normal");
                lastWasAJump = false;
            }
            lastTime = time;
            iterations++;

            if (time >= firstTime + testLength) {
                break;
            }
        }

        out.println(iterations + " iterations.");
        out.println(jumpsBackward + " jumps backwards");
        out.println(jumpsForward + " jumps forwards");
        out.println("Java " + System.getProperty("java.version"));
    }

    public synchronized static void main(String[] args) {
        Thread t  = new Thread(new TimerTest());
        t.setPriority(Thread.MAX_PRIORITY);
        t.start();
    }
}


--Mario
21  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-14 23:44:20
Try using Toolkit.getDefaultToolkit().sync(); just after you call show() of BufferStrategy.

That dramatically improves things. Interestingly, it causes Windows Vista to revert to what it calls a basic colour scheme: "The following program has performed an action that requires Windows to temporarily change the colour scheme to Windows Basic." The popup help hints at the fact that there is either: (i) insufficient memory to continue displaying Windows Aero (the default scheme on Windows Vista) translucent Windows. Which is unlikely, or (ii) the computer's hardware configuration or screen resolution was changed.

Looks like a call to sync() triggers this behaviour on Windows Vista. Bu-ut, the frame rate is now more or less steady at 58-60 FPS. Thanks jezek2.

--Mario
22  Games Center / Showcase / Re: Battle tank 2 - a bird eye view shooter on: 2008-11-14 03:35:35
You're not gonna believe what just happened. I was reloading the Applet over and over again. On about the twentieth reload the applet left the window and reappeared in the top left hand corner of the screen! Cheesy BTW I saw no memory issues in task manager.

This Applet stuff is getting hysterical, it really is.

--Mario
23  Discussions / General Discussions / Re: Java Applets. Problems? What problems? on: 2008-11-14 01:39:55
I've seen to many gray boxes on web pages to have any real faith in Java Applets.
[move]Isn't this an annoying thing to do? Grin[/move]
24  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-13 21:36:53
@Dzzd: Okay, there's a strong possibility that I have hardware that Java just doesn't like very much. But, the problem is that I can write a rock-solid game using C & SDL and the timing will be 100% accurate. This code works just great on my machine so I don't think my hardware can be all that bad, I'm more inclined to think that the problem lies with Java not me. True, I should not have locked up the CPU in the while loop but I fixed that and it made no difference.

I'm just totally bemused by the way the Java code behaves, it seems to have a mind of its own and that makes me feel nervous and unsafe when I'm writing code on top of code that makes things move around unpredictably over time. All I can think about is that if the Java code is doing this to me then chances are it is going to do the same to a lot of other people too. What it boils down to is that if I use C I get no timing problems, but if I use Java I get timing problems.

--Mario
25  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-13 21:01:47
@Kev: I'm not a Java hater. It is impossible to hate a language which is obviously so beautifully engineered. At heart I'm a C programmer and I use Java because I think it has a great class library, blindingly good tools and a knockout windowing kit all built-in to one package. Also, server-side Java goes like sh*t off a shovel. The speed of Java isn't an issue for me, it is the reliability of the programming APIs. I don't know about you, but for me timing bugs are a source of major headaches and Java's timing (I'm basing this upon what David Brackeen and Dzzd has said) isn't up to the job for games writing.

I would like to be able to write games in Java because it gives me one-click deployment off a web page but I'm forced back into C simply because Java has got the fundamentals wrong. In gaming, timing is everything.

--Mario
26  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-13 20:48:37
@Riven: Yeah, you've hit the nail on the head. My only raison d'etre for using Java is the gorgeous IDEs and other build tools (like Ant) that are available. Plus the Javadoc popup thing in the editor makes coding to libraries a breeze. But, if I can't get a stable frame rate because the platform timer sucks then no way am I going to use Java.

BTW Pulpcore is excellent David, but the applets are jerky. It is such a shame 'cos Pulpcore has got a beautiful timing and animation framework. I wrote a quick 2D shooter using Pulpcore and it was just dead easy to do, but I stopped writing when I noticed the jerky screen updates becase I thought that nobody will play a game for more than ten seconds if it is lagging and jerking around on screen. In fact, I think players will actually start to *hate* you for publishing a jerky game. Jerky games are my number one biggest turn off.

I have no idea whether the problem is due to the Java system's timer, or the graphics libraries. I just know that I can't use it to write games 'cos the stutter & lag offends my sensibilities as a programmer first and as an avid games player second.

--Mario
27  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-13 20:02:03
So in summary, is it fair to say that Java is bad choice for game development if you do not include native libs?

I think the answer to the question is fairly obvious really. I don't mind using native libraries from within Java, but using them increases the likelihod that my game will fail to start up on another machine. For example, neither LWJGL nor JOGL will work on this Windows Vista laptop that I'm using despite the fact that it is a reasonably well specc'd machine. LWJGL complains about an unsupported pixel format (video card trouble) and JOGL regularly crashes the JRE, though software emulation works just fine but is far too slow for games work. I can't play Puppy Games' games because they won't start up on my machine. The failure to start problem is just *eating* away at your profits Cas. A DirectX version in C++ would have run just fine. A shame really 'cos I really like playing shoot-em up games --they help me to concentrate.

As for writing games in pure Java, I've given up! There are timing problems and screen update problems that I just don't get if I use C and a really simple hardware layer interface library like SDL. Additionally, there is something deeply suspicious about the inner-workings of System.nanotime() and the lag and stutter in the main game loop is causing me so many headaches. Again, as Kev suggested, it is probably a hardware problem but I no longer care about Java's hardware interface problems. My lack of care in this respect is prompted in part by the suspiciously low coupling of Java  to hardware.

Anyway, back to the point. If I can't do something really, really basic like time the appearance of game objects and move them *smoothly* around on screen (even at low frame rates on really bad hardware) then I don't really want to know what else Java can do. Hell, even Blitz Basic and Dark Basic will give me a smooth, consistent main loop on a crappy 500Mhz Pentium, why won't Java? Christ, even Flash will give me a steady frame rate and Flash is the suckiest of the suckiest arse-over-tit, extra-ecma-anal game programming environments. On this machine, I only get a stable frame rate for my test code in Java if I drop the frame rate to ten frames per seconds, which is unusable except for the simplest of puzzle games.

It is not enough to say, well there's something wrong with the way you're doing your screen updates in the test code (as Dzzd said) and you need code to stabalize the frame rate. That's just a load of bollocks Dzzd. There's nothing wrong with the code: time the game objects update & drawing operations and then sleep for a period of time to sync the loop at sixty frames per second, or whatever frame rate you can get away with. It doesn't get much simpler than that. Coding a game loop is trivial, yet Java just doesn't seem to be able to handle the timing and synchronisation requirements and produces inexplicable stutters and lags in the main loop. Let's face it, stutter and lag are just anathema to a games writer. Its the kind of thing that furrows your brow when you're falling off to sleep and it is annoying because the problem subtracts thinking time from designing and implementing the game play and game mechanic. Incidentally, when I ported the test code across to C and SDL, I got a rock steady frame rate. As expected, with none of the stupid bollocky timing artifacts that Java seems to throw in to the mix.

The other thing that is bothering me, which cas has touched upon, is that there is no console support in Java. If I write a game for the PC and it does reasonably well then the obvious thing to do would be to use the profits generated from the PC version to purchase a console development kit and port the game across. If I've already written the game in C then porting becomes trivial, if it is written in Java with native lib dependencies then porting is not so easy and straight-forward. In fact, it is probably near enough a complete rewrite.

IMO Java fails as a choice for game writing at the most basic level: the game's update/render loop. This is unpardonable for a runtime that wants to make it in the game writing arena. If the timing in your game is off then the players will notice and stop playing the game and they certainly won't buy a game that stutters and lags. I'm a little annoyed not to mention peeved at the amount of time (wasted in my opinion) I have spent writing and debugging code on a platform that just doesn't perform well enough and no amount of tinkering will coax the JRE, or the graphics libraries or the timer or whatever the Hell the problem is with Java's jerky screen updates into giving me a stable main loop on top of which I can build a playable game.

I'll continue to hang around the forum to see if things improve, but TBH I think that Java's games writing problems are fundamental and located within the JRE and the native interface code. Aargh, all those bloody layers just to get at the hardware! I'm sorry, but I think you are completely wrong to spend your time writing games in Java. C/C++ is a much better choice. Using Java for games writing just brings to mind a modern curse: may your games stutter and lag for all eternity.

I'll stick around the forum to view the games showcase releases (I do like seeing those) and just generally monitor the Java performance related posts but as for using Java to write a commercial game, I think I'd rather eat a pooh sandwhich and wash it down with an extra large cup of vommit. Grin Heh, not that I'm in the habit of consuming such eye wateringly disgusting repasts. My experiences with Java game programming have given me a bloody twitch. Right, where the Hell's my C compiler? Sanity extends an elegant, manicured finger and beckons with a sultry call "this way young Jedi, this way...".

Jesus, you know what? I'm actually beginning to believe that I'll need a theraputic course in advanced cognitive neronal repair after my experiences with that JRE and class library. I feel that my experience of writing games in Java has just caused the window of opportunity to slam down on my fingernails, throwing me breathless to the floor. And there I lied, helpless, as I watched the Sun Necrosystems vultures descend from the sky to pick at my loathsome bones...

--Mario

28  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-13 00:04:41
... at least add a thread.yield or you will produce a cpu lock (if your blitting has been delayed for example it will be locked..), (there are severals java source code available and able to produce a stable frame rate).

Yes, you're right. I added the Thread.yield() call into the main loop.

Quote
IMHO : even  from an algorithm point of view the method you have used is innacurate as the error are cumulative over time => with your method at 60fps after 100 s you can have produced a number of frame very different than 6000 (60*100)

The method I'm using is the only one I know for producing a reasonably acceptable frame rate. Do you have any code to share that can increase the accuracy? For example, do I need code that will measure the frame rate while the game is running and increase the frame rate to compensate for cumulative errors over time?

--Mario
29  Game Development / Shared Code / When System.nanotime() runs backwards on: 2008-11-12 23:30:06
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
package gameloop;

/**
 *
 * @author Mario
 */

public class NanoTimeBackwards {

    public static void main(String[] args) {
        long diff = Long.MAX_VALUE - System.nanoTime();
        long days = (diff / 1000000000L) / 60 / 60 / 24;
        long years = days / 365;
        System.out.println(
                "Your nano timer will run backwards in "+years+" years.");
    }
}


Edit: Oops, was multiplying instead of dividing.


--Mario
30  Discussions / General Discussions / Re: Reasons why Java is not a good language for game development on: 2008-11-12 22:46:54
Doesn't work.  Sad Task manager shows the java.exe consuming only 76% of the CPU.

--Mario
Pages: [1] 2
 

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

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (36 views)
2014-04-15 18:08:23

BurntPizza (32 views)
2014-04-15 03:46:01

UprightPath (47 views)
2014-04-14 17:39:50

UprightPath (30 views)
2014-04-14 17:35:47

Porlus (47 views)
2014-04-14 15:48:38

tom_mai78101 (68 views)
2014-04-10 04:04:31

BurntPizza (128 views)
2014-04-08 23:06:04

tom_mai78101 (228 views)
2014-04-05 13:34:39

trollwarrior1 (193 views)
2014-04-04 12:06:45

CJLetsGame (200 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30
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!