Search code examples
javaopengllwjglglu

Terrain flickers through water | Depth buffer precision issue?


I have an issue with the water in my terrain, which is currently just a quad with a transparent blue colour.

When close up to it, it looks like this: enter image description here

As you can see, it's simple enough - A flat transparent quad representing water.

However, when I get further away, this happens: enter image description here

For those who can't see the GIF, or need an external link (or can't understand what's going on), the terrain is glitching around the water. If you look near the water near enough, you will see the terrain glitching above/below it.

Here is the code where I prepare the 3D view:

static void ready3D()
{
    glViewport(0, 0, Display.getWidth(),Display.getHeight());
    glMatrixMode(GL_PROJECTION);

    glLoadIdentity();
    GLU.gluPerspective(45, (float) Display.getWidth()/Display.getHeight(), 50f, 500f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glDepthFunc(GL_LEQUAL);
    glEnable(GL_DEPTH_TEST);
}

Does anyone know what the issue is, and how I could improve the precision of the depth buffer (presuming the depth buffer is the issue)?


Solution

  • It's difficult to tell from the GIF, but what I'm gathering is that you're experiencing an instance of Z-Fighting.

    There are several solutions that tend to be most effective for dealing with Z-Fighting:

    • Increase the Resolution of the Z-Buffer.
    • Adjust the relative positions of the Water & Land to separate them further, thus reducing the chance of the two geometries colliding like this
    • Make use of the Stencil Buffer to ensure that objects are drawn correctly.

    I've also seen solutions that try to disable Depth Testing when handling certain objects, but those are almost never good as a general solution.