tutorial - draw a triangle
This tutorial builds on the code we developed in the previous tutorial. Click here
to get it.
define your vertex structure
DirectX 8.0 allows you to create your own vertex structure. For the purpose of this tutorial
we're going to define a very simple vertex that stores the x, y, z coordinates
and the color associated with the vertex. At the top of your source file add the following lines:
struct D3DVertex
{
FLOAT x, y, z;
DWORD color;
};
#define D3DFVF_D3DVertex (D3DFVF_XYZ|D3DFVF_DIFFUSE)
create a vertex buffer
DirectX 8.0 uses vertex buffers to store vertices so that hardware texture and lighting
units (TnL) can perform these operations in the background while the CPU works on other
things. Although less than 0.1% of the graphics card on the market today support hardware
TnL, Microsoft is anticipating the future.
Add the following lines into your rendering routine right below BeginScene():
// Create a Vertex Buffer
LPDIRECT3DVERTEXBUFFER8 theBuffer;
if( FAILED( g_pd3dDevice->CreateVertexBuffer( 3*sizeof(D3DVertex),
0, D3DFVF_D3DVertex,
D3DPOOL_DEFAULT, &theBuffer)))
{
return;
}
This will create a vertex buffer that holds 3 vertices of the type D3DVertex.
load the vertex buffer
Now we load the vertex buffer with the points of our triangle:
// Declare the vertices of our triangle
D3DVertex mytriangle[3] = {
{-0.5f, 0.0f, 0.0f, D3DCOLOR_XRGB(255,0,0)},
{0.5f, 0.5f, 0.0f, D3DCOLOR_XRGB(0,255,0)},
{0.5f, -0.5f, 0.0f, D3DCOLOR_XRGB(0,0,255)}
};
// Copy triangle vertices into the buffer
D3DVertex* pVertices;
if( FAILED( theBuffer->Lock( 0, sizeof(D3DVertex) * 3, (BYTE**)&pVertices, 0 )))
return;
memcpy( pVertices, mytriangle, sizeof(D3DVertex) * 3);
theBuffer->Unlock();
draw the vertex buffer
Once the vertex buffer is in place we can begin to draw it. We do this by setting
the current "working" vertex buffer to the buffer with out triangle in it,
then we set tell Direct3D that the vertex buffer also contains color shading information,
and finally draw the vertex buffer as a triangle:
// Draw the vertex buffer
g_pd3dDevice->SetStreamSource( 0, theBuffer, sizeof(D3DVertex) );
g_pd3dDevice->SetVertexShader( D3DFVF_D3DVertex );
g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );
// Destroy the vertex buffer
theBuffer->Release();
Notice the D3DPT_TRIANGLELIST parameter. If you want to draw another type of
primitive, such as a line or triangle fan, you can pass different parameters here.
When we're done we destroy the vertex buffer with the Release() method.
source file
The source file for the tutorial up until this point is located here.
Tutorial Menu