Assuming you have some experience with Android animations, you probably know that there are many ways to create an animation in Android, so many that it gets confusing!
Currently I'm developing a game that has about 100 different objects on the screen that need to be animated at all times, a task - that as I understand it - may cost lots of CPU.
So, my questions are:
What is the best Animation class to use in a case like this?
What will be the right approach to go about that?
NOTE: THE ANIMATED OBJECTS PARAMETERS MUST TO BE CONTROLLED AND CHANGED FROM JAVA AT RUN TIME, SO XML ANIMATION IS NOT A SUITABLE SOLUTION.
Any code snippets will be very much appreciated!!
I'm a novice programmer and recently I came across many methods of animation:
Using BufferedImages , ie. draw to image and display using double buffering or triple buffering methods .
Making my sprites components by extending Component or Button . and repainting by repaint(g).
Rastering, using rasters and integer arrays, bitmaps and the like.
I realise that method 1 and 2 are similar as they use paint() methods , however Rastering involves self-made functions , eg. creating functions that set background by traversing the whole array representing each pixel and setting colour to desired colour .
I've seen many folks online use raster methods even though 1 & 2 seem simpler .
Please help me out here guys and tell me what path i should follow and why .
The first and second methods are very similar and would come down to the context of the problem.
The third option would, for the most part come down to providing a flexible API which was independent of the toolkit or framework which was to be used to dipslay it. One could argue that there is a speed increase, but with Swing and JavaFX working more directly with the DirectX and OpenGL pipelines, this is less of an issue.
Unless your planning on dong some seriously low level functionality or interfacing to a non-standard API I wouldn't worry to much about it (some effects painting might be faster done this way, but it's all about context)
Personally, it would focus on developing an understanding of the basics and principles involved and how they might be implemented using the first two options as it allows you to focus on those concepts with a relatively easy API
As time progress or you come across a situation that can't be resolved using these techniques, then it might be time to consider playing with the rastering approach.
Remember though, you still need to get that byte array into a format that the API wants which in of itself, will add overheads
I was given the task of improving the performance of a stock market charting software that uses SWT's GC to draw the charts. The chart drawing needs to be improved because the charts sometimes are redrawn many times per second, and it consumes lots of processor time.
After googling a little, I found a blog entry that suggests the direct modification of ImageData objects instead of using GC's methods, promising great performance gains.
It's an easy task to draw horizontal and vertical straight lines and square shapes using this technique, but when it comes to drawing circles and other irregular shapes there is no easy way.
Does anyone know if there is a library to draw shapes on ImageData objects, just like GC's methods do on Image objects?
Also, does anyone know another way to improve SWT performance?
Thanks in advance.
Measure the performance of your solution. Where is most time spent? Guessing is not enough. In 90% of the cases, your guesses will be wrong. If you don't know, you can't solve the issue.
SWT itself is not slow. In fact, SWT is just a very thin layer over the respective OS system calls to draw.
One of the problems of SWT is that it's synchronized. To make sure that threading issues cause no problems, there is a global lock. So if you render from several threads at once, this can be a problem.
Or maybe you're not caching resources like colors and fonts properly. These are expensive to create. How many GCs do you create? Do you keep one around or do you create a new one per frame?
But I'm just guessing here. Unless you can prove with a performance monitor "most time is spent in ...", there is no way to help you.
Instead of improving the performance of the drawing routines I would concentrate on the drawing logic. Maybe you can just redraw the difference between the old and the new chart? This of course largely depends on how the charts look like and what data they present.
Try to reduce the drawing operations. Do not try to make them faster.
It may seem like a big step (and it is), but the best approach to improve SWT drawing performance for me was to switch to OpenGL rendering. I do not imply that you should draw your whole UI with it, but the charts part.
There are many approaches to do that. My choice was to use the JOGL library. There are also some examples around the net, showing how to integrate with SWT.
The downside to this approach is that you have to learn and use a new API which is very different from what one knows from java.
On the other hand, as your scenes are getting more complex, the gains of externalizing the rendering to the GPU are getting bigger. I have experienced FPS gains between 2x and 10x. Another good thing is that you don't have to make a deep dive into OpenGL, there are great libraries like jMonkeyEngine, hiding much of the underlying complexity.
I've run into an organizational problem with an application I am working on, on the Android platform. The application uses sensors as input and OpenGL as output.
The traditional method is something
like organizing the project into an
MVC where I have the main activity
class load an OpenGL view and a
sensor handling class and will then
probably register some callbacks or
possibly do it on a clock.
The sloppy alternative is having a single class that implements GLSurfaceView and SensorEventListener and then offload the logic into other classes.
Assume very simple drawing code and somewhat complex control system code that will attempt to refresh at 60ish Hz. I am looking for performance, maintainability and easy of development implications, so any and all input is valuable. Also I am a complete novice when it comes to Android or mobile development so if you can show me the light with a third alternative that'd be great too.
Sometimes, over-planning things can be a waste of time.
Different games use different approaches, you'll want to take a look at the replica island's dev blog and code for various hints on how to organize your code using a GLSurfaceView. http://replicaisland.net/
I use your latter approach, but it's not as sloppy as you make it seem.
You don't really need any logic code in your GLSurfaceView, just calls to your classes when certain events happen. (onDraw, onTouch, onKey, etc)
Not sure what's sloppy about this, I maintain my logic in their proper classes.
For example, in my onDrawFrame() I simply do MyAreaManager.draw(gl)
The MyAreaManager class would maintain it's own logic and know what to draw.
As for the clock, you'll most likely want two threads. One for rendering (the GLSurfaceView thread) and one for game logic that runs at a certain logic frame rate.
The logic frame, would simply change the state of the canvas objects and the draw frame would simply draw them as fast as possible.
This way you render as fast as possible and still maintain a steady logic frame rate.
For my university assignment I have to make a networkable version of pacman. I thought I would best approach this problem with making a local copy of pacman first and then extend this functionality for network play.
I would have to say that I am relatively new to java GUI development and utilizing such features within java.
http://www.planetalia.com/cursos/Java-Invaders/
http://javaboutique.internet.com/PacMan/source.html
I have started following the above links with regards to game development within java and an example of the pacman game.
I decided to represent the maze as an int array with different values meaning different things. However when the paint method inside the main game loop is run i am redrawing the whole maze with this method.
for (int i : theGame.getMaze())
{
if (i == 4)
{
g.setColor(mazeWallColour);
g.fillRect(curX, curY, cellSize, cellSize);
curX += 25;
}
else
{
curX += cellSize;
}
index++;
// Move to new row
if (index == 25)
{
index = 0;
curX = 10;
curY += cellSize;
}
}
However this is providing me with less then 1fps. Although i've noticed the example linked above uses a similar way of redrawing each time the paint method is called and i believe does this on a image that is not viewable (kinda like double buffering [I've used a BufferStrategy like the first link explains]) What would be a better way to redraw the maze?
Any pointers/advice with this would be useful.
Thank you for your time.
http://pastebin.com/m25052d5a - for the main game class.
Edit: I have just noticed something very weird happening after trying to see what code was taking so long to execute.
In the paintClear(Graphics g) method i have added
ocean = sprites.getSprite("oceano.gif");
g.setPaint(new TexturePaint(ocean, new Rectangle(0,t,ocean.getWidth(),ocean.getHeight())));
g.fillRect(10, 10,getWidth() - 20,getHeight() - 110);
which made the whole thing run smoothly - however when i removed these lines the whole thing slowed down? What could have caused this?
Updated code
First off, I'd recommend that you use named constants rather than having random magic numbers in your code and consider using enums for your cell types. While it won't make your code run any faster, it certainly will make it easier to understand. Also, 'i' is normally used as a counter, not for a return value. You should probably call it cellType or something similar. I'd also recommend that you use a 2D array for your stage map since it makes a number of things easier, both logistically and conceptually.
That said, here are a few things to try:
Pull the setColor() out of the loop and do it once. The compiler might be able to do loop-invariant hoisting and thus do this for you (and probably will), but conceptually, you should probably do this anyway since it appears you want all of your walls to be one color anyway.
Try calling drawRect() instead of fillRect() and see if that draws faster. I don't think it will, but it is worth a shot, even if it looks uglier. Similarly, you can try creating an Image and then drawing that. This has the advantage that it is really easy to tell your Graphics object to implement a transform on your image. Also, consider taking this out completely and make sure that it is being a significant performance hit.
Also, normally you don't need to ask for the parent for its Graphics object and implement painting directly on it. Rather, you should override its paintComponent() method and just utilize the Graphics given to you (possibly calling helper methods as you do). Swing components are double-buffered by default, so you don't need to implement that yourself; just let the swing object do its job and let you know when to paint.
Also, you end up repainting the entire screen, which is something of overkill. If you call repaint(Rectangle), Swing can choose to redraw only the sections of your board that are explicitly marked dirty. When you update one of your sprites, call repaint(r) only on the area of the sprite's old and new locations. When you complete a level and need a new board, then you can call repaint() (without parameters) to redraw the entire map.
You should also look at Sun's tutorial to get some tips for efficiency in Swing.
I still consider myself a beginner with Java, but I recently developed a Frogger-esque game with dynamic map and editor using some of the techniques you've mentioned, and I'm only too happy to provide some help.
As mentioned, enum's are the way to go. I set my map up as a 2-dimensional array and set an enum for each different type, writing a method inside my map class to take in one image and divide each square in the map to each value in my enum.
A tutorial that helped me with mapping can be found on Coke and Code. All the source code is there if you need a hand with any of it, although you do seem to have a decent grasp of what you're doing. If you still need help I could always drag out some source code.
It looks like your call to Thread.sleep doesn't do what you intended, but I don't think it's the source of your trouble. You have:
Thread.sleep(Math.max(0, startTime - System.currentTimeMillis()));
startTime will always be less than System.currentTimeMillis(), so startTime - System.currentTimeMillis() will always be negative and thus your sleep will always be for 0 milliseconds. It's different from the example you showed because the example increments startTime by 40 milliseconds before doing the calculation. It is calculating how long to sleep for to pad out the drawing time to 40 milliseconds.
Anyway, back to your problem. I'd recommend measurement to figure out where your time is being spent. There's no point optimising until you know what's slow. You already know how to use System.currentTimeMillis(). Try using that to measure where all the time goes. Is it all spent drawing the walls?
EDIT - I see this got marked as accepted, so should I infer that the problem went away when you fixed the sleep time? I don't have a lot of Java GUI experience, but I can speculate that perhaps your code was starving out other important threads. By setting your thread to have maximum priority and only ever calling sleep(0), you pretty much guarantee that no other thread in your process can do anything. Here's a post from Raymond Chen's blog that explains why.
The code you listed above can't be the source of the 1fps problem... I have code doing far more than this that runs far faster.
Can you benchmark that code and make sure it's the root of the problem?
I'm no game developer, but that framerate seems very slow.
I'm not quite sure how your code is working, but one possibility for improving rendering performance would be to find those parts of the display that don't change much (such as the walls of the maze) and avoid re-creating them for each frame.
Create a BufferedImage containing the constant elements (maze?, background) and then re-draw it first for each frame. On top of this Buffered image, draw the variable elements (PacMan, ghosts, dots, etc).
This technique, along with many other Java2D performance tips, is discussed in Romain Guy's excellent book Filthy Rich Clients.
Just so you don't worry that it's Java, I worked on a Spectrum Analyzer (Like an o-scope) where the entire GUI portion(the trace, menus, button & wheel handling) was done in Java. When I got there it was getting 1fps, when I left it was 12-20. That had a lot of processing going on and was running on a very slow processor.
Look at only updating parts of the GUI that you need to update. Often you can redraw the entire screen but just set a clipping region to the part that is truly updated.
Be careful about inner loops--they are The Speed Killer.
Try to avoid allocating and freeing huge numbers of objects. I'm not saying don't use objects, I'm saying don't create one for each pixel :)
Good luck
Wow, that's a pretty tough problem to give someone just learning Java.
My advice? Think in terms of objects. Can you write something WITHOUT a user interface that mimics the behavior of the game itself? Once you get that working, you can concentrate on the special problems of the user interface. Yes, start with a local version before the networked piece.
I'm not a gamer. I wonder what Java2D API would offer to make your life better?
How much time do you have to finish it?
This might sound obvious but your performance problem is because you are redrawing the entire maze, which doesn't need to be done, instead you need to redraw only changed parts of your maze.
The way I've approached this issue before is by seperating the updating of the maze from the actual redrawing into different threads (kind of like a threaded MVC). Every time you change a cell in your maze you would mark it as "dirty", your redraw thread will check every now and then to redraw only the dirty cells.
Sorry for the extremly generic advice
Java/Swing double-buffers by default. If you're using Swing, you don't need to double-buffer separately, like other answers suggest.
I agree with Allain, that the code you listed can't be the cause of 1fps. I've written highly inefficient Java/Swing animation code that runs much faster than you describe. Do some more testing to narrow down the cause of the slowness.
If possible, you should keep an image of the maze, and draw it in one library call. It probably doesn't need to be full resolution, either -- if you want a blocky, 8-bit feel, I expect the graphics library will be more than happy to oblige 8^)
Also, as others have mentioned, you can save time by redrawing only those parts of the screen that need updating. This can be annoying to implement, but it may allow you to significantly improve your frame rate. Be sure to do some experiments to make sure this is the case before exerting the required effort!