Navigation: DirectX 9.0

Tutorial 1 - Setting up Direct3D


Overview

This tutorial is about preparing a Visual Studio project for 3D game development. You will learn the components of a DirectX application and by the end of the tutorial you will have a DirectX program up and running. The program will simply display a blue colour in a window but this will be performed by the GPU rather than an ordinary windows window so it will be much faster. Once you have the program set up you can start adding 3d objects to the world and make an interactive game. The game kit I have provided that you can download from this website has a set of objects to accompany making 3D games that you can use if you want; for example the "Mesh" object makes it easy to load a static .x mesh like a cube or a castle and put it in your world.

The DirectX SDK

The DirectX Software Development Kit is a set of objects, functions and libraries that you need to develop raw DirectX applications. You must download this from the internet before you begin.

Note: You will need the Microsoft DirectX SDK (June 2010) or the August 2008 versions of the DirectX SDK for these tutorials. These are the DirectX 9 versions of the SDK. Visual Studio 2008 may not work with other versions.

Setting up a Project for DirectX 9.0 Development

Basically the first thing you need is a window, or a project with a window, like described in Tutorial 6 of Introduction To Programming found on this website.

You can setup a new Win32 empty project for this and add the following file to begin:

Now you need to tell Visual Studio where the path to the DirectX SDK you downloaded is. This is done slightly differently in Visual Studio 2010 than in Visual Studio 2008. I will only explain how to specify the path for Visual Studio 2008:

1. Open the project with your window code.
2. Go to Project->Properties.
3. Click the arrow next to Configuration Properties to expand the menu.
4. Expand the menu for C/C++ and select the General tab.
5. Click on Additional Include Directories and select the button with 3 dots(See Figure 1.)


Figure 1.

6. Add the Include directory of your SDK, on my computer the directory is: C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include

Note: The include directory is the directory where all the DirectX headers are .h files.

7. Expand the menu for Linker and select the General tab.
8. Select Additional Library Directories.
9. Add the directory to the library files of the DirectX Sdk, on my computer it is: C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86

These directories you just added tell Visual Studio where to look for .h files and .lib files.

Now you need to tell Visual Studio what library files your project will use. A library file .lib is some compiled code that has definitions for functions and classes like .cpp files contain definitions. .lib files however are compiled code. The ones we will be using are needed to make some DirectX functions and objects work. For our Direct3D projects the only lib files we need are d3d9.lib and d3dx9.lib

10. Click on Linker->Input
11. Type the following into Additional Dependencies:

d3d9.lib d3dx9.lib

(See Figure 2.)


Figure 2.

12. Click Apply to apply the changes.

That's the project set up now for creating a DirectX game!

Direct3D

Direct3D is a subset of DirectX used for doing 3D stuff. You can use the term DirectX and Direct3D interchangably when you talk about a 3D game that utilizes Direct3D and it's not a problem. Other subsets of DirectX are DirectPlay, DirectSound and DirectShow. DirectPlay allows you to incorporate networking facilities into your game for example.

Initializing Direct3D

Here we will be looking at how to set up a program that can be used to render(same thing as draw) a 3d world into a window or fullscreen. We need to describe some properties that we want our D3D device to use when running our game, for example should the program use the CPU(central processing unit) or the GPU(Graphics processing unit), to process our 3d world and what size is the area, back buffer, we want to use to contain all the pixels of the world.

We describe such properties with the D3DPRESENT_PARAMETERS structure. As it's name suggests, an instance of D3DPRESENT_PARAMETERS is used to hold parameters to another function; the function being d3d9->CreateDevice(...).

Ok, if this is your first experience of using DirectX code, you might find it heavy going. But I will explain the code in some detail so that you will be ready to move on and create an interactive 3d environment.

Let's start by creating a class to represent the state of a game, handling setting everything up, updating the game and cleaning up any resources used by the game. It is useful to have a single class that manages these things, updating the game objects such as characters and freeing memory used by DirectX objects. Let's call it "Game". I will show you the skeleton of the Game object below, and next I will talk you through it's implementation until you understand it quite well. In these tutorials we will be using the Game class and add to it as we go.

