Search code examples
c++openglsfmlglm-mathglew

How to send float value to fragment shader?


I have no idea, how can I pass the float to my fragment shader. I want to change

float ambientStrength;

as a value taken from mainloop. There should be a case ("O" key) which change this ambientStrength to 1.0 for example.

case sf::Event::KeyPressed:
                switch (windowEvent.key.code) {
                case sf::Keyboard::Escape:
                    running = false;
                    break;
                case sf::Keyboard::O:
                    
                    break;
                }

Fragment shader looks like this:

const GLchar* fragmentSource = R"glsl(
#version 150 core
in vec3 Color;
in vec2 TexCoord;
in vec3 Normal;
in vec3 FragPos;
in vec3 lightPos;
in int lightOn
out vec4 outColor;
uniform sampler2D texture1;

void main()
{
float ambientStrength = 0.1; //I WANT CHANGE THIS FROM THE PRESSED KEY
vec3 ambientlightColor = vec3(1.0,1.0,1.0);
vec4 ambient = ambientStrength * vec4(ambientlightColor,1.0);
vec3 difflightColor = vec3(1.0,1.0,1.0);
vec3 norm = normalize(Normal);
vec3 lightDir = normalize(lightPos - FragPos);
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse = diff * difflightColor;
outColor = vec4(Color, 1.0);
outColor = (ambient+vec4(diffuse,1.0)) * texture(texture1, TexCoord);

//outColor=texture(texture1, TexCoord);
}
)glsl";

Solution

  • Include "uniform float ambientStrength" in fragment shader and use this in your C++ code keystroke:

        GLint loc = glGetUniformLocation(ProgramObject, "ambientStrength");
        if (loc != -1)
        {
          const float value = 0.5;
          glUniform1f(loc, value);
        }