Game Development Reference
In-Depth Information
dotProduct = dot(vNormalWorldSpace, g_LightDir[i]);
dotProduct = max(0, dotProduct);
dottedLightColor = g_LightDiffuse[i] * dotProduct;
vTotalLightDiffuse += dottedLightColor;
}
Output.vDiffuse.rgb = g_vDiffuseObjectColor * vTotalLightDiffuse +
g_vAmbientObjectColor * g_fAmbient;
Output.vDiffuse.a = 1.0f;
return Output;
}
The first thing you notice is a comment, using the familiar syntax of the
to begin
one. As always, it is a good idea to comment well. This is especially true in shaders,
where very simple-looking operations can have interesting results.
The next block of code defines a
cbuffer
, which is very similar to a
struct
in C,
except that you can define where the data will be stored and how it is packed. In
earlier shader models, each parameter needed by the shader had to be sent individu-
ally, which lowered performance greatly. Starting with shader model 4.0, constant
buffers could group parameters together so they could be submitted to the video
card at once. The maximum size of a constant buffer is 4,096 vectors, each vector
containing up to four 32-bit values. You are limited to 14 constant buffers per pipe-
line stage.
It
“
//
”
s a good idea to group data that changes at the same rate into the same constant
buffer. For example, if you have data that changes only once per frame, such as a
transformation matrix or lighting, store those separately from data that changes
more frequently. A great example of this would be a texture or material, which
could change for each object in your scene.
Packing and storing the
cbuffer
is done with the
register
and
packoffset
key-
word. The
register (b0)
tells the shader to put the constant buffer into slot zero.
This isn
'
t truly necessary in this simple shader, but if you had more than one con-
stant buffer, this is a clear way to define which slot it occupies and which you
'
ll need
to know for your C++ code that sends data to the shader. Packing tells the shader
compiler how you want data stored, especially if you have simple integers or Boo-
leans you want to send to the shader.
The
cbuffer cbMatrices
structure defined at the top of the shader stores two
4 × 4 matrices. The first,
g_mWorldViewProjection
, stores the transformation
needed to get from object space to screen space. Each position member of each vertex
'