class Game
{
public:
	~Game();
	bool InitGame(HWND render_window);
	void UpdateGame(float deltaTime);
	void RenderWorld();

private:
	bool InitializeDirect3D();
	void FreeAllResources();

private:
	//Member Variables have m_ prefix
	HWND m_mainWindow;
	IDirect3DDevice9* m_d3dDevice;
	D3DPRESENT_PARAMETERS m_present_parameters;

private:
	//Helper Functions.
	D3DPRESENT_PARAMETERS CreatePresentParameters(HWND render_window);
};

This is the only class we need for a first DirectX program, there won't be any other classes in this first tutorial.

So if you look at the Game class above, you can see that it has three member variables, m_mainWindow, m_d3dDevice and m_present_parameters. m_mainWindow will hold a handle to the game window, which allows us to work with the window later if we need to. m_d3dDevice will hold a pointer to the Direct3D device object. The d3d device object is how we communicate with the computer's graphics card and basically use DirectX; it is this object that is used to render a 3d world and control properties related to how the 3d world is rendered. For example we can use the d3d device to clear the window to a colour, and use it to allocate memory on the graphics card to hold textures or sprites. m_present_parameters will hold details about how to setup Direct3D, the back buffer width and height for example; more on this in a bit.

UpdateGame() is used to update all the objects in the game, 3d models, monsters and things. The deltaTime parameter is used to keep the game running at the same speed on a slower computer as on a faster computer. delta means change, for example "change in time" and deltaTime will be the amount of time that has passed since the UpdateGame() function was called last. It is our job to calculate deltaTime and pass it as a parameter. InitGame() is the function that will setup the game, along with InitializeDirect3D(); And RenderWorld() is the function that will draw everything in our game to the screen or the window.

Let's first look at InitGame(HWND render_window). It will return true if the game is initialized successfully and false otherwise.

bool Game::InitGame(HWND render_window)
{
	this->m_mainWindow = render_window;

	return InitializeDirect3D();
}

All it does is set m_mainWindow and call InitializeDirect3D(); If there is anything else related to the game and not specifically to Direct3D, then we can setup those things in InitGame().

The implementation of UpdateGame(float deltaTime) is left empty for this tutorial but we will use it to do some error handling later.

void Game::UpdateGame(float deltaTime)
{
	//Update game objects here.

}

RenderWorld() will make the window blue. Here is a first glimpse of using the direct3d device.

void Game::RenderWorld()
{
	//TODO: Add Device lost handling.
	m_d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 
				0xff0000ff, 1.0f, 0);

	if(SUCCEEDED(m_d3dDevice->BeginScene()))
	{

		m_d3dDevice->EndScene();
	}

	// Swap buffers.
	m_d3dDevice->Present(NULL, NULL, NULL, NULL);
}


I will come back to this function after we have looked at some Direct3D initialisation. m_d3dDevice->Clear(...) clears the screen to blue.

Now we have come to bool InitializeDirect3D(); This function is responsible for setting up Direct3D so that once Direct3D is set up we can start adding 3d objects and characters. The code here will be quite beefy, but once you've grasped it somewhat you might never have to look at it again. Actually most of the code related to setting up Direct3D is in CreatePresentParameters().

bool Game::InitializeDirect3D()
{
	//Create the Direct3D object
	IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION);

	if(d3d9 == NULL)
	{
		return false;
	}

	m_present_parameters = CreatePresentParameters(m_mainWindow);

	if(FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT,
			     D3DDEVTYPE_HAL,
			     m_mainWindow,
			     D3DCREATE_HARDWARE_VERTEXPROCESSING,
			     &m_present_parameters,
			     &m_d3dDevice)))
	{
		return false;
	}

	//We no longer need the direct3d object
	SAFE_RELEASE(d3d9);

	//Success.
	return true;
}

