Understanding How Unity3D Shaders Execute on the GPU
Before examining execution specifics, it helps to review how a shader fits into the rendering pipeline. A shader is a program that defines surface appearance by controlling vertex transforms and pixel-level coloring. Unity shaders are written in HLSL (High-Level Shading Language) and run on the GPU. The typical execution flow involves several stages.
Uploading Vertex Data
At the start of a draw call, vertex data (positions, normals, texture coordinates, etc.) is sent to GPU memory. In Unity, Mesh objects store this information and supply it to the hardware.
Vertex Shader Stage
The GPU invokes the vertex shader once for each vertex. Inside this program, you can transform coordinates, compute per-vertex lighting, or pass through texture coordinates. After execution, the transformed data travels to the rasterizer.
Rasterization
Rasterization converts processed vertex data into fragments. The hardware automatically generates fragments for each pixel that the triangle covers. No manual code is needed for this step.
Fragment Shader Stage
Each fragment enters the fragment shader, where final color and depth are determined. Operations such as texture sampling, lighting calculations, and blending occur here. The result is a set of color values that movee toward the frame buffer.
Writing to the Frame Buffer
Processed fragment colors are written into a render target, often the default frame buffer that appears on screen. Unity manages this target automatically.
Next, let’s look at concrete HLSL implementations illustrating the vertex and fragment stages using different variable names and logic structures.
Vertex Shader Code
// Per-vertex input data
struct VertexInput
{
float4 pos : POSITION;
float3 nrm : NORMAL;
float2 texcoord : TEXCOORD0;
};
// Data passed to fragment stage
struct VertexOutput
{
float4 clipPos : SV_POSITION;
float2 uv : TEXCOORD0;
};
// Vertex program
VertexOutput vert_main(VertexInput input)
{
VertexOutput output;
output.clipPos = UnityObjectToClipPos(input.pos);
output.uv = input.texcoord;
return output;
}
This shader receives per-vertex attributes, projects the position into clip space, and forwards the texture coordinate unchanged.
Fragment Shader Code
// Data from vertex stage
struct VertexOutput
{
float4 clipPos : SV_POSITION;
float2 uv : TEXCOORD0;
};
sampler2D _MainTexture;
// Fragment program
float4 frag_main(VertexOutput input) : SV_TARGET
{
// Sample texture and return color
float4 sampledColor = tex2D(_MainTexture, input.uv);
return sampledColor;
}
Here the fragment program samples a texture using the passed UV coordinates, then outputs the fetched color. This simple setup serves as a foundation for more advanced effects such as specular highlights, normal mapping, or environment reflections.