Search code examples
javaopengllwjglalphaslick2d

Slick2d / LWJGL Adjusting alpha channel in OpenGL layer ( Java )


I apologize for some of my ignorance as I am fairly new to Slick2D and LWJGL. Essentially what I'm trying to do is make a scene look like night time by covering it with a GL_QUADS rectangle that is tinted blue and is translucent.

That part is easy enough. What I want to do from there is draw triangles into this layer that vary the alpha channel so. The reason I want to do this is so I can simulate a light source by decreasing the opacity of the blue tinted rectangle as it gets closer to the light source.

I drew an example of what the expected result should be with the green being the background, the blue being the nighttime effect created by a blue tinted rectangle, and the increasingly dim light source in the center.

I need to find a way to do this with triangles because I created a raycasting algorithm that generates the result as a series of gradient triangles.

I apologize if this is explained poorly. I will answer any questions you might have.

Intended result

Here is the chunk of code used to create the blue tinted rectangle:

    glColor4f (0.0f,0.0f,1.0f,0.4f);
    glBegin(GL_QUADS);
    glVertex2f(0,0);
    glVertex2f(screenWidth,0);
    glVertex2f(screenWidth,screenHeight);
    glVertex2f(0,screenHeight);
    glEnd();

I would like to write a modified version of the following code to adjusted the alpha channel of that rectangle.

    glBegin(GL_TRIANGLES);
    setAlphaOfPriorLayer(0.0f);
    glVertex2f(x1,y1);
    setAlphaOfPriorLayer(0.4f);
    glVertex2f(x2,y2);
    setAlphaOfPriorLayer(0.4f);
    glVertex2f(x3,y3);
    glEnd();

Again, I'm using triangles to approximate a circle and allow for proper raycasting.


Solution

  • To achieve this, the use of a Frame Buffer Object is super useful. A FBO allows you to essentially render to a texture which can then be displayed on the screen. In my particular case, I rendered the elements to a FBO then used a shader while drawing it to the screen to get the desired opacities.