Is it good to separate game thread and display thread? - java

It is the first time I want to write a java game, and I chose to do a Snake Line.
I learnt from a piece of source code from online. It updates the game states and displays in one thread. I changed around that code, and when I changed the FPS (from 60 to 30), animation slows down. More to this, the game behavior changes too. It is duck shooting game, and the space between ducks get narrower.
So I decided to separate the game thread and the display thread to avoid the above problem. But then I realize it brings out the concurrency problem which will be all over the place.
So as the title indicates, is it good to separate game thread and display thread? What is the common practice and why?

From the changes you experience, it sounds like you are using frame as a unit of time measurement. Or, more precisely, you use pixel/frame(or something like that) for velocity and second for time.
This might be OK for a simple game like yours, ones that are light enough on the system resources so that the delay between frames you specify in the code is practically the same as the real delay, meaning you are in complete control over the FPS. When the game get heavier and modern systems can no longer guarantee that property, you have a problem.
The solution is usually not to separate the game and display loops to separate threads, but to not use frames as unit of measurement for game mechanics calculations. Instead, each frame measure the time from the previous frame and use that value for the calculations, eg. multiply it by the speed to know how much to move a game object in this frame.
Not that separating those loops is such a bad idea. You don't get concurrency problems "all over the place", since the interaction between the game logic and the display shouldn't be "all over the place". The interaction should be one-way: the game loop writes data and the display loop reads it. That means you shouldn't have race conditions, but you can still get other multithreading hazards, which you can solve with volatile variables.

Related

Separate logic and rendering threads?

I have heard some people advising the separation of logic and rendering into different threads when making games. Apparently, while rendering needs to happen at ~60fps, logic may only need to happen at ~10fps.
I have a few questions about this:
How can the rendering be faster than logic, if logic is what changes the scene? Surely the rendering thread will be repeatedly drawing the exact same image until the logic kicks in to move the entities around the screen, etc?
Won't this create all sorts of nasty concurrency issues, as the logic and rendering may require simultaneous access to the game's objects?
Can I assume that it's perfectly acceptable to keep my logic and rendering in the same thread? I am using the LWJGL, whose tutorials all seem to suggest a common "game loop" which includes both logic and rendering.
If your game logic does not change the scene, your rendering thread could detect this by giving the scene a dirty flag. if the scene is not dirty, the rendering thread may return the old rendered scene again. Sometimes a scene will change even if the game did nothing due to animated objects like grass, trees or flags.
This will happen because two threads do access the same data. But if the game logic thread processes junks of objects locally and updates those chunks kind of atomically, the concurrent access to the same data should be reduced while processing that data. What I try to say is, do not process the concurrently accessed data in a fine grained way but in a coarse grained way to reduce locking.
In my opinion you should never over-complicate a design if not needed. If you have enough time to process the scene 10-times in a second and to draw it, then you should not use more than one thread. All the older games did it one threaded and it worked. As soon as your game gets more and more complex and one thread can't do all the stuff in 1 / 60 seconds, you may want to use more than one thread to take advantage of a multi-core machine. But you should wait until need be, before introducing many threads.
A sprite may be animating through a series of frames, but no game logic (crash detection, movement, etc) may be required.
You will need to use some form of synchronisation or locking.
It depends how much work your rendering and logic code sections are doing.

Is there a more ideal way to send draw commands?

I'm still working on moving my android app over to OpenGL and i'm once again having an issue.
I have gotten to the point where everything FUNCTIONS, the only problem is that the animation seems a little juddery.
I'm monitoring the frame rates and seeing that the drawing thread isn't slowing down, but every once in a while, the main loop slows a bit and I suspect I'm having a problem I was worried about.
The way the app works is that as new objects (say for instance, enemies) are created, 2 objects are actually created. The first one is created and mapped in the main thread, and then in it's constructor, it creates a mesh object which is then added to a group to be drawn continuously by the renderer.
Every time an attribute for the object is changed, (such as its coordinates) The object relays the necessary command to its mesh counterpart (in this example to translate the mesh.)
It was suggested that this was thread safe communication, but i'm having my doubts. I also notice a greater amount of frame skip when new objects are created, I can fix this somewhat by reusing the same mesh object for identical Game objects, but I don't believe this will fix everything by itself.
Can you think of a way to make this more efficient and thread-safe?
Another possible solution: The game logic does not HAVE to go at full speed (realtime) I have it actually set up so that no updates are made untill 33 millis pass. So obviously, I should have plenty of time between frames to draw, can I set it up so that draw is only called on command in the thread (after the game logic has been updated)?
It looks like you need something like a ScheduledThreadPoolExecutor.
With one of these you could put your renderer on a schedule so it executes at 30fps leaving your main/control thread to do whatever it needs to do to the object map between frames.
I don't think you need any wait/notify interlocking as all you really need is to block access to the map while the renderer is walking it. To do this you just need to make the map synchronized. As this will only happen once every 1/30th of a second you are certainly not introducing a significant overhead.
Your main aim should be to put as little unnecessary load on the CPU as possible, this is the key to smooth multithread work. Try to spend as much time as possible either sleeping or blocked.
Added
I subtract the time it took to loop from 33ms, and use the result to specify the length of sleep().
I wonder if that may be part of your issue. On a Windows machine you often get a 15ms resolution on the currentTimeMillis so your sleeps may end up hardly sleeping at all. It may be worth experimenting with a ScheduledThreadPoolExecutor just to see if it improves your timing. ... oops ... this is Android isn't it. Still ... it may be worth a try.

Lag in Java Game

