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

 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


Ads

Recycling vertices using inidices

-- Small note: If your hardware is rather old, or if your pc isn’t equipped with a real graphics card, it’s possible that running this chapter will give you an empty window. If this is the case, you can let your CPU do all the graphics operations for you. This will allow you to use all DirectX commands, but a CPU is a lot slower than a graphics card for this. You can switch to CPU processing by using this code:

 device = new Device(0, DeviceType.Reference, this,  CreateFlags.SoftwareVertexProcessing, presentParams);

Instead of this:

 device = new Device(0, DeviceType.Hardware, this,  CreateFlags.SoftwareVertexProcessing, presentParams);

-- End of note --

The triangle was nice, but what about a lot of triangles ? You would need to specify 3 vertices for each triangle. Consider next example:



Only 4 out of 6 vertices are unique. So the other 2 are simply a waste of bandwidth to your graphics card! It would be better to define the 4 vertices in an array from 0 to 3, and to define triangle 1 as vertices 1,2 and 3 and triangle 2 as vertices 2,3 and 4. This way, the complex vertex data is not duplicated. This is exactly the idea behind IndexBuffers. Suppose we would like to draw these 2 triangles :



Normally we would have to define 6 vertices, now only 5. So change our VertexDeclaration method as follows:

 private void VertexDeclaration()
 {
     vb = new VertexBuffer(typeof(CustomVertex.PositionColored), 5, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default);
 
     vertices = new CustomVertex.PositionColored[5];
     vertices[0].Position = new Vector3(0f, 0f, 0f);
     vertices[0].Color = Color.White.ToArgb();
     vertices[1].Position = new Vector3(5f, 0f, 0f);
     vertices[1].Color = Color.White.ToArgb();
     vertices[2].Position = new Vector3(10f, 0f, 0f);
     vertices[2].Color = Color.White.ToArgb();
     vertices[3].Position = new Vector3(5f, 5f, 0f);
     vertices[3].Color = Color.White.ToArgb();
     vertices[4].Position = new Vector3(10f, 5f, 0f);
     vertices[4].Color = Color.White.ToArgb();
 
     vb.SetData(vertices, 0 ,LockFlags.None);
 }

The middle part of this method is easy: we simply define our 5 needed vertices to draw the 2 triangles. However, the first and last lines are new. The first one creates a new VertexBuffer, which will later be needed to link our indices to. The first argument tells the buffer what vertex format to expect. Then the numbers of vertices, our device and some default settings. The last line links our vertex array to the vertex buffer. Of course, you first have to declare vb before this will compile :

 private VertexBuffer vb;

You can already declare our array of indices we are going to fill next, togerther with its IndexBuffer, ib :

 private int[] indices;
 private IndexBuffer ib;

Next, create this IndicesDeclaration method:

 private void IndicesDeclaration()
 {
     ib = new IndexBuffer(typeof(int), 6, device, Usage.WriteOnly, Pool.Default);
     indices = new int[6];
 
     indices[0]=3;
     indices[1]=1;
     indices[2]=0;
     indices[3]=4;
     indices[4]=2;
     indices[5]=1;
 
     ib.SetData(indices, 0, LockFlags.None);
 }

As with our VertexDefinition method, the first line declares the buffer that will be used to draw triangles from. As you can see, we now will need 6 indices, since 1 triangle is defined by 3 indices. Next, our indices array is initiated. As you can see, vertex number 1 is used twice, this was our initial goal. In this case, the profit is rather small, but in real-life application (as you will see soon ;)this is the way to go. Also note that the triangles have been defined in a clockwise order again, so DirectX will see them as facing the camera. The last line attaches the array to the buffer.

-- NOTE: Andy Beatty pointed to me this chapter wouldn’t run on his PC. After some digging, he found this might be a limitation of his graphics card, which has a maximum indexbuffer size of 65.543 indices. Instead of using an index buffer consisting of integers (‘int’), he used the type ‘short’, making this chapter run on his computer! Thanks Andy for this info! --

Make sure to call this method from our Main method :

 our_directx_form.IndicesDeclaration();

All that's left for this chapter is to draw the triangles from our buffer! Make the following changes to your OnPaint method :

 device.BeginScene();
 device.VertexFormat = CustomVertex.PositionColored.Format;
 
 device.SetStreamSource(0, vb, 0);
 device.Indices = ib;
 
 device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 5, 0, 2);
 
 device.EndScene();

You still have to indicate what format is to be expected. Then you set your sources, the VertexBuffer and the IndexBuffer. Finally, you call the DrawIndexedPrimitives method. We still offer a list of separate triangles. The first zero indicates at which index to start counting in your indexbuffer. Then you indicate the minimum amount of used indices. We give 0, which will bring no speed optimization. Then the amount of used vertices and the starting point in our vertexbuffer. Finally, we have to indicate how many primitives (=triangles) we want to be drawn.

