How to add fog in a 2D ortho scene?

Started by
2 comments, last by shinypixel 9 years, 11 months ago

I used to make fog in a 3D scene with glEnable(GL_FOG).

Now, I'm working on a 2D scene. I have no idea if this would work. If not, are there some alternatives? I'd like fog turbulence in a 2D game like the screenshot below.

glOrtho(0.0, SCREEN_WIDTH, 0.0, SCREEN_HEIGHT, 0.0, 1.0);

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    GLfloat fLowLight[4] = { 0.7f, 0.7f, 0.7f, 0.1f };

    glEnable(GL_FOG); // Turn Fog on
    glFogfv(GL_FOG_COLOR, fLowLight); // Set fog color to match background
    glFogf(GL_FOG_START, 0.0f); // How far away does the fog start
    glFogf(GL_FOG_END, 0.0f); // How far away does the fog stop
    glFogi(GL_FOG_MODE, GL_LINEAR); // Which fog equation do I use?
 

I'm just getting a gray screen, and my texture objects aren't showing up. Changing GL_FOG_END to 1.0f does show my textures, but there is no fog present.

The style I'm trying to go for is attached. Overall, I'm wondering how I can do something similar in a 2D environment possibly with GL_FOG.

Advertisement

Looks like I got it, more or less. I used glFogCoordf().

Adding this just so that you understand what happened here.

Fixed pipeline fog depends on the distance of the objects being drawn from the viewpoint, so in a typical 2D scene - with all objects being drawn at the same distance - it's natural to expect all objects to recieve the same amount of fogging.

In your first case (mode is linear, end is 0, start is 0) the formula is (end - dist) / (end - start). Plugging in your numbers we see that you actually have a division by zero error here. We can assume that your driver or hardware catches this and does some form of substitution rather than crashing and burning horribly. Either way there's no expected behaviour, so we can't predict if you'll get fully fogged, no fog, partial fog, or a grand-unified theory of everything as a result.

In your second case you've set fog end to 1, but your objects are still all being drawn at the same constant distance - I'm assuming that's with a z of 0, which is specified for a 2-component position attribute. So it's natural to expect no fogging, since the objects are right at your fog start position.

Using glFogCoord means that you get to specify the position used by each vertex for it's fog calculation rather than have it automatically come from the vertex position itself, and now things happen and you start to get results.

Direct3D has need of instancing, but we do not. We have plenty of glVertexAttrib calls.

Interesting! Thanks for sharing.

Here's an end-result video with the fog:
https://m.youtube.com/watch?feature=youtu.be&v=szUgMLioD58

This topic is closed to new replies.

Advertisement