Search code examples
shaderhlsl

Textured glass refraction and transparency


I am trying to create a shader that would allow a sprite to both slightly magnify (or just offset a bit) its background and showing its texture at the same same, just like a piece of painted glass would do. I found a shader that almost does it, however it also changes the background based on how bright the upper layer/sprite is:

sampler2D img;
sampler2D bkd : register(s1);

float4 ps_main(in float2 In: TEXCOORD0) : COLOR0    {
    float4 L = tex2D(img,In);
    float4 B = tex2D(bkd,In);
    return (L<0.5)?min(B,(2.0*L)):max(B,(2.0*(L-0.5)));
}

technique tech_main { pass P0 { PixelShader = compile ps_2_0 ps_main(); }  }

I tried to modify the parameters but the results are awful.


Solution

  • To combine the textures, either lerp between B and L, or lerp between B and L*B. You can expose the lerp factor as a uniform for control.

    For the magnification, you want to scale the UV coordinates of the background texture in the texture lookup. Just scaling it outright won't work though, you need to get the distance between the UV coordinates of your screen buffer sample and the center of your magnifying glass, scale that, then add it to your original UV coordinates.

    Here is a short magnifying glass shader on shadertoy showing you what i mean (in GLSL):

    https://www.shadertoy.com/view/lsjczh