Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 2D Drawing Optimal Performance

I'm in the process of writing a Java 2D game. I'm using the built-in Java 2D drawing libraries, drawing on a Graphics2D I acquire from a BufferStrategy from a Canvas in a JFrame (which is sometimes full-screened). The BufferStrategy is double-buffered. Repainting is done actively, via a timer. I'm having some performance issues though, especially on Linux.

And Java2D has so very many ways of creating graphics buffers and drawing graphics that I just don't know if I'm doing the right thing. I've been experimenting with graphics2d.getDeviceConfiguration().createCompatibleVolatileImage, which looks promising, but I have no real proof it it's going to be any faster if I switch the drawing code to that.

In your experience, what is the fastest way to render 2D graphics onto the screen in Java 1.5+? Note that the game is quite far ahead, so I don't want to switch to a completely different method of drawing, like OpenGL or a game engine. I basically want to know how to get the fastest way of using a Graphics2D object to draw stuff to the screen.

like image 496
Zarkonnen Avatar asked Sep 29 '08 12:09

Zarkonnen


2 Answers

A synthesis of the answers to this post, the answers to Consty's, and my own research:

What works:

  • Use GraphicsConfiguration.createCompatibleImage to create images compatible with what you're drawing on. This is absolutely essential!
  • Use double-buffered drawing via Canvas.createBufferStrategy.
  • Use -Dsun.java2d.opengl=True where available to speed up drawing.
  • Avoid using transforms for scaling. Instead, cache scaled versions of the images you are going to use.
  • Avoid translucent images! Bitmasked images are fine, but translucency is very expensive in Java2D.

In my tests, using these methods, I got a speed increase of 10x - 15x, making proper Java 2D graphics a possibility.

like image 131
Zarkonnen Avatar answered Sep 18 '22 12:09

Zarkonnen


I'm having the same issues as you are I think. Check out my post here:

Java2D Performance Issues

It shows the reason for the performance degradation and how to fix it. It's not guaranteed to work well on all platforms though. You'll see why in the post.

like image 42
Consty Avatar answered Sep 21 '22 12:09

Consty