DirectX - Pixel Shader



The Pixel Shader is called once per pixel in comparison to vertex shader which it calls as per vertex and gets its data from the preceding pipeline station respectively from the preceding Shader. It calculates the required pixel color (pixel depth or any other values are possible) and returns them to the required pipeline.

The Pixel Shader is considered as the last Shader in the pipeline and therefore already gives the data to the Output Merger, which helps us to determine the final pixel color. Pixel Shaders are prominently used for rendering surfaces but in comparison to shaders, they can be used for special calculations. The two most important ways to use them include texturing and lighting, for which we will focus on the example following the pixel shader representation or structure.

Structure of a Pixel Shader

In principle with reference to snapshot given below, you will find there is no real difference to a Vertex Shader, only the input and output data is different.

Pixel Shader

Texturing and lighting with a Pixel Shader

The following code demonstrates how texturing and lighting with a Pixel Shader is done −

struct PixelShaderInput{
   float4 position : SV_POSITION;
   float3 outVec : POSITION0;
   float3 normal : NORMAL0;
   float3 light : POSITION1;
};
float4 main(PixelShaderInput input) : SV_TARGET{
   float3 L = normalize(input.light);
   float3 V = normalize(input.outVec);
   float3 R = normalize(reflect(L, input.normal));
   float4 diffuse = Ka + (lightColor * Kd * max(dot(input.normal, L), 0.0f));
   diffuse = saturate(diffuse);
   float4 specular = Ks * pow(max(dot(R, V), 0.0f), shininess.x - 50.0f);
   specular = saturate(specular);
   float4 finalColor = diffuse + specular;
   return finalColor;
}

The buffer includes the light position in world coordinates which is created and a texture with reference to sampler is always used. The Sampler is mandatory to read the texture color on the corresponding texture coordinates. The Pixel Shader includes the input data received from the Vertex Shader which is interpolated by DirectX. This means with reference to the current pixel from the three vertices of the current triangle we can draw, distance- and mode-dependent "averages" are calculated.

Advertisements