|
|
|
|
Coding the first Pixel Shader |
Now we have written our first vertex shader and fed it with a small vertexstream, it’s time we have a look at the pixel shader. Using the vertex shader, we could only instruct the GPU to calculate the color of every pixel as linear interpolation between the colors of the corners of our triangles, the vertices.
When you take a look at the flowchart, you’ll notice there are 2 arrows going from the vertex shader to the pixel shader. The left one is necessary, as it is the position of the pixel in 2D screen coordinates. The tesselator and interpolator, as well as the pixel shader, need it to do their work. One remark: by default you can NOT use this position as input to your pixel shader. The bigger arrow is not necessary, but you’ll always want to use it, as it contains the data the pixel shader uses as input. This can be, for example, the interpolated color, interpolated normal, interpolated texture coordinates, etc. I guess by now you noticed the emphasis I put on the word ‘Interpolated’. If you want, you can also pass the 2D screen position in this arrow, so your pixel shader can use it.

I could go on with a theoretic description of the pixel shader, but I think it’s better to just start coding. First, we have to declare we’ll be using our own pixel shader, so change this line in your technique definition:
PixelShader = compile ps_1_1 OurFirstPixelShader();
This indicates every pixel will be drawn by the OurFirstPixelShader method, which has to be compiler as a pixel shader written in HLSL v1.1 language.
As with the vertex shader, I think it’s best practice to first define the output structure of our pixel shader. For every pixel, you only need to specify the color, as the 2D position is already known (again, interpolation between positions of the vertices). Optionally, you can also specify the value that has to be written in the Z-buffer, which is what we are going to do in a next chapter. For now, the color will be enough, so put this definition at the top of your code:
struct PixelToFrame { float4 Color : COLOR0; };
When you look at the flowchart, you’ll see the pixel shader eventually sends its output to the frame buffer. This is where multiple renderings get blended in case of alpha blending. More on this later, I just mentioned this to explain the name of the output struct.
So now we can go ahead and code our first pixel shader, which will simply route the color it receives from the interpolator to its output:
PixelToFrame OurFirstPixelShader(VertexToPixel PSIn) { PixelToFrame Output = (PixelToFrame)0;
Output.Color = PSIn.Color;
return Output; }
Pretty self-explaining: you initialize an output structure, and fill the Color member with the input you receive.
This would be the default pixel shader. When you run your DirectX app, you should see the same result as with the last chapter. You can try to experiment by setting the color of the pixel shader to a solid color, which again will give you a solid colored triangle:
Output.Color.rg = 1;
Now it’s time to show you something specific about pixel shaders: we’re going to program the color of each of the pixels separately. We’re going to do the exercise of last chapter again, only this time using a pixel shader. Remember, we want each of the 3 color channels to take the values of each of the three 3D-coordinates of the pixel.
What we need as input to our pixel shader, is the 3D coordinate of the pixel. The only coordinate we calculated is the 2D screen position (remember we cannot use this value in our pixel shader, as it is the left arrow in our flowchart). So what we need to do is pass the 3D coordinate from our vertex shader to our pixel shader. First redefine the output structure of your vertex shader:
struct VertexToPixel { float4 Position : POSITION; float4 Color : COLOR0; float4 Position3D : TEXCOORD0; };
You see we added a member to store the 3D position. As semantic, we used TEXCOORD0. You can use TEXCOORD0 to TEXCOORD16 to pass float4 values from your vertex shader to your pixel shader.
Next we’ll update our vertex shader so it routes the 3D position it receives from the vertex stream to its output. To do this, we simply have to add the following line to our vertex shader:
Output.Position3D = inPos;
This will have our 3D position sent to the interpolator, which will interpolate the 3D position of every pixel in the triangle. For each pixel, this interpolated 3D coordinate will be sent to the pixel shader.
Now we will have our pixel shader set the color components to the value of this 3D coordinate. In your pixel shader, put this line as you color definition:
Output.Color.rgb = PSIn.Position3D.yxz;
By now you should know what this does: it sets the value of the y coordinate as the red color component, and so on. Compile the code by pressing Ctrl+S. When you did everything well, you shouldn’t see any error messages. Now go to Visual Studio, and run the code. You should see the same as the image below: a simple triangle, with pixels that display color that aren’t linear interpolations of the colors of the corner points. So we have programmed the color of every pixel individually!

