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

Additional info

Latest Forum posts

 Account settings
  Posted by: Anonymous
  When: 07/05/2014 at 09:48:39

 forced subtitle
  Posted by: Applefly
  When: 07/05/2014 at 06:00:48

 convert DVD into PMS
  Posted by: Applefly
  When: 07/05/2014 at 05:55:25

 DVD to Digital Copy easily
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:52:29

 DVD on Xbox 360/Xbox One Console
  Posted by: VIKIVannessa
  When: 05/05/2014 at 06:51:47

 Extract .Srt Subtitles
  Posted by: Applefly
  When: 04/05/2014 at 03:54:38

 Encode Movie collection
  Posted by: Applefly
  When: 04/05/2014 at 03:52:41

 Convert DVD to WMV
  Posted by: Applefly
  When: 29/04/2014 at 05:53:50

 rip DVDs into digital files
  Posted by: Applefly
  When: 29/04/2014 at 05:51:20

 iTunes movies/music to Kindle Fire
  Posted by: ciciyu80
  When: 29/04/2014 at 05:10:20


Starting point for Series 3

Welcome to this 3rd installment of my Tutorials on DirectX. Because this Series will cover a lot of ground, I would like to take a jumpstart by starting from the code presented below. As you can see on the screenshot below, it will only draw a simple triangle. Of course, the code contains a few more helper classes we’ll be using throughout the Series. There is nothing in this code that hasn’t been covered yet in the previous 2 series or in the short tuts, except of the framerate counter, which is explained below. Anyway, on this page you can find a short description of most methods used in the code:

  • The program is started once again from the Main method, which you can find at the bottom of the code.
  • The device is created in the InitializeDevice method, exactly as described in the short tut “Checking device capabilities”. In the end, we hook a method to the OnReset event to handle window resizings, as described in the short tut “Handling device resets”.
  • The AllocateResources and FillResources simply fill an index buffer with 3 vertices, defining a colored triangle. Note we’ve used a custom-made vertex format, ‘myvertexformat’. See the tut “Point sprites” in Series 2 for more info on this.
  • I have included helper methods to load and display meshes. Although we’re not using any right now, it will be useful later on in the Series. Also I set up a helper method to load a font. You can find info on all of this throughout Series 2.

    The only ‘new’ code you’ll find is in the UpdateFramerate method. This method checks how many times it’s been called the last second, and puts that value on the screen. To achieve this, it simply uses the value returned by Environment.TickCount, which is the amount of milliseconds the computer has been running. As a sidenote, I should warn you that this value is only updated every 20 milleseconds or so. This could mean, in the worst case, that it returns the same value during 39 milliseconds, which corresponds to only 25 frames/second. This gives severe problems when you’re writing a game and you’re basing the amount of movement on the TickCount value. In our case, however, there’s no reason why we shouldn’t use the TickCount method, so here is the code:

     private void UpdateFramerate()
          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);

    First we increment the number of frames. Then we check if a second has passed since the last value was written to screen. If so, we store the framerate in LastFrameRate. I have used this formula, so we can also display framerates smaller than 1. The last line puts the value on the screen, rounded to 2 decimal values.

    DirectX Tutorial 1 - Starting point

    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:
  • Error on compiling
          Hi, I've just used the code given below, but w...
  • FillResources
          Hi, when i try copy-paste the code and run, that d...
  • problems with compliling
          Hi, I have a problem like that, i was coding an...
  • my FPS is less than 1
          Hi together, I'm reading and trying to underst...
  • why my fps less than 20?
          just copy your code , and running slow . At wi...

    That’s about it for our starting code. If you have been following my tutorials up to this point, simply copy-paste this code into Visual Studio:

     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 Matrix matView;
             private Matrix matProjection;
             private int LastTickCount = 1;
             private int Frames = 0;
             private float LastFrameRate = 0;
             private D3D.Font text;
             public WinForm()
                 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)
             private void AllocateResources()
                 vb = new VertexBuffer(typeof(myownvertexformat), 3, device, Usage.WriteOnly, VertexFormats.Position | VertexFormats.Normal | VertexFormats.Texture0, Pool.Managed);                        
             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);
                 device.RenderState.Lighting = false;
             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]);
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
                 device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkSlateBlue, 1.0f, 0);
                 device.Transform.World = Matrix.Identity;
                 device.VertexFormat = CustomVertex.PositionColored.Format;
                 device.SetStreamSource(0, vb, 0);
                 device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);    
             private void UpdateFramerate()
                 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);
             protected override void Dispose(bool disposing)
                 if (disposing)
                     if (components != null)
             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())


    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


    XNA 2.0 Recipes Book (8)
    XNA 3.0 Recipes Book (8)
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Tutorials (160)
    XNA 4.0 using C# (89)
    DirectX using C# (54)
    Series 1:Terrain (14)
    Series 2: Flightsim (19)
    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
    Multiple lights
    Adjusting Z values
    Finishing touch
    Short Tuts (2)
    DirectX using C++ (15)
    DirectX using VB (2)
    -- Expand all --

    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!