Ins and outs - Advanced Rendering - Shader Learning

Advanced Rendering

Ins and outs

Task

Create a program that passes the fragment's normal (in world space) and its color from the vertex shader to the fragment shader, and implements diffuse lighting based on a directional light source.

Theory

In OpenGL 3.3, shaders use in and out attributes to pass data between different stages of the rendering pipeline. This tutorial will guide you through the basics of using these attributes to transfer parameters between vertex and fragment shaders.


Vertex Shader


The vertex shader processes each vertex and passes data to the fragment shader:

// Input attributes from the vertex buffer
in vec4 color;

// Output attributes to the fragment shader
out vec4 vColor;

void main() {
    vColor = color;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

Fragment Shader


The fragment shader receives data from the vertex shader and processes each fragment:

// Input attributes from the vertex shader
in vec4 vColor;

// Output color to the framebuffer
out vec4 FragColor;

void main() {
    FragColor = vColor;
}

Attribute Names and Types


It's important to note that the names and types of the in and out attributes must match between shaders. For example, if the vertex shader outputs a variable named vColor of type vec4, the fragment shader must have an input variable with the same name vColor and the same type vec4. This ensures that the data is correctly passed from one shader stage to the next.


The out attribute in the fragment shader typically outputs a vec4 representing the RGBA color. This should match the color format of the framebuffer. For example, if your framebuffer is set up to use an RGBA format, your fragment shader should output a vec4.