That's it! When you run the program, you'll see 2 white triangles next to each other. Try putting this line directly after your device creation :

 device.RenderState.FillMode = FillMode.WireFrame;

This will only draw the lines of our triangles, instead of solid triangles.




DirectX Tutorial 6 - Indices

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:
  • Camera Moved
          A small point, which might explain why some people...
  • Triangle rotates on redraw only
          Hey! Thanks for the tuts! They come in jolly handy...
  • ushort instead of int
          Just a suggestion... If indices are "indexes"...
  • problem with drawprimitives
          namespace DXApp1 { public class Program:Syst...
  • Index Buffer Problem
          Hi, Regarding the index buffer issue you mentione...
  • Displaying DirectX in a User Control
           Hi Reamer, Thank you for the good work that y...
  • just draw a triangle
          My Qustion about chapter "Recycling vertices usin...
  • Solid Triangles
          Hey, just wondering if it matters that my two tria...
  • Empty Window
          Hi, thanks for the awsome tutorials. When I run t...
  • doesn't work too
          sadly, I can't display anything. Neither with you...
  • Blank Screen
          Hi. recently i have started my study on Game prgr...
  • Nothing on my screen
          Hi Riemer, Thanks a lot for the wonderful tutor...



    Here's the whole code this far:

     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;
     
     namespace DirectX_Tutorial
     {
     
         public class WinForm : System.Windows.Forms.Form
         {
             private Device device;
             private System.ComponentModel.Container components = null;
             private float angle = 0f;
             private CustomVertex.PositionColored[] vertices;
             private VertexBuffer vb;
             private int[] indices;
             private IndexBuffer ib;
     
             public WinForm()
             {
                 InitializeComponent();
                 this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
             }
     
             public void InitializeDevice()
             {
                 PresentParameters presentParams = new PresentParameters();
                 presentParams.Windowed = true;
                 presentParams.SwapEffect = SwapEffect.Discard;
                 device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
                 device.RenderState.CullMode = Cull.None;
                 device.RenderState.FillMode = FillMode.WireFrame;
             }
     
             private void CameraPositioning()
             {
                 device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI/4, this.Width/this.Height, 1f, 50f);
                 device.Transform.View = Matrix.LookAtLH(new Vector3(0,0,-30), new Vector3(0,0,0), new Vector3(0,1,0));
                 device.RenderState.Lighting = false;
             }
     
             private void VertexDeclaration()
             {
                 vb = new VertexBuffer(typeof(CustomVertex.PositionColored), 5, device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionColored.Format, Pool.Default);
     
                 vertices = new CustomVertex.PositionColored[5];
                 vertices[0].Position = new Vector3(0f, 0f, 0f);
                 vertices[0].Color = Color.White.ToArgb();
                 vertices[1].Position = new Vector3(5f, 0f, 0f);
                 vertices[1].Color = Color.White.ToArgb();
                 vertices[2].Position = new Vector3(10f, 0f, 0f);
                 vertices[2].Color = Color.White.ToArgb();
                 vertices[3].Position = new Vector3(5f, 5f, 0f);
                 vertices[3].Color = Color.White.ToArgb();
                 vertices[4].Position = new Vector3(10f, 5f, 0f);
                 vertices[4].Color = Color.White.ToArgb();
     
                 vb.SetData(vertices, 0 ,LockFlags.None);
             }
     
             private void IndicesDeclaration()
             {
                 ib = new IndexBuffer(typeof(int), 6, device, Usage.WriteOnly, Pool.Default);
                 indices = new int[6];
     
                 indices[0]=3;
                 indices[1]=1;
                 indices[2]=0;
                 indices[3]=4;
                 indices[4]=2;
                 indices[5]=1;
     
                 ib.SetData(indices, 0, LockFlags.None);
             }
     
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 device.Clear(ClearFlags.Target, Color.DarkSlateBlue , 1.0f, 0);
     
                 device.BeginScene();
                 device.VertexFormat = CustomVertex.PositionColored.Format;
     
                 device.SetStreamSource(0, vb, 0);
                 device.Indices = ib;
     
                 device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 5, 0, 2);
     
                 device.EndScene();
     
                 device.Present();
     
                 this.Invalidate();
                 angle += 0.05f;
             }
     
             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 = "DirectX Tutorial";
             }
     
             static void Main()
             {
                 using (WinForm our_directx_form = new WinForm())
                 {
                     our_directx_form.InitializeDevice();
                     our_directx_form.CameraPositioning();
                     our_directx_form.VertexDeclaration();
                     our_directx_form.IndicesDeclaration();
                     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)
    XNA 3.0 Recipes Book (8)
    Downloads
    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)
    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)
    Series 3: HLSL (19)
    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!