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

 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

 XNA 4.0
  Posted by: Anonymous
  When: 15/03/2013 at 19:43:57


Ads

Drawing your first Triangle

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

Every object drawn by Direct3D is drawn using triangles. 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.

DirectX has a construct that fits perfectly to hold our vertex information: the CustomVertex class. Just add the following code to the beginning of the OnPaint method :

 CustomVertex.TransformedColored[] vertices = new CustomVertex.TransformedColored[3];
 
 vertices[0].Position = new Vector4(150f, 100f, 0f, 1f);
 vertices[0].Color = Color.Red.ToArgb();
 vertices[1].Position = new Vector4(this.Width/2+100f, 100f, 0f, 1f);
 vertices[1].Color = Color.Green.ToArgb();
 vertices[2].Position = new Vector4(250f, 300f, 0f, 1f);
 vertices[2].Color = Color.Yellow.ToArgb();

The first line creates an array to hold the information for 3 vertices. TransformedColored means the coordinates of the points will be screen coordinates and each of the points can have its own color. Next we fill in the position and information for 3 points. The'f' behind the numbers simply convert the integers to floats, the expected format. Don't pay attention to the 4th coordinate for now.

All we have to do now is tell the device to paint the triangle! Right after the Clear call, add these lines:

 device.BeginScene();
 
 device.EndScene();


The first line tells the device the we’re going to build the 'scene'. The scene is the whole world of objects the device has to display. The last line indicates the end of the scene definition. The following lines will define our scene (that currently only consists of 1 simple triangle), so add them between the BeginScene and EndScene calls:

 device.VertexFormat = CustomVertex.TransformedColored.Format;
 device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertices);

First we tell the device what kind of vertex information to expect. The last line actually draws the triangle. The first argument indicates that a list of separate triangles is coming. If you would draw 4 triangles, you would need a vertex 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 the TriangleStrip in C# Series 3 : "Triangle Strip".

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.

There still is a problem you might encounter while resizing the window. Try adjusting the width of the window. Sometimes, Windows doesn't consider resizing a window important enough to repaint the whole window. To solve the problem, simply add the following line to the bottom of your OnPaint method:

 this.Invalidate();

You should also add the following line to the constructor of your form:

 this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);




DirectX Tutorial 3 - Drawing a 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:
  • unresolved external symbol _direct3...
          Hi!!! When I try to compile the code of this tu...
  • out of OutOfVideoMemoryException
          DirectX.Direct3D.OutOfVideoMemoryException was unh...
  • VECTOR4
          I got a little tripped up, but figured it out. Wh...
  • this.Invalidate(); buttons problem
          ... at least for me it doesn't :) Hello there ...
  • Series 4 for DX C# ??
          Will there be a series 4 tutorial for Direct X usi...
  • this.Invalidate() causes problem
          First of all, thanks for sharing this information,...
  • Fourth dimension
          Hi, Why are we using four parameters to create ...
  • Position
          when i build the code it gives me an error about p...
  • with PictureBox
          hi, i've finished all the tutorial and now i n...
  • DrawUserPrimitive Error
          I have just started going through the DirectX C# t...
  • A lot of errors
          Hi, I'm getting a lot of errors. First is t...
  • Doesn't draw after resizing
          Hi there. First of all, thanks alot for your deta...



    Much better. I've listed the total code below :

     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;
     
             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);
             }
     
             protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
             {
                 CustomVertex.TransformedColored[] vertices = new CustomVertex.TransformedColored[3];
     
                 vertices[0].Position = new Vector4(150f, 100f, 0f, 1f);
                 vertices[0].Color = Color.Red.ToArgb();
                 vertices[1].Position = new Vector4(this.Width/2+100f, 100f, 0f, 1f);
                 vertices[1].Color = Color.Green.ToArgb();
                 vertices[2].Position = new Vector4(250f, 300f, 0f, 1f);
                 vertices[2].Color = Color.Yellow.ToArgb();
     
                 device.Clear(ClearFlags.Target, Color.DarkSlateBlue , 1.0f, 0);
     
                 device.BeginScene();
                 device.VertexFormat = CustomVertex.TransformedColored.Format;
                 device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertices);
                 device.EndScene();
     
                 device.Present();
     
                 this.Invalidate();
             }
     
             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();
                     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!