Wednesday, Jan 5, 2022

In the previous post the cube with a block spot was fixed so it is time to explain how the effect of color change is achieved.

Periodic functions

Let’s see again the fragment shader and focus on the abs(...) part of line 9

 1#version 330
 2
 3out vec4 outColor;
 4in vec3 posObj;
 5uniform float uTime;
 6uniform float uTimeFreq;
 7
 8void main() {
 9  outColor = vec4(posObj * abs(sin(uTime * uTimeFreq)), 1);  
10}

The params uTime is a value passed from SHADERed and its value is the elapsed time since the application has been started. uTimeFreq is the user defined variable with a value that influences how fast the objects fades.

The core of the fading effect is given by the periodic function sin. The image below shows a graph of the sine function with domain values between [-2π,2π].

Sine function from -2π to 2π
Sine (and cosine) functions are periodic functions : they repeat themselves after a specific interval. In this case the period is 2π, which means that for sin(x) is equal to sin(x + 2π).

Moreover, no matter which value is passed to the function, the result is always a number between -1 and 1 : this is not entirely true when the function is computed using floating point values, but this is another story and let’s pretend that the previous assertion is true (for more information see here)

This is particularly handy when we want to animate a value between 0 and 1 in a “ping-pong” fashion. However, as previously said, the results are between -1 and 1. To “move” them in the positive range 0-1 there are two ways :

Sine function with results in range [0,1]
Absolute value of sine function and with results in range [0,1]

The choice in the shader was to use $abs(sin(x))$ : the animation below shows the values assumed by the function. As you can see it goes from 0 to 1, then it reverses the direction and when it reaches 0 again it repeats.

Frequency

The last parameter to explain is uTimeFreq : it represents the frequency, that is the inverse of the period. Incresing the value of uTimeFreq speeds up the fading effect. The following graph shows the function $sin(4 \cdot x)$

Sin (4x)