1
$\begingroup$

I've been following TheCherno's OpenGL tutorials and I got to the point where I could render a square by using an index buffer. Now I wanted to vary the color of the square by using $$\frac{\sin(t) + 1}{2}$$ as my normalized time-varying function to be used in each of the RGB entries in color. I thought I might proceed as follows: this is my fragment shader.

#shader fragment
#version 330 core
layout(location = 0) out vec4 color;
uniform float time;

float time_Color(float t) {
    return (sin(t) + 1) / 2;
}

void main()
{
    color = vec4(time_Color(time), time_Color(time - 0.2), time_Color(time - 0.4), 1.0f);
}

in my main loop in main.cpp, I have:

int location = glGetUniformLocation(theProgram, "time");

//Main loop
glfwSetTime(0);
while (!glfwWindowShouldClose(mainWindow)) {
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    glUniform1f(location, static_cast<float>(glfwGetTime()));
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

    glfwSwapBuffers(mainWindow);

    glfwWaitEvents();
}

When I run this program, I do see a color-varying square but the change in color becomes slower and slower as the program continues. Initially the change is gradual but then sometime after like 7 secs, I start to get abrupt changes in color that only get updated after a long time. I suspect this is to do with the sin computation in the GPU but I don't actually know since I'm just beginning out. So why is this code working so slowly/inefficiently the longer the program executes?

$\endgroup$
2
  • $\begingroup$ it's not the sin function and I see nothing else in the fragment shader that would cause a problem. This issue probably has something to do with glfw my guess would be the wait events function but I don't use glfw so that is just a guess. I wrote a shader toy here that shows it shadertoy.com/view/cl3cDf $\endgroup$
    – pmw1234
    Nov 11 at 17:30
  • $\begingroup$ Ok yeah, changing glfwWaitEvents() to glfwPollEvents() made the color change smooth. Thanks. $\endgroup$
    – Doobius
    Nov 11 at 19:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.