How get distance to camera in shader?

I want to make a fog shader. Somethink like this: http://in2gpu.com/2014/07/22/create-fog-shader/
I am not good with shader.
How can i get distance from sprite to camera?

Looks like distance is gl_Position.z

It work :grinning:

7 Likes

Do you have source of what you did for the fog anywhere?

1 Like

Here https://github.com/d954mas/defold-dungeon-crawler/blob/master/assets/materials/3dsprite.vp

2 Likes

It looks like no matter how I set the values sprites snap between not foggy and completely foggy without any transition? Any idea what I should change? The 3D space I’m using has large value ranges.

1 Like

You would likely need to linearize your depth values: https://stackoverflow.com/questions/6652253/getting-the-true-z-value-from-the-depth-buffer

1 Like
varying mediump vec2 var_texcoord0;

uniform lowp sampler2D texture_sampler;

varying mediump float dist;
uniform mediump vec4 fog_color;
uniform mediump vec4 fog; //x start distance, y fog end

void main()
{
    float f = (dist-fog.x) / (fog.x - fog.y);
    f = clamp(f, 0.0, 1.0);
    vec4 texColor = texture2D(texture_sampler, var_texcoord0.xy);
    vec3 color  = (1.0-f) * fog_color.rgb +  f * texColor.rgb;
    color = mix(vec3(0.0),color, texColor.a);
    if(texColor.a < 0.01){
        discard;
    }
    gl_FragColor = vec4(color,texColor.a);
}

This seems to work. And then for range I’m using 2000 to 4000.

0%20-%20Faerie%20Solitaire%20Harvest

3 Likes

Does the fog parameters equate to your near and far values? Looks better now in any case :slight_smile:

1 Like

Yes, fog.x is near, fog.y is far. I’ll be using black for my fog color only used grey for testing. This will be used in a cutscene where 3d camera zooms through some scenes with 2d elements.

3 Likes

Very nice! Looking forward to seeing it in action later!

3 Likes

Just a friendly reminder to keep floating point precision in mind. E.g. quickly test with highp to see if it helps. (http://litherum.blogspot.com/2013/04/precision-qualifiers-in-opengl-es.html)

4 Likes