So what's happening here? Direct3DCreate9() is a function defined in the d3d9.h header and creates a d3d9 object. A pointer to that object is then returned by the function and stored in the "d3d9" variable above. If the function Direct3DCreate9() returns NULL, which is 0, it failed to create the Direct3D9 object and we return false to reflect the failure. The d3d9 object is only needed to create the d3d device and can be discarded once the device is created. Notice the line d3d9->CreateDevice(). Next we come to the present parameters; The Present Parameters are a set of parameters that we store in a D3DPRESENT_PARAMETERS structure. These parameters are used to describe the properties of the Direct3D Device object we want to create. This object is different from the d3d9 object.

Ok, so let's examine the parameters. I have made a function CreatePresentParameters() to add a bit of clarity to the code to create the present parameters. Here it is:

D3DPRESENT_PARAMETERS Game::CreatePresentParameters(HWND render_window)
{
	D3DPRESENT_PARAMETERS pp;

	memset(&pp, 0, sizeof(D3DPRESENT_PARAMETERS));
	pp.BackBufferWidth = 800;
	pp.BackBufferHeight = 600;
	pp.BackBufferFormat = D3DFMT_A8R8G8B8;
	pp.BackBufferCount = 1;
	pp.MultiSampleType = D3DMULTISAMPLE_NONE;
	pp.MultiSampleQuality = 0;
	pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	pp.hDeviceWindow = render_window;
	pp.Windowed = true;
	pp.EnableAutoDepthStencil = true;
	pp.AutoDepthStencilFormat = D3DFMT_D24S8;
	pp.Flags = 0;
	pp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
	pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	return pp;
}

These parameters are then passed to the CreateDevice() function. Let's go over them.

First we create an instance pp. memset() sets all the values of the instance to 0. sizeof(D3DPRESENT_PARAMETERS) tells memset how much memory to 0. Starting at the address given by &pp, memset knows what memory to set to 0. We do this because 0 is usually the default value for something; if one of the parameters was not zero and we did not set the parameter ourselves like FullScreen_RefreshRateInHz for example, the refresh rate could be any random non-default value. D3DPRESENT_RATE_DEFAULT is actually 0.

Notice pp.BackBufferWidth and pp.BackBufferHeight. The back buffer is a segment of memory that a 3d scene gets rendered to before it becomes the front buffer, the pixels that are actually displayed on the screen. If there was only a front buffer and not a back buffer then a tearing effect might occur, for example, while the front buffer could be being displayed and new pixels are written to the front buffer, you might see some of the old pixels overlapping with some of the new pixels of a scene. This effect is known as tearing. That is why we need a back buffer. When the pixels of a new scene or frame of a scene have been drawn to the back buffer, the front buffer and back buffer are then swapped, so the front buffer becomes the back, and the back buffer becomes the front. BackBufferWidth and BackBufferHeight of the present parameters specifies the number of pixels that a scene will have; back buffer width * back buffer height.

pp.BackBufferFormat is the format of each pixel in the back buffer. A8R8G8B8 means that there will be 8 bits for alpha(A), 8 bits for red(R), 8 bits for green and 8 bits for blue. This format represents 32-bit True colour - 8+8+8+8. Aplha is the component that controls the opacity of a pixel, the amount you can see through it, so it blends with what's underneath it or currently written to the back buffer.

pp.BackBufferCount is the number of back buffers to use. The reason you might have two back buffers for example is if it takes a long time to render a scene to a buffer, there might be circumstances where you could prepare a second back buffer so while the front buffer and second buffer are ready to display you will have a third buffer that is ready because you have prepared it and this may speed up a game that requires heavy GPU processing.

