Google News
logo
Computer Graphics - Interview Questions
Discuss the main differences between vertex shaders and fragment shaders in shading languages like GLSL or HLSL. Provide examples of where each is used.
Vertex shaders and fragment shaders are distinct stages in the graphics pipeline. Vertex shaders process individual vertices, handling tasks like transformations, skinning, and per-vertex lighting. Fragment shaders, on the other hand, operate on fragments generated by rasterization, determining their final color and depth values.

Vertex shaders are used for operations such as :

1. Transforming vertex positions from model space to clip space.
2. Calculating per-vertex lighting or passing data to be interpolated across fragments.

Example : Transform a vertex position using a model-view-projection matrix.
vec4 transformedPosition = u_mvpMatrix * a_position;?

Fragment shaders are used for operations such as :

1. Texturing – sampling textures and combining them with fragment colors.
2. Per-pixel lighting – calculating lighting based on interpolated normals and positions.
3. Post-processing effects – modifying final pixel colors based on various factors.

Example : Calculate Phong shading with diffuse and specular components.
vec3 normal = normalize(v_normal);
vec3 lightDir = normalize(u_lightPosition - v_position);
float diffIntensity = max(dot(normal, lightDir), 0.0);
vec3 reflectDir = reflect(-lightDir, normal);
vec3 viewDir = normalize(-v_position);
float specIntensity = pow(max(dot(reflectDir, viewDir), 0.0), u_shininess);
vec3 finalColor = (u_diffuseColor * diffIntensity) + (u_specularColor * specIntensity);?
Advertisement