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

Terrain creation basics


At last, we've seen enough topics to start creating our terrain. Letís start small, with 4x3 given points. However, we will make our engine dynamic, so next chapter we can load a much larger number of points. To do this, we have to define 2 constants at the top of our file:

 #define WIDTH    4
 #define HEIGHT    3

We will suppose the 4x3 points are equidistant. So the only thing we don't know about our points is the Z coordinate. We will use an array to hold this information, which we create and fill in the beginning of our FillVertices function:

 float flt_HeightData[WIDTH][HEIGHT];
 
 flt_HeightData[0][0]=0;
 flt_HeightData[1][0]=0;
 flt_HeightData[2][0]=0;
 flt_HeightData[3][0]=0;
 
 flt_HeightData[0][1]=1;
 flt_HeightData[1][1]=0;
 flt_HeightData[2][1]=2;
 flt_HeightData[3][1]=2;
 
 flt_HeightData[0][2]=2;
 flt_HeightData[1][2]=2;
 flt_HeightData[2][2]=4;
 flt_HeightData[3][2]=2;

Now we will position our camera on the positive side of the Z-axe. This way, vertices with a higher Z coordinate will be drawn closer to the camera. So find the line where you define the position of your camera and replace it with this one:

 D3DXVECTOR3 m_EyePos(0, 0, 15);

With our height array filled, we can now define our vertices. Since we have a 4x3 terrain, 12 (=WIDTH*HEIGHT) vertices will do. The points are equidistant,†so we already know the x and y coordinates. As Z coordinates we will use 0 for now, so we can clearly see the difference later:


for (int x=0;x< WIDTH;x++)    {

        for (int y=0; y< HEIGHT;y++)        {
            cv_Vertices[y*WIDTH + x].x = -x;
            cv_Vertices[y*WIDTH + x].y = y;
            cv_Vertices[y*WIDTH + x].z = 0;
            cv_Vertices[y*WIDTH + x].color = 0xffffffff;
        }
    }

    if (FAILED(p_dx_Device->CreateVertexBuffer(WIDTH*HEIGHT*sizeof(OURCUSTOMVERTEX), 0, D3DFVF_XYZ|D3DFVF_DIFFUSE, D3DPOOL_DEFAULT, &p_dx_VertexBuffer, NULL)))
    {
        MessageBox(han_Window,"Error while creating VertexBuffer","FillVertices()",MB_OK);
    }

    VOID* p_Vertices;
    if (FAILED(p_dx_VertexBuffer->Lock(0, WIDTH*HEIGHT*sizeof(OURCUSTOMVERTEX), (void**)&p_Vertices, 0)))
    {
        MessageBox(han_Window,"Error trying to lock","FillVertices()",MB_OK);
    }else{
        memcpy(p_Vertices, cv_Vertices, WIDTH*HEIGHT*sizeof(OURCUSTOMVERTEX));
        p_dx_VertexBuffer->Unlock();
    }

Nothing magic going on here, you simply define your 12 points and make them white. Notice we use Ėx as the X coordinate, so our triangles will be displayed at the right side of our window (our viewpoint is the positive Z axe, up is the positive Y axe, so the positive X axe is pointing to left). Then you simply ask DirectX to create a VertexBuffer which can hold 12 vertices instead of 3.

Next comes a more difficult part: creating the needed triangles to connect the 12 vertices. Of course, this is again done using indexing. The best way to do this is by creating two sets of vertices:



We'll start by drawing the right-topped set of triangles. To do this, change your FillIndices method like this:

 short s_Indices[(WIDTH-1)*(HEIGHT-1)*3];
 

for (int x=0;x< WIDTH-1;x++){

    for (int y=0; y< HEIGHT-1;y++)    {
        s_Indices[(x+y*(WIDTH-1))*3+2] = x+y*WIDTH;
        s_Indices[(x+y*(WIDTH-1))*3+1] = (x+1)+y*WIDTH;
        s_Indices[(x+y*(WIDTH-1))*3] = (x+1)+(y+1)*WIDTH;
    }
}

if (FAILED(p_dx_Device->CreateIndexBuffer((WIDTH-1)*(HEIGHT-1)*3*sizeof(short),D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&p_dx_IndexBuffer,NULL)))
{
    MessageBox(han_Window,"Error while creating IndexBuffer","FillIndices()",MB_OK);
}

VOID* p_Indices;
if (FAILED(p_dx_IndexBuffer->Lock(0, (WIDTH-1)*(HEIGHT-1)*3*sizeof(short), (void**)&p_Indices, 0)))
{
    MessageBox(han_Window,"Error trying to lock","FillIndices()",MB_OK);
}else{
    memcpy(p_Indices, s_Indices, (WIDTH-1)*(HEIGHT-1)*3*sizeof(short));
    p_dx_IndexBuffer->Unlock();
}

For every triangle, you first define the bottom left corner, then the bottom right corner, and then the top right corner. This way we have defined our triangle in a counterclockwise way, so DirectX will display it. Once again, you have to let DirectX know your IndexBuffer will contain 3 indices for every triangle, which gives a total of (WIDTH-1)*(HEIGHT-1)*3 triangles.

All thatís left to do is to specify how many triangles DirectX has to draw from how many indices and vertices. This is done in the DrawScene method. Fin the line that specifies all this and change it to this one:

 p_dx_Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,WIDTH*HEIGHT,0,(WIDTH-1)*(HEIGHT-1));

Our VertexBuffer now contains WIDTH*HEIGHT vertices, and our IndexBuffer defines (WIDTH-1)*(HEIGHT-1) triangles. Try compiling and running this code now! You should see DirectX draws 6 triangles for you. You could imaging a while terrain of these triangles giving a nice result, however there would be 2 problems:

1) The left and upper edges of your terrain would be jagged
2) Suppose you would like to fill the triangles with a color. Since only half of each square is covered by a triangle, only half of your terrain would have this color!

So thatís why we need to define the extra series of triangles, indicated by the image above. We need no extra vertices, but we need to double our index buffer. So redefine your FillIndices method by this:

 short s_Indices[(WIDTH-1)*(HEIGHT-1)*6];
 

for (int x=0;x< WIDTH-1;x++){

    for (int y=0; y< HEIGHT-1;y++)    {
        s_Indices[(x+y*(WIDTH-1))*6+2] = x+y*WIDTH;
        s_Indices[(x+y*(WIDTH-1))*6+1] = (x+1)+y*WIDTH;
        s_Indices[(x+y*(WIDTH-1))*6] = (x+1)+(y+1)*WIDTH;

        s_Indices[(x+y*(WIDTH-1))*6+3] = (x+1)+(y+1)*WIDTH;
        s_Indices[(x+y*(WIDTH-1))*6+4] = x+y*WIDTH;
        s_Indices[(x+y*(WIDTH-1))*6+5] = x+(y+1)*WIDTH;
    }
}

This also defines the indices for the second series of triangles: first you define the top right corner, then the bottom left corner and the bottom right corner, thus always in a counterclockwise way. In the lower part of the method you also have to specify the amount of indices has been doubled, by replacing (WIDTH-1)*(HEIGHT-1)*3 by (WIDTH-1)*(HEIGHT-1)*6. Then, in the DrawScene, simply specify DirectX has to draw twice as much triangles:

 p_dx_Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,WIDTH*HEIGHT,0,(WIDTH-1)*(HEIGHT-1)*2);

Running this should give you 6 nicely drawn quads, each of them consisting of 2 triangles. Now itís time to inject the data from our flt_HeightData into the vertices, so change the line in your FillVertices that defines the Z coordinate of your vertices to this:

 cv_Vertices[y*WIDTH + x].z = flt_HeightData[x][y];

Running this should give you a window very similar to this one†:




DirectX Tutorial 10 - Terrain creation

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:
  • Math boggles me
          Hi, First off, these are a wonderful set of tuto...



    With all this, we are finally ready to render our whole terrain. Inserting all height data manually however would be quite time-consuming, to in the next chapter we are going to load the height data from an image file!

    You can find the code here:


    #include<windows.h>
    #include<d3d9.h>
    #include<d3dx9.h>

     #define WIDTH    4
     #define HEIGHT    3
     
     struct OURCUSTOMVERTEX
     {
         float x,y,z;
         DWORD color;
     };
     
     int int_AppRunning = 1;
     
     LRESULT CALLBACK OurWindowProcedure(HWND han_Wind,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)
     {
         switch(uint_Message)
         {
             case WM_KEYDOWN:
             {
                 int_AppRunning = 0;
                 break;
             }
             break;
         }
     
         return DefWindowProc(han_Wind,uint_Message,parameter1,parameter2);
     }
     
     HWND NewWindow(LPCTSTR str_Title,int int_XPos, int int_YPos, int int_Width, int int_Height)
     {
         WNDCLASSEX wnd_Structure;
     
         wnd_Structure.cbSize = sizeof(WNDCLASSEX);
         wnd_Structure.style = CS_HREDRAW | CS_VREDRAW;
         wnd_Structure.lpfnWndProc = OurWindowProcedure;
         wnd_Structure.cbClsExtra = 0;
         wnd_Structure.cbWndExtra = 0;
         wnd_Structure.hInstance = GetModuleHandle(NULL);
         wnd_Structure.hIcon = NULL;
         wnd_Structure.hCursor = NULL;
         wnd_Structure.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
         wnd_Structure.lpszMenuName = NULL;
         wnd_Structure.lpszClassName = "WindowClassName";
         wnd_Structure.hIconSm = LoadIcon(NULL,IDI_APPLICATION);
     
         RegisterClassEx(&wnd_Structure);
     
         return CreateWindowEx(WS_EX_CONTROLPARENT, "WindowClassName", str_Title, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE, int_XPos, int_YPos, int_Width, int_Height, NULL, NULL, GetModuleHandle(NULL), NULL);
     }
     
     LPDIRECT3DDEVICE9 InitializeDevice(HWND han_WindowToBindTo)
     {
         LPDIRECT3D9 p_dx_Object;
         LPDIRECT3DDEVICE9 p_dx_Device;
     
         p_dx_Object = Direct3DCreate9(D3D_SDK_VERSION);
         if (p_dx_Object == NULL)
         {
             MessageBox(han_WindowToBindTo,"DirectX Runtime library not installed!","InitializeDevice()",MB_OK);
         }
     
         D3DPRESENT_PARAMETERS dx_PresParams;
         ZeroMemory( &dx_PresParams, sizeof(dx_PresParams) );
         dx_PresParams.Windowed = TRUE;
         dx_PresParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
         dx_PresParams.BackBufferFormat = D3DFMT_UNKNOWN;
     
         if (FAILED(p_dx_Object->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, han_WindowToBindTo, D3DCREATE_HARDWARE_VERTEXPROCESSING, &dx_PresParams, &p_dx_Device)))
         {
             if (FAILED(p_dx_Object->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, han_WindowToBindTo, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &dx_PresParams, &p_dx_Device)))
             {
                 MessageBox(han_WindowToBindTo,"Failed to create even the reference device!","InitializeDevice()",MB_OK);
             }
      }
     
         p_dx_Device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
         p_dx_Device->SetRenderState(D3DRS_LIGHTING,false);
         p_dx_Device->SetRenderState(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
     
         return p_dx_Device;
     }
     
     void DrawScene(LPDIRECT3DDEVICE9 p_dx_Device, LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer, LPDIRECT3DINDEXBUFFER9 p_dx_IndexBuffer)
     {
         p_dx_Device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(72,61,139), 1.0f, 0);
         p_dx_Device->BeginScene();
     
         p_dx_Device->SetStreamSource( 0, p_dx_VertexBuffer, 0, sizeof(OURCUSTOMVERTEX) );
      p_dx_Device->SetFVF(D3DFVF_XYZ|D3DFVF_DIFFUSE);
         p_dx_Device->SetIndices(p_dx_IndexBuffer);
         p_dx_Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,WIDTH*HEIGHT,0,(WIDTH-1)*(HEIGHT-1)*2);
     
         p_dx_Device->EndScene();
         p_dx_Device->Present(NULL, NULL, NULL, NULL);
     }
     
     LPDIRECT3DVERTEXBUFFER9 FillVertices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
     {
         LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer;
         OURCUSTOMVERTEX cv_Vertices[WIDTH*HEIGHT];
         float flt_HeightData[WIDTH][HEIGHT];
     
         flt_HeightData[0][0]=0;
         flt_HeightData[1][0]=0;
         flt_HeightData[2][0]=0;
         flt_HeightData[3][0]=0;
     
         flt_HeightData[0][1]=1;
         flt_HeightData[1][1]=0;
         flt_HeightData[2][1]=2;
         flt_HeightData[3][1]=2;
     
         flt_HeightData[0][2]=2;
         flt_HeightData[1][2]=2;
         flt_HeightData[2][2]=4;
         flt_HeightData[3][2]=2;
     

        for (int x=0;x< WIDTH;x++)    {

            for (int y=0; y< HEIGHT;y++)        {
                cv_Vertices[y*WIDTH + x].x = -x;
                cv_Vertices[y*WIDTH + x].y = y;
                cv_Vertices[y*WIDTH + x].z = flt_HeightData[x][y];
                cv_Vertices[y*WIDTH + x].color = 0xffffffff;
            }
        }

        if (FAILED(p_dx_Device->CreateVertexBuffer(WIDTH*HEIGHT*sizeof(OURCUSTOMVERTEX), 0, D3DFVF_XYZ|D3DFVF_DIFFUSE, D3DPOOL_DEFAULT, &p_dx_VertexBuffer, NULL)))
        {
            MessageBox(han_Window,"Error while creating VertexBuffer","FillVertices()",MB_OK);
        }

        VOID* p_Vertices;
        if (FAILED(p_dx_VertexBuffer->Lock(0, WIDTH*HEIGHT*sizeof(OURCUSTOMVERTEX), (void**)&p_Vertices, 0)))
        {
            MessageBox(han_Window,"Error trying to lock","FillVertices()",MB_OK);
        }else{
            memcpy(p_Vertices, cv_Vertices, WIDTH*HEIGHT*sizeof(OURCUSTOMVERTEX));
            p_dx_VertexBuffer->Unlock();
        }


         return p_dx_VertexBuffer;
     }
     
     LPDIRECT3DINDEXBUFFER9 FillIndices(HWND han_Window, LPDIRECT3DDEVICE9 p_dx_Device)
     {
         LPDIRECT3DINDEXBUFFER9 p_dx_IndexBuffer;
         short s_Indices[(WIDTH-1)*(HEIGHT-1)*6];
     

        for (int x=0;x< WIDTH-1;x++)    {

            for (int y=0; y< HEIGHT-1;y++)        {
                s_Indices[(x+y*(WIDTH-1))*6+2] = x+y*WIDTH;
                s_Indices[(x+y*(WIDTH-1))*6+1] = (x+1)+y*WIDTH;
                s_Indices[(x+y*(WIDTH-1))*6] = (x+1)+(y+1)*WIDTH;

                s_Indices[(x+y*(WIDTH-1))*6+3] = (x+1)+(y+1)*WIDTH;
                s_Indices[(x+y*(WIDTH-1))*6+4] = x+y*WIDTH;
                s_Indices[(x+y*(WIDTH-1))*6+5] = x+(y+1)*WIDTH;

            }
        }

        if (FAILED(p_dx_Device->CreateIndexBuffer((WIDTH-1)*(HEIGHT-1)*6*sizeof(short),D3DUSAGE_WRITEONLY,D3DFMT_INDEX16,D3DPOOL_MANAGED,&p_dx_IndexBuffer,NULL)))
        {
            MessageBox(han_Window,"Error while creating IndexBuffer","FillIndices()",MB_OK);
        }

        VOID* p_Indices;
        if (FAILED(p_dx_IndexBuffer->Lock(0, (WIDTH-1)*(HEIGHT-1)*6*sizeof(short), (void**)&p_Indices, 0)))
        {
            MessageBox(han_Window,"Error trying to lock","FillIndices()",MB_OK);
        }else{
            memcpy(p_Indices, s_Indices, (WIDTH-1)*(HEIGHT-1)*6*sizeof(short));
            p_dx_IndexBuffer->Unlock();
        }

     
         return p_dx_IndexBuffer;
     }
     
     void SetUpCamera(LPDIRECT3DDEVICE9 p_dx_Device)
     {
         D3DXVECTOR3 m_EyePos(0, 0, 15);
         D3DXVECTOR3 m_TargetPos(0, 0, 0);
         D3DXVECTOR3 m_UpVector(0, 1, 0);
         D3DXMATRIXA16 m_View;
         D3DXMatrixLookAtLH(&m_View, &m_EyePos, &m_TargetPos, &m_UpVector);
         p_dx_Device->SetTransform(D3DTS_VIEW, &m_View);
     
         D3DXMATRIX m_Projection;
         D3DXMatrixPerspectiveFovLH(&m_Projection, D3DX_PI/4, 500/500, 1, 50);
         p_dx_Device->SetTransform(D3DTS_PROJECTION, &m_Projection);
     }
     
     int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPreviousInstance,LPSTR lpcmdline,int nCmdShow)
     {
         MSG msg_Message;
     
         HWND han_Window = NewWindow("DirectX C++ Tutorial",100,100,500,500);
         LPDIRECT3DDEVICE9 p_Device = InitializeDevice(han_Window);
         LPDIRECT3DVERTEXBUFFER9 p_dx_VB = FillVertices(han_Window, p_Device);
         LPDIRECT3DINDEXBUFFER9 p_dx_IB = FillIndices(han_Window, p_Device);
         SetUpCamera(p_Device);
     
         while(int_AppRunning)
         {
             if(PeekMessage(&msg_Message,han_Window,0,0,PM_REMOVE))
             {
                 DispatchMessage(&msg_Message);
             }
             DrawScene(p_Device, p_dx_VB, p_dx_IB);
         }
     
         p_dx_VB->Release();
         p_dx_IB->Release();
         p_Device->Release();
         DestroyWindow(han_Window);
     
         return 0;
     }
     


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