This is the 15th day of my participation in the August More Text Challenge

rendering

Simple pulse wave (serrated half sine wave) drawing

Triangle wave

First let’s see how to draw triangle wave. The core algorithm code used by triangle wave (like sawtooth) is as follows

abs(mod(x * 0.2.2.0) - 1.0) - 0.5;
Copy the code

The diagram of the function is as follows

A half sine wave

Then there is the half-sine wave (a portion of it that looks like a mountain rising from the horizon), which uses the following core algorithm code

    if (x < 0.0 || x > sineWidth)
        return 0.0;
    else
        return sin(x * pi / sineWidth) * height;
Copy the code

The diagram of the function is as follows

In the actual code we use the time-dependent parameter T, so that over time our half-sine waveform can move from left to right to the specified position

The combination of two wave functions

Combining the two, we get the following result

The complete code and comments are shown below

float triangle(float x)
{
    /// @note Triangle wave
    return abs(mod(x * 0.2.2.0) - 1.0) - 0.5;
}

#iUniform float height = 40.0 in {40..250.}
float truncSine(float x)
{
    /// @note Half sine wave
    const float sineWidth = 40.0;
    const float pi = 3.1415;

    if (x < 0.0 || x > sineWidth)
        return 0.0;
    else
        return sin(x * pi / sineWidth) * height;
}

/// @note
float rdWave(float x, float t)
{
    /// @note half sine wave translation with time
    return truncSine(x - t) * triangle(x);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    float yOffset = iResolution.y * . 5;
    float x = floor(fragCoord.x);
    float y = floor(fragCoord.y) - yOffset;

    float t = mod(iTime, 10.) * 40.0;

    if (y < rdWave(x, t))
        fragColor = vec4(1.0.0.0.0.0.1.0);
    else
        fragColor = vec4(0.0.0.0.0.0.1.0);
}
Copy the code

Bonus

With a little modification we can get the following effect similar to the beating pulse of the heart

Part of the modified code is as follows

    bool center = rdWave(x, t) >  y;
    bool right  = rdWave(x - 1.0, t) >  y;
    bool left   = rdWave(x + 1.0, t) >  y;
    bool up     = rdWave(x, t) >  y + 1.0;
    bool down   = rdWave(x, t) >  y - 1.0;

    if(center && ! (right && left && up && down)) fragColor =vec4(1.0.0.0.0.0.1.0);
    else
        fragColor = vec4(0.0.0.0.0.0.1.0);
Copy the code