andersch.dev

<2024-07-07 Sun>

Post-Processing Effects

In computer graphics, post-processing (postproc) describes rendering techniques that act on a finished rendered image as a whole to add visual effects.

OpenGL Post-Processing via Framebuffers

Using FBOs, the fragment shader that samples the rendered texture can apply a visual effect using kernels. Here is the GLSL code that sharpens the image:

in vec2 TexCoords;

uniform sampler2D screenTexture;

const float offset = 1.0 / 600.0; // may want separate vertical and horizontal offsets

void main() {
    // sharpen kernel
    float kernel[9] = float[](
        -1, -1, -1,
        -1,  9, -1,
        -1, -1, -1,
    );

    vec4 col = vec4(0.0);

    col += kernel[0] * texture(screenTexture, TexCoords.st + vec2(-offset,  offset)); // top-left
    col += kernel[1] * texture(screenTexture, TexCoords.st + vec2(0.0f,     offset)); // top
    col += kernel[2] * texture(screenTexture, TexCoords.st + vec2(offset,   offset)); // top-right
    col += kernel[3] * texture(screenTexture, TexCoords.st + vec2(-offset,    0.0f)); // left
    col += kernel[4] * texture(screenTexture, TexCoords.st + vec2(0.0f,       0.0f)); // center
    col += kernel[5] * texture(screenTexture, TexCoords.st + vec2(offset,     0.0f)); // right
    col += kernel[6] * texture(screenTexture, TexCoords.st + vec2(-offset, -offset)); // bottom-left
    col += kernel[7] * texture(screenTexture, TexCoords.st + vec2(0.0f,    -offset)); // bottom
    col += kernel[8] * texture(screenTexture, TexCoords.st + vec2(offset,  -offset)); // bottom-right

    FragColor = col;
}

See: OpenGL - Framebuffer Objects