The next parameter is mult-sample type: D3DMULTISAMPLE_NONE(No multi-sampling). Multi-sampling is a techinique used to "improve" the quality of an image. If you picture a black straight line made up of pixels(See Figure 3.) on a computer you notice a stair-step effect. Multi-sampling is a technique used to eliminate the stair-step effect and give an image more of a blend. Other types are D3DMULTISAMPLE_5_SAMPLES, D3DMULTISAMPLE_11_SAMPLES. More multi-samples are more processor intensive. pp.MultiSampleQuality can be from 0 to some value.

Figure 3.

D3DSWAPEFFECT_DISCARD means that the back buffer is discarded after it has been swapped. Don't ask me what is meant by DISCARD because I don't know. It is just apparently the fastest swap effect so I always use it.

pp.hDeviceWindow of course is the window to render to.

pp.Windowed = true; Windowed can be true or false. It means render the scene to a window(true) or use fullscreen(false).

Set pp.EnableAutoDepthStencil to true to enable depth testing and stencil buffer. Depth testing is where the z(depth) value of a pixel is tested against the z(depth) value of a pixel already on the buffer. The pixel with the lowest z value is written to the buffer. This allows objects closer to the human eye to overlap objects further away. Imagine you have a 3 dimensional sphere in front of another 3 dimensional sphere. The first sphere is closer to the camera, so the pixels making up the first sphere should overwrite or exist where the first sphere occludes(is in front of) the other sphere. If the first, closer, sphere was written to the back buffer first and then the second sphere and the depth values of the pixels were not compared with each other then the second sphere might appear closer even though it is further away. Depth testing enables a z or depth value of one pixel to be tested with the z value of a pixel already on the buffer so that objects closer to the eye overlapp objects further away.

pp.AutoDepthStencilFormat is the format of the depth buffer and the stencil buffer. These are two buffers of same dimensions as the back buffer but can have different number of bits per pixel. Here we specify D3DFMT_D24S8. That is 24 bits per pixel for the depth buffer and 8 bits per pixel for the stencil buffer. The stencil buffer can be used to achieve special effects like mirrors or reflections in water and shadows on the ground.

pp.Flags = 0; You can safely ignore flags for now.

pp.FullScreen_RefreshRateInHz. A typical refresh rate of a monitor is 60Hz(Hertz). Using a default refresh rate value should be fine. D3DPRESENT_RATE_DEFAULT.

Finally, we set the Presentation Interval to Immediate so the window client area, where the scene is rendered, is updated immediately when the front and back buffers are swapped.

GPU and CPU

The GPU, Graphics Processing Unit, is a bit of hardware, that is designed to do graphics processing extremely fast. It is some circuitry built-in to most computers. The CPU, Central Processing Unit, is also circuity built-in to a computer. The difference basically is that if you tell DirectX to use the GPU, your whole 3d world will harness more processing speed and there won't be any slowness that might occur if you used the CPU to do your graphics processing. You still may need to design you game to run fast but basically, GPU is faster than CPU.

Now that we have filled out the present parameters we can look at the next bit of code in InitializeDirect3D():

if(FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT,
			     D3DDEVTYPE_HAL,
			     m_mainWindow,
			     D3DCREATE_HARDWARE_VERTEXPROCESSING,
			     &m_present_parameters,
			     &m_d3dDevice)))
	{
		return false;
	}


This is where we create the Direct3D Device. D3DADAPTER_DEFAULT let's the operating system choose a default display adapter; I assume this means it uses the graphics card for something or if there are two graphics cards it will pick one of them. D3DDEVTYPE_HAL tells DirectX to use the Hardware Abstraction Layer, which means it will utilize the power of the GPU or the CPU if needed for e.g. lighting calculations of a 3d scene. This basically means it will use the hardware, GPU, for rasterization - turning a scene into pixels. m_mainWindow tells the device that will be created to use our window for rendering. D3DCREATE_HARDWARE_VERTEXPROCESSING tells the device to use the GPU for vertex processing. Vertices are the 3D points that make up 3d models. &m_present_parameters passes the present parameters we filled out to the function. The present parameters describe the properties of the device we discussed in the section on present parameters above.

