How to create fog using Open GL ES 2.0 or WebGL?

2019-04-11 13:24发布

问题:

I would like to create a fog effect for my game but I can't find any tutorials on how to do it using OpenGL ES 2.0. If anyone has links to tutorials, can provide an explanation, or source code I would be grateful.

回答1:

There's a section on replicating fixed-function fog using shaders in the OpenGL ES 2.0 Programming Guide on page 224. The source code is available on the google code project (MIT License). It's a gigantic rendermonkey XML file, but the shader source embedded in it is pretty straightforward (I would copy it directly here, but not sure if that's OK).

The idea is to use the distance to a particular pixel as the input to some fog function. In that example, they calculate the eye to vertex distance in the vertex shader, then provide the interpolated distance to each fragment by passing it as a varying.

They then do a simple linear fog function. There's some minimum distance where there would be zero fog color, and some maximum distance where the output would be all fog color. You mix (linearly interpolate) the fog color and the fragment color by where the pixel distance falls between the max and the min.

As mentioned in the book, once you have that working, there's no reason to limit yourself to linear fog. You can easily make it exponential, dependent on other variables (e.g. distance to a floor, variable due to a texture lookup or noise functions), make god rays through it, etc.

It's not clear from your question what exactly you're after, so if you want to go really dynamic, that's a whole other ballgame (and not always worth the development effort and performance costs for the effect you get). For existing WebGL code, you might try something like the loading screen of Three Dreams of Black, which you can find somewhere in the source code, or you can go more simulation-based by actually modeling the fog as a 3d fluid.