XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   
My XNA Book
      
       Go to section on this site

Additional info


Latest Forum posts

 Tutorial 3 for Windows Phone 7
  Posted by: Anonymous
  When: 20/05/2013 at 02:30:13

 No download link for 2d series: shooter
  Posted by: zaboleq
  When: 07/05/2013 at 15:46:28

 Collision Class?
  Posted by: Anonymous
  When: 05/05/2013 at 19:03:59

 stack overflow
  Posted by: cityguy
  When: 07/04/2013 at 01:58:38

 Meshes looks strange.
  Posted by: ab_saratov
  When: 01/04/2013 at 04:31:08

 Lamppost Not loaded
  Posted by: Anonymous
  When: 22/03/2013 at 06:43:52

 Collision Class?
  Posted by: Da_Boom
  When: 21/03/2013 at 01:23:09

 Math boggles me
  Posted by: cityguy
  When: 17/03/2013 at 03:44:48

 Collision Class?
  Posted by: Da_Boom
  When: 16/03/2013 at 03:44:42

 Tree update
  Posted by: Anonymous
  When: 15/03/2013 at 21:11:22


Ads

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!




DirectX Tutorial 5 - Pixel Shader

If you appreciate the amount of time I spend creating and updating
these pages, feel free to donate -- any amount is welcome !



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);
                 }
             }
         }
     }


    Google
     
    Webwww.riemers.net


    If you appreciate the amount of time I spend creating and updating
    these pages, feel free to donate -- any amount is welcome !



    - Website design & XNA + DirectX code : Riemer Grootjans -
    ©2003 - 2011 Riemer Grootjans
  • Translations

    This site in English
    This site in Korean
    This site in Czech

    Microsoft MVP Award



    2007 - 2011 MVP Award
    DirectX - XNA

    Contents

    News
    Home
    Forum
    XNA 2.0 Recipes Book (8)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    XNA 3.0 Recipes Book (8)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Team Project (1)
    News
    Tutorials (160)
    XNA 4.0 using C# (89)
    2D Series: Shooters (22)
    Starting a project
    Drawing fullscreen images
    Positioning images
    SpriteBatch.Draw()
    Rotation
    Keyboard input
    Writing text
    Angle to Direction
    Direction to Angle
    Smoke trail
    Manual texture creation
    Random terrain
    Texture to Colors
    Coll Detection Overview
    Coll Detection Matrices
    Putting CD into practice
    Particles
    Additive alpha blending
    Particle engine
    Adding craters
    Sound in XNA
    Resolution independency
    3D Series 1: Terrain (13)
    Starting a project
    The effect file
    The first triangle
    World space
    Rotation - translation
    Indices
    Terrain basics
    Terrain from file
    Keyboard
    Adding colors
    Lighting basics
    Terrain lighting
    VertexBuffer & IndexBuffer
    3D Series 2: Flightsim (14)
    Starting point
    Textures
    Loading the floorplan
    Creating the 3D city
    Loading a Model
    Ambient and diffuse
    Quaternion camera
    Flight kinematics
    Collision detection
    Adding targets
    Point sprites
    Alpha blending
    Skybox
    Camera delay
    3D Series 3: HLSL (18)
    Starting point
    HLSL introduction
    Vertex format
    Vertex shader
    Pixel shader
    Per-pixel colors
    Textured triangle
    Triangle strip
    World transform
    World normals
    Per-pixel lighting
    Shadow map
    Render to texture
    Projective texturing
    Real shadow
    Shaping the light
    Preshaders
    3D Series 4: Adv. terrain (19)
    Starting code
    Mouse camera
    Textured terrain
    Multitexturing
    Adding detail
    Skydome
    The water technique
    Refraction map
    Reflection map
    Perfect mirror
    Ripples
    The Fresnel term
    Moving water
    Specular highlights
    Billboarding
    Region growing
    Billboarding renderstates
    Perlin noise
    Gradient skybox
    Short Tuts (3)
    Run XNA on older pcs
    MessageBox in XNA
    Normal generation
    DirectX using C# (54)
    Series 1:Terrain (14)
    Opening a window
    Linking to the Device
    Drawing a triangle
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing bmp files
    Colored vertices
    DirectX Light basics
    Mesh creation
    Mesh lighting
    Series 2: Flightsim (19)
    Starting code
    Textures
    The floorplan
    Creating the 3D City
    Meshloading from file
    Ambient light
    Action
    Flight kinematics
    Collision detection
    Skybox
    Texture filtering
    Adding targets
    Point sprites
    Alpha blending
    DirectSound
    Sounds in 3D
    Playing MP3 files
    Displaying text
    Going fullscreen
    Series 3: HLSL (19)
    Starting point
    HLSL Introduction
    Vertex Shader
    Shaded triangle
    Pixel Shader
    Textured Triangle
    Triangle Strip
    World transform
    Adding normals
    The first light
    Shadow mapping
    Render To Texture
    Projective texturing
    The first shadow
    Shaping the light
    Preshaders
    Multiple lights
    Adjusting Z values
    Finishing touch
    Short Tuts (2)
    Resizing problem
    Checking Device caps
    DirectX using C++ (15)
    Series 1: Terrain (15)
    Opening a window
    Ending the game loop
    Linking to the Device
    Clearing your window
    Drawing a triangle
    Culling
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing .bmp files
    Adding colors
    DirectX Light basics
    DirectX using VB (2)
    Series 1: Intro (2)
    The first triangle
    Rotation - translation
    -- Tree view --


    Thank you!

    Support this site --
    any amount is welcome !

    Stay up-to-date

    I don't have the time to keep a News section, so stay informed about the updates by clicking on this RSS file!