I'm writing a game in Java. And, oh wonder, i have performance issues. I benchmarked the paint itself - 1000 cycles in 3 ms tops. The game logic is even below that. So far, so good. But i still encounter an annoying lag: When scrolling, when zooming, when clicking. The problems get worse when i zoom in and more objects are placed. But still - even when I loop the painting a 1000 times the lags stays more or less the same, so that cant be it.
I tried putting the loop in a task - still the same. I tried pausing the task in between paints - still the same.
Animations run as smooth as silk (since the framerate is stable and high, that makes sense). So how on earth do i organize the inputs in an orderly fashion? Put them all in a seperate thread?
Any input would and will be greatly appreciated!
It sounds like you're using listener callbacks directly on the Swing Event Dispatch Thread, where the UI updates are being done. You should use a command queue, and put events on the queue when a callback is invoked, with the nature of the command, then you use this in the main game update loop that has nothing to do with the EDT.

Choppy Image on multithreaded android game

I decided to convert my spritesbased 2d game for android to use opengl-es to help with some render-related framerate issues. Currently the setup is as follows:
Rendering tkaes place in its own thread, with rendermode set to continuous. Game logic updating takes place in a seperate threaad. Both threads interact with a synchronized drawlock class which ensures that they are never touching the game information simultaneously.
So basically, the render thread waits for any current update to finish before drawing and the update thread waits for the current render to end before starting an update. Everything looks great except or some choppiness I've noticed in the picture when moving around the screen.
I believe this is likely due to a lack of consistency in the number of updates that happen in between each render, on average twice as many updates happen because as of right now not a whole lot is happening in the update. But this lacks consistency so sometimes 1 gets through, sometimes 2, 3 etc so the delta in positions of items being drawn is also not consistent thus creating the choppiness.
Anyone have an idea how I might rectify this? The update thread is regulated to 60 times per second with sleeps...maybe something similar needs to happen under render? I'm just not sure at this point.
Depending on how voluminous your game data is, you might try replicating it. While the game engine is updating one copy, the rendering engine is working off the other. When an update is finished, the rendering engine switches to reading the updated copy while the game engine waits until the updates are transferred to the older copy (which the engine will then update on the next cycle). It's kind of a double-buffering approach, but applied to the game data instead of to the display buffer.

Gameloop for j2me "turn-based" game

Edit: This makes alot more sense to me now that i've taken a step away from the code, thanks for the help.
Just found stack overflow the other day through Coding Horror and it looks awesome. Figure that i'd ask the community about a problem i'm currently trying to work out.
I'm developing a roguelike sortof game using j2me for midp 2.0 phones. The project is still in the basic stages of development as I figure out how it's going to work. The part i'm currently stuck on has to do with threading.
The game has a custom HaxCanvas class which extends GameCanvas and Implements runnable. It's run method calls repaint() and then sleeps for 50 ms, resulting in a frame rate of 20 FPS. This allows me to write the rest of the game without having to put repaint everywhere and should make animations and effects easier to do later on. (at least in theory).
The flow of the game is controlled by a GameManager class, which loops through all the NPC's on the map, taking their turns, until it's the player's turn. At this point I need to get input to allow the player to move around and/or attack things. I originally was calling gameManager.runUntilHeroTurn() in the keyPressed method of my HaxCanvas. However after reading up on j2me system threads I realized that putting a method with the potential to run for a while in a callback is a bad idea. However I must used keyPressed to do input handeling, since i need access to the number keys, and getKeyStates() does not support this.
Sofar my attempts to put my gameloop in it's own thread have resulted in disaster. A strange "uncaught ArrayIndexOutOfBoundsException" with no stack trace shows up after the game has run for several turns .
So i suppose my question is this:
For a "turn based" game in j2me, what's the best way to implement the game loop, allowing for input handeling only when it's the player's turn?
Although not j2me specifically you should capture user input, the general strategy is to queue the input it until its time to process the input.
input ---> queue <---> Manager(loop)
This way you can even script input for debug purposes.
So you don't need a new thread. Each time the user presses key you store them in a buffer, and then process the contents of the buffer when necessary. If the player buffer has no input, the manager should skip all gameplay, do animations and then start over (since the game is not an action game).
I would avoid threading for the game logic as J2ME threading, depending on manufacturer of course, does not do a great job of sharing the limited resources. You will often see pauses while a thread does heavy processing. I would only recommend threads for loading or network connectivity features as in this case you will just be giving the user basic "Loading..." feedback.
To handle this, I would not have sub-loops to update each of the AI in one frame. I would do something like following in the run function:
public void run() {
while(true) {
// Update the Game
if(gameManager.isUsersTurn()) {
// Collect User Input
// Process User Input
// Update User's State
}
else {
// Update the active NPC based on their current state
gameManager.updateCurrentNPC();
}
// Do your drawing
}
}
You want to avoid having everything updated in one frame as 1) the updating might be slow, resulting in no immediate visual feedback for the user 2) you can't animate each individual NPC as they make their action. With this setup you could have NPC states, NPC_DECIDE_MOVE and NPC_ANIMATING, that would allow you further control of what the NPC is doing. NPC_ANIMATING would basically put the game in a waiting state for the animation to take place, avoiding any further processing until the animation is complete. Then it could move on to the next NPC's turn.
Also, I would just have a gameManager.update() and gameManager.paint(g) (paint would be called from paint) that would handle everything and keep the run method thin.
Finally, did you look into flushGraphics()? With the GameCanvas you usually create a Graphics object, draw everything to that and then call flushGraphics(), then wait. The method you mention is the way of tackling it for the Canvas class. Just thought I would mention this and post a link:
Game Canvas Basics

Categories

Resources