|
|
|
|
Terrain creation from file |
It's time to finally create a nice looking landscape. Instead of manually entering the HeightData array, we are going to fill it from a file. To do this, we are going to load a 64x64 black&white image, and use the 'white value' of every pixel as the Z coordinate for the corresponding pixel! This means completely black pixels will give the lowest Z coordinate, while completely white pixels give the highest Z coordinate. You can download my example file here (link). To open and read files, you need to add the following line to your include-block:
#include <fstream>
Also, since our file contains 64x64 pixels, change the constants to reflect this:
#define WIDTH 64 #define HEIGHT 64
Now go to your FillVertices method and find the lines where you fill the array containing the Z coordinates. Replace the top of this method by this code:
LPDIRECT3DVERTEXBUFFER9 p_dx_VertexBuffer; OURCUSTOMVERTEX cv_Vertices[WIDTH*HEIGHT]; std::ifstream f_DataFile; f_DataFile.open("heightdata.raw", std::ios::binary); if (f_DataFile.is_open()) {
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 = f_DataFile.get()/50; cv_Vertices[y*WIDTH + x].color = 0xffffffff; } } }else{ MessageBox(han_Window,"HeighData file not found!","FillVertices()",MB_OK); }
f_DataFile.close();
The third line opens a new object, which can hold a input file stream. Then we link the file “heightdata.raw” to this object, which tries to open the file for binary input. In a .raw file, the 'white value' of every pixel if stored byte after byte. So the only thing we have to do is load byte after byte as our Z coordinate! We divide by 50, otherwise the Z coordinates would be way too high. We also check if the file could be found, otherwise an error message is displayed. If this would happen, try placing the .raw file in the same map as your code files.
You can try running this code now. You should see the bottom left corner of a flat terrain. So let’s introduce a translation before drawing the triangles, so the middle of the terrain is in the (0,0,0) position. Add the following line right before you call the DrawIndexedPrimitive in your DrawScene method:
D3DXMATRIX m_Translation; D3DXMatrixTranslation(&m_Translation,32,-32,0); p_dx_Device->SetTransform(D3DTS_WORLD, & m_Translation);
With the terrain in the center of our window, the only thing left to do is reposition our camera!
D3DXVECTOR3 m_EyePos(-40, 0, 50); D3DXVECTOR3 m_TargetPos(-5, 0, 0); D3DXVECTOR3 m_UpVector(1, 0, 0);
Notice that I also changed the up vector of the camera. The end of this chapter would be an excellent moment to experiment with this setting. When you run this code, you’ll see that most of the terrain is not being displayed! This is because it is being clipped away, because the distance between our camera and most vertices is larger that 50. To solve this, simply enlarge the distance to our far clipping plane to 100:
D3DXMatrixPerspectiveFovLH(&m_Projection, D3DX_PI/4, 500/500, 1, 100);
I also set the background color to black to have a nicer result. Now run the program and you'll see a nice terrain :-)

Click here to go to the forum on this chapter!
Or click on one of the topics on this chapter to go there: Terrain Map Sizes After increase stack size to allow for larger file...Texture terrian c++ Hello, i was just wondering if a tutorial will com...Problem Using Any Other Heightmaps I've been following this tutorial in the creation...Displacement Mapping in Directx Hi Riemer,
Great job, dude! I'm stuck with direc...Culling Problem Hi,
So I just started and got to the Terrain fr...How to do textured terrain? Hello everybody!
I have an important question. ...stack overflow When Im trying to create terrain larger than 128/1...
We’ve already translated our terrain, so rotating would be easy. See how you can have your terrain rotated by using the keyboard in the next chapter!
Here’s the code:
#include<windows.h>
#include<d3d9.h>
#include<d3dx9.h>
#include<fstream>
#define WIDTH 64 #define HEIGHT 64
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(0,0,0), 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);
D3DXMATRIX m_Translation; D3DXMatrixTranslation(&m_Translation,32,-32,0); p_dx_Device->SetTransform(D3DTS_WORLD, & m_Translation);
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];
std::ifstream f_DataFile; f_DataFile.open("heightdata.raw", std::ios::binary); if (f_DataFile.is_open()) {
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 = f_DataFile.get()/50; cv_Vertices[y*WIDTH + x].color = 0xffffffff; } } }else{ MessageBox(han_Window,"HeighData file not found!","FillVertices()",MB_OK); }
f_DataFile.close();
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(-40, 0, 50); D3DXVECTOR3 m_TargetPos(-5, 0, 0); D3DXVECTOR3 m_UpVector(1, 0, 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, 100);
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; }
- Website design & XNA + DirectX code : Riemer Grootjans - ©2003 - 2011 Riemer Grootjans
|
|
|
|
|