简体   繁体   中英

Passing current time to OpenGL ES 2.0 shader for texture-animation: animation stops after certain time

I want to pass the current time to my Shader for texture-animation like this:

float shaderTime = (float)((helper::getMillis() - device.stat.startTime));
glUniform1f(uTime, shaderTime);

To animate the texture I do: GLSL Fragment Shader:

#if defined GL_ES && defined GL_FRAGMENT_PRECISION_HIGH
    #define HIGHFLOAT highp
#endif
uniform HIGHFLOAT float uTime;

...

void main()
{
    vec2 coord = vTexCoord.xy;
    coord.x += uTime*0.001;

    gl_FragColor = texture2D(uTex, coord);
}

My problem is: if I run the program for a while:

  • The first minute: Everything is animating fine

  • After ~5 minutes: The animation stutters

  • After ~10 minutes: The animation has stopped

Any Ideas how to fix this?

floats lose precision as they get larger which will result in the stuttering as the number gets larger. Also the coordinates that you can use to sample a texture will have a numerical limit so will fail after you go over it.

You should wrap your time value so it doesn't go over a certain point. For example, adding 1.5 to the UV coordinates across an entire triangle is the same as adding 0.5, so just wrap your values so that uTime*0.001 is always between 0 and 1.

You can also consider switching time to be an integer so that it doesn't lose precision. You can multiply this integer by a constant delta value in your shader. eg multiply by 1/30 if your framerate is 30fps.

Like Muzza says, the coordinates that using to sample a texture will have a limit. This leads to the problem you face.

There are also some alternative methods to do texture-animation without modify the fragment shader. For example, revise the projection matrix to choose which part of the texture you want to see. Modify the view port when the time goes is another way can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM