HLSL Basics
From GameStudio Wiki
Hi there! This wiki page introduces you to basic hlsl shader programming.
Let's start with some theory. Every effect uses at least one so called technique which contains your shader. An effect file can but needn't contain more than one technique. If the first technique fails (due to inapropriate graphics hardware) it uses the next available technique.
Each technique consists of passes. Each passes runs through the shader pipeline one time. We will use only one pass at the beginning. Our basic code looks like this:
technique my_first_shader
{
pass p0
{
// your shader starts here
}
}
Shaders use vertex and pixel pipelines which process the vertices or the pixels of a polygon. Furthermore a vertex shader can "send" information to the pixel shader.
I'll start with a basic vertex shader that only passes vertex positions and texture coordinates. Write the following code above the technique:
float4x4 matWorldViewProj; // declare projection matrix
void mainVS(
in float4 inPosition : POSITION0,
in float2 inTexCoord : TEXCOORD0,
out float4 outPosition : POSITION0,
out float2 outTexCoord : TEXCOORD0
)
{
outPosition = mul(inPosition, matWorldViewProj);
outTexCoord = inTexCoord;
}
This might be hard to understand. We'll now add a basic pixel shader and then try to understand what happens. Place the following code below the vertexshader and above the technique:
void mainPS(
in float4 inTexCoord: TEXCOORD0,
out float4 outColor : COLOR0
)
{
outColor = 0;
outColor.r = 1;
}
The last thing we need to do is to compile the shaders in our pass:
technique my_first_shader
{
pass p0
{
VertexShader = compile vs_2_0 mainVS();
PixelShader = compile ps_2_0 mainPS();
}
}
Assign this effect to an entity in your level, build and run. It should be pure red now. So what happened? First let's have a look at the vertex shader: We declare a 4x4 matrix "matWorldViewProj". We must use it later. Next our vertex shader starts with "void mainVS(...)". Void means there's no value returned. mainVS is the name of the vertex shader. The arguments of the shader are "in" our "out" values. "in" means the shader receives information, "out" means the shader sends information. Example:
in float4 inPosition : POSITION0\\
in: information from the engine\\ float4: data type. It's a float vector (with think of it as variable[4])\\ inPosition: the name of the vector\\ POSITION0: the semantic of the variable. It tells the shader to fill the variable with the position of a vertex\\
