Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a shader fade to a color?

Tags:

c++

shader

sfml

This is the current shader I am using. It fades the object by slowly reducing the opacity. I want to fade to purple. How can this be done?

shader.frag:

uniform sampler2D texture;
uniform float opacity;

void main()
{
    vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);
    gl_FragColor = pixel * vec4(1.0, 1.0, 1.0, opacity);
}

shader.vert:

void main()
{
    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
    gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;
    gl_FrontColor = gl_Color;
}

application of shader in main function:

sf::Shader shader;
if (!shader.loadFromFile("shader.vert", "shader.frag"))
    return EXIT_FAILURE;

float opacity = 1.0; //transparency of shader
shader.setParameter("texture", sf::Shader::CurrentTexture); //shader.vert
shader.setParameter("opacity", opacity);                    //shader.frag

////////////////////////////

//Delete Text Display
    counter1 = 0;
    for (iter8 = textDisplayArray.begin(); iter8 != textDisplayArray.end(); iter8++)
    {
        if (textDisplayArray[counter1].destroy == true)
        {
            //shader
            opacity -= 0.1;         
            if (opacity <= 0)
            {
                textDisplayArray.erase(iter8);
                opacity = 1;
            }
            shader.setParameter("opacity", opacity);
        }
like image 802
agtv Avatar asked Oct 20 '25 12:10

agtv


1 Answers

The RGB value for purple is vec3( 1.0, 0.0, 1.0 ) (maximum red, minimal green and maximum blue). You have to interpolate between your frgment color and the color value of purpel, similar as you do it with opacity. Use mix for this. mix(x, y, a) performs a linear interpolation between x and y using a to weight between them. The return value is computed as x×(1−a)+y×ax×(1−a)+y×a.

uniform sampler2D texture;
uniform float opacity;
uniform float purpleFac;

void main()
{
    vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);
    vec3 mixedCol = mix( vec3( 1.0, 0.0, 1.0 ), pixel.rgb, purpleFac );
    gl_FragColor = vec4( mixedCol , opacity );
}

Note you have to set uniform purpleFac similar as you do it with opacity. purpleFac shoud be in range [0.0, 1.0]. If purpleFac is 1.0 your fragment is colord purple and if it is 0.0 your fragment colol is the color of the texture only.

like image 61
Rabbid76 Avatar answered Oct 23 '25 03:10

Rabbid76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!