Shader Naming Conventions: A Quick Guide - vquanghuy/learn-opengl GitHub Wiki

Writing clear and readable shader code is essential for maintainability and collaboration. While there's no single strict standard, adopting consistent naming conventions can significantly improve the clarity of your GLSL shaders. A widely used approach involves using prefixes to indicate the type or purpose of a variable.

#version 410 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;

out vec2 vTexCoord;

uniform mat4 uModel;
uniform mat4 uView;
uniform mat4 uProjection;

void main()
{
    gl_Position = uProjection * uView * uModel * vec4(aPos, 1.0);
    vTexCoord = aTexCoord;
}

Attributes (a prefix)

Vertex attributes are the per-vertex inputs to your vertex shader, typically coming from your Vertex Buffer Objects (VBOs). Using the prefix a for these variables clearly identifies them as attribute data.

  • Convention: a + Descriptive Name (e.g., aPos, aColor, aTexCoord, aNormal)
  • Usage: Declared with the in keyword in the vertex shader.

Uniforms (u prefix)

Uniforms are variables that receive data from your application code (CPU) and remain constant across an entire draw call. Using the prefix u helps distinguish these values that are set externally.

  • Convention: u + Descriptive Name (e.g., uModel, uView, uProjection, uTextureSampler, uLightPosition)
  • Usage: Declared with the uniform keyword in any shader stage (vertex, fragment, etc.).

Varyings (v prefix)

Varyings are used to pass data from one shader stage to the next (most commonly from the vertex shader to the fragment shader). The values are calculated per vertex and then interpolated across the primitive. Using the prefix v indicates that this data is interpolated and passed between stages.

  • Convention: v + Descriptive Name (e.g., vColor, vTexCoord, vFragPos)
  • Usage: Declared with the out keyword in the sending shader stage (e.g., vertex) and the in keyword in the receiving shader stage (e.g., fragment).

Consistency is Key

The most important aspect of any naming convention is consistency. Choose a convention (like the a, u, v prefixes) and apply it uniformly throughout all your shader files. This will make your shaders much easier to read, understand, and debug.

References