maandag 15 augustus 2011

Introduction to HLSL - Part 1

Naming conventions
 

In programming it's good practice to name your variables logically. Often I see this practice not executed in shader writing. That's why I'm starting with some variable naming conventions I like to adhere to. One of the most basic things a shader has to do is to transform the rendered object from object space into clip space. I'll come back to mathematics behind this, but for now it's enough to know that this transformation can be done by a single matrix multiplication. The matrix in question has the input semantic WORLDVIEWPROJECTION. The code for the transformation is commonly written as:
float4x4 wvp: WORLDVIEWPROJECTION;
out.pos = mul(in.pos, wvp);
In this code we find two distinct variables that are both named pos. The one in the in structure is the position in object space, while the one in the out structure is the position in clip space. The first naming convention I adhere to is to add the space a vector is in as a suffix. So we update the transformation above into this one:
float4x4 wvp: WORLDVIEWPROJECTION;
out.pos_clip = mul(in.pos_object, wvp);
Next lets look at the variable wvp. These three letters are a logical shorthand of WorldViewProjection, but what is the function of this variable in our code? We will almost always use this matrix to convert a vector from object space into clip space. So we'll call the variable object_to_clip instead. We'll also lengthen in and out a little bit to input and output:
float4x4 object_to_clip: WORLDVIEWPROJECTION;
output.pos_clip = mul(input.pos_object, object_to_clip);
This concludes the first part of the introduction to HLSL. In the next part we'll take this must have piece of code and extend it into our first full HLSL shader.

Geen opmerkingen:

Een reactie posten