Search code examples
javagraphicsgame-physicstilelight

Java Tile Based Lighting Performance Issues


I am trying to implement a tile based lighting system into my game, while keeping optimal performance. Currently, without lighting I have around 700-800 fps. When I render lighting the fps drops to around 300-400.

I render lights using the g.fillRect() with a color of Color(0,0,0,alphaValue)

Code:

for (int y = startY; y<endY; y++) {
    for (int x = startX; x<endX;x++) {
        g.setColor(new Color(0, 0, 0, 255/lightData[y][x]));
        g.fillRect((x*Tile.width)-Camera.x, (y*Tile.height)-Camera.y,
                   Tile.width, Tile.height);
    }
}

LightData[y][x] is a value from 1-8.

I am wondering if there is another way of more efficiently rendering lights. Any help would be greatly appreciated.


Solution

  • While I understand your concern you might be doing something called "premature optimization". 300-400 FPS is a lot, usually you are fine even with "only" 30. When you are starting to implement a game and the engine is simple you will get insane numbers on FPS, every added feature will make the FPS drop. But if you are over some reasonable amount (like 50) i would not worry too much. Start to optimize once you have all features done and you see its slow or want to polish the engine more.

    Basically focus on getting all the features done first and only then worry about performance.

    What you can do however is to precompute this:

    255/lightData[y][x]

    Instead of storing 1-8 in lightData, store 255/1, 255/2 etc. Division is quite expensive. This will likely not bring a lot, but it is something and should be easy to do. You can even go as far as having the darkened/lightened tiles prerendered in a buffer and drawing them from that.