<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule">

<channel>
	<title>Minalien.com &#187; Tutorials</title>
	<atom:link href="http://www.minalien.com/index.php/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.minalien.com</link>
	<description>My brain makes things explode.</description>
	<lastBuildDate>Thu, 29 Jul 2010 16:13:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
<creativeCommons:license>http://creativecommons.org/licenses/by-nc-sa/3.0/us/</creativeCommons:license>		<item>
		<title>C++/D3D Pong Tutorial 04: Adding Keyboard Input</title>
		<link>http://www.minalien.com/index.php/2010/04/25/cd3d-pong-tutorial-04-adding-keyboard-input/</link>
		<comments>http://www.minalien.com/index.php/2010/04/25/cd3d-pong-tutorial-04-adding-keyboard-input/#comments</comments>
		<pubDate>Mon, 26 Apr 2010 01:09:55 +0000</pubDate>
		<dc:creator>Samantha</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Computers]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Pong (C++/DirectX)]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[D3DPong]]></category>
		<category><![CDATA[Direct3D]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Win32]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.minalien.com/?p=240</guid>
		<description><![CDATA[Tutorial Description In the last tutorial, we established a rendering engine and got scene objects working, with basic physics. In this tutorial, we are going to implement the initial Input manager, which will be focusing on the keyboard. I was planning to include mouse input, but it turns out that DirectInput only handles the mouse]]></description>
			<content:encoded><![CDATA[<p><strong>Tutorial Description</strong><br />
In the last tutorial, we established a rendering engine and got scene objects working, with basic physics. In this tutorial, we are going to implement the initial Input manager, which will be focusing on the keyboard. I was planning to include mouse input, but it turns out that DirectInput only handles the mouse in relative positioning &#8211; which is perfect for three-dimensional first-person shooter games that need to track the movement of the mouse &#8211; but it&#8217;s poor for two-dimensional casual games. For those of you that do wish to use mouse input, I will be covering it a later tutorial &#8211; the methods of getting absolute positioning will require a bit of modification to our engine.</p>
<p><strong>Downloads</strong><br />
<em>Please note that I&#8217;ve switched to using 7-zip in place of WinRAR for compression</em><br />
<a href="http://files.minalien.com/D3DPong/04/D3DPong-Bin.7z">Binary Only (20.4KB)</a><br />
<a href="http://files.minalien.com/D3DPong/04/D3DPong-Src.7z">Full VS2010 Project Dir (26.8KB)</a></p>
<p><strong>SVN Repository</strong><br />
As of this tutorial, I have created and added a Subversion repository on Assembla to store the code for the tutorial series. I will continue to upload the source for each tutorial &#8211; the SVN will merely contain the code as I write it, so you can feel free to play around with the code that I&#8217;m working on before I release a tutorial. Mostly, this is to help people play around with things if there&#8217;s a point where I&#8217;m slow to create the tutorial following the code (as was the case with this tutorial).</p>
<p>SVN URL: <a href="http://svn2.assembla.com/svn/d3dpong" title="D3DPong SVN Repository">http://svn2.assembla.com/svn/d3dpong</a></p>
<p><strong>Starting Words</strong><br />
Notice: This tutorial continues from where “<a href="http://www.minalien.com/index.php/2010/03/21/cd3d-pong-tutorial-03-scene-objects-and-sprite-rendering/" title="C++/D3D Pong Tutorial 03: Scene Objects and Sprite Rendering">C++/D3D Pong Tutorial 03</a>” article left off. Please read it if you have not already.</p>
<p><span id="more-240"></span></p>
<p><strong>Libraries</strong><br />
You will need to add a single library to the project to build with the code in this tutorial:<br />
dinput.lib</p>
<p><strong>Code Listing 1: CInputManager.h</strong></p>
<pre class="brush: cpp;">#pragma once

// Global Header Files
#include &lt;Windows.h&gt;
#include &lt;d3d9.h&gt;
#include &lt;d3dx9.h&gt;
#include &lt;dinput.h&gt;

// Local Header Files
#include &quot;CGameEngine.h&quot;
#include &quot;CKeyboardState.h&quot;

namespace D3DPong
{
	class CInputManager
	{
	private:
		/** Constructor &amp; Destructor **/
		CInputManager(void);						// ctor
		CInputManager(CInputManager const&amp;) { }		// copy ctor
		~CInputManager(void);						// dtor

		static CInputManager* _instance;

		// DirectInput Devices
		LPDIRECTINPUT8			_device;	// Core DirectInput Object
		LPDIRECTINPUTDEVICE8	_keyboard;	// Keyboard

		// Keyboard-related Variables
		CKeyboardState* _preKeyboardState;
		CKeyboardState* _curKeyboardState;

		// Device Initialization
		bool initKeyboard(void);

	public:
		/** Singleton **/
		static CInputManager* Instance(void) { return CInputManager::_instance; }

		/** Public Functions **/
		bool Init(void);
		void Update(void);

		/** Keyboard Functions **/
		bool IsKeyDown(int);
		bool IsKeyUp(int);
		bool WasKeyPressed(int);
		bool WasKeyReleased(int);

		/** Accessors &amp; Mutators **/
		LPDIRECTINPUT8 GetDevice(void) { return this-&gt;_device; }
		CKeyboardState* GetCurKeyboardState(void) { return this-&gt;_curKeyboardState; }
		CKeyboardState* GetPreKeyboardState(void) { return this-&gt;_preKeyboardState; }
	};
};</pre>
<p>Here is the framework for our Input Manager. Again, we&#8217;re back down to lower source sizes &#8211; because we&#8217;re not trying to implement the world here. As we did with our Game Engine class, we&#8217;ve turned our Input Manager into a singleton &#8211; we only want one of them to be created throughout the application.</p>
<pre class="brush: cpp;">		// DirectInput Devices
		LPDIRECTINPUT8			_device;	// Core DirectInput Object
		LPDIRECTINPUTDEVICE8	_keyboard;	// Keyboard

		// Keyboard-related Variables
		CKeyboardState* _preKeyboardState;
		CKeyboardState* _curKeyboardState;

		// Device Initialization
		bool initKeyboard(void);</pre>
<p>The first two variables are input devices &#8211; the first, as with our Direct3D object, we have an object that we will use to access the DirectInput system. The second is the actual object that we will use to access the keyboard device &#8211; when adding a Mouse or a Gamepad/Joystick, you will add another LPDIRECTINPUTDEVICE8. If you&#8217;ve noticed the 8, you&#8217;ll notice that this is something from DirectX 8 &#8211; DirectInput hasn&#8217;t changed since then. In all honesty, the use of DirectInput isn&#8217;t recommended by Microsoft, but it will suffice for our purposes. We then add two variables to store the keyboard state &#8211; the current keyboard state, which will contain the state as of the current frame, and the previous, which will (if you haven&#8217;t guessed) store the state of the last frame. We do this so that we can not only check whether a key is <em>currently</em> being pressed, but also whether it was pressed or released between the current and last frame. This makes things easier on us, in the long run, because we can wait for (for example) the escape key to be released before we end the game, and it will make managing our game menus much easier when we want to handle selection of menu options game console style. Finally, we define a private function that will initialize our keyboard. It will help keep our Init() function tidy for the future addition of controllers, mice, and other input devices.</p>
<pre class="brush: cpp;">		/** Public Functions **/
		bool Init(void);
		void Update(void);</pre>
<p>These two functions are pretty obvious in what they do. Init() will initialize all of our input devices, and update will update the current/previous states of our devices. I&#8217;ll explain them more when we actually flesh them out.</p>
<pre class="brush: cpp;">		/** Keyboard Functions **/
		bool IsKeyDown(int);
		bool IsKeyUp(int);
		bool WasKeyPressed(int);
		bool WasKeyReleased(int);</pre>
<p>Last on the list of things to look at is our key-checking functions. The first two will return whether the key is currently pressed or released, which can be useful for continuous motion checking, such as what we will be doing with our pong paddles. The latter two check if they key&#8217;s state has changed between this frame and the last (if the key has been pressed or released).</p>
<p><strong>Code Listing 2: CInputManager.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;CInputManager.h&quot;
#include &quot;CKeyboardState.h&quot;

namespace D3DPong
{
	CInputManager* CInputManager::_instance = new CInputManager();

	CInputManager::CInputManager(void)
		: _device(NULL), _keyboard(NULL),
		_curKeyboardState(NULL), _preKeyboardState(NULL)
	{
	}

	CInputManager::~CInputManager(void)
	{
		if(this-&gt;_keyboard != NULL)
		{
			this-&gt;_keyboard-&gt;Unacquire();
			this-&gt;_keyboard-&gt;Release();
			this-&gt;_keyboard = NULL;
		}

		if(this-&gt;_device != NULL)
		{
			this-&gt;_device-&gt;Release();
			this-&gt;_device = NULL;
		}
	}

	bool CInputManager::Init(void)
	{
		// Initialize the DirectInput Device
		if(FAILED(DirectInput8Create(GetModuleHandle(NULL),	// Instance Handle
			DIRECTINPUT_VERSION,							// DirectInput Version
			IID_IDirectInput8, 								// Device Type
			(LPVOID*)&amp;this-&gt;_device,						// Pointer to device storage
			NULL)))
		{
			MessageBox(NULL, L&quot;Error initializing Input Manager&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		// Initialize the Keyboard
		if(!this-&gt;initKeyboard())
			return false;

		// Call update once to populate the input states
		this-&gt;Update();

		return true;
	}

	bool CInputManager::initKeyboard(void)
	{
		if(FAILED(this-&gt;_device-&gt;CreateDevice(GUID_SysKeyboard,
			&amp;this-&gt;_keyboard,
			NULL)))
		{
			MessageBox(NULL, L&quot;Error initializing Keyboard&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		if(FAILED(this-&gt;_keyboard-&gt;SetDataFormat(&amp;c_dfDIKeyboard)))
		{
			MessageBox(NULL, L&quot;Error setting keyboard data format&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		if(FAILED(this-&gt;_keyboard-&gt;SetCooperativeLevel(CGameEngine::Instance()-&gt;GetWindowHandle(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
		{
			MessageBox(NULL, L&quot;Error setting keyboard cooperative level&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		if(FAILED(this-&gt;_keyboard-&gt;Acquire()))
		{
			MessageBox(NULL, L&quot;Error acquiring keyboard device&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		// Create the keyboard states
		this-&gt;_curKeyboardState = new CKeyboardState();
		this-&gt;_preKeyboardState = new CKeyboardState();

		return true;
	}

	void CInputManager::Update(void)
	{
		// Update the keyboard
		this-&gt;_preKeyboardState-&gt;CopyKeyBuffer(this-&gt;_curKeyboardState-&gt;GetKeyStates());

		// Make sure we reacquire the keyboard if the device was lost
		if(this-&gt;_keyboard-&gt;GetDeviceState(this-&gt;_curKeyboardState-&gt;GetBufferSize(), this-&gt;_curKeyboardState-&gt;GetKeyBuffer()) == DIERR_INPUTLOST)
			this-&gt;_keyboard-&gt;Acquire();
	}

	bool CInputManager::IsKeyDown(int keyCode)
	{
		return this-&gt;_curKeyboardState-&gt;IsKeyDown(keyCode);
	}

	bool CInputManager::IsKeyUp(int keyCode)
	{
		return this-&gt;_curKeyboardState-&gt;IsKeyUp(keyCode);
	}

	bool CInputManager::WasKeyPressed(int keyCode)
	{
		if(this-&gt;_curKeyboardState-&gt;IsKeyDown(keyCode) &amp;&amp; this-&gt;_preKeyboardState-&gt;IsKeyUp(keyCode))
			return true;
		else
			return false;
	}

	bool CInputManager::WasKeyReleased(int keyCode)
	{
		if(this-&gt;_curKeyboardState-&gt;IsKeyUp(keyCode) &amp;&amp; this-&gt;_preKeyboardState-&gt;IsKeyDown(keyCode))
			return true;
		else
			return false;
	}
};</pre>
<p>Here are the guts of our system. Not everything will need covered, because it will be pretty obvious based on other parts, but here goes:</p>
<pre class="brush: cpp;">	bool CInputManager::Init(void)
	{
		// Initialize the DirectInput Device
		if(FAILED(DirectInput8Create(GetModuleHandle(NULL),	// Instance Handle
			DIRECTINPUT_VERSION,							// DirectInput Version
			IID_IDirectInput8, 								// Device Type
			(LPVOID*)&amp;this-&gt;_device,						// Pointer to device storage
			NULL)))
		{
			MessageBox(NULL, L&quot;Error initializing Input Manager&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		// Initialize the Keyboard
		if(!this-&gt;initKeyboard())
			return false;

		// Call update once to populate the input states
		this-&gt;Update();

		return true;
	}</pre>
<p>This method initializes our input management system. The first thing that we must do is initialize our DirectInput device, because it will be used to create any DirectInput-based input systems later (keyboard, mouse, and joypad, for example). We then call initKeyboard() to initialize our keyboard (when adding a Mouse or Joystick, you would also add an initMouse/initJoystick function, just to keep things clean), make sure it worked properly, then capture the current state of the input system.</p>
<pre class="brush: cpp;">	bool CInputManager::initKeyboard(void)
	{
		if(FAILED(this-&gt;_device-&gt;CreateDevice(GUID_SysKeyboard,
			&amp;this-&gt;_keyboard,
			NULL)))
		{
			MessageBox(NULL, L&quot;Error initializing Keyboard&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		if(FAILED(this-&gt;_keyboard-&gt;SetDataFormat(&amp;c_dfDIKeyboard)))
		{
			MessageBox(NULL, L&quot;Error setting keyboard data format&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		if(FAILED(this-&gt;_keyboard-&gt;SetCooperativeLevel(CGameEngine::Instance()-&gt;GetWindowHandle(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
		{
			MessageBox(NULL, L&quot;Error setting keyboard cooperative level&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		if(FAILED(this-&gt;_keyboard-&gt;Acquire()))
		{
			MessageBox(NULL, L&quot;Error acquiring keyboard device&quot;, L&quot;Error&quot;, MB_OK);
			return false;
		}

		// Create the keyboard states
		this-&gt;_curKeyboardState = new CKeyboardState();
		this-&gt;_preKeyboardState = new CKeyboardState();

		return true;
	}</pre>
<p>Not much to see here, in spite of the length &#8211; most of it&#8217;s error checking. First, we use the DirectInput device to create our Keyboard device, then we follow up by setting the data format and cooperative level. The cooperative level sets how our application works with the operating system and other applications running, when it comes to handling input on the device. Setting a Foreground cooperative level makes it so that our game only responds to input when the game window is our active window. This way, if the player were to open Notepad and press the escape key, it wouldn&#8217;t close our game. Setting this to background, on the other hand, allows this to happen. The second piece of our cooperative level determines whether other applications will be allowed to access the input device when the game is using them. Nonexclusive means that the input device can be shared with others, and that works best to keep our application on friendly terms with any software our players may be using. The only time you really want to use exclusive mode is when using a mouse in a three-dimensional shooter game, to prevent our mouse from slipping out the side of the window when we&#8217;re turning. Finally, we capture (acquire) our input device, and create two empty instances to store the state of the keyboard.</p>
<pre class="brush: cpp;">	void CInputManager::Update(void)
	{
		// Update the keyboard
		this-&gt;_preKeyboardState-&gt;CopyKeyBuffer(this-&gt;_curKeyboardState-&gt;GetKeyStates());

		// Make sure we reacquire the keyboard if the device was lost
		if(this-&gt;_keyboard-&gt;GetDeviceState(this-&gt;_curKeyboardState-&gt;GetBufferSize(), this-&gt;_curKeyboardState-&gt;GetKeyBuffer()) == DIERR_INPUTLOST)
			this-&gt;_keyboard-&gt;Acquire();
	}</pre>
<p>The update method updates our keyboard states. First, we use the CopyKeyBuffer (which, as you will see when we design our Keyboard State class, simply copies the key buffer array from another array). We then check to make sure that the device was not lost (for example, if the window is switched). If it is, we re-acquire it. When we use the GetDeviceState() function within the if() statement, we are also capturing the keyboard state &#8211; first, we pass the size of the buffer, then we pass a pointer to the buffer array. GetDeviceState will copy the state of our keyboard to the key buffer array.</p>
<p>Because the IsKeyUp and IsKeyDown functions directly map to functions of the same name on the current keyboard state, we&#8217;ve only one last thing to cover:</p>
<pre class="brush: cpp;">	bool CInputManager::WasKeyPressed(int keyCode)
	{
		if(this-&gt;_curKeyboardState-&gt;IsKeyDown(keyCode) &amp;&amp; this-&gt;_preKeyboardState-&gt;IsKeyUp(keyCode))
			return true;
		else
			return false;
	}</pre>
<p>This is pretty obvious, but I want to be completely clear on how we&#8217;re working this. If the state has been changed between the current frame and the last, we return true. In the case above, we are checking if the key has been pressed. We check the current state of the key against the previous state &#8211; if it was released (up) on the last frame, but is pressed (down) now, we return true &#8211; the key has been pressed between the current and last frames. Otherwise, it hasn&#8217;t, so we return false.</p>
<p><strong>Code Listing 3: CKeyboardState.h</strong></p>
<pre class="brush: cpp;">#pragma once

#include &lt;Windows.h&gt;

namespace D3DPong
{
	class CKeyboardState
	{
	private:
		char _keyStates[256];

	public:
		/** Constructor &amp; Destructor **/
		CKeyboardState(void);
		~CKeyboardState(void);

		/** Public Methods **/
		bool IsKeyDown(int);
		bool IsKeyUp(int);
		void CopyKeyBuffer(char*);

		/** Accessors &amp; Mutators **/
		char* GetKeyStates(void) { return this-&gt;_keyStates; }
		LPVOID GetKeyBuffer(void) { return (LPVOID)&amp;this-&gt;_keyStates; }
		DWORD GetBufferSize(void) { return sizeof(this-&gt;_keyStates); }
	};
};</pre>
<p>The only member variable here is our key buffer &#8211; which is a simple char array, exactly what will be set by the keyboard device&#8217;s GetDeviceState function. I&#8217;ll cover the functions below:</p>
<p><strong>Code Listing 4: CKeyboardState.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;CKeyboardState.h&quot;

namespace D3DPong
{
	CKeyboardState::CKeyboardState(void)
	{
	}

	CKeyboardState::~CKeyboardState(void)
	{
	}

	bool CKeyboardState::IsKeyDown(int keyCode)
	{
		if(this-&gt;_keyStates[keyCode] &amp; 0x80)
			return true;
		else
			return false;
	}

	bool CKeyboardState::IsKeyUp(int keyCode)
	{
		return !this-&gt;IsKeyDown(keyCode);
	}

	void CKeyboardState::CopyKeyBuffer(char* buffer)
	{
		for(int i = 0; i &lt; 256; i++)
			this-&gt;_keyStates[i] = buffer[i];
	}
};</pre>
<p>Here we go!</p>
<pre class="brush: cpp;">	bool CKeyboardState::IsKeyDown(int keyCode)
	{
		if(this-&gt;_keyStates[keyCode] &amp; 0x80)
			return true;
		else
			return false;
	}</pre>
<p>To check whether or not a key is up, we simply do a BITWISE AND operation against the key state (stored in our buffer) at the keycode in our array against 0&#215;80. The keyCode integer will be a pre-defined DirectInput keycode, such as DIK_ESCAPE or DIK_HOME &#8211; you can find a list of DirectInput keycodes <a href="http://www.gamespp.com/directx/directInputKeyboardScanCodes.html" title="DirectX / DirectInput Keyboard Scan Codes - Games++:">here</a>. To find out if the key is up, we need only check if it is not down &#8211; so our IsKeyUp merely returns !IsKeyDown.</p>
<pre class="brush: cpp;">	void CKeyboardState::CopyKeyBuffer(char* buffer)
	{
		for(int i = 0; i &lt; 256; i++)
			this-&gt;_keyStates[i] = buffer[i];
	}</pre>
<p>Here, we actually copy the key buffer. There are only 256 indexes in the key buffer array, so that&#8217;s all we need to copy. In case you&#8217;re surprised, yes, arrays are simply glorified pointers with fixed sizes &#8211; and you can easily use an array as a pointer.</p>
<p><strong>Wrapping it into our engine</strong><br />
Now, we need to make some ties to bring our singleton into the application. Open up WinMain.cpp, and let&#8217;s get started.</p>
<pre class="brush: cpp;">#define InputManager D3DPong::CInputManager::Instance()</pre>
<p>Just as we did with the instance of the game engine, we are going to create a Macro to access our Input Manager singleton. Now, we can just use InputManager->WasKeyPressed instead of going out of our way to type D3DPong::CInputManager::Instance()->WasKeyPressed.</p>
<pre class="brush: cpp;">	// Initialize the Game Engine
	GEInstance-&gt;SetWindowHandle(hWnd);
	if(!GEInstance-&gt;Init(GEInstance-&gt;GetScreenWidth(), GEInstance-&gt;GetScreenHeight(), GEInstance-&gt;GetColorDepth()))
		return 0;

	if(!InputManager-&gt;Init())
		return 0;

	// Message Loop
	while(GEInstance-&gt;GetGameRunning())
	{
		while(PeekMessage(&amp;msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&amp;msg);
			DispatchMessage(&amp;msg);
		}

		InputManager-&gt;Update();
		GEInstance-&gt;Update();
	}</pre>
<p>The only changes here are the lines regarding the InputManager &#8211; these parts are all we need to tie the input manager into our engine. They&#8217;re quite obvious in what they do &#8211; initialize and update the input manager &#8211; so I doubt that I need to give much explanation.</p>
<p><strong>Adding input to our test game</strong><br />
I&#8217;m only going to cover checking for the escape key on this, but if you look at the tutorial files, I&#8217;ve added some simple platformer-esque input handling to our earlier rendering and physics tests.</p>
<pre class="brush: cpp;">void GameUpdate(float delta)
{
	if(InputManager-&gt;WasKeyReleased(DIK_ESCAPE))
		GEInstance-&gt;SetGameRunning(false);

	// [...] The rest of our update method
}</pre>
<p>Here, we check if the Escape key has been released &#8211; this will allow us to easily exit our window via a single keystroke. I choose to check for the release of the escape key out of personal preference, because I prefer acting on the release of most keystrokes, but you could achieve similar results by doing WasKeypressed &#8211; it would merely act when the key was pressed, instead of when it was released (&lt;/obvious&gt;).</p>
<p>And there you have it, the (long awaited?) keyboard input tutorial. If I missed something between the downloadable source and what I&#8217;ve posted, please let me know so I can fix it &#8211; I wrote the code for this ages ago, and only finally got around to writing the tutorial portion recently.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minalien.com/index.php/2010/04/25/cd3d-pong-tutorial-04-adding-keyboard-input/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>C++/D3D Pong Maintenance: The Game Loop/Frame Delta</title>
		<link>http://www.minalien.com/index.php/2010/03/25/cd3d-pong-maintenance-game-loop/</link>
		<comments>http://www.minalien.com/index.php/2010/03/25/cd3d-pong-maintenance-game-loop/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 01:23:52 +0000</pubDate>
		<dc:creator>Samantha</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Pong (C++/DirectX)]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[Direct3D]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[Games]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Win32]]></category>

		<guid isPermaLink="false">http://www.minalien.com/?p=220</guid>
		<description><![CDATA[Tutorial Description While running the game/engine that we&#8217;ve been developing throughout this tutorial series, you may have noticed that the engine kind of runs&#8230; like crap. So, before moving onto the next tutorial in the series (the code for which is completed), which will cover keyboard and mouse input, I feel that it&#8217;s somewhat important]]></description>
			<content:encoded><![CDATA[<p><strong>Tutorial Description</strong><br />
While running the game/engine that we&#8217;ve been developing throughout this tutorial series, you may have noticed that the engine kind of runs&#8230; like crap. So, before moving onto the next tutorial in the series (the code for which is completed), which will cover keyboard and mouse input, I feel that it&#8217;s somewhat important to fix this. It&#8217;s just going to be some small updates to CGameEngine.cpp, so it won&#8217;t be hard.</p>
<p><strong>Code Listing 1: CGameEngine.cpp -> <em>CGameEngine::CGameEengine(void)</em></strong><br />
First, we&#8217;re going to correct an error with our game timer, which we never actually <em>created</em> an instance of in code &#8211; causing the GetRunTime feature to fail due to a member variable not being initialized (CGameTimer::_start). Replace the constructor for CGameEngine with the following, in CGameEngine.cpp</p>
<pre class="brush: cpp;">	CGameEngine::CGameEngine(void)
		: _windowHandle(NULL), _windowTitle(L&quot;D3DPong&quot;),
		_screenWidth(640), _screenHeight(480), _colorDepth(32),
		_gameRunning(true), _gameTimer(new CGameTimer())
	{
	}</pre>
<p><strong>Code Listing 2: CGameEngine.cpp -> <em>CGameEngine::Update(void)</em></strong><br />
Our new Update method is much smaller than it was before. We&#8217;re still using fast-as-possible rendering and updating, so this isn&#8217;t going to fix the minor graphics tearing that you&#8217;ve no doubt noticed before this, but it is going to make things run a little better.</p>
<pre class="brush: cpp;">	void CGameEngine::Update(void)
	{
		float delta = this-&gt;_gameTimer-&gt;GetRunTime();

		GameUpdate(delta);

		this-&gt;_gameTimer-&gt;Reset();

		this-&gt;BeginRender();

		GameRender(delta);

		this-&gt;EndRender();
	}</pre>
<p>Nicer, cleaner, shorter. This was caused by a bit of an inconsistency and laziness on my part, but things should run a bit smoother now. In the next tutorial, we&#8217;re going to be adding input, and will put the beginning pieces of our game into effect. I&#8217;ll cover enabling VSync at a later point, because I&#8217;m too lazy to deal with it right now. It&#8217;ll probably be in another &#8220;Maintenance&#8221; mini-tutorial.</p>
<p>Expect Tutorial 4 soon!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minalien.com/index.php/2010/03/25/cd3d-pong-maintenance-game-loop/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C++/D3D Pong Tutorial 03: Scene Objects and Sprite Rendering</title>
		<link>http://www.minalien.com/index.php/2010/03/21/cd3d-pong-tutorial-03-scene-objects-and-sprite-rendering/</link>
		<comments>http://www.minalien.com/index.php/2010/03/21/cd3d-pong-tutorial-03-scene-objects-and-sprite-rendering/#comments</comments>
		<pubDate>Sun, 21 Mar 2010 20:28:21 +0000</pubDate>
		<dc:creator>Samantha</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Pong (C++/DirectX)]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[Direct3D]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[Pong]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.minalien.com/?p=197</guid>
		<description><![CDATA[Tutorial Description In the last tutorial, we finished getting Direct3D set up, implemented a timer system to allow us to calculate the time between each frame, and set up the framework that will grant us access to our game without interfering with the core engine. In this tutorial, we are going to implement a reusable]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.minalien.com/index.php/2010/03/21/cd3d-pong-tutorial-03-scene-objects-and-sprite-rendering/d3dpong3/" rel="attachment wp-att-202"><img src="http://www.minalien.com/wp-content/uploads/2010/03/D3DPong3-300x225.png" alt="Where&#039;s the fluffy tail? D:" title="D3DPong Tutorial 3" width="300" height="225" class="alignright size-medium wp-image-202" /></a></p>
<p><strong>Tutorial Description</strong><br />
In the last tutorial, we finished getting Direct3D set up, implemented a timer system to allow us to calculate the time between each frame, and set up the framework that will grant us access to our game without interfering with the core engine. In this tutorial, we are going to implement a reusable Scene Object class, which will be the parent for all future classes that we wish to enable in a scene manager. The scope of this tutorial series makes a full-fledged instance management system overkill, so we will not be building one in here. However, as this tutorial series will act as the base for future tutorials that will implement a scene manager, I am going to implement the scene object class here.</p>
<p><strong>Downloads</strong><br />
<a href="http://files.minalien.com/D3DPong/03/D3DPong-Bin.rar">Binary Only (18.8KB)</a><br />
<a href="http://files.minalien.com/D3DPong/03/D3DPong-Src.rar">Full VS2010 Project Dir (28.4KB)</a></p>
<p><strong>Starting Words</strong><br />
I just wanted to point out that this tutorial series borrows a lot of the structure of Jonathan Harbour&#8217;s Advanced2D game engine, from the book &#8220;<a href="http://www.amazon.com/Advanced-Game-Development-Jonathan-Harbour/dp/1598633422">Advanced 2D Game Development</a>&#8220;. While I certainly believe it to be a wonderful book, and an excellent starting point for beginners (in fact, the reason for me borrowing the format for his engine is <em>because</em> I find the method well-suited for beginners), I find that I have a lot of personal quirks with Jonathan&#8217;s methods and programming habits, and there are a number of inconsistencies in it. Furthermore, there are some topics that are covered in the book that just aren&#8217;t well-suited for beginners, and can cause things to be a bit confusing and convoluted. In this tutorial series, I don&#8217;t plan to implement three-dimensional rendering, which he does cover briefly, and have no intention of including game scripting, though several more advanced tutorials will cover these aspects at a later date (read: when I stop being lazy). Anybody looking at learning to program two-dimensional games with DirectX and C++ should look into the book, but should remember that there will always be better ways to implement certain systems than what is shown to you in a book &#8211; or an online tutorial. Anybody that wants to gain a solid understanding and truly grasp the depth of these programming systems is highly encouraged to look up information on any subjects that they are unfamiliar with. I strongly recommend <a href="http://www.safaribooksonline.com">Safari Books Online</a> &#8211; I read a lot of books there, and it&#8217;s certainly helped me improve myself. Advanced 2D Game Development is available on SBO, as well.</p>
<p><em>Notice: This tutorial continues from where &#8220;<a href="http://www.minalien.com/index.php/2010/02/15/pong-series-02/">C++/D3D Pong Tutorial 02</a>&#8221; article left off. Please read it if you have not already.</em></p>
<p><span id="more-197"></span></p>
<p><strong>Libraries</strong><br />
You will not need to add any more libraries to your project at this time. As of the last tutorial, the following should be in your project:<br />
d3d9.lib<br />
d3dx9.lib<br />
dxguid.lib</p>
<p><strong>Fixing up some Bugs</strong><br />
While writing this tutorial, I&#8217;ve come across a bug in the engine that had remained unnoticed until now. Because of how we&#8217;ve set up the game engine to handle the end of the game (specifically, the destruction of the game window), we end up calling our GameEnd function twice, which will cause issues when deleting the game sprites that we are going to be creating in this tutorial. The following changes will fix the problem:</p>
<p>In <em>CGameEngine.h</em>, add:</p>
<pre class="brush: cpp; toolbar: false;">void SetGameRunning(bool val) { this-&gt;_gameRunning = val; }</pre>
<p>below the rest of the Mutator functions.</p>
<p>In <em>CGameEngine.cpp</em>, change:</p>
<pre class="brush: cpp;">	void CGameEngine::End(void)
	{
		this-&gt;_gameRunning = false;
		GameEnd();
	}</pre>
<p>to</p>
<pre class="brush: cpp;">	void CGameEngine::End(void)
	{
		GameEnd();
	}</pre>
<p>In <em>WinMain.cpp</em>, change</p>
<pre class="brush: cpp;">	case WM_QUIT:
	case WM_CLOSE:
	case WM_DESTROY:{
		GEInstance-&gt;End();
					} break;</pre>
<p>to</p>
<pre class="brush: cpp;">	case WM_QUIT:
	case WM_CLOSE:
	case WM_DESTROY:{
		GEInstance-&gt;SetGameRunning(false);
					} break;</pre>
<p>and add</p>
<pre class="brush: cpp; toolbar: false;">	// End the Game
	GEInstance-&gt;End();</pre>
<p>And our issues should be solved. The problem here is that WM_DESTROY is called a frame after WM_CLOSE/WM_QUIT are called, and the game will still execute a frame. Making these changes will make sure that &#8220;D3DPong::CGameEngine::Instance()->_gameRunning&#8221; is merely set to false, which we are checking in our Main loop, so that we can just stop execution of the frames.</p>
<p>There is one other error that I&#8217;ve uncovered. I&#8217;d forgotten to actually clear the scene before we begin rendering. In <em>CGameEngine.cpp</em>, add the following to the BeginRender() method, right after we check the Direct3D Device (and right before we Begin the scene).</p>
<pre class="brush: cpp; toolbar: false;">		this-&gt;_device-&gt;Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);</pre>
<p>&#8230;Holy hell, I think I wasn&#8217;t paying much attention when I first programmed this, but I guess that&#8217;s how programming goes. There will always be bugs to fix. Here&#8217;s the last one. Our Game Engine&#8217;s Update() method wasn&#8217;t taking the first frame into account. With how we were handling our delta calculation, that meant that our first frame would have an incredibly high delta. So, replace the update method with the following:</p>
<pre class="brush: cpp;">	void CGameEngine::Update(void)
	{
		static float lastFrame = 0.0f;
		static bool firstFrame = true;

		float delta = ((float)((int)this-&gt;_gameTimer-&gt;GetTime())) - lastFrame;
		lastFrame = ((float)((int)this-&gt;_gameTimer-&gt;GetTime()));

		if(firstFrame)
		{
			delta = 0;
			firstFrame = false;
		}

		GameUpdate(delta);

		this-&gt;BeginRender();

		GameRender(delta);

		this-&gt;EndRender();
	}</pre>
<p><strong>What we are implementing</strong><br />
Since we are starting to get into the juicier parts of the system, I am going to start by providing information on <em>why</em> we are doing things as we are doing them &#8211; what the point behind our systems, why certain design decisions are made, etc.</p>
<p>In a game as simple as Pong, we could easily get away with making every scene object a sprite, taking with it all of our rendering capabilities and continuing on with life. However, it is always important to be looking into the future. It&#8217;s much better (and easier) to upgrade an engine that you&#8217;ve already gotten a lot of work done on than it is to build a new one from scratch. Say, for example, that you are working on a two-dimensional adventure game, such as <em>The Legend of Zelda: The Minish Cap</em>. There are several points in such a game that having scene objects that don&#8217;t necessarily have rendering capabilities would be very useful, such as a hidden trap or a trigger area in which the player will constantly lose health. While you could define them and merely not have anything to render for them, they will still have space made for them in the system&#8217;s memory for the texture data and all of the little render flags, and rendering methods will always be called on them, creating extra overhead. Therefore, it would be much easier to have a base Scene Object class, without any of the extra rendering data, that would help us to cut down on the game&#8217;s resource usage.</p>
<p>For our Scene Object class, we are going to hold basic atomic data, such as the scene object&#8217;s position, size, rotation, velocity, acceleration, friction, and a three-dimensional gravity (allowing us to do horizontal &#8220;gravity&#8221; as well as the usual vertical gravity). We are going to use a three-dimensional vector provided to us by D3DX (the D3DXVECTOR3 struct), rather than defining our own to store this information. Position will be a basic value storing the object&#8217;s position, velocity will be a value added to our Position every frame (all of these will be curbed by the frame delta), acceleration will be added to velocity every frame, and friction will then be either added to or subtracted from the velocity before it is finalized. Friction will always go in the direction of a velocity of &#8220;zero,&#8221; and will have a check to ensure that it is a positive value before modifying the velocity. Gravity will be the last to be applied, and will be the very last thing to be accounted for within the scene object&#8217;s velocity.</p>
<p><strong>Code Listing 1: CSceneObject.h</strong></p>
<pre class="brush: cpp;">#pragma once

// Global Header Files
#include &lt;Windows.h&gt;
#include &lt;d3d9.h&gt;
#include &lt;d3dx9.h&gt;

namespace D3DPong
{
	class CSceneObject
	{
	private:
		// Position, Rotation, and Size data
		D3DXVECTOR2 _position;
		D3DXVECTOR2 _size;
		D3DXVECTOR2 _scale;
		float _rotation;

		// Velocity and other basic movement data
		D3DXVECTOR2 _velocity;
		D3DXVECTOR2 _acceleration;
		D3DXVECTOR2 _friction;
		D3DXVECTOR2 _gravity;

	protected:
		bool _canUpdate;
		bool _canRender;

	public:
		/** Constructor &amp; Destructor **/
		CSceneObject();
		~CSceneObject();

		/** Function Declarations **/
		void Update(float);

		/** Accessors &amp; Mutators **/
		bool CanRender(void) { return this-&gt;_canRender; }
		bool CanUpdate(void) { return this-&gt;_canUpdate; }

		float GetLeft(void) { return this-&gt;_position.x; }
		float GetRight(void) { return (this-&gt;_position.x + (this-&gt;_size.x * this-&gt;_scale.x)); }
		float GetTop(void) { return this-&gt;_position.y; }
		float GetBottom(void) { return (this-&gt;_position.y + (this-&gt;_size.y * this-&gt;_scale.y)); }
		float GetWidth(void) { return this-&gt;_size.x; }
		float GetHeight(void) { return this-&gt;_size.y; }
		D3DXVECTOR2 GetCenter(void) { return D3DXVECTOR2(((float)(this-&gt;_size.x * this-&gt;_scale.x)/2), ((float)(this-&gt;_size.y * this-&gt;_scale.y)/2)); }

		D3DXVECTOR2 GetPosition(void) { return this-&gt;_position; }
		void SetPosition(D3DXVECTOR2 val) { this-&gt;_position = val; }
		void SetPositionX(float val) { this-&gt;_position.x = val; }
		void SetPositionY(float val) { this-&gt;_position.y = val; }

		D3DXVECTOR2 GetSize(void) { return this-&gt;_size; }
		void SetSize(D3DXVECTOR2 val) { this-&gt;_size = val; }
		void SetWidth(float val) { this-&gt;_size.x = val; }
		void SetHeight(float val) { this-&gt;_size.y = val; }

		D3DXVECTOR2 GetScale(void) { return this-&gt;_scale; }
		void SetScale(D3DXVECTOR2 val) { this-&gt;_scale = val; }
		void SetScaleX(float val) { this-&gt;_scale.x = val; }
		void SetScaleY(float val) { this-&gt;_scale.y = val; }

		float GetRotation(void) { return this-&gt;_rotation; }
		void SetRotation(float val) { this-&gt;_rotation = val; }

		D3DXVECTOR2 GetVelocity(void) { return this-&gt;_velocity; }
		void SetVelocity(D3DXVECTOR2 val) { this-&gt;_velocity = val; }
		void SetVelocityX(float val) { this-&gt;_velocity.x = val; }
		void SetVelocityY(float val) { this-&gt;_velocity.y = val; }

		D3DXVECTOR2 GetAcceleration(void) { return this-&gt;_acceleration; }
		void SetAcceleration(D3DXVECTOR2 val) { this-&gt;_acceleration = val; }
		void SetAccelerationX(float val) { this-&gt;_acceleration.x = val; }
		void SetAccelerationY(float val) { this-&gt;_acceleration.y = val; }

		D3DXVECTOR2 GetFriction(void) { return this-&gt;_friction; }
		void SetFriction(D3DXVECTOR2 val) { this-&gt;_friction = val; }
		void SetFrictionX(float val) { this-&gt;_friction.x = val; }
		void SetFrictionY(float val) { this-&gt;_friction.y = val; }

		D3DXVECTOR2 GetGravity(void) { return this-&gt;_gravity; }
		void SetGravity(D3DXVECTOR2 val) { this-&gt;_gravity = val; }
		void SetGravityX(float val) { this-&gt;_gravity.x = val; }
		void SetGravityY(float val) { this-&gt;_gravity.y = val; }
	};
};</pre>
<p>It looks big, but it&#8217;s not all that hard. Most of the code here is creating the Mutator and Accessor functions. Let&#8217;s get cracking, then:</p>
<pre class="brush: cpp;">		// Position, Rotation, and Size data
		D3DXVECTOR2 _position;
		D3DXVECTOR2 _size;
		D3DXVECTOR2 _scale;
		float _rotation;</pre>
<p>These are three important variables. The first three are all two-dimensional vectors &#8211; they hold an X and a Y value. Position will store the object&#8217;s position in world space (in this series, world space and screen space are one and the same. In future series, when we implement a sort of two-dimensional camera or viewport system, the two will be different. Size stores the object&#8217;s size, in pixels, and will be used later when we implement our basic collision-detection system. The object&#8217;s scale represents how large it is. Our sprite class (for two-dimensional images) will scale the image on rendering to this value, and our GetBottom and GetRight take the scale into account. Again, this information will be very important for our collision detection system later. Our final variable, rotation, is a floating-point value representing the number of degrees that our object is rotated by &#8211; it can be from zero to three-hundred sixty, though higher (or lower) values will automatically wrap.</p>
<pre class="brush: cpp;">		// Velocity and other basic movement data
		D3DXVECTOR2 _velocity;
		D3DXVECTOR2 _acceleration;
		D3DXVECTOR2 _friction;
		D3DXVECTOR2 _gravity;</pre>
<p>If these physics variables make you cringe in fear,then let me take this moment to ease your mind by saying that they aren&#8217;t even remotely complicated concepts. These are exactly as explained above &#8211; velocity is the object&#8217;s current, linear velocity, acceleration will be added to the velocity, friction will drag our velocity toward zero, and gravity will drag us toward a certain direction in game space.</p>
<pre class="brush: cpp;">	protected:
		bool _canUpdate;
		bool _canRender;</pre>
<p>These protected variables will prove to be very important in future tutorials, when we implement an instance manager. Basically, each sub-class of CSceneObject will set these variables in their constructor. _canUpdate represents whether or not the class implements an Update() method, while _canRender represents whether or not it implements a Render() method.</p>
<pre class="brush: cpp;">		/** Function Declarations **/
		void Update(float);</pre>
<p>Finally, we declare an Update() function. We are going to have a default Update() method defined because it is incredibly rare that we will ever need to have a scene object that doesn&#8217;t implement updating. We will be able to stop Update from being called, if needed, which can later be checked by an instance manager.</p>
<p><strong>Code Listing 2: CSceneObject.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;CSceneObject.h&quot;

namespace D3DPong
{
	CSceneObject::CSceneObject(void)
		: _position(0,0), _size(0,0),
		_scale(1,1), _rotation(0),
		_velocity(0,0), _acceleration(0,0),
		_friction(0,0), _gravity(0,0),
		_canUpdate(true), _canRender(false)
	{
	}

	CSceneObject::~CSceneObject(void)
	{
	}

	void CSceneObject::Update(float delta)
	{
		// First, add our Acceleration to the object's velocity
		this-&gt;_velocity += this-&gt;_acceleration;

		// Now, we need to handle friction. This will be handled based on whether the velocity is positive or negative.
		if(this-&gt;_velocity.x &gt; 0)
		{
			this-&gt;_velocity.x -= abs(this-&gt;_friction.x);
			if(this-&gt;_velocity.x &lt; 0)
				this-&gt;_velocity.x = 0;
		}
		else if(this-&gt;_velocity.x &lt; 0)
		{
			this-&gt;_velocity.x += abs(this-&gt;_friction.x);
			if(this-&gt;_velocity.x &gt; 0)
				this-&gt;_velocity.x = 0;
		}

		if(this-&gt;_velocity.y &gt; 0)
		{
			this-&gt;_velocity.y -= abs(this-&gt;_friction.y);
			if(this-&gt;_velocity.y &lt; 0)
				this-&gt;_velocity.y = 0;
		}
		else if(this-&gt;_velocity.y &lt; 0)
		{
			this-&gt;_velocity.y += abs(this-&gt;_friction.y);
			if(this-&gt;_velocity.y &gt; 0)
				this-&gt;_velocity.y = 0;
		}

		// Finally, it's time to handle gravity
		this-&gt;_velocity -= this-&gt;_gravity;

		// And then we add the velocity (multiplied by the frame delta) to the position
		this-&gt;_position += (this-&gt;_velocity * (delta/100));
	}
};</pre>
<p>This one&#8217;s not very large &#8211; really, the only important method here is the Update() function, so that&#8217;s what I&#8217;ll break down:</p>
<pre class="brush: cpp;">	void CSceneObject::Update(float delta)
	{
		// First, add our Acceleration to the object's velocity
		this-&gt;_velocity += this-&gt;_acceleration;

		// Now, we need to handle friction. This will be handled based on whether the velocity is positive or negative.
		if(this-&gt;_velocity.x &gt; 0)
		{
			this-&gt;_velocity.x -= abs(this-&gt;_friction.x);
			if(this-&gt;_velocity.x &lt; 0)
				this-&gt;_velocity.x = 0;
		}
		else if(this-&gt;_velocity.x &lt; 0)
		{
			this-&gt;_velocity.x += abs(this-&gt;_friction.x);
			if(this-&gt;_velocity.x &gt; 0)
				this-&gt;_velocity.x = 0;
		}

		if(this-&gt;_velocity.y &gt; 0)
		{
			this-&gt;_velocity.y -= abs(this-&gt;_friction.y);
			if(this-&gt;_velocity.y &lt; 0)
				this-&gt;_velocity.y = 0;
		}
		else if(this-&gt;_velocity.y &lt; 0)
		{
			this-&gt;_velocity.y += abs(this-&gt;_friction.y);
			if(this-&gt;_velocity.y &gt; 0)
				this-&gt;_velocity.y = 0;
		}

		// Finally, it's time to handle gravity
		this-&gt;_velocity -= this-&gt;_gravity;

		// And then we add the velocity (multiplied by the frame delta) to the position
		this-&gt;_position += (this-&gt;_velocity * (delta/100));
	}</pre>
<p>The D3DXVECTOR2 structure provides operator support to allow us to easily add and multiply values and the vectors. We can add, multiply, subtract, etc, for example, two vectors, or even a vector and a floating-point value. Doing operations on a vector will perform that operation on both axes dealt with by the vector (X &#038; Y), or on corresponding vectors in the case of vector-to-vector operations (so this->_velocity += this->_acceleration adds acceleration&#8217;s X to velocity&#8217;s X, and acceleration&#8217;s Y to velocity&#8217;s Y). My explanation may be a little confusing, but looking at the code should clarify things.</p>
<p><strong>Code Listing 3: CTexture.h</strong><br />
Before we move on to defining the Game Sprite class, we need a class to store our game&#8217;s textures. While we could easily just lump this into the Game Sprite class, it makes more sense to move this to its own class &#8211; after all, what if we want to implement an object with rendering that doesn&#8217;t inherit from the game sprite class? So, here we go. This is pretty simple to implement.</p>
<pre class="brush: cpp;">#pragma once

// Global Header Files
#include &lt;Windows.h&gt;
#include &lt;d3d9.h&gt;
#include &lt;d3dx9.h&gt;

namespace D3DPong
{
	class CTexture
	{
	private:
		LPDIRECT3DTEXTURE9 _texture;
		D3DXIMAGE_INFO _imageInfo;

	public:
		CTexture(void);
		~CTexture(void);

		/** Function Declarations **/
		bool Load(LPCWSTR);

		/** Accessors **/
		LPDIRECT3DTEXTURE9 GetTexture(void) { return this-&gt;_texture; }
		float GetWidth(void) { return (float)this-&gt;_imageInfo.Width; }
		float GetHeight(void) { return (float)this-&gt;_imageInfo.Height; }
	};
};</pre>
<pre class="brush: cpp;">		LPDIRECT3DTEXTURE9 _texture;
		D3DXIMAGE_INFO _imageInfo;</pre>
<p>Just a couple small things in the declaration side. The first variable stores the Direct3D texture structure, and will hold the actual image data. The second variable provides us valuable information about the image, and will be populated before we actually load the image. This will allow us to automatically set the texture&#8217;s height, width, etc.</p>
<pre class="brush: cpp; toolbar: false;">		bool Load(LPCWSTR);</pre>
<p>This function takes one argument &#8211; the filename that we want to load. It can be either an absolute location (L&#8221;C:/Sprite.png&#8221;) or a relative location (&#8220;./media/img/Sprite.png&#8221;). In any project you run, you&#8217;ll generally want to use relative locations. The function will return true if it succeeded in loading the file, or false if it failed.</p>
<p><strong>Code Listing 4: CTexture.cpp</strong><strong></p>
<pre class="brush: cpp;">#include &quot;CTexture.h&quot;

#include &quot;CGameEngine.h&quot;

namespace D3DPong
{
	CTexture::CTexture(void)
		: _texture(NULL)
	{
	}

	CTexture::~CTexture(void)
	{
		if(this-&gt;_texture != NULL)
			this-&gt;_texture-&gt;Release();
	}

	bool CTexture::Load(LPCWSTR fileName)
	{
		if(FAILED(D3DXGetImageInfoFromFile(fileName, &amp;_imageInfo)))
		{
			this-&gt;_texture = NULL;
			return false;
		}

		if(FAILED(D3DXCreateTextureFromFileEx(CGameEngine::Instance()-&gt;GetDevice(),
			fileName, 											// File Name
			this-&gt;_imageInfo.Width, this-&gt;_imageInfo.Height, 1,	// Width, Height, and MIP Level Count
			D3DPOOL_DEFAULT, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT,	// Usage method, Format, and Pool
			D3DX_DEFAULT, D3DX_DEFAULT,							// Image and MIP Filters
			D3DCOLOR_XRGB(255, 0, 255),							// Transparency Key (Magenta)
			&amp;this-&gt;_imageInfo, NULL, &amp;this-&gt;_texture			// Image information structure, color pallete, and destination texture
			)))
		{
			this-&gt;_texture = NULL;
			return false;
		}

		return true;
	}
};</pre>
<p>This time, I&#8217;m not going to bother re-pasting the code for the Load function, and I&#8217;ll just explain it here, since it&#8217;s the only thing of importance. Just note that we call the texture structure&#8217;s Release() function when we delete the object, to make sure it is cleared from memory.</p>
<p>The first thing we do in the Load function is get the file information from the file. The only parts we&#8217;re bothering with are the Width and Height of the image file, but we do get some other information from the file.After that, we actually create the texture from a file, using the aptly-named D3DXCreateTextureFromFileEx. This takes the filename, the image size data, various pieces of information that we&#8217;re not going to worry about (usage, format, etc), and we pass the image information and the texture data. The transparency key that we provide will allow us to use a color key transparency method, if we&#8217;re not interested in using alpha transparency provided by several formats (such as PNG). Any pixel of Magenta color (Red 255, Green 0, Blue 255) will be completely transparent. D3DX will also automatically, properly handle images that support transparency, so you can save yourself some trouble by using a good image editor that can output alpha transparency (GIMP, Paint.NET, and Photoshop all support these formats).</p>
<p></strong><strong>Code Listing 5: CGameSprite.h</strong></p>
<pre class="brush: cpp;">#pragma once

// Global Header Files
#include &lt;Windows.h&gt;
#include &lt;d3d9.h&gt;
#include &lt;d3dx9.h&gt;

// Local Header Files
#include &quot;CSceneObject.h&quot;
#include &quot;CTexture.h&quot;

namespace D3DPong
{
	class CGameSprite : public CSceneObject
	{
	private:
		/** Texture Data **/
		CTexture* _texture;
		bool _visible;
		D3DXMATRIX _matRotate, _matScale;

		/** Function Declarations **/
		void transform(void);

	public:
		/** Constructor &amp; Destructor **/
		CGameSprite(void);
		~CGameSprite(void);

		/** Function Declarations **/
		bool Load(LPCWSTR);
		void Render(float);

		/** Accessors &amp; Mutators **/
		CTexture* GetTexture(void) { return this-&gt;_texture; }
		void SetTexture(CTexture* val) { this-&gt;_texture = val; }

		bool IsVisible(void) { return this-&gt;_visible; }
		void SetVisible(bool val) { this-&gt;_visible = val; }
	};
};</pre>
<p>And here&#8217;s our sprite class. Because we&#8217;re inheriting from CSceneObject, we don&#8217;t need to worry about all of the extra atomic data for the object. We&#8217;re going to have to store a texture for the sprite, store whether or not the object is visible (so that we can easily make an object appear and disappear), two Matrices to allow us to apply rotation. When using the D3DXSprite sprite handler, we can easily just provide a position and not worry about matrices at all &#8211; which works great for most games. However, because we want to implement scaling and rotation, we will have to use matrices. Matrices are used to provide translation (position), rotation, and scaling in three-dimensional games. They are also used in a number of two-dimensional games, to provide hardware-accelerated graphics functions. The transformation will be performed in the private &#8220;transform()&#8221; method, which will be called from our Render() method.</p>
<p><strong>Code Listing 6: CGameSprite.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;CGameSprite.h&quot;

#include &quot;CGameEngine.h&quot;

namespace D3DPong
{
	CGameSprite::CGameSprite(void)
		: _texture(NULL), _visible(true)
	{
	}

	CGameSprite::~CGameSprite(void)
	{
		if(this-&gt;_texture != NULL)
			delete this-&gt;_texture;
	}

	void CGameSprite::transform(void)
	{
		D3DXMATRIX mat;

		D3DXMatrixTransformation2D(&amp;mat, NULL, 0,
			&amp;this-&gt;GetScale(), &amp;this-&gt;GetCenter(), this-&gt;GetRotation(), &amp;this-&gt;GetPosition());

		CGameEngine::Instance()-&gt;GetSpriteHandler()-&gt;SetTransform(&amp;mat);
	}

	bool CGameSprite::Load(LPCWSTR fileName)
	{
		if(this-&gt;_texture != NULL)
			delete this-&gt;_texture;

		this-&gt;_texture = new CTexture();
		if(this-&gt;_texture-&gt;Load(fileName))
		{
			this-&gt;SetSize(D3DXVECTOR2(this-&gt;_texture-&gt;GetWidth(), this-&gt;_texture-&gt;GetHeight()));
			return true;
		}
		else
			return false;
	}

	void CGameSprite::Render(float)
	{
		this-&gt;transform();

		if(this-&gt;_texture != NULL &amp;&amp; this-&gt;_visible)
			CGameEngine::Instance()-&gt;GetSpriteHandler()-&gt;Draw(this-&gt;_texture-&gt;GetTexture(), NULL, NULL, NULL, D3DCOLOR_XRGB(255, 255, 255));
	}
};</pre>
<p>It doesn&#8217;t look all that difficult, I hope.</p>
<pre class="brush: cpp;">	void CGameSprite::transform(void)
	{
		D3DXMATRIX mat;

		D3DXMatrixTransformation2D(&amp;mat, NULL, 0,
			&amp;this-&gt;GetScale(), &amp;this-&gt;GetCenter(), this-&gt;GetRotation(), &amp;this-&gt;GetPosition());

		CGameEngine::Instance()-&gt;GetSpriteHandler()-&gt;SetTransform(&amp;mat);
	}</pre>
<p>The first method we handle, as explained, creates the transformation matrix, and then sets the current transformation on the sprite handler. We need a D3DXMATRIX variable to store the transformation Matrix, then we create the actual 2D transformation Matrix. We specify that the matrix to output to is our newly-defined mat variable, and we pass our Scale, Rotation, and Position vectors to the object. We also pass a new vector, that returns the center of the object, which will form the base around which our object rotates.</p>
<pre class="brush: cpp;">	void CGameSprite::Render(float)
	{
		this-&gt;transform();

		if(this-&gt;_texture != NULL &amp;&amp; this-&gt;_visible)
			CGameEngine::Instance()-&gt;GetSpriteHandler()-&gt;Draw(this-&gt;_texture-&gt;GetTexture(), NULL, NULL, NULL, D3DCOLOR_XRGB(255, 255, 255));
	}</pre>
<p>And here is our rendering method. First, we call our transform, so that we can get the object placed, rotated, and scaled properly. Next, we check to make sure that our texture is loaded, and whether or not our object is actually visible, before we render. This ensures that we don&#8217;t try to draw a NULL texture, which would cause our engine to crash. We pass the texture and a color to the Draw() method. The color we pass will saturate the image &#8211; we use white, to keep things as they are in the image.</p>
<pre class="brush: cpp;">bool CGameSprite::Load(LPCWSTR fileName)
	{
		if(this-&gt;_texture != NULL)
			delete this-&gt;_texture;

		this-&gt;_texture = new CTexture();
		if(this-&gt;_texture-&gt;Load(fileName))
		{
			this-&gt;SetSize(D3DXVECTOR2(this-&gt;_texture-&gt;GetWidth(), this-&gt;_texture-&gt;GetHeight()));
			return true;
		}
		else
			return false;
	}</pre>
<p>Finally, we delete the old texture (if we want to load a new texture, we want to prevent memory leaks and clean up after ourselves). Then, we recreate the texture object and attempt to load the image, then set the object&#8217;s size to match that of the image. Simple, clean, efficient.</p>
<p><strong>Code Listing 7: Game.cpp</strong><br />
We can keep the exact same Game.h that we created in the last project, and provide the following code to test our game engine&#8217;s most recent additions:</p>
<pre class="brush: cpp;">#include &quot;Game.h&quot;

#include &quot;CGameEngine.h&quot;

#define GEInstance D3DPong::CGameEngine::Instance()

D3DPong::CGameSprite* testSprite;

bool GamePreLoad(void)
{
	GEInstance-&gt;SetScreenWidth(800);
	GEInstance-&gt;SetScreenHeight(600);
	GEInstance-&gt;SetWindowTitle(L&quot;Direct3D Pong Tutorial 03 - Scene Objects and Sprite Rendering&quot;);

	return true;
}

bool GameInit(void)
{
	// Load a test sprite
	testSprite = new D3DPong::CGameSprite();
	if(!testSprite-&gt;Load(L&quot;./media/img/testSprite.png&quot;))
		MessageBox(NULL, L&quot;Failed to Load&quot;, L&quot;:(&quot;, MB_OK);

	float x = (float)(GEInstance-&gt;GetScreenWidth() - testSprite-&gt;GetWidth());
	float y = (float)(GEInstance-&gt;GetScreenHeight() / 2);

	testSprite-&gt;SetPositionX(x);
	testSprite-&gt;SetPositionY((y - testSprite-&gt;GetCenter().y));

	testSprite-&gt;SetVelocityX(-10);

	return true;
}

void GameUpdate(float delta)
{
	testSprite-&gt;Update(delta);

	if(testSprite-&gt;GetLeft() &lt;= 0)
	{
		testSprite-&gt;SetVelocityX(0);
		testSprite-&gt;SetPositionX(0);
	}
}

void GameRender(float delta)
{
	testSprite-&gt;Render(delta);
}

void GameEnd(void)
{
	if(testSprite != NULL)
		delete testSprite;
}</pre>
<p>All of the code in this test are pretty self-explanatory &#8211; we create and load the sprite, then we position it right and centered on the screen, and give the object a negative velocity on the X-axis &#8211; making it move to the left until it hits the end and stops.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minalien.com/index.php/2010/03/21/cd3d-pong-tutorial-03-scene-objects-and-sprite-rendering/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>C++/D3D Pong Tutorial 02: Setting up Direct3D and our Engine Framework</title>
		<link>http://www.minalien.com/index.php/2010/02/15/pong-series-02/</link>
		<comments>http://www.minalien.com/index.php/2010/02/15/pong-series-02/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 20:16:28 +0000</pubDate>
		<dc:creator>Samantha</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Pong (C++/DirectX)]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[Direct3D]]></category>
		<category><![CDATA[DirectX]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[Pong]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.minalien.com/?p=68</guid>
		<description><![CDATA[Tutorial Description In the last tutorial, we set up the basics required for the Windows API to open our window. While basic, the task was also essential, though many people who are familiar with Win32 Programming will likely have gained nothing from it. Here, we are going to do several tasks. In no particular order,]]></description>
			<content:encoded><![CDATA[<p><strong>Tutorial Description</strong><br />
In the last tutorial, we set up the basics required for the Windows API to open our window. While basic, the task was also essential, though many people who are familiar with Win32 Programming will likely have gained nothing from it. Here, we are going to do several tasks. In no particular order, they are as follows:<br />
1) Set up Direct3D rendering<br />
2) Set up the framework for our game engine<br />
3) Implementing game timing</p>
<p><strong>Downloads</strong><br />
<a href="http://files.minalien.com/D3DPong/02/D3DPong-Bin.rar">Binary Only (10.4KB)</a><br />
<a href="http://files.minalien.com/D3DPong/02/D3DPong.rar">Full VS2010 Project Dir (13.1MB)</a></p>
<p><strong>Starting Words</strong><br />
<em>Notice: This tutorial continues from where &#8220;<a href="http://www.minalien.com/index.php/2010/01/24/pong-series-01/">C++/D3D Pong Tutorial 01</a>&#8221; article left off. Please read it if you have not already.</em></p>
<p><span id="more-68"></span></p>
<p><strong>Libraries</strong><br />
You will need to add the following three libraries to your project:<br />
d3d9.lib<br />
d3dx9.lib<br />
dxguid.lib</p>
<p><strong>Code Listing 1: CGameTimer.h</strong></p>
<pre class="brush: cpp;">#pragma once

// Global Headers
#include &lt;time.h&gt;
#include &lt;Windows.h&gt;

namespace D3DPong
{
	class CGameTimer
	{
	private:
		// Marks the starting point of the timer
		DWORD _start;

	public:
		/** Constructor &amp; Destructor **/
		CGameTimer(void);

		/** Function Declarations **/
		DWORD GetTime(void);		// Retrieve the current time (in milliseconds)
		DWORD GetStartTime(void);	// Get the Timer's start time (in milliseconds)
		DWORD GetRunTime(void);		// Get the Timer's running time (in millseconds)
		void Reset(void);			// Reset the timer.
	};
};</pre>
<p>This small bit of code will mark the base of our game timing system. This system will make it possible to use delta timing, so that we do not have to cap the frame limit by using unnecessary processing. You will see how this works when we start setting up the rendering engine, but for now, allow me to give you an explanation of the class.</p>
<pre class="brush: cpp;">	private:
		// Marks the starting point of the timer
		DWORD _start;</pre>
<p>The game timer&#8217;s only variable, this DWORD value will store the start time, in milliseconds, for when the timer started (its creation or a call to reset()).</p>
<pre class="brush: cpp;">		/** Function Declarations **/
		DWORD GetTime(void);		// Retrieve the current time (in milliseconds)
		DWORD GetStartTime(void);	// Get the Timer's start time (in milliseconds)
		DWORD GetRunTime(void);		// Get the Timer's running time (in millseconds)
		void Reset(void);			// Reset the timer.</pre>
<p>Constructor declarations aren&#8217;t anything special, so I won&#8217;t bother going into detail about that. These four functions, however, are very important to the engine.</p>
<p><strong>GetTime()</strong> will give us an easier method of getting the system time, in milliseconds. It takes away some of our reliance on the Windows API.<br />
<strong>GetStartTime()</strong> will allow us to retrieve the time that the Timer was last started or reset.<br />
<strong>GetRunTime()</strong> will give us the running time of our timer object. This will be vital when we implement Delta timing.<br />
<strong>Reset()</strong> will reset the timer&#8217;s &#8220;start time.&#8221; This will allow us to more easily handle timed events, if a timer doesn&#8217;t need to continually run.</p>
<p><strong>Code Listing 2: CGameTimer.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;CGameTimer.h&quot;

namespace D3DPong
{
	CGameTimer::CGameTimer(void)
	{
		this-&gt;_start = timeGetTime();
	}

	DWORD CGameTimer::GetTime(void)
	{
		return timeGetTime();
	}

	DWORD CGameTimer::GetStartTime(void)
	{
		return this-&gt;_start;
	}

	DWORD CGameTimer::GetRunTime(void)
	{
		return (timeGetTime() - this-&gt;_start);
	}

	void CGameTimer::Reset(void)
	{
		this-&gt;_start = this-&gt;GetTime();
	}
};</pre>
<p>And here we are, the flesh and bones of the game timer class. All of these are single-line functions, but this will make a large portion of our engine&#8217;s logic. Most of it should be pretty obvious, if you read the descriptions above.</p>
<p><b>Creating our Entry Point</b><br />
Before we get into the nitty-gritty portions of creating our engine framework and setting up Direct3D, I&#8217;m going to do two things. First, I&#8217;m going to show you where we are going to set up and handle our game logic, which will be separate from our Engine code. After that, I am going to give you a brief roadmap before jumping into the large bits of code that will make up our game engine.</p>
<p><b>Code Listing 3: Game.h</b></p>
<pre class="brush: cpp;">#pragma once

#include &lt;windows.h&gt;

extern bool GamePreLoad(void);
extern bool GameInit(void);
extern void GameUpdate(float);
extern void GameRender(float);
extern void GameEnd(void);</pre>
<p>These functions, when fleshed out, will contain all of our game&#8217;s logic.<br />
<i>GamePreLoad()</i> &#8211; Within this method, we will do some initial setup (such as setting up the game window dimensions)<br />
<i>GameInit()</i> &#8211; And here, we will load our initial game resources and set up initial logic settings.<br />
<i>GameUpdate(delta)</i> &#8211; This function will be called every frame, and will contain our game logic. The floating-point value that it is passed is the timing delta (the time between the last frame and this one). We will use this timing delta<br />
<i>GameRender(delta)</i> &#8211; This function will also be called every frame, and will always be called <em>after</em> GameUpdate. Our rendering logic will be executed here.<br />
<i>GameEnd()</i> &#8211; This will be called to execute last-minute cleanup for the game.</p>
<p><strong>Code Listing 4: Game.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;Game.h&quot;

bool GamePreLoad(void)
{
	return true;
}

bool GameInit(void)
{
	return true;
}

void GameUpdate(float delta)
{
}

void GameRender(float delta)
{
}

void GameEnd(void)
{
}</pre>
<p>This is just the empty framework for now. All of our game logic, when we begin work on it in future tutorials, will go here. We&#8217;ll modify this at the end of this tutorial to do some basic setup in the PreLoad function.</p>
<p><strong>What Lies Ahead</strong><br />
Alright, we&#8217;ve got some fun work ahead of us. First, we are going to be setting up the game engine&#8217;s code. That will be a pretty decent-sized trek through the woods, but I&#8217;m going to try to cover it as thoroughly as I can without stepping into a discussion about the various pieces of clockwork that aren&#8217;t entirely necessary.</p>
<p><strong>Code Listing 5: CGameEngine.h</strong></p>
<pre class="brush: cpp;">#pragma once

// Global Header Files
#include &lt;Windows.h&gt;
#include &lt;d3d9.h&gt;
#include &lt;d3dx9.h&gt;

// Local Header Files
#include &quot;CGameTimer.h&quot;
#include &quot;Game.h&quot;

namespace D3DPong
{
	class CGameEngine
	{
	private:
		CGameEngine(void);						// ctor
		CGameEngine(CGameEngine const&amp;) { };	// copy ctor
		virtual ~CGameEngine(void);				// dtor

		static CGameEngine* _instance;

		HWND	_windowHandle;

		LPDIRECT3D9			_d3d;
		LPDIRECT3DDEVICE9	_device;
		LPD3DXSPRITE 		_spriteHandler;

		LPCWSTR	_windowTitle;
		int		_screenWidth, _screenHeight, _colorDepth;

		const static D3DCOLOR _ambientColor;

		CGameTimer*	_gameTimer;
		bool		_gameRunning;

	public:
		static CGameEngine* Instance(void) { return _instance; }

		bool Init(int, int, int);
		void End(void);
		void Update(void);
		void BeginRender(void);
		void EndRender(void);

		LPDIRECT3DDEVICE9 GetDevice(void) { return this-&gt;_device; }
		LPD3DXSPRITE GetSpriteHandler(void) { return this-&gt;_spriteHandler; }
		HWND GetWindowHandle(void) { return this-&gt;_windowHandle; }
		LPCWSTR GetWindowTitle(void) { return this-&gt;_windowTitle; }
		int GetScreenWidth(void) { return this-&gt;_screenWidth; }
		int GetScreenHeight(void) { return this-&gt;_screenHeight; }
		int GetColorDepth(void) { return this-&gt;_colorDepth; }
		bool GetGameRunning(void) { return this-&gt;_gameRunning; }
		CGameTimer* GetGameTimer(void) { return this-&gt;_gameTimer; }

		void SetWindowHandle(HWND val) { this-&gt;_windowHandle = val; }
		void SetWindowTitle(LPCWSTR);
		void SetScreenWidth(int val) { this-&gt;_screenWidth = val; }
		void SetScreenHeight(int val) { this-&gt;_screenHeight = val; }
		void SetColorDepth(int val) { this-&gt;_colorDepth = val; }
	};
};</pre>
<p>Aaaannnd here we go. Time for the explanations. I&#8217;ll leave out the accessor &#038; mutators, as those should be second nature to anybody who has been able to follow along thus far.</p>
<pre class="brush: cpp;">		CGameEngine(void);						// ctor
		CGameEngine(CGameEngine const&amp;) { };	// copy ctor
		virtual ~CGameEngine(void);				// dtor

		static CGameEngine* _instance;</pre>
<p>Here, we have the constructor, copy constructor, and destructor. These are all defined in the private section because we only want to allow them to be initialized when the engine instance (which is a <a href="http://en.wikipedia.org/wiki/Singleton_pattern" target="_blank">singleton</a>) is first defined (in CGameEngine.cpp). The copy constructor is left empty (it wont be used at all), and the destructor is made virtual in case we decide to create a class that inherits from it at a later point (which is unlikely, but the option will still be available). Lastly, we create a static pointer that will serve as the singleton. We will be able to access the game engine at any time by calling CGameEngine::Instance().</p>
<pre class="brush: cpp;">		HWND	_windowHandle;

		LPDIRECT3D9			_d3d;
		LPDIRECT3DDEVICE9	_device;
		LPD3DXSPRITE 		_spriteHandler;

		LPCWSTR	_windowTitle;
		int		_screenWidth, _screenHeight, _colorDepth;

		const static D3DCOLOR _ambientColor;

		CGameTimer*	_gameTimer;
		bool		_gameRunning;</pre>
<p>Most of the member variables are self-explanatory. The engine will need an instance of the game window&#8217;s handle for some of the Direct3D setup, as well as for other tasks, such as changing the window&#8217;s title. The three Direct3D variables are the Direct3D instance, which gives us access to a lot of the device creation features, the Direct3D device itself, which will handle our game&#8217;s rendering backbone, and then the D3DX sprite handler, which will allow us to do 2D rendering without going through the trouble of creating and texturing 3D quads, which anybody with experience doing that method of 2D will tell you is a royal pain in the ass. Finally, we create variables to store our window&#8217;s attributes (title, screen size, color depth), a static variable to store our ambient color (which will not change throughout the game), a boolean to keep track of whether or not the game is running (which will be important when we start modifying our game loop), and a game timer, which we will use to track the time between frames in the game.</p>
<pre class="brush: cpp; toolbar: false;">		CGameEngine* Instance(void) { return _instance; }</pre>
<p>Again, back to our Singleton implementation. Although this is simply an accessor, I wanted to point it out because of its importance to our singleton implementaiton.</p>
<pre class="brush: cpp;">		bool Init(int, int, int);
		void End(void);
		void Update(void);
		void BeginRender(void);
		void EndRender(void);</pre>
<p>And these methods make up the meat of our game engine.<br />
<em>Init(width, height, depth)</em> &#8211; This method will initialize the Direct3D systems, and will configure our render settings.<br />
<em>End()</em> &#8211; This is called to end the game.<br />
<em>Update()</em> &#8211; This method is called every frame, will calculate the timing delta and call our GameUpdate() and GameRender() methods.<br />
<em>BeginRender()</em> &#8211; Basic rendering setup (starting the D3D device, starting the sprite handler, etc)<br />
<em>EndRender()</em> &#8211; The inverse of our BeginRender function &#8211; this method ends the rendering systems started in BeginRender, then presents the scene (swaps the render buffers)</p>
<pre class="brush: cpp; toolbar: false;">void SetWindowTitle(LPCWSTR);</pre>
<p>You may have noticed this lonely mutator sitting here, undefined. Fight your urge to follow the other mutators on this one &#8211; we&#8217;re going to be defining this one in CGameEngine.cpp, so that if we would decide to change our window title in-game, we can, and doing so requires a touch more than changing the value of _windowTitle.</p>
<p>And here we go, the meat of our game engine.</p>
<p><strong>Code Listing 6: CGameEngine.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;CGameEngine.h&quot;
#include &quot;WinMain.h&quot;

namespace D3DPong
{
	const D3DCOLOR CGameEngine::_ambientColor = D3DCOLOR_RGBA(255, 255, 255, 0);
	CGameEngine* CGameEngine::_instance = new CGameEngine();

	CGameEngine::CGameEngine(void)
		: _windowHandle(NULL), _windowTitle(L&quot;D3DPong&quot;),
		_screenWidth(640), _screenHeight(480), _colorDepth(32),
		_gameRunning(false),
	{
	}

	CGameEngine::~CGameEngine(void)
	{
		if(this-&gt;_gameRunning)
			this-&gt;_gameRunning = false;

		if(this-&gt;_spriteHandler)
			this-&gt;_spriteHandler-&gt;Release();

		if(this-&gt;_device)
			this-&gt;_device-&gt;Release();

		if(this-&gt;_d3d)
			this-&gt;_d3d-&gt;Release();

		delete this-&gt;_spriteHandler;
		delete this-&gt;_device;
		delete this-&gt;_d3d;
	}

	bool CGameEngine::Init(int width, int height, int depth)
	{
		// Set up Engine Vars
		this-&gt;_screenWidth = width;
		this-&gt;_screenHeight = height;
		this-&gt;_colorDepth = depth;
		// Initialize Direct3D
		this-&gt;_d3d = Direct3DCreate9(D3D_SDK_VERSION);
		if(!this-&gt;_d3d)
			return false;

		// Get the Display Mode (to ensure maximum compatibility)
		D3DDISPLAYMODE disp;
		this-&gt;_d3d-&gt;GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &amp;disp);

		// Presentation Parameters
		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory(&amp;d3dpp, sizeof(D3DPRESENT_PARAMETERS));
		d3dpp.Windowed = true;
		d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
		d3dpp.EnableAutoDepthStencil = true;
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
		d3dpp.BackBufferFormat = disp.Format;
		d3dpp.BackBufferWidth = this-&gt;_screenWidth;
		d3dpp.BackBufferHeight = this-&gt;_screenHeight;
		d3dpp.hDeviceWindow = this-&gt;_windowHandle;

		// Create the Direct3D Device
		this-&gt;_d3d-&gt;CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, this-&gt;_windowHandle, D3DCREATE_HARDWARE_VERTEXPROCESSING, &amp;d3dpp, &amp;this-&gt;_device);

		if(!this-&gt;_device)
			return false;

		// Enable Z-buffering, set the fill mode, and set the ambient color (white)
		this-&gt;_device-&gt;SetRenderState(D3DRS_ZENABLE, true);
		this-&gt;_device-&gt;SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
		this-&gt;_device-&gt;SetRenderState(D3DRS_AMBIENT, this-&gt;_ambientColor);

		// Initialize the Sprite handler
		if(FAILED(D3DXCreateSprite(this-&gt;_device, &amp;this-&gt;_spriteHandler)))
			return false;

		// Game Initialization
		if(!GameInit())
			return false;

		return true;
	}

	void CGameEngine::End(void)
	{
		this-&gt;_gameRunning = false;
		GameEnd();
	}

	void CGameEngine::Update(void)
	{
		static float lastFrame = 0.0f;

		float delta = ((float)((int)this-&gt;_gameTimer-&gt;GetTime())) - lastFrame;
		lastFrame = ((float)((int)this-&gt;_gameTimer-&gt;GetTime()));

		GameUpdate(delta);

		this-&gt;BeginRender();

		GameRender(delta);

		this-&gt;EndRender();
	}

	void CGameEngine::BeginRender(void)
	{
		if(!this-&gt;_device)
			return;

		if(FAILED(this-&gt;_device-&gt;BeginScene()))
			return;

		if(FAILED(this-&gt;_spriteHandler-&gt;Begin(D3DXSPRITE_ALPHABLEND)))
			return;
	}

	void CGameEngine::EndRender(void)
	{
		if(!this-&gt;_device)
			return;

		this-&gt;_spriteHandler-&gt;End();

		if(FAILED(this-&gt;_device-&gt;EndScene()))
			return;

		if(FAILED(this-&gt;_device-&gt;Present(NULL, NULL, NULL, NULL)))
			return;
	}

	void CGameEngine::SetWindowTitle(LPCWSTR val)
	{
		this-&gt;_windowTitle = val;

		if(this-&gt;_windowHandle)
			SetWindowText(this-&gt;_windowHandle, this-&gt;_windowTitle);
	}
};</pre>
<p>Ready? Here we go.</p>
<pre class="brush: cpp;">	const D3DCOLOR CGameEngine::_ambientColor = D3DCOLOR_RGBA(255, 255, 255, 0);
	CGameEngine* CGameEngine::_instance = new CGameEngine();</pre>
<p>Here, we are creating and defining the singleton instance, and setting up the ambient color constant. Pretty simple.</p>
<pre class="brush: cpp;">	CGameEngine::CGameEngine(void)
		: _windowHandle(NULL), _windowTitle(L&quot;D3DPong&quot;),
		_screenWidth(640), _screenHeight(480), _colorDepth(32)
		_gameRunning(false),
	{
	}</pre>
<p>Technically, this is an empty constructor, but we&#8217;re using a shorthand method of setting default values for some of our class&#8217;s member variables.</p>
<pre class="brush: cpp;">	CGameEngine::~CGameEngine(void)
	{
		if(this-&gt;_gameRunning)
			this-&gt;_gameRunning = false;

		if(this-&gt;_spriteHandler)
			this-&gt;_spriteHandler-&gt;Release();

		if(this-&gt;_device)
			this-&gt;_device-&gt;Release();

		if(this-&gt;_d3d)
			this-&gt;_d3d-&gt;Release();

		delete this-&gt;_spriteHandler;
		delete this-&gt;_device;
		delete this-&gt;_d3d;
	}</pre>
<p>A standard cleanup within the Game Engine&#8217;s destructor. First, we have to release all of the DirectX devices, to ensure that none of them are currently being used, and so that they can do their internal cleanup. Finally, we delete the pointers, as a final cleanup. Because this will mark the end of the application, this wouldn&#8217;t cause any sort of memory leak, but I&#8217;d prefer not to rely on the operating system to clean up our leftovers.</p>
<pre class="brush: cpp;">	bool CGameEngine::Init(int width, int height, int depth)
	{
		// Set up Engine Vars
		this-&gt;_screenWidth = width;
		this-&gt;_screenHeight = height;
		this-&gt;_colorDepth = depth;
		// Initialize Direct3D
		this-&gt;_d3d = Direct3DCreate9(D3D_SDK_VERSION);
		if(!this-&gt;_d3d)
			return false;

		// Get the Display Mode (to ensure maximum compatibility)
		D3DDISPLAYMODE disp;
		this-&gt;_d3d-&gt;GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &amp;disp);</pre>
<p>Onto the Initialization. This one&#8217;s a big one. First, we&#8217;re just setting our member variables, so that we can keep track of our size and depth changes. Initializing Direct3D itself is easy and straightforward &#8211; you just call Direct3DCreate9 to create a Direct3D 9 manager, and pass the SDK version (Always pass it as D3D_SDK_VERSION, to ensure that the engine is compatible with future Direct3D releases).</p>
<p>Finally, we get the display mode of the desktop. This will be used when we are setting the Direct3D Presentation Parameters, which define hour our rendering is handled with the graphics card. While we could stick with a generic D3DFMT_R5G6B5, which will work almost universally, this will ensure that the display format used is compatible with the current video card and monitor.</p>
<pre class="brush: cpp;">		// Presentation Parameters
		D3DPRESENT_PARAMETERS d3dpp;
		ZeroMemory(&amp;d3dpp, sizeof(D3DPRESENT_PARAMETERS));
		d3dpp.Windowed = true;
		d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
		d3dpp.EnableAutoDepthStencil = true;
		d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
		d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
		d3dpp.BackBufferFormat = disp.Format;
		d3dpp.BackBufferWidth = this-&gt;_screenWidth;
		d3dpp.BackBufferHeight = this-&gt;_screenHeight;
		d3dpp.hDeviceWindow = this-&gt;_windowHandle;</pre>
<p>The presentation parameters are incredibly important to Direct3D. It tells the system how large to make the back buffer (we&#8217;re using our screen dimensions), what to do when it swaps the buffers (discards the currently-rendering, then displays the new buffer), and sets the window handle that is used.</p>
<pre class="brush: cpp;">		// Create the Direct3D Device
		this-&gt;_d3d-&gt;CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, this-&gt;_windowHandle, D3DCREATE_HARDWARE_VERTEXPROCESSING, &amp;d3dpp, &amp;this-&gt;_device);

		if(!this-&gt;_device)
			return false;

		// Enable Z-buffering, set the fill mode, and set the ambient color (white)
		this-&gt;_device-&gt;SetRenderState(D3DRS_ZENABLE, true);
		this-&gt;_device-&gt;SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
		this-&gt;_device-&gt;SetRenderState(D3DRS_AMBIENT, this-&gt;_ambientColor);</pre>
<p>Now we&#8217;re creating the Direct3D rendering device. We are configuring it as follows:<br />
1) It will use the default adapter (the primary monitor/video card), everything will be handled on the hardware level (graphics card) for rendering, rather than software rendering (basically, use the GPU instead of the CPU), and we pass the presentation parameters and the address to map the newly created device to. Finally, we set three render states: Z-buffering, Solid fill mode, and ambient color. These settings will enhance our graphics quality, and give us some fun tools to use in later games. (Have you noticed, yet, that the engine is something that can easily be re-used in later projects?)</p>
<pre class="brush: cpp;">		// Initialize the Sprite handler
		if(FAILED(D3DXCreateSprite(this-&gt;_device, &amp;this-&gt;_spriteHandler)))
			return false;

		// Game Initialization
		if(!GameInit())
			return false;</pre>
<p>Getting back to more simple-to-comprehend steps. Here, we&#8217;re ensuring that we are able to create our sprite handler (which will make our two-dimensional rendering a lot easier to implement), and calling the game&#8217;s initialization method, so that it can handle game setup. And we&#8217;re done.</p>
<pre class="brush: cpp;">	void CGameEngine::End(void)
	{
		this-&gt;_gameRunning = false;
		GameEnd();
	}</pre>
<p>This method will allow us to end the game. First, it changes the &#8220;running&#8221; flag, which will tell our engine to jump out of the loop, and then it calls the GameEnd method, allowing us to do some last-minute cleanup before the engine itself closes out.</p>
<pre class="brush: cpp;">	void CGameEngine::Update(void)
	{
		static float lastFrame = 0.0f;

		float delta = ((float)((int)this-&gt;_gameTimer-&gt;GetTime())) - lastFrame;
		lastFrame = ((float)((int)this-&gt;_gameTimer-&gt;GetTime()));

		GameUpdate(delta);

		this-&gt;BeginRender();

		GameRender(delta);

		this-&gt;EndRender();
	}</pre>
<p>Another important one. The first thing we do is declare a static floating-point value, to store the time (in millseconds) of our last frame. We then calculate the delta (the time between calls to the Update() method) by subtracting the time the last frame started from the current game time. After calculating the delta, it changes frameTime to reflect the start of <em>this</em> frame. After that, we give a call to our GameUpdate method, passing the timing delta, start rendering, call GameRender, and then end rendering. In case you were wondering, the delta passed to GameRender is for animation purposes &#8211; the rendering method is the best place to put frame calculations for animations, in my opinion.</p>
<pre class="brush: cpp;">	void CGameEngine::BeginRender(void)
	{
		if(!this-&gt;_device)
			return;

		if(FAILED(this-&gt;_device-&gt;BeginScene()))
			return;

		if(FAILED(this-&gt;_spriteHandler-&gt;Begin(D3DXSPRITE_ALPHABLEND)))
			return;
	}</pre>
<p>Here, we start rendering. First of all, if our device isn&#8217;t active, we&#8217;re going to crash if we try to call any methods on it, so we do a check to make sure it exists. Then, we begin the Direct3D scene, and begin 2D rendering within the sprite handler. By passing the D3DXSPRITE_ALPHABLEND parameter to the sprite handler, we ensure that alpha values will be honored by the rendering system, making transparency an easy task to deal with &#8211; it&#8217;s the artist&#8217;s problem now. Transparent PNGs are the best thing to use for two-dimensional game art, at the moment (excluding, of course, custom, optimized file formats created for an engine).</p>
<pre class="brush: cpp;">	void CGameEngine::EndRender(void)
	{
		if(!this-&gt;_device)
			return;

		this-&gt;_spriteHandler-&gt;End();

		if(FAILED(this-&gt;_device-&gt;EndScene()))
			return;

		if(FAILED(this-&gt;_device-&gt;Present(NULL, NULL, NULL, NULL)))
			return;
	}</pre>
<p>Now, we&#8217;re doing the opposite. We still need to make sure our device exists before we stop rendering, but beyond that, we stop the systems in the order they were presented. The last method, Present, swaps the display buffers, and is required if we want our rendering to actually appear.</p>
<pre class="brush: cpp;">	void CGameEngine::SetWindowTitle(LPCWSTR val)
	{
		this-&gt;_windowTitle = val;

		if(this-&gt;_windowHandle)
			SetWindowText(this-&gt;_windowHandle, this-&gt;_windowTitle);
	}</pre>
<p>Do you remember how I said our SetWindowTitle was a special mutator? Here it is. We could just stick with setting our _windowTitle member variable, but that would make this function useful only in the GamePreLoad method, which is called before the game window is created. This method, however, allows us to find out if the window has been created already. If it has, it updates the title there, as well, allowing for us to, for example, display the game score in the window&#8217;s title (not recommended, and I will not be showing you how to do so.)</p>
<p><strong>Moving on</strong><br />
Well, we&#8217;ve got our engine laid out, and it&#8217;s something that we&#8217;ll be able to use in future projects as well as this one &#8211; we&#8217;ll just need to change the contents of our game functions (GamePreLoad, GameInit, etc), though we might want to replace the namespace (D3DPong) with another at a later date. Now that we&#8217;ve got the hard part out of the way, we are going to make changes to the WinMain.cpp file that we created in the last tutorial, so that we can call our GamePreLoad function and actually make use of the game engine. You just got done with a lot of code, so I won&#8217;t hold it against you if you go take a breather, get some soda, or play a game for a while.</p>
<p><strong>Code Change Set 1: WinMain.cpp</strong><br />
All of these changes will be to the WinMain.cpp file.</p>
<p>For starters, scroll to the top of the file, and include CGameEngine.cpp after including WinMain.h</p>
<pre class="brush: cpp; toolbar: false;">#include &quot;WinMain.h&quot;
#include &quot;CGameEngine.h&quot;</pre>
<p>Remove g_bGameOver variable declaration. We&#8217;re going to be using our game engine&#8217;s GetGameRunning accessor in its place. Don&#8217;t worry about replacing it anywhere in code yet, we&#8217;ll do that on our way through.</p>
<p>We&#8217;re going to add a preprocessor directive to create an alias for CGameEngine::Instance(), to make it easier to access our game engine. Add the following after the two include directives:</p>
<pre class="brush: cpp; toolbar: false;">#define GEInstance D3DPong::CGameEngine::Instance()

using namespace D3DPong;</pre>
<p>This will allow us an easier method of getting our game engine&#8217;s instance (make sure you don&#8217;t add a semicolon to that preprocessor macro &#8211; if you do, we can&#8217;t use GEInstance->method. We are then telling our engine that this source file will be using the D3DPong namespace, so that we don&#8217;t have to prefix all of our engine features with <i>D3DPong::</i>.</p>
<p>Now, search for:</p>
<pre class="brush: cpp;">	case WM_QUIT:
	case WM_CLOSE:
	case WM_DESTROY:{
		g_bGameOver = true;
					} break;</pre>
<p>and replace it with:</p>
<pre class="brush: cpp;">	case WM_QUIT:
	case WM_CLOSE:
	case WM_DESTROY:{
		GEInstance-&gt;End();
					} break;</pre>
<p>Makes things easier, doesn&#8217;t it? It also ensures that our GameEnd function is called when we end the game.</p>
<p>Remove the initialization of g_bGameOver from our WinMain function.</p>
<pre class="brush: cpp; toolbar: false;">	// Setup Globals
	g_bGameOver = false;</pre>
<p>We want to allow our game the chance to set up the window and do some other system initialization before we set everything up, so add a call to GamePreLoad() where the g_bGameOver global used to be defined.</p>
<pre class="brush: cpp;">	WNDCLASSEX wc;	// Window Class Structure

	if(!GamePreLoad())
		return 0;

	// Fill the structure</pre>
<p>Now, we want to update our CreateWindowEx call to use the engine&#8217;s width and height, which will be set in GamePreLoad() (or left to their default 640&#215;480 values, if not set):<br />
Replace the entire call with:</p>
<pre class="brush: cpp;">	// Create the Program Window
	hWnd = CreateWindowEx(NULL,										// dwExStyle
		L&quot;GameWindow&quot;,												// Class Name - must match the lpszClassname of a registered window class
		GEInstance-&gt;GetWindowTitle(),								// Window Title
		WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,	// dwStyle
		0, 0,														// Screen Coordinates (X, Y)
		GEInstance-&gt;GetScreenWidth(), GEInstance-&gt;GetScreenHeight(),// Screen Size (Width, Height)
		NULL,														// Parent Window
		NULL,														// Menu
		hInstance,													// Instance Handle
		NULL);														// Extra Parameters</pre>
<p>Below that, after we Show and Update the window, we wil make a call to the game engine&#8217;s Init function:</p>
<pre class="brush: cpp;">	// Initialize the Game Engine
	GEInstance-&gt;SetWindowHandle(hWnd);
	if(!GEInstance-&gt;Init(GEInstance-&gt;GetScreenWidth(), GEInstance-&gt;GetScreenHeight(), GEInstance-&gt;GetColorDepth()))
		return 0;</pre>
<p>We pass the width, height, and color depth to the init function. It was designed this way, again, to allow later classes to inherit from the current engine. A note, for anybody who would do that: you&#8217;ll need to go into CGameEngine.cpp and change <i>CGameEngine* CGameEngine::_instance = new CGameEngine();</i> to <i>CGameEngine* CGameEngine::_instance = new NewClassName();</i>. The singleton method that I used for this project is somewhat rough, and certainly isn&#8217;t the best method, but it&#8217;s one of the easiest to understand for new developers.</p>
<p>Finally, we update our application&#8217;s loop:</p>
<pre class="brush: cpp;">// Message Loop
	while(GEInstance-&gt;GetGameRunning())
	{
		while(PeekMessage(&amp;msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&amp;msg);
			DispatchMessage(&amp;msg);
		}

		GEInstance-&gt;Update();
	}</pre>
<p>Build, run, and see if it comes up with a black screen for you.</p>
<p><strong>Game Setup Test</strong><br />
Now we&#8217;re going to do a quick, easy test to make sure we can properly configure our game at startup (in GamePreLoad). Open Game.cpp, and change GamePreLoad to the following:</p>
<pre class="brush: cpp;">bool GamePreLoad(void)
{
	D3DPong::CGameEngine::Instance()-&gt;SetScreenWidth(800);
	D3DPong::CGameEngine::Instance()-&gt;SetScreenHeight(600);
	D3DPong::CGameEngine::Instance()-&gt;SetWindowTitle(L&quot;Direct3D Pong Tutorial 02&quot;);

	return true;
}</pre>
<p><em>Note: I recommend creating the same Macro we defined in WinMain.cpp, so that you can shorten calls as GEInstance.</em></p>
<p>Run it, and you should have an 800&#215;600 window, titled &#8220;Direct3D Pong Tutorial 02&#8243;.</p>
<p><strong>Conclusion</strong><br />
That concludes the second tutorial in the D3D Pong series. Stay tuned for the next tutorial series, where we create a class to handle and render game sprites and scene objects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minalien.com/index.php/2010/02/15/pong-series-02/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++/D3D Pong Tutorial 01: Setting up the Project</title>
		<link>http://www.minalien.com/index.php/2010/01/24/pong-series-01/</link>
		<comments>http://www.minalien.com/index.php/2010/01/24/pong-series-01/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 01:51:19 +0000</pubDate>
		<dc:creator>Samantha</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Pong (C++/DirectX)]]></category>
		<category><![CDATA[Series]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Game Programming]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[Pong]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Win32]]></category>

		<guid isPermaLink="false">http://www.minalien.com/?p=55</guid>
		<description><![CDATA[Alright, the time has come for me to start up my tutorials again. Suppose I&#8217;ll start off with creating a Pong clone using C++ and Direct3D 9 (the game will be in two dimensions, though, for this product. Perhaps a 3D Pong tutorial can come later.) Welcome to the D3D Pong Tutorial Series Throughout this]]></description>
			<content:encoded><![CDATA[<p>Alright, the time has come for me to start up my tutorials again. Suppose I&#8217;ll start off with creating a Pong clone using C++ and Direct3D 9 (the game will be in two dimensions, though, for this product. Perhaps a 3D Pong tutorial can come later.)</p>
<p><strong>Welcome to the D3D Pong Tutorial Series</strong><br />
Throughout this tutorial series, we will be developing a two-dimensional Pong clone using C++ and Direct3D 9. The tutorial assumes basic knowledge of the C++ language, as well as basic familiarity with namespaces, pointers, and the Microsoft Visual Studio IDE.</p>
<p><strong>System Requirements</strong><br />
This tutorial series assumes that the following are true:<br />
1) You have the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=B66E14B8-8505-4B17-BF80-EDB2DF5ABAD4&#038;displaylang=en">DirectX SDK</a> installed and configured on your system.<br />
2) You know how to configure your IDE to use the header files and libraries included within the DirectX SDK<br />
3) You know how to set up a new Win32 project (vice the use of a console project) in your IDE<br />
4) You know how to add static libraries to a project within your IDE</p>
<p><strong>Tutorial Description</strong><br />
This tutorial covers the first part of the D3D Pong project. We will create a Windows Application project, add the appropriate libraries, and will create the game/application window. In the next tutorial, we will cover setting up Direct3D, and will lay out the framework for the game engine.</p>
<p><span id="more-55"></span></p>
<p><strong>Starting Words</strong><br />
In this tutorial series, I&#8217;m not going to give instructions to any particular IDE. I personally use Visual Studio 2010 B2 right now, and will at least be assuming the use of Visual Studio as far as some code samples go. If your particular compiler toolchain doesn&#8217;t support the </p>
<pre class="brush: cpp; toolbar: false;">#pragma once</pre>
<p>directive, simply replace any instances of that with the following:</p>
<pre class="brush: cpp; toolbar: false;">#ifndef _FILENAME_H_
#define _FILENAME_H_</pre>
<p>and put a</p>
<pre class="brush: cpp; toolbar: false;">#endif</pre>
<p>at the end of your file. This should be habit for most C++ developers, but I&#8217;m including this notice for the people who aren&#8217;t as familiar as the rest of us.</p>
<p><strong>Project Setup</strong><br />
Go ahead and create a new Win32 Project within your IDE. Make sure that you are creating an empty Windows Application project, without MFC or any other fancy ties.</p>
<p>At this point in the project, we&#8217;re only going to add a single library to the project: winmm.lib.</p>
<p><strong>Code Listing 1: WinMain.h</strong></p>
<pre class="brush: cpp;">#pragma once

// Trim the size of Windows.h
#define WIN32_LEAN_AND_MEAN

// Global Header Files
#include &lt;Windows.h&gt;

// Function Declarations
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int);
LRESULT CALLBACK WinProc(HWND, UINT, WPARAM, LPARAM);</pre>
<p>This header should look standard to anybody with any Win32 API experience. Defining WIN32_LEAN_AND_MEAN strips a lot of the contents of Windows.h that we&#8217;ll never need, which will shorten the build time for the project. After bringing in the Windows header, we declare the two primary functions of any Windows application: WinMain and WinProc. Onto the big one..</p>
<p><strong>Code Listing 2: WinMain.cpp</strong></p>
<pre class="brush: cpp;">#include &quot;WinMain.h&quot;

// Global Variables
bool g_bGameOver;</pre>
<p>We start by including the WinMain.h header file that we created from the first code block, then define a global boolean variable called g_bGameOver. This variable will actually later be <em>declared</em> in our engine&#8217;s main header as an external variable, so that the rest of the game code can access it, but we are going to have the declaration done within WinMain.cpp.</p>
<pre class="brush: cpp;">// Window Callback
LRESULT CALLBACK WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
		// Called when the game window is closed
	case WM_QUIT:
	case WM_CLOSE:
	case WM_DESTROY:{
		g_bGameOver = true;
					} break;
	}

	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}</pre>
<p>This is our Window procedure, which handles all events on the game window. We are only worried about three events, which all relate to the same thing: the user exited the game. Through this method, we can perform any last-minute computations before we actually exit the application.</p>
<pre class="brush: cpp;">// Application Entry Point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
{
	// Local Variables
	MSG msg;		// Message Structure
	HWND hWnd;		// Window Handle
	WNDCLASSEX wc;	// Window Class Structure

	// Setup Globals
	g_bGameOver = false;</pre>
<p>Moving onto the Application&#8217;s entry point, we declare three variables in the local scope to hold our messages, our window handle, and the window structure itself, then assign a value of <em>false</em> to the g_bGameOver global.</p>
<pre class="brush: cpp;">
	// Fill the structure
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WinProc;
	wc.cbClsExtra = NULL;
	wc.cbWndExtra = NULL;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = L&quot;GameWindow&quot;;
	wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

	// Register the structure
	RegisterClassEx(&amp;wc);</pre>
<p>Standard Win32 structure filling. The things of note here are the assigning of a window icon, a cursor, a Small Icon, and most importantly, the window&#8217;s class name. The class name is important because it is what we will use to tell CreateWindowEx what it will use as window class when creating the application window.</p>
<pre class="brush: cpp;">
	// Create the Program Window
	hWnd = CreateWindowEx(NULL,										// dwExStyle
		L&quot;GameWindow&quot;,												// Class Name - must match the lpszClassname of a registered window class
		L&quot;D3D Pong Tutorial&quot;,										// Window Title
		WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,	// dwStyle
		0, 0,														// Screen Coordinates (X, Y)
		640, 480,													// Screen Size (Width, Height)
		NULL,														// Parent Window
		NULL,														// Menu
		hInstance,													// Instance Handle
		NULL);														// Extra Parameters

	// Ensure that there were no creation errors
	if(!hWnd)
	{
		MessageBox(NULL, L&quot;Error Creating Application Window&quot;, L&quot;Fatal Error&quot;, MB_OK | MB_ICONERROR);
		return 0;
	}</pre>
<p>Standard window creation code. Always make sure that you test pivotal objects and ensure that they were actually created before attempting to use them. If our window isn&#8217;t created, we can&#8217;t do anything at all. Note that, like in the class definition, we are putting an L in front of the strings &#8211; this casts native strings into the LPCWSTR type, which will ensure that it is formatted as intended for the window.</p>
<pre class="brush: cpp;">
	// Display the window
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	// Message Loop
	while(!g_bGameOver)
	{
		while(PeekMessage(&amp;msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&amp;msg);
			DispatchMessage(&amp;msg);
		}
	}

	// Exit
	return 0;
}</pre>
<p>Finally, we show the window, do an initial Update call, and begin listening for messages. While this tutorial wasn&#8217;t much, especially for anybody experienced with the Win32 API, it provides us a firm ground on which we can start the rest of the tutorials in the series.</p>
<p><strong>Code Listing 3: WinMain.cpp (Full Listing)</strong><br />
Just for reference, here is the complete WinMain.cpp file:</p>
<pre class="brush: cpp;">#include &quot;WinMain.h&quot;

// Global Variables
bool g_bGameOver;

// Window Callback
LRESULT CALLBACK WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
		// Called when the game window is closed
	case WM_QUIT:
	case WM_CLOSE:
	case WM_DESTROY:{
		g_bGameOver = true;
					} break;
	}

	return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

// Application Entry Point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
{
	// Local Variables
	MSG msg;		// Message Structure
	HWND hWnd;		// Window Handle
	WNDCLASSEX wc;	// Window Class Structure

	// Setup Globals
	g_bGameOver = false;

	// Fill the structure
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WinProc;
	wc.cbClsExtra = NULL;
	wc.cbWndExtra = NULL;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = L&quot;GameWindow&quot;;
	wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

	// Register the structure
	RegisterClassEx(&amp;wc);

	// Create the Program Window
	hWnd = CreateWindowEx(NULL,										// dwExStyle
		L&quot;GameWindow&quot;,												// Class Name - must match the lpszClassname of a registered window class
		L&quot;D3D Pong Tutorial&quot;,										// Window Title
		WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,	// dwStyle
		0, 0,														// Screen Coordinates (X, Y)
		640, 480,													// Screen Size (Width, Height)
		NULL,														// Parent Window
		NULL,														// Menu
		hInstance,													// Instance Handle
		NULL);														// Extra Parameters

	// Ensure that there were no creation errors
	if(!hWnd)
	{
		MessageBox(NULL, L&quot;Error Creating Application Window&quot;, L&quot;Fatal Error&quot;, MB_OK | MB_ICONERROR);
		return 0;
	}

	// Display the window
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	// Message Loop
	while(!g_bGameOver)
	{
		while(PeekMessage(&amp;msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&amp;msg);
			DispatchMessage(&amp;msg);
		}
	}

	// Exit
	return 0;
}</pre>
<p>The remaining tutorials in this series will be set up as a series of code blocks, vice this single, full-listing, except under certain circumstances. I included the full code listing for this because it doesn&#8217;t require a lot of explanation for people who are at least passingly familiar with the Win32 API.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.minalien.com/index.php/2010/01/24/pong-series-01/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