Finally, we pass the m_d3dDevice variable by reference and if the d3d device is created successfully, m_d3dDevice will point to the newly created device object. If the function failed to create the device, the address m_d3dDevice points to will be NULL(0).

FAILED() is a Macro defined in a DirectX or Windows header that turns an HRESULT(the value returned by CreateDevice()) into >0 if the function was successful.

The next bit of code is:

	//We no longer need the direct3d object
	SAFE_RELEASE(d3d9);

	//Success.
	return true;

SAFE_RELEASE() is a Macro I have defined. All DirectX objects such as d3d9 and m_d3dDevice have a Release() function that can be called to free resources, or memory, used by the objects. SAFE_RELEASE() calls for example d3d9->Release() and then sets d3d9=NULL. It is called SAFE because it ensures the reference is NULL in case we try to use the object after it has been released. We can check if an object is NULL so we know not to use it. You can put the Macro in a header like so:

Macros.h
#pragma once

#ifndef SAFE_RELEASE
#define SAFE_RELEASE(x) \
   if(x != NULL)        \
   {                    \
      x->Release();     \
      x = NULL;         \
   }
#endif


FreeAllResources() is defined as:

void Game::FreeAllResources()
{
	SAFE_RELEASE(m_d3dDevice);
}


To make sure all resources are freed at the end of the game, let's call FreeAllResources() in the Game Destructor:

Game::~Game()
{
	//Make sure all resources are freed when game is destroyed.
	FreeAllResources();
}

Now we can come back to Game::RenderWorld().

void Game::RenderWorld()
{
	//TODO: Add Device lost handling.
	m_d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 
				0xff0000ff, 1.0f, 0);

	if(SUCCEEDED(m_d3dDevice->BeginScene()))
	{

		m_d3dDevice->EndScene();
	}

	// Swap buffers.
	m_d3dDevice->Present(NULL, NULL, NULL, NULL);
}

The third parameter is D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER. Here we have a bitwise OR |. The bitwise OR pretty much adds the two values D3DCLEAR_TARGET and D3DCLEAR_ZBUFFER together to get a new value. Because the values of D3DCLEAR_TARGET and D3DCLEAR_ZBUFFER both have numbers to the power of 2, when you add any number of numbers that are to the power of 2 you get a unique value. This unique value can be used to identify the flags you used, in our case the flags are D3DCLEAR_TARGET and D3DCLEAR_ZBUFFER.

D3DCLEAR_TARGET indicates we want to update the colour of the pixels in the back buffer and D3DCLEAR_ZBUFFER indicates we want to update the z(depth) buffer.

The fourth parameter is 0xff0000ff. This value is known as a hexadecimal number. This value represents a colour. Since we specified A8R8G8B8 in the present parameters, ff is the alpha, 00 is the red, 00 is the green and ff is the blue. ff is the maximum value in hexadecimal format, f is equivalent to 15, and each number runs from 0-9, a-f. In this case we have cleared the screen to blue. The alpha value ff means that the values written to the back buffer are not at all see-through.

The fifth parameter is 1.0f, and this indicates that we want to clear all the z values in the depth buffer to 1.0f. 1.0f is the furthest distance, 0.0f being the closest, so any 3d objects rendered will pass the initial depth test.

The next bit of code is:

	if(SUCCEEDED(m_d3dDevice->BeginScene()))
	{

		m_d3dDevice->EndScene();
	}

All the 3D rendering we want to do has to go between BeginScene() and EndScene().

	// Swap buffers.
	m_d3dDevice->Present(NULL, NULL, NULL, NULL);

Present() swaps the back buffer with the front buffer and by doing that, the back buffer becomes what we actually see in our window.

We will ignore the parameters used for m_d3dDevice->Present(NULL, NULL, NULL, NULL) because we do not use them for these tutorials. (If you need further information you can Google these functions and find them on the MSDN website)

Using the Game class

Now we finally get to to actually use the game class. Hopefully you have some understanding of it's implementation or maybe you just want to use it.

