Graphics Reference
In-Depth Information
We have reorganized our shaders so that we can re-use the structures defined between
multiple shaders. The example provided here is the use of the
SimplePS
and
DepthPS
pixel
shaders, although we shall shortly see more examples using different lighting techniques.
The vertex shader now calculates a number of additional properties to pass to the pixel
shader. The
WorldNormal
and
WorldPosition
properties of the pixel shader input are
both important properties for determining the correct lighting. Although our pixel shaders do
not yet make use of this information, we will be able to use the
PerFrame
constant buffer
to retrieve the current camera's position to create the vector that points from the current
WorldPosition
to the camera (in world space).
As already discussed, in order to support non-uniform scaling, the normal must be
transformed using the inverse transpose of the
World
matrix and excluding the
homogeneous
W
component.
Using C# structures with HLSL constant buffers
In HLSL, data is packed into 4 bytes in such a way that it does not cross a 16-byte boundary.
When creating our structures for use with a constant buffer, it is important that we take this
memory layout into consideration.
For example, given a constant buffer with two
floats
and a
float3
variable, we must
layout our structure in C# so that it matches the valid memory layout as shown in the
following figure:.
An incorrect structure for this would be defined like this:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct IncorrectStruct {
public float a;
public float b;
public Vector3 c;
}
Invalid
4-bytes
a
b
c.X
c.Y
c.Z
16-bytes
16-bytes
4-bytes
Valid
a
b
c.X
c.Y
c.Z
16-bytes
16-bytes
Invalid and valid memory layouts for the HLSL buffer