Click here to go to the forum on this chapter!
Or click on one of the topics on this chapter to go there: Vertex and Pixel Shader Versions? Up to the beginning of the third C# series my lapt...thx to riemer The riemer's tutorials are wonderful! I tried wri...
Note we haven’t changed anything to our DirectX code, only the HLSL part has been changed. This means our CPU still has the same workload. Only the GPU will have to work a bit harder, but this still is nothing compared to the capabilities of the GPUs present on today’s Radeon and GeForce boards.
The HLSL code:
struct VertexToPixel { float4 Position : POSITION; float4 Color : COLOR0;
float4 Position3D : TEXCOORD0;
};
struct PixelToFrame { float4 Color : COLOR0; };
float4x4 xViewProjection;
VertexToPixel SimplestVertexShader( float4 inPos : POSITION, float4 inColor : COLOR0) { VertexToPixel Output = (VertexToPixel)0; Output.Position =mul(inPos, xViewProjection); Output.Color.rgb = inPos.yxz;
Output.Position3D = inPos;
return Output; }
PixelToFrame OurFirstPixelShader(VertexToPixel PSIn) { PixelToFrame Output = (PixelToFrame)0; Output.Color.rgb = PSIn.Position3D.yxz; return Output; }
technique Simplest { pass Pass0 { VertexShader = compile vs_1_1 SimplestVertexShader();
PixelShader = compile ps_1_1 OurFirstPixelShader();
} }
The DirectX code:
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using D3D = Microsoft.DirectX.Direct3D; namespace DirectX_Tutorial { struct myownvertexformat { public Vector3 Pos; public int Color; public myownvertexformat(Vector3 _Pos, int _Color) { Pos = _Pos; Color = _Color; } } public class WinForm : System.Windows.Forms.Form { private System.ComponentModel.Container components = null; private D3D.Device device; private VertexBuffer vb; private Vector3 CameraPos; private VertexDeclaration vd; private Effect effect; private Matrix matView; private Matrix matProjection; private int LastTickCount = 1; private int Frames = 0; private float LastFrameRate = 0; private D3D.Font text; public WinForm() { InitializeComponent(); this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true); } public void InitializeDevice() { PresentParameters presentParams = new PresentParameters(); presentParams.Windowed = true; presentParams.SwapEffect = SwapEffect.Discard; presentParams.AutoDepthStencilFormat = DepthFormat.D16; presentParams.EnableAutoDepthStencil = true; Caps DevCaps = D3D.Manager.GetDeviceCaps(0, D3D.DeviceType.Hardware); D3D.DeviceType DevType = D3D.DeviceType.Reference; CreateFlags DevFlags = CreateFlags.SoftwareVertexProcessing; if ((DevCaps.VertexShaderVersion >= new Version(2, 0)) && (DevCaps.PixelShaderVersion >= new Version(2, 0))) { DevType = D3D.DeviceType.Hardware; if (DevCaps.DeviceCaps.SupportsHardwareTransformAndLight) { DevFlags = CreateFlags.HardwareVertexProcessing; if (DevCaps.DeviceCaps.SupportsPureDevice) { DevFlags |= CreateFlags.PureDevice; } } } device = new D3D.Device(0, DevType, this, DevFlags, presentParams); device.DeviceReset += new EventHandler(this.HandleDeviceReset); } private void HandleDeviceReset(object sender, EventArgs e) { FillResources(); } private void AllocateResources() { vb = new VertexBuffer(typeof(myownvertexformat), 3, device, Usage.WriteOnly, VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture0, Pool.Managed); InitializeFont(); effect = D3D.Effect.FromFile(device, @"../../OurHLSLFile.fx", null, null, ShaderFlags.None, null); } private void FillResources() { myownvertexformat[] vertices = new myownvertexformat[30]; vertices[0] = new myownvertexformat(new Vector3(2, -2, -2), Color.Red.ToArgb()); vertices[1] = new myownvertexformat(new Vector3(0, 2, 0), Color.Yellow.ToArgb()); vertices[2] = new myownvertexformat(new Vector3(-2, -2, 2), Color.Green.ToArgb()); vb.SetData(vertices, 0, LockFlags.None); SetUpCamera(); VertexElement[] velements = new VertexElement[] { new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), new VertexElement(0, 12, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), VertexElement.VertexDeclarationEnd }; vd = new VertexDeclaration(device, velements); } private void InitializeFont() { System.Drawing.Font systemfont = new System.Drawing.Font("Arial", 12f, FontStyle.Regular); text = new D3D.Font(device, systemfont); } private void DrawMesh(Mesh mesh, Material[] meshmaterials, Texture[] meshtextures) { for (int i = 0; i < meshmaterials.Length; i++) { if (meshtextures.Length > 3) device.SetTexture(0, meshtextures[i]); mesh.DrawSubset(i); } } protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkSlateBlue, 1.0f, 0); device.BeginScene(); device.SetStreamSource(0, vb, 0); device.VertexDeclaration = vd; effect.Technique = "Simplest"; effect.SetValue("xViewProjection", matView * matProjection); int numpasses = effect.Begin(0); for (int i = 0; i < numpasses; i++) { effect.BeginPass(i); device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); effect.EndPass(); } effect.End(); UpdateFramerate(); device.EndScene(); device.Present(); this.Invalidate(); } private void UpdateFramerate() { Frames++; if (Math.Abs(Environment.TickCount - LastTickCount) > 1000) { LastFrameRate = (float)Frames * 1000 / Math.Abs(Environment.TickCount - LastTickCount); LastTickCount = Environment.TickCount; Frames = 0; } text.DrawText(null, string.Format("Framerate : {0:0.00} fps", LastFrameRate), new Point(10, 430), Color.Red); } private void SetUpCamera() { CameraPos = new Vector3(0, -6, 5); matProjection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 20f); matView = Matrix.LookAtLH(CameraPos, new Vector3(0, -1, 0), new Vector3(0, 1, 1)); device.Transform.Projection = matProjection; device.Transform.View = matView; } private void LoadMesh(string filename, ref Mesh mesh, ref Material[] meshmaterials, ref Texture[] meshtextures) { ExtendedMaterial[] materialarray; GraphicsStream adj = null; mesh = Mesh.FromFile(filename, MeshFlags.Managed, device, out adj, out materialarray); if ((materialarray != null) && (materialarray.Length > 0)) { meshmaterials = new Material[materialarray.Length]; meshtextures = new Texture[materialarray.Length]; for (int i = 0; i < materialarray.Length; i++) { meshmaterials[i] = materialarray[i].Material3D; meshmaterials[i].Ambient = meshmaterials[i].Diffuse; if ((materialarray[i].TextureFilename != null) && (materialarray[i].TextureFilename != string.Empty)) { meshtextures[i] = TextureLoader.FromFile(device, materialarray[i].TextureFilename); } } } mesh = mesh.Clone(mesh.Options.Value, CustomVertex.PositionNormalTextured.Format, device); mesh.ComputeNormals(); } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.Size = new System.Drawing.Size(500, 500); this.Text = "Riemer's DirectX & HLSL Tutorial using C# -- Season 3"; } static void Main() { using (WinForm our_directx_form = new WinForm()) { our_directx_form.InitializeDevice(); our_directx_form.AllocateResources(); our_directx_form.FillResources(); Application.Run(our_directx_form); } } } }
- Website design & XNA + DirectX code : Riemer Grootjans - ©2003 - 2011 Riemer Grootjans
|
|
|
|
|