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

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)
    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!