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

Drawing your first Triangle

This chapter will cover the basics of drawing. First a few things you should know about.

Every object drawn in 3D is drawn using triangles. Even spheres can be represented using triangles, if you use enough of them. Surprisingly enough, a triangle is defined by 3 points. Every point is defined by a vector, specifying the X, Y and Z coordinates of the point. However, just knowing the coordinates of a point might not be enough. For example, you might want to define a color for the given point as well. This is where a vertex (pl. vertices) comes in: it is the list of properties of a given point, including the position, color and so on.

XNA has a structure that fits perfectly to hold our vertex information: the VertexPositionColor struct. A vertex of this type can hold a position and a color, which is perfect to begin with. To define a triangle, we’ll need 3 of those vertices, which we will store in an array. So let’s declare this variable at the top of our class:

 VertexPositionColor[] vertices;

Next, we will add a small method to our code, SetUpVertices, which will fill this array with 3 vertices:

 private void SetUpVertices()
 {
     vertices = new VertexPositionColor[3];
 
     vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
     vertices[0].Color = Color.Red;
     vertices[1].Position = new Vector3(0, 0.5f, 0f);
     vertices[1].Color = Color.Green;
     vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
     vertices[2].Color = Color.Yellow;
 }

The array is initialized to hold 3 vertices, after which it is filled. For now, we’re using coordinates that are relative to the screen: the (0,0,0) point would be the middle of our screen, the (-1, -1, 0) point bottom-left and the (1, 1, 0) point top-right. So in the example above, the first point is halfway to the bottom left of the window, and the second point is halfway to the top in the middle of our screen. (As they are not really 3D coordinates, they don’t need to be transformed to 2D coords. Hence, the name of the technique: ‘Pretransformed’)

The 'f' behind some of the numbers indicates the values are floats, the format of preference when working with XNA. We set each of the vertices to different colors.
We still need to call this SetUpVertices method. As it uses the device, call it at the end of the LoadContent method:

 SetUpVertices();

All we have to do now is tell the device to draw the triangle! Go to our Draw method, where we should draw the triangle after the call to pass.Apply:

 device.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);

This line actually tells our graphics card to draw the triangle: we want to draw 1 triangle from the vertices array, starting at vertex 0. TriangleList means that our vertices array contains a list of triangles (in our case, a list of only 1 triangle). If you would want to draw 4 triangles, you would need an array of 12 vertices. Another possibility is to use a TriangleStrip, which can perform a lot faster, but is only useful to draw triangles that are connected to each other. More on all kinds of primitives in Recipe 5-1.

The last moment specifies the VertexDeclaration, which is quite important. We have stored the position and color data for 3 vertices inside an array. When we instruct XNA to render a triangle based on this data, XNA will put all this data in a byte stream and send it over to the graphics card. Our graphics card receives the byte stream, but doesn’t know what’s in there! That’s where the VertexDeclaration comes in: this object tells the graphics device what kind of vertices it can expect.

The VertexDeclaration is very important, as you will always need it before you can render any triangle to the screen. By specifying the VertexPositionColor.VertexDeclaration, we inform the graphics card that there are vertices coming its way that contain Position and Color data. We’ll see how we can create our own vertex types later on in this series.

Running this code should give you this window:




DirectX Tutorial 3 - The first triangle

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:
  • Warning not error
          Warning 1 Warning compiling c:usersshineydocume...
  • Custom Shader
          When I try to run the program (emulator) I get the...
  • Effect Passes error
          Hello I am beginner in game developpment, I have...
  • defining indices
          I have a short question, not about the how, but ho...
  • Plz Help
          I want to shrink and expand the triangle and chang...
  • Plz Help
          using System; using System.Collections.Generic; ...
  • Question about Null.
          Hi,I have a question about the 3rd step. If I...
  • XNA 3.1 code
          Great tutorial but do you still have the code for ...
  • XNA 4.0 VertexDeclaration
          I am going through these tutorials using Visual St...
  • noob question about orgin of screen
          What line of code sets the orgin to the center of ...
  • Drawing Two Triangle To Fill The Screen
          Hi Guys, I decided to try one of Riemers exersi...
  • XNA or GameStudio A7
          Hi there, First off, great tutorials. However, ...
  • What does the 0 do in pretransformed
           VertexToPixel Output = (VertexToPixel)0; Pi...
  • InvalidOperationExcpetion
          Hi, and thanks for the tutorials. I have an Inval...
  • Error With the Effect File
          Um i downloaded your effect file, added it to my p...
  • strange behaviour with basic effect
          hey riemer, thank you for helping so many of us wi...
  • some advanced thoughts
          Hi everybody I already did some stuff with XNA,...
  • Vertices problem
          Hi, great tutorials, though when I run the program...
  • LineStrip color stealing texture
          Hey Riemer, Your tutorials are awesome, however...
  • Please Help me Anybody
          I'm having serious trouble, getting things to com...
  • effect.CurrentTechnique null value
          Code line: effect.CurrentTechnique = effect.Techn...
  • verify file location
          Your tutorial is neat and gets right to the point....
  • Novice stupid question
          Hi Riemer, Sorry for bothering u with this stup...
  • vertices problem
          private void SetUpVertices() { ...
  • Argument exception null was unhandled
          Hi, Thanks for the tutorial. It's great I fina...
  • Missing a step
          Hello, I'l loving the walk through so far, ver...
  • this.Invalidate(); buttons problem
          ... at least for me it doesn't :) Hello there ...
  • Errors in Step 2
          Hi, These tutorials are great! Thanks very much...
  • Cant change vertices position
          In SetUpVertices(), if you change the position of ...
  • Background color
          Hey there riemers! First off, thank you very mu...
  • Error @ step 3 of series 1
          I get this compliling error at step 3 of series 1....


    That's all there is to it! Running this code will already give you a colorful triangle on a blue background. Feel free to experiment with the colors and the coordinates.

    You can try these exercises to practice what you've learned:
  • Make the bottom-left corner of the triangle collide with the bottom-left corner of your window.
  • Render 2 triangles, covering your whole window.
    I've listed the total code below :

     using System;
     using System.Collections.Generic;
     using System.Linq;
     using Microsoft.Xna.Framework;
     using Microsoft.Xna.Framework.Audio;
     using Microsoft.Xna.Framework.Content;
     using Microsoft.Xna.Framework.GamerServices;
     using Microsoft.Xna.Framework.Graphics;
     using Microsoft.Xna.Framework.Input;
     using Microsoft.Xna.Framework.Media;
     
     namespace Series3D1
     {
         public class Game1 : Microsoft.Xna.Framework.Game
         {
             GraphicsDeviceManager graphics;
             SpriteBatch spriteBatch;
             GraphicsDevice device;
     
             Effect effect;
             VertexPositionColor[] vertices;
     
             public Game1()
             {
                 graphics = new GraphicsDeviceManager(this);
                 Content.RootDirectory = "Content";
             }
     
             protected override void Initialize()
             {
                 graphics.PreferredBackBufferWidth = 500;
                 graphics.PreferredBackBufferHeight = 500;
                 graphics.IsFullScreen = false;
                 graphics.ApplyChanges();
                 Window.Title = "Riemer's XNA Tutorials -- 3D Series 1";
     
                 base.Initialize();
             }
     
             protected override void LoadContent()
             {
                 spriteBatch = new SpriteBatch(GraphicsDevice);
     
                 device = graphics.GraphicsDevice;

                effect = Content.Load<Effect> ("effects");
     
                 SetUpVertices();
             }
     
             protected override void UnloadContent()
             {
             }
     
             private void SetUpVertices()
             {
                 vertices = new VertexPositionColor[3];
     
                 vertices[0].Position = new Vector3(-0.5f, -0.5f, 0f);
                 vertices[0].Color = Color.Red;
                 vertices[1].Position = new Vector3(0, 0.5f, 0f);
                 vertices[1].Color = Color.Green;
                 vertices[2].Position = new Vector3(0.5f, -0.5f, 0f);
                 vertices[2].Color = Color.Yellow;
             }
     
             protected override void Update(GameTime gameTime)
             {
                 if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                     this.Exit();
     
                 base.Update(gameTime);
             }
     
             protected override void Draw(GameTime gameTime)
             {
                 device.Clear(Color.DarkSlateBlue);
     
                 effect.CurrentTechnique = effect.Techniques["Pretransformed"];
     
                 foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                 {
                     pass.Apply();
     
                     device.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);
                 }
     
                 base.Draw(gameTime);
             }
         }
     }
     
     


    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!