Graphics Reference
In-Depth Information
of a primitive. While more complex operations are often specified, in this case
the operation is a simple one: The red, green, blue, and alpha components of the
fragment's color are attenuated by the floating-point variable
brightness
.The
term
shader,
taken from Pixar's RenderMan Shading Language, is often used to
refer to fragment processing programs (and also to vertex processing and primi-
tive processing programs) although they have far more functionality than simply
computing color.
Listing 38.1: A simple HLSL fragment processing program (Microsoft refers to
this as a “pixel shader”). Fragment color is attenuated by the floating-point
variable
brightness
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
float
brightness = 0.5;
struct
v2f {
float4 Position : POSITION;
float4 Color : COLOR0;
};
struct
f2p {
float
Depth : DEPTH0;
float4 Color : COLOR0;
}
//
attenuate fragment brightness
void
main(in v2f Input, out f2p Output) {
Output.Depth = Input.Position.z;
Output.Color = brightness
*
Input.Color;
}
HLSL is designed to be familiar to C and C++ programmers. As it would in
C++, the first line of the shader declares
brightness
as a global, floating-point
variable with initial value 0.5. Again, as in C++, because
brightness
is a global
variable, its value can be changed by nonlocal code. In HLSL such nonlocal code
includes the code of the Direct3D application that is driving the GPU pipeline. For
example, the application can change the value of
brightness
to 0.75 by calling
the Direct3D function.
SetFloat("brightness",0.75);
Structures
v2f
and
f2p
are defined much as they would be in C++. There
are two important additions: vector data types and semantics.
Vector data types,
such as
float4
, are a shorthand notation that is similar to a C++ array typedef
(in this case,
typedef float[4] float4;
), but with additional capabilities. This
notation can be used for vectors of lengths two, three, and four. It is also avail-
able for square matrices (e.g.,
float4x4
) and for all HLSL data types (i.e., for
half
,
float
,
double
,
int
, and
bool
).
Semantics
are the predefined tokens, such
as
POSITION
and
COLOR0
, that are separated by colons from the variable names
(such as
Position
and
Color
). These tokens associate HLSL-program variables
with mechanisms in the fixed-function stages of the pipeline—they are the glue
that connects application-specified shaders to architecture-specified fixed-function
mechanisms.
Operation of the fragment shader is specified by the
main
function. Input
to
main
is through structure variable
Input
of type
v2f
, and output is through