Note that this tutorial is a complete extension to the windows application from Tutorial 6 of Introduction To Programming found on this website.

Here is the modified WinMain() function:

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
			PSTR cmdLine, int showCmd)
{
	HWND my_window = CreateMyWindow(hInstance);

	if(!my_window){return E_FAIL;}

	//Window has been created, now create an instance of the game.
	Game game;

	//Initialize the game.
	if(!game.InitGame(my_window))
	{
		//Failed to setup the game.
		return E_FAIL;
	}

	ShowWindow(my_window, SW_SHOW);
	UpdateWindow(my_window);

	MSG msg;
	memset(&msg, 0, sizeof(MSG));

	DWORD startTime = GetTickCount();
	float deltaTime = 0.0f;

	//Enter the message loop.
	while(msg.message != WM_QUIT)
	{
		if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			//Put the message in a recognizable form
			TranslateMessage(&msg);
			//Send the message to the window procedure
			DispatchMessage(&msg);
		}
		else{

			//Update the game
			DWORD t=GetTickCount();
			deltaTime=float(t-startTime);
			//Pass time in seconds
			game.UpdateGame(deltaTime);
			startTime = t;

			//Render the world
			game.RenderWorld();
		}
	}

	return (int)msg.wParam;
}


If you've been following the previous tutorials the code above should be fairly self explanatory. First, create an instance of Game in the WinMain() method. Call game.InitGame(my_window) passing the window as a parameter to initialize the game and Direct3D.

PeekMessage() does not force us to wait for a message unlike GetMessage(), it peeks every cycle of the loop, which is extremely fast so game.UpdateGame() and game.RenderWorld() will be called every cycle of the loop pretty much. deltaTime is the current time in milliseconds since the system was started - the previous time in milliseconds, so the difference is the time elapsed since the last time game.UpdateGame() was called. This gives us the change in time, deltaTime, in milliseconds.

Finally, when the game loop ends, the game instance is destroyed and it's destructor called. All resources are freed using the Game::FreeAllResources() that is called in the game destructor.

Putting it All Together

Here is the complete code for the application covered in this tutorial.

Macros.h
#pragma once

#ifndef SAFE_RELEASE
#define SAFE_RELEASE(x) \
   if(x != NULL)        \
   {                    \
      x->Release();     \
      x = NULL;         \
   }
#endif

main.cpp
#include "Macros.h"
#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>

class Game
{
public:
	~Game();
	bool InitGame(HWND render_window);
	void UpdateGame(float deltaTime);
	void RenderWorld();

private:
	bool InitializeDirect3D();
	void FreeAllResources();

private:
	//Member Variables have m_ prefix
	HWND m_mainWindow;
	IDirect3DDevice9* m_d3dDevice;
	D3DPRESENT_PARAMETERS m_present_parameters;

private:
	//Helper Functions.
	D3DPRESENT_PARAMETERS CreatePresentParameters(HWND render_window);
};

bool Game::InitGame(HWND render_window)
{
	this->m_mainWindow = render_window;

	return InitializeDirect3D();
}

void Game::UpdateGame(float deltaTime)
{
	//Update game objects here.

}

void Game::RenderWorld()
{
	//TODO: Add Device lost handling.
	m_d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff0000ff, 1.0f, 0);

	if(SUCCEEDED(m_d3dDevice->BeginScene()))
	{

		m_d3dDevice->EndScene();
	}

	// Swap buffers.
	m_d3dDevice->Present(NULL, NULL, NULL, NULL);
}

void Game::FreeAllResources()
{
	SAFE_RELEASE(m_d3dDevice);
}

Game::~Game()
{
	//Make sure all resources are freed when game is destroyed.
	FreeAllResources();
}

//Create function prototypes.
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

D3DPRESENT_PARAMETERS Game::CreatePresentParameters(HWND render_window)
{
	D3DPRESENT_PARAMETERS pp;

	memset(&pp, 0, sizeof(D3DPRESENT_PARAMETERS));
	pp.BackBufferWidth = 800;
	pp.BackBufferHeight = 600;
	pp.BackBufferFormat = D3DFMT_A8R8G8B8;
	pp.BackBufferCount = 1;
	pp.MultiSampleType = D3DMULTISAMPLE_NONE;
	pp.MultiSampleQuality = 0;
	pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	pp.hDeviceWindow = render_window;
	pp.Windowed = true;
	pp.EnableAutoDepthStencil = true;
	pp.AutoDepthStencilFormat = D3DFMT_D24S8;
	pp.Flags = 0;
	pp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
	pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

	return pp;
}

bool Game::InitializeDirect3D()
{
	//Create the Direct3D object
	IDirect3D9* d3d9 = Direct3DCreate9(D3D_SDK_VERSION);

	if(d3d9 == NULL)
	{
		return false;
	}

	m_present_parameters = CreatePresentParameters(m_mainWindow);

	if(FAILED(d3d9->CreateDevice(D3DADAPTER_DEFAULT,
			     D3DDEVTYPE_HAL,
			     m_mainWindow,
			     D3DCREATE_HARDWARE_VERTEXPROCESSING,
			     &m_present_parameters,
			     &m_d3dDevice)))
	{
		return false;
	}

	//We no longer need the direct3d object
	SAFE_RELEASE(d3d9);

	//Success.
	return true;
}

HWND CreateMyWindow(HINSTANCE hInstance)
{
	WNDCLASS wc;
	memset(&wc, 0, sizeof(WNDCLASS));
	
	wc.style=CS_HREDRAW | CS_VREDRAW; //Redraws the window if width or height changes.
	wc.hbrBackground = CreateSolidBrush(RGB(0,0,0));
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.lpfnWndProc=(WNDPROC)WndProc; //Associates the window procedure with the window.
	wc.hInstance=hInstance; //Record handle to this application's instance.
	wc.lpszClassName=L"My Window Class"; //Class Name.

	//Register the window class with the operating system.
	if(FAILED(RegisterClass(&wc))){
		//Failed to create window.
		return NULL;
	}

	//Create the Window.
	HWND my_window = CreateWindow(L"My Window Class", //The window class to use
			      L"Basic Window", //window title
				  WS_OVERLAPPEDWINDOW, //window style
			      200, //x
			      200, //y
			      CW_USEDEFAULT, //Default width
			      CW_USEDEFAULT, //Default height
				  NULL,
				  NULL,
			      hInstance, //Application instance
			      0); //Pointer to value parameter, lParam of WndProc

	//If window was created successfully then non-NULL
	//value will be returned.
	return my_window;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR cmdLine, int showCmd)
{
	HWND my_window = CreateMyWindow(hInstance);

	if(!my_window){return E_FAIL;}

	//Window has been created, now create an instance of the game.
	Game game;
	//Initialize the game.
	if(!game.InitGame(my_window))
	{
		//Failed to setup the game.
		return E_FAIL;
	}

	ShowWindow(my_window, SW_SHOW);
	UpdateWindow(my_window);

	MSG msg;
	memset(&msg, 0, sizeof(MSG));

	DWORD startTime = GetTickCount();
	float deltaTime = 0.0f;

	//Enter the message loop.
	while(msg.message != WM_QUIT)
	{
		if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			//Put the message in a recognizable form
			TranslateMessage(&msg);
			//Send the message to the window procedure
			DispatchMessage(&msg);
		}
		else{

			//Update the game
			DWORD t=GetTickCount();
			deltaTime=float(t-startTime);
			//Pass time in seconds
			game.UpdateGame(deltaTime);
			startTime = t;

			//Render the world
			game.RenderWorld();
		}
	}

	return (int)msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	//Handle window creation and destruction events
	switch(msg)
	{
	case WM_CREATE:
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}

	//Handle all other events with default procedure
	return DefWindowProc(hWnd, msg, wParam, lParam);
}