I'm making a scrolling 2D map/tile based game. Each tile (stored as tile[21][11] - 231 tiles total per map) can contain up to 21 values (stored as int[3][7]). While full-screen I see about 8 maps at once.
On average, each map takes about 0.03 seconds to draw (found with System.nanoTime). The problem is that as soon as more than 1 map is on the screen, the Swing event polling noticeably slows down.
Is there any solution to this? I can't draw the map a single time to save it as an image because it has transparency involving moving actors, so it changes too frequently. Also I don't think I can call a thread in paintComponent to draw the maps without it glitching out, but I'm not positive.
My Tiles aren't any type of JComponent, they're just data. I call their container the MapPane, which draws all of the tiles in its paintComponent.
Likewise, JTable cells are just data rendered inside a JComponent; the flyweight pattern, mentioned here, is still applicable: the goal is to omit any effort to render non-visible cells. Profile and self-time with a view toward optimizing the rendering; some approaches are examined in the KineticModel cited here.
A BufferedImage that needs no scaling is best. If you must scale, experiment with RenderingHints related to interpolation type. If composition is too expensive, construct maps in the background using SwingWorker; publish() them as they become available and process() them on the EDT, as shown here.
Related
I recently started working on a 2d platformer in java, and am asking a performance related question.
In my game, I have a world (relatively small for now).
But over half+ of the world isn't visible to the players camera, however I'm still painting the entire world (even the unseen parts).
Here's what I'm doing right now.
#Override
public void paintComponent(Graphics g){
g.translate(player.camX(), player.camY());
for (GameObject gameObject : solidObjects){
if (gameObject.isTouching(player.getCameraRect()))
gameObject.paint(g);
}
player.paint(g);
for (GameObject gameObject : unSolidObjects){
if (gameObject.isTouching(player.getCameraRect()))
gameObject.paint(g);
}
}
So the question is, would it be faster having an if-statement checking if its on the screen before painting?
Yes.
Doing a check to see if it's on a screen should take no more than 1 or 2 steps.
Painting everything requires you to draw every single pixel on to the screen regardless of whether it's used or not.
If gameObject.paint(g); involves a lot of drawing calls, most likely the branching (check) would save more work than it costs. If it's only like one drawing call to paint a sprite though, your library would already perform such a check to avoid buffer overruns and yours would be redundant.
That said, if you are starting to face performance issues here, then I recommend using some kind of data structure. A simple one is a grid like so:
When your elements move, remove them from the grid cells they occupy and insert them to the new one(s) they occupy. That should just involve manipulating a few integers if you implement this efficiently.
Then when you want to draw elements on the screen, only draw the elements in the grid cells that overlap. That'll prevent you from looping over every single element in the game world. This also comes in handy for accelerated collision detection if you need it.
A quad-tree is an alternative though a little bit more costly to update, but it can provide better search quality if the elements in your game are sparsely distributed.
I have a very large complicated diagram that needs to be drawn on the fly.
I am already using a double buffered technique to paint the image (from this answer: Using threads to paint panel in java) however, the generated image that is being painted is so large that it cant be painted as a single image (and the multiple images required to paint it cant be stored in memory all at the same time). For this reason, I paint the currently visible area of the view + some margin. As I scroll, I paint the area that is going to come next, and remove from memory the area we just came from. However, if the user then decides to change direction, they need to wait for this area to be painted again. My question is this:
If a single "frame" of the screen being painted is approximately 1000*1000 pixels, in which approximately 5000 lines/circles are drawn (nodes/edges of a graph) is it likely to be more efficient to repaint this image each time, or is there a way to affectively cache the image to hard disk (to avoid java heap limitations).
Ive already optimised the paint method as much as I can think of, but there are still several seconds of delay if a user scrolls to quickly (i.e. moves out of the painted area before the next set of "frames" are painted). So my second question is this: Will moving to OpenGL offer a large improvement, and will it require major changes to the infrastructure of the code? (I tried doing this a couple of days ago, and found it was not as simple as I thought - often led to the computer crashing).
Several things come to mind:
Profile to verify your working hypotheses; self-time the animation budget on your target platform for comparison, as shown in this AnimationTest.
Compare your approach to the example cited here; it scales into the 1000's and accommodates dragging selections into the hundreds.
If your frames have a suitable geometry, consider adopting the flyweight pattern for rendering; JTable rendering is an example; the underlying mechanism using CellRendererPane is examined here.
I'm making a map editor for my 2d tile based RPG game, and I'm running into a roadblock. The problem is actually how to draw the grid lines efficiently for very large maps like, say 300x300 tiles.
Originally I called redrew the entire grid panel every time you moved the mouse or clicked(since it allows you to drag and also highlights the tile you are hovering over). This was horrible for large maps and was very slow.
So my solution was to create a bufferedImage for the grid of a specified size right when a new empty map was created, and redraw that image every time paint was called. This worked very well, except that for anything above 200x200ish java would run out of heap space in creating that bufferedImage. I can't really have a preloaded image because the user should be able to specify a new map to be any size. Also, I like the grid to be drawn over the tiles, otherwise the tiles cover up the lines and it looks messier. That means the grid has to be drawn again every time tiles are added right?
My question is, is there another way to draw a very large grid that will repaint each time you move the mouse?
The program Tiled can easily create maps of 1000x1000 or more, how is it done?? Thanks
EDIT:
I mean the actual grid LINES, not the grid content such as tiles. Right now when the grid is drawn it iterates through the 2D array and draws a line at every length of a tile.
EDIT:
I got it to work by painting only the visible portion of the screen. Turns out it's not that hard to find the coordinates of the view pane in a JScrollPane. :)
Ok so this is similair I guess to what im working on at the moment. I am currently writing a bit of simulation software with a 3D frontend in Ogre3D. I have a tile based map that can be easily 3000 x 3000 sometimes they may be even larger.
Now im not sure how you are going about drawing your grid, if you are just doing 2D/3D, but the main problem for me was how to apply different textures to each tile. If this isnt relevant then hopefully this may help anyway for future lol. The problem for me is that creating a seperate object for eacch tile is a no no, due to speed. If there are even 1024 x 1024 your looking at over 1 million tiles, each with attributes. This worked great on my first tests where I only had 10 x 10 maps but on larger maps it just ground to a halt.
What I am currently doing is rewriting it, the new approach is as follows. (You may be able to adapt this for what you are doing if it helps). The grid is now only 1 object, its a mesh in my case as im working in 3d. Each vertex holds a couple of values, one is the column and one is the row. I have a seperate texture which is the same size as my map, so for a map with 100 columns and 100 rows i create a texture 100 x 100 (this is created dynamically).
I then pass this texture and the vertices to my cg shader (this is where tyou may have to think of an equivalent way of doing things, but I think it should be doable). By looking up the colour at the pixel in this texture relating to the grid slot I want to texture I can find a colour value, these colour values relate to my texture atlas which holds all my possible textures for my map. All you then have to do is use that particular part of the texture atlas for that particular part of the mesh / grid.
I hope that makes some sort of sense, if not then id be happy to explain a bit more. I think even though im using CG shaders, you should be able to come up with an equivalent for non CG based stuff in java. The advantage of this is that you end up with one lookup texture, one object in memory and a buffer holding your vertices which is very quick for lookup.
Hope this helps.
While I am not doing some animation or drawing a very complicated graphics.
I need (sort of) double buffering for drawing several primitives. In the application, user enters name of Shape followed by related arguments and that shape is drawn on buffer, and then on screen.
Eg of a command is RECT 100, 50, 200, 120.
For persistence, I can store all commands in list and in
public void paintComponent(Graphics g) of JPanel I draw them one by one.
But this is highly inefficient, because of iterating through list and using a hash map each time to call (or dispatch) the relevant shape-drawing-interface.
How and on what type of buffer can I draw? How can different methods draw on this buffer?
Additionally is there a convenient way to be able to undo previous draws with buffer? Or do I need to redraw on buffer each time a undo is done?
Thanks, I don't want full code, but relevant class names and small pseudocode is appreciated.
JPanel is double buffered by default, so selecting and dragging are typically quite smooth. GraphPanel is a simple object drawing program that illustrates such operations on a List<Node>. A similar approach has been successfully used with thousands of nodes.
The details of implementing an undo strategy depend significantly on the desired behavior, but remove() and repaint() are effective.
Addendum: One common optimization for rendering large numbers of objects uses the flyweight pattern. JTable, JFreeChart and JGraph are examples. This simplified example illustrates the essential mechanism.
For my internship on Brain-Computer Interfacing I need to generate some very fast flickering squares on a CRT monitor (flickering = alternating between two colors). The monitor's refresh rate is 85Hz and we would like this to be the bottleneck, which means that repainting all squares can take at most 1000/85 = 11ms.
My language of preference for GUI/graphics programming is Java, so I tried making a prototype with AWT, because it's synchronous (unlike Swing). I now seem to have two problems: the first is that time measurements show that the repainting of even 9 squares simply takes too long. My algorithm takes the desired frequency and calculates the times at which the system should repaint in advance and then uses a loop (with no sleep/wait delay) that checks everytime if the next 'time' was reached and if so, loops through all the squares to repaint them. The way I implemented it now is that the squares are Panels with background color A and are contained in another Panel with background color B and the flickering happens because the Panels' visibility is changed. I figured that this would be faster than one Panel that has to draw Rectangles all the time.
I don't have a decent profiling tool (can't get Eclipse TPTP or NetBeans profiler to work) so I can't be sure, but I have the feeling that the bottleneck is actually not in the repainting, but in the looping (with conditional checking etc.). Can you recommend anything about what I should do?
The second problem is that it seems like the squares are rendered top-to-bottom. It's like they unroll really fast, but still visibly. This is unacceptable. What I'm wondering though, is what causes this. Is it Java/AWT, or Windows, or just me writing a slow algorithm?
Can you recommend some things for me to try? I prefer to use Java, but I will use C (or something) if I must.
I would avoid any kind of high-level "components", like JPanels and the like. Try getting a Graphics2D representing the window's contents, and use its fillRect() method.
Failing that, you could probably do this easy enough in C and OpenGL. rasonly.c is a standard template program that sets up OpenGL to work as a "rasterizer" only, i.e. 2D mode. Using this as a starting point, you should be able to get something running that draws your desired "squares" without too much trouble.
You don't describe your desired scene very well, it sounds from that equation as if you want to draw 100 squares, each having a different color. For maximum performance in OpenGL, you should draw all squares of the same color together, to minimize the "state changes" between drawing calls. This is probably a purely theoretical point though, as drawing 100 2D squares at 85 Hz really shouldn't tax OpenGL.
UPDATE: Oh, so it's been a bunch of years, and nowadays you probably need to take the above with a grain of salt and read some modern tutorial. Things have changed. Look up the Vulkan API.
(I remember a demonstration of this using the BBC micro and palette switching, though that would be 50fps rather than 85, as it was a British domestic TV)
I'd switch to jogl and use display lists. They get very high fps rates in Java.