<?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"
	>

<channel>
	<title>Guy and his Travelling Macbook...</title>
	<atom:link href="http://www.guysherman.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.guysherman.com</link>
	<description>...the scooter files</description>
	<pubDate>Sat, 30 Jan 2010 23:59:34 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.3</generator>
	<language>en</language>
			<item>
		<title>What to do when your car alarm remote dies and nobody sells the right battery</title>
		<link>http://www.guysherman.com/2010/01/31/what-to-do-when-your-car-alarm-remote-dies-and-nobody-sells-the-right-battery/</link>
		<comments>http://www.guysherman.com/2010/01/31/what-to-do-when-your-car-alarm-remote-dies-and-nobody-sells-the-right-battery/#comments</comments>
		<pubDate>Sat, 30 Jan 2010 23:59:34 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[Battery]]></category>

		<category><![CDATA[External]]></category>

		<category><![CDATA[Hack]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=184</guid>
		<description><![CDATA[The other night, my flatmate Dan&#8217;s car alarm remote died, and we couldn&#8217;t find anybody who was open that stocked the right size battery - we needed a 12 volt A27 size battery, the best we could get was an A26, which is too fat to fit in the remote.
So here&#8217;s a couple of pics [...]]]></description>
			<content:encoded><![CDATA[<p>The other night, my flatmate Dan&#8217;s car alarm remote died, and we couldn&#8217;t find anybody who was open that stocked the right size battery - we needed a 12 volt A27 size battery, the best we could get was an A26, which is too fat to fit in the remote.</p>
<p>So here&#8217;s a couple of pics of the scheme that I devised&#8230;</p>
<div id="attachment_186" class="wp-caption alignnone" style="width: 310px"><a href="http://www.guysherman.com/wp-content/uploads/27-01-10_2210.jpg"><img class="size-medium wp-image-186" title="Internals" src="http://www.guysherman.com/wp-content/uploads/27-01-10_2210-300x225.jpg" alt="An external battery wired into the remote." width="300" height="225" /></a><p class="wp-caption-text">An </p></div>
<div id="attachment_185" class="wp-caption alignnone" style="width: 310px"><a href="http://www.guysherman.com/wp-content/uploads/27-01-10_2209.jpg"><img class="size-medium wp-image-185" title="Battery" src="http://www.guysherman.com/wp-content/uploads/27-01-10_2209-300x225.jpg" alt="A blury pic of the external battery" width="300" height="225" /></a><p class="wp-caption-text">A blury pic of the external battery</p></div>
<p>We took the next 12V battery we could get, and cellotaped some wires to it. We then twisted the other ends of the wires around the battery contacts of the remote, and wedged the old battery in to make it snug. Voila, one working car remote with external power-supply.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2010/01/31/what-to-do-when-your-car-alarm-remote-dies-and-nobody-sells-the-right-battery/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Learning DirectX and C++: Step 3, Timing and Text</title>
		<link>http://www.guysherman.com/2010/01/23/learning-directx-and-c-step-3-timing-and-text/</link>
		<comments>http://www.guysherman.com/2010/01/23/learning-directx-and-c-step-3-timing-and-text/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 20:38:09 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[C++]]></category>

		<category><![CDATA[DirectX]]></category>

		<category><![CDATA[Performance Counter]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=176</guid>
		<description><![CDATA[I&#8217;ve pondered, for a while, on the merits of me writing out every lesson I learn on my journey to become a game programmer, and I think that the HOWTO format is not going to be sustainable. So, from now on I&#8217;ll be jotting down some notes, and some key points, but I&#8217;ll be dispensing [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve pondered, for a while, on the merits of me writing out every lesson I learn on my journey to become a game programmer, and I think that the HOWTO format is not going to be sustainable. So, from now on I&#8217;ll be jotting down some notes, and some key points, but I&#8217;ll be dispensing with full code listings and blow-by-blow coverage of what&#8217;s going on.</p>
<p>So, on to timers and clocks in DirectX.</p>
<p><span id="more-176"></span></p>
<h3>Timing is everything</h3>
<p>Clearly, animation, physics and many other calculations need to be based on some measure of time. Ideally we&#8217;d like to know how long since the last frame. We&#8217;d probably also like to know how long we&#8217;ve been running for, and we&#8217;d also like to know the elapsed time versus &#8220;game&#8221; time (wall-clock versus time actually spent playing).</p>
<p>So, the first order of business is finding out the current time. Windows has the Performance Timer, and it measures in <strong>counts</strong>. We can find out how many counts there are per second and thus convert all our timings to seconds. The following functions are of use to us:</p>
<pre style="padding-left:30px;">        QueryPerformanceCounter( LARGE_INTEGER* currentTime ); // Writes the current time in counts into the address pointed to by currentTime
        QueryPerformanceFrequency( LARGE_INTEGER* countsPerSec ); // Get how many seconds per count there are</pre>
<p>So, we can quite easily get the current time in seconds (not entirely sure since when, but hey it doesn&#8217;t really matter). If we store this value, and then get a new value some time from now we can easily find out a measure of the time between this. So our class will have a private member which stores the last time value we queried, and also the last delta we worked out. We&#8217;ll then have a <strong>tick</strong><em> </em>member function to refresh this. On might like to call this every frame or something.</p>
<p>So, how about total time? We&#8217;ll store the time when we start the timer, and then we can get a delta between the very first time and now. To allow us to pause the clock, we&#8217;ll keep track of the time whenever we pause it, and whenever we unpause the clock we&#8217;ll increment a counter of the time spent paused with the delta between pausing and unpausing - then, if we want to ignore time spent paused we simply subtract that from the overall elapsed time since we started. We&#8217;ll also store the current time every time we tick. I can&#8217;t see much point from the way the clock is implemented in the Luna book, but I&#8217;m going to use the current time member in all the other methods, rather than re-querying the current time. My reason for this is so that we truly quantise time, rather than have slight differences part way through the frame. In all likelihood the timer is not accurate enough for this to be an issue, but we&#8217;ll be perfectionist.</p>
<p>It&#8217;d be nice to be able to reset our timer as well.</p>
<h3>Text</h3>
<p>Oddly enough, DirectX has built in text functionality, so why XNA uses sprite-sheet based text drawing is a mystery to me. I guess maybe the xbox does not have a comparable font engine to windows, and as such all xbox code needs to use sprite-based fonts. Makes sense I guess.</p>
<p>Anyhow, to do text you need to describe the font that you want, and then get DirectX to create it and return a pointer to it for you. Then you simply draw the text. I&#8217;m going to stick the code in my initialiseDirect3d() member function. The code you need to describe the font is the following:</p>
<pre style="padding-left:30px">        D3DX10_FONT_DESC font;
	font.Height = 24;
	font.Width = 0;
	font.Weight = 0;
	font.MipLevels = 1;
	font.Italic = false;
	font.CharSet = DEFAULT_CHARSET;
	font.OutputPrecision = OUT_DEFAULT_PRECIS;
	font.Quality = DEFAULT_QUALITY;
	font.PitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
	wcscpy(font.FaceName, L"Times New Roman");

	D3DX10CreateFontIndirect(this-&gt;device, &amp;font, &amp;( this-&gt;defaultFont ) );</pre>
<p>Finally I&#8217;ll draw the text in my draw method, outputting the frame rate and last frame time, using the following method:</p>
<pre style="padding-left: 90px; ">INT ID3DX10Font::DrawText(
    LPD3DX10SPRITE pSprite,  // Can be null
    LPCSTR pString,
    INT Count, // -1 seems to output the whole string
    LPRECT pRect, // can just use a zero width/height to position text if
    UINT Format, // you use DT_NOCLIP here
    D3DXCOLOR Color
);</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2010/01/23/learning-directx-and-c-step-3-timing-and-text/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Learning DirectX and C++: Step 2, Initialise DirectX</title>
		<link>http://www.guysherman.com/2010/01/09/learning-directx-and-c-step-2-initialise-directx/</link>
		<comments>http://www.guysherman.com/2010/01/09/learning-directx-and-c-step-2-initialise-directx/#comments</comments>
		<pubDate>Sat, 09 Jan 2010 05:29:41 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[C++]]></category>

		<category><![CDATA[DirectX]]></category>

		<category><![CDATA[Win32]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=166</guid>
		<description><![CDATA[In order to make the most simple use of DirectX we must set up the required infrastructure. This is as follows:

A swap chain (at least two areas of memory, one for drawing into, one for displaying to the screen).
A RenderTargetView (a reference to the area of memory from the swap chain for drawing into).
A Depth/Stencil [...]]]></description>
			<content:encoded><![CDATA[<p>In order to make the most simple use of DirectX we must set up the required infrastructure. This is as follows:</p>
<ul>
<li>A swap chain (at least two areas of memory, one for drawing into, one for displaying to the screen).</li>
<li>A RenderTargetView (a reference to the area of memory from the swap chain for drawing into).</li>
<li>A Depth/Stencil buffer, and a view onto it. (Used to help decided whether any given pixel should be drawn).</li>
<li>Bind the RT (RenderTarget) and Depth/Stencil views to an Output Merger stage.</li>
<li>Set the Viewport (a sub-rectangle of the BackBuffer that we will draw to).</li>
</ul>
<p>Naturally after we have set up this infrastructure we have repeatedly draw some sort of scene; we will get to that after we have discussed the topics above.</p>
<p><span id="more-166"></span><br />
<h3>The Swap Chain</h3>
<p>The Swap Chain is an object which manages a number of frame buffers for us, typically two or more. One of the frame buffers (that is, an area of memory which can contain an image we generate) is for us to draw into, another is what is currently displayed on screen, and if needed, one can introduce more frame buffers, but we won&#8217;t look at that for now. We&#8217;re going to create a Swap Chain with two frame buffers in it, and it will allow us to &#8220;swap&#8221; them, so that after we have finished drawing, we can display what we have just drawn on the screen and begin drawing the next frame in the frame buffer that was just on screen.</p>
<p>What I have done, is added a couple of pointers, and a member function to the <strong>protected</strong> section of my <em>Form</em> class:</p>
<pre style="padding-left:30px;">                // We do our directX initialisation in here
		virtual bool initialiseDirect3d();

                ID3D10Device	*device;
		IDXGISwapChain	*swapChain;</pre>
<p>The definition of the <em>initialiseDirect3d()</em> method is as follows:</p>
<pre style="padding-left:30px;">	DXGI_SWAP_CHAIN_DESC scDesc;
	scDesc.BufferDesc.Width = this-&gt;width;
	scDesc.BufferDesc.Height = this-&gt;height;
	scDesc.BufferDesc.RefreshRate.Numerator = 60;
	scDesc.BufferDesc.RefreshRate.Denominator = 1;
	scDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	scDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	scDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	// Set it up so there is no multi-sampling on the back-buffer
	scDesc.SampleDesc.Count = 1;
	scDesc.SampleDesc.Quality = 0;

	scDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	scDesc.BufferCount = 1;
	scDesc.OutputWindow = this-&gt;formWindowHandle;
	scDesc.Windowed = true;
	scDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	scDesc.Flags = 0;

	UINT createDeviceFlags = 0;
#if defined(DEBUG)  || defined(_DEBUG)
	createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif
	HRESULT createSuccess = D3D10CreateDeviceAndSwapChain(0, D3D10_DRIVER_TYPE_HARDWARE, 0, createDeviceFlags, D3D10_SDK_VERSION, &amp;scDesc, &amp;(this-&gt;swapChain), &amp;(this-&gt;device));

	if ( FAILED( createSuccess ) )
	{
		MessageBox(0, L"CreateDeviceAndSwapChain FAILED", 0, 0);
		return false;
	}

	return true;</pre>
<p>Finally I have added a call to <em>initialiseDirect3d</em> from our <em>Run</em> member function, just after the calls to <em>ShowWindow()</em> and <em>UpdateWindow()</em>.</p>
<h3>The Render Target View</h3>
<p>In DirectX, resources (such as the backbuffer) are bound to pipeline stages (such as the output merge stage), but not directly. First we must create a <em>View</em> of that resource, and that view will be bound to the pipeline stage. The backbuffer was created when we created the D3D10 Device and the Swap Chain, now we need to create a view of it that we can bind to pipeline stages.</p>
<p>In order to do this, we must get a pointer to the backbuffer as an ID3D10Texture2D instance, and then create an ID3D10RenderTargetView. We do not need to keep the ID3D10Texture2D pointer after we have used it, but we do need to keep our pointer to the ID3D10RenderTargetView, so we&#8217;ll make it a member of our class, in the protected section.</p>
<pre style="padding-left:30px;">		ID3D10RenderTargetView	*renderTargetView;</pre>
<p>To our <em>initialiseDirect3d()</em> member function we add a few lines of code to get the back buffer, create the render target view, and release the reference to the backbuffer afterwards:</p>
<pre style="padding-left:30px;">	// Get a reference to the back buffer
        ID3D10Texture2D *backBuffer;
	this-&gt;swapChain-&gt;GetBuffer(0, __uuidof(ID3D10Texture2D), reinterpret_cast(&amp;backBuffer));

        // Create the RT View
	this-&gt;device-&gt;CreateRenderTargetView(backBuffer, 0, &amp;(this-&gt;renderTargetView));

	// Release the reference to the backbuffer.
        if ( backBuffer )
	{
		backBuffer-&gt;Release();
	}
	backBuffer = NULL;</pre>
<p>Just a few more steps to go&#8230;</p>
<h3>The Depth/Stencil Buffer</h3>
<p>The <em>Depth/Stencil</em> buffer is another area of memory, which is used to inform the <em>Depth</em> and <em>Stencil</em> tests respectively. These tests help the GPU know whether or not to overwrite a given pixel in the back buffer. We&#8217;ll probably talk about them in more detail later. We&#8217;ll need to add two more pointers as members to our <em>Form</em> class: one for the actual memory buffer (we&#8217;ll add it as a ID3D10Texture2D), and one for the view onto that buffer (we&#8217;ll add it as an ID3D10DepthStencilView).</p>
<pre style="padding-left:30px;">		ID3D10Texture2D			*depthStencilBuffer;
		ID3D10DepthStencilView	*depthStencilView;</pre>
<p>Next we add some code to our <em>initialiseDirect3d</em> member function to create the buffer and the view.<br />
First we describe the buffer:</p>
<pre style="padding-left:30px;">	D3D10_TEXTURE2D_DESC depthStencilDesc;
	depthStencilDesc.Width = this-&gt;width;
	depthStencilDesc.Height = this-&gt;height;
	depthStencilDesc.MipLevels = 1;
	depthStencilDesc.ArraySize = 1;
	depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthStencilDesc.SampleDesc.Count = 1;
	depthStencilDesc.SampleDesc.Quality = 0;
	depthStencilDesc.Usage = D3D10_USAGE_DEFAULT;
	depthStencilDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
	depthStencilDesc.CPUAccessFlags = 0;
	depthStencilDesc.MiscFlags = 0;</pre>
<p>Note that the <em>SampleDesc</em> field values must be the same as for the render target.</p>
<p>Next we create the buffer and view:</p>
<pre style="padding-left:30px;">	createSuccess = this-&gt;device-&gt;CreateTexture2D(&amp;depthStencilDesc, 0, &amp;(this-&gt;depthStencilBuffer));
	if ( FAILED( createSuccess ) )
	{
		MessageBox(0, L"CreateTexture2D FAILED", 0, 0);
		return false;
	}

	createSuccess = this-&gt;device-&gt;CreateDepthStencilView(this-&gt;depthStencilBuffer, 0, &amp;(this-&gt;depthStencilView));
	if ( FAILED( createSuccess ) )
	{
		MessageBox(0, L"CreateDepthStencilView FAILED", 0, 0);
		return false;
	}</pre>
<p>Finally, we need to bind both the RT view and the Depth/Stencil view to the Output Merger pipeline stage. Effectively this tells the GPU which render target, and which depth/stencil buffer to use for now.</p>
<pre style="padding-left:30px;">	this-&gt;device-&gt;OMSetRenderTargets(1, &amp;(this-&gt;renderTargetView), &amp;(this-&gt;depthStencilView));</pre>
<h3>The Viewport</h3>
<p>The last bit of infrastructure we must set up is the <em>Viewport</em>. This is effectively a window within our back buffer, to which drawing is constrained. We&#8217;ll use the whole backbuffer for now. But you could use a smaller viewport for effects like picture-in-picture, etc. Simply, we describe the viewport, and then set it; we do not need to keep it around or anything, as it is really part of the state of the GPU.</p>
<pre style="padding-left:30px;">	D3D10_VIEWPORT viewPort;
	viewPort.TopLeftX = 0;
	viewPort.TopLeftY = 0;
	viewPort.Width = this-&gt;width;
	viewPort.Height = this-&gt;height;
	viewPort.MinDepth = 0.0f;
	viewPort.MaxDepth = 1.0f;

	this-&gt;device-&gt;RSSetViewports(1, &amp;vp);</pre>
<h3>Let&#8217;s do something with it all&#8230;</h3>
<p>Right, now that we&#8217;ve done all this hard work, let&#8217;s do something with it&#8230; how about painting the window blue you ask? Great, that&#8217;s just what I was thinking. We&#8217;ll introduce a new member function to our class called <em>Draw</em>, and we&#8217;ll call it from the message handler, in the part of the if statement that we have set aside for consuming the time that we don&#8217;t spend handing messages.</p>
<p>All we do is clear the render target with a specific colour, clear the depth and stencil buffers, and then tell the swap chain to <em>Present</em>, which makes it swap the back buffer with the one currently displayed on screen.</p>
<p>In the protected section:</p>
<pre style="padding-left:30px;">		virtual void draw();</pre>
<p>And the method definition:</p>
<pre style="padding-left:30px;">void Form::draw()
{
	float color[4] = { 0.0f, 0.125f, 0.6f, 1.0f };
	this-&gt;device-&gt;ClearRenderTargetView(this-&gt;renderTargetView, color );

	this-&gt;device-&gt;ClearDepthStencilView( this-&gt;depthStencilView, D3D10_CLEAR_DEPTH|D3D10_CLEAR_STENCIL, 1.0f, 0 );

	this-&gt;swapChain-&gt;Present(0, 0);
}</pre>
<p>And that&#8217;s really all there is to it. Once again, I&#8217;ve uploaded the <a href="http://www.guysherman.com/wp-content/uploads/stage3.zip">code</a>, as a zip file this time. Also, don&#8217;t forget to link against d3d10.lib and d3dx10.lib.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2010/01/09/learning-directx-and-c-step-2-initialise-directx/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Learning C++ and DirectX: Step one, create a window.</title>
		<link>http://www.guysherman.com/2009/12/22/learning-c-and-directx-step-one-create-a-window/</link>
		<comments>http://www.guysherman.com/2009/12/22/learning-c-and-directx-step-one-create-a-window/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 07:53:41 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[C++]]></category>

		<category><![CDATA[Win32]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=142</guid>
		<description><![CDATA[I planned, quite some time ago now, to start writing a series covering my journey, well I&#8217;ve finally gotten round to the first bit of it. Hopefully I&#8217;ll write a bit more frequently than I have recently, but we&#8217;ll see - I&#8217;m not making any promises.
I&#8217;ve bought some books on C++ and DirectX and have [...]]]></description>
			<content:encoded><![CDATA[<p>I planned, quite some time ago now, to start writing a series covering my journey, well I&#8217;ve finally gotten round to the first bit of it. Hopefully I&#8217;ll write a bit more frequently than I have recently, but we&#8217;ll see - I&#8217;m not making any promises.</p>
<p>I&#8217;ve bought some books on C++ and DirectX and have started working through them. The book I am working through at the moment <strong><a title="Introduction to 3D Game Programming with DirectX 10" href="http://www.d3dcoder.net/d3d10.aspx" target="_blank">Introduction to 3D Game Programming with DirectX 10</a></strong>, has based its demos on a small, bespoke application framework. Whilst this is all well and good, I find that I learn by doing, by writing the programs myself, rather than reviewing demo code. So, I&#8217;ll be starting from scratch, writing my own, similar application framework, following the lessons in the book, and blogging about it here. So, onto &#8220;Step one, create a window&#8221;.<span id="more-142"></span></p>
<h3>Creating the Visual Studio Project</h3>
<p>To start with, create a new Win32 project in Visual C++. Do this by selecting File -&gt; New -&gt; New Project, then by selecting Win32 in the Project Types pane, and Win32 in the Project Templates pane. Give it a name, and a location, and click OK. You&#8217;ll then be presented with a wizard. Click Next, then tick the box which says &#8220;Empty project&#8221;. You should now have a solution with a single project in it. The project should contain three folders &#8220;Header Files&#8221;, &#8220;Resource Files&#8221; and &#8220;Source Files&#8221;.</p>
<div id="attachment_148" class="wp-caption alignnone" style="width: 310px"><a href="http://www.guysherman.com/wp-content/uploads/addnewproject.png"><img class="size-medium wp-image-148" title="Add New Project wizard" src="http://www.guysherman.com/wp-content/uploads/addnewproject-300x179.png" alt="Figure 1: Creating a new Win32 project in Visual C++" width="300" height="179" /></a><p class="wp-caption-text">Figure 1: Creating a new Win32 project in Visual C++</p></div>
<p>Now we can start coding. We&#8217;ll start by making a flat, single-file program which throws up a window, and then we&#8217;ll go about abstracting the window functionality into a class. We could have got Visual Studio to create a whole bunch of code that creates the window for us, but that skips the learning process, and gives us over-complicated code.</p>
<h3>Create Your C++ File</h3>
<p>I&#8217;ve uploaded the code for the first stage of our lesson <a href="http://www.guysherman.com/wp-content/uploads/stage1.cpp">here</a>.</p>
<p>I&#8217;ll go through it section by section, although I&#8217;ve stripped out the comments because I&#8217;m giving an explanation here.</p>
<pre style="padding-left: 30px;">#include &lt;windows.h&gt;</pre>
<p>This tells the C++ compiler to include the headers for the Win32 API. This gives us all the declarations we need to write code against the Win32 API. Angle brackets indicate that the file is in one of the include path directories. Alternatively we could use speech marks, and give a file name relative to our project folder.</p>
<pre style="padding-left: 30px;">HWND MainWindowHandle = 0;</pre>
<p>This declares our window handle. It&#8217;s a variable which will hold an unique id for our window when we get windows to create it.</p>
<pre style="padding-left:30px">bool InitWindow(HINSTANCE hInstance, int showCmd);
int Run();
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);</pre>
<p>We declare the prototypes for some functions:</p>
<ul>
<li>InitWindow will be the function which initialises our window and throws it onto the screen.</li>
<li>Run will handle the message queue.</li>
<li>WndProc is called while handling the message queue, and actually handles the messages we want to handle (like when the window closes)</li>
</ul>
<pre style="padding-left: 30px">int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nShowCmd)
{
    if ( !InitWindow( hInstance, nShowCmd ) )
        return 0;

    return Run();
}</pre>
<p>This is our entry-point. WinMain, is the windows equivalent of main(). All we do here is initialise our window and, if it was successful, start handling messages.</p>
<pre style="padding-left: 30px;">bool InitWindow(HINSTANCE instanceHandle, int showCmd)
{
	WNDCLASS wc;
	wc.style			= CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc			= WndProc;
	wc.cbClsExtra			= 0;
	wc.cbWndExtra			= 0;
	wc.hInstance			= instanceHandle;
	wc.hIcon			= LoadIcon(0, IDI_APPLICATION);
	wc.hCursor			= LoadCursor(0, IDC_ARROW);
	wc.hbrBackground		= (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszMenuName		        = 0;
	wc.lpszClassName		= L"BasicWndClass";			

	if(!RegisterClass(&amp;wc))
	{
		MessageBox(0, L"RegisterClass FAILED", 0, 0);
		return false;
	}

	MainWindowHandle = CreateWindow(
		L"BasicWndClass",
		L"Basic Win32 Window",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		0,
		0,
		instanceHandle,
		0);						

	if ( MainWindowHandle == 0 )
	{
		MessageBox(0, L"CreateWindow FAILED", 0, 0);
		return false;
	}

	ShowWindow(MainWindowHandle, showCmd);
	UpdateWindow(MainWindowHandle);

	return true;
}</pre>
<p>This is where a bunch of the magic happens. In the first &#8220;paragraph&#8221; we create a structure and fill it out. This structure defines a class. If you think of the window you see on screen as a class, we&#8217;re defining that class here. (see the cpp file for the specifics, its got comments in). The next part registers the class with windows, effectively we&#8217;re saying &#8220;hey Windows, here&#8217;s a window class definition that I want to be able to make instances (windows) of.&#8221; After we&#8217;ve registered the class we can create a window from it with our call to CreateWindow. The parameters are the class name, the window name, the window style, the x, y, width and height, the handle of the parent, the handle of the menu, the handle of the windows application instance, and potential extra parameters. If that worked we continue onwards to show, and update the window. Simple.</p>
<pre style="padding-left: 30px;">int Run()
{
	MSG msg = {0};

	while ( msg.message != WM_QUIT )
	{
		if ( PeekMessage( &amp;msg, NULL, 0, 0, PM_REMOVE ) )
		{
			TranslateMessage(&amp;msg);
			DispatchMessage(&amp;msg);
		}
		else
		{

		}

	}

	return (int)msg.wParam;

}</pre>
<p>This method effectively loops until we get a WM_QUIT message. Some people like to do it slightly differently and use GetMessage instead of PeekMessage. GetMessage blocks if there are no messages, which is not particularly useful if you want to use the time not spent handling messages to update your game, or draw your scene. If you&#8217;re implementing a renderer that runs in a separate thread, you would probably want to use GetMessage. The calls to TranslateMessage and DispatchMessage do some processing on the messages (like converting key values), and dispatch the message to your WndProc respectively. We&#8217;ll eventually expand the else bit to draw a scene and stuff.</p>
<pre style="padding-left: 30px;">LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{

	switch ( msg )
	{
		case WM_DESTROY:
			PostQuitMessage(0);
			return 0;
	}

	return DefWindowProc(hWnd, msg, wParam, lParam);
}</pre>
<p>Here we handle the messages, in this case if we get a WM_DESTROY (from someone going ALT+F4, or clicking the X), then we post a WM_QUIT (which will end the loop in Run) and return.</p>
<p>This code should run and you should get a window with a white background, and the title &#8220;Basic Win32 Window&#8221;.</p>
<h3>It&#8217;s Refactoring Time</h3>
<p>What we have is all well and good, some simple code to create a Win32 window. What we have, however, does not represent particularly good design; it would be far better if we abstracted this code into a class which we could instantiate from WinMain, and call Start, or Run or something. So what we&#8217;ll do is cover the process of abstracting our code into a class - we&#8217;ll call it Form. I&#8217;ve uploaded the following files which, once again, give you the full source: <a href="http://www.guysherman.com/wp-content/uploads/stage2.cpp">stage2.cpp</a>, <a href="http://www.guysherman.com/wp-content/uploads/form.cpp">form.cpp</a>, <a href="http://www.guysherman.com/wp-content/uploads/form.h">form.h</a>.</p>
<p>Lets talk through Form.h: First we include a few things like the Win32 API, and the string and exception classes from the STL (Standard Template Library, the primary C++ framework).</p>
<pre style="padding-left: 30px;">#include
#include
#include</pre>
<p>Next we declare our class, that is we write down a skeleton of the class, with all the member variables, and prototypes of all the member functions:</p>
<pre style="padding-left: 30px;">        class Form
	{
	public:

	protected:

	};</pre>
<p>Inside &#8220;public:&#8221; we have:</p>
<pre style="padding-left: 30px;">                Form(HINSTANCE appInstanceHandle);
		virtual ~Form(void);

		int Run(int showCmd);

		void SetCaption( std::wstring windowCaption );

		void SetWidth( int windowWidth );
		void SetHeight( int windowHeight );</pre>
<p>And inside &#8220;protected:&#8221; we have:</p>
<pre style="padding-left: 30px;">		virtual bool initialiseWindow(HINSTANCE appInstanceHandle);

		virtual LRESULT WndProc(HWND windowHandle, UINT message, WPARAM wParam, LPARAM lParam);
		static LRESULT CALLBACK MainWndProc(HWND windowHandle, UINT message, WPARAM wParam, LPARAM lParam);

		HWND formWindowHandle;
		HINSTANCE appInstanceHandle;

		int width;
		int height;
		std::wstring windowCaption;</pre>
<p>I won&#8217;t put the full code for Form.cpp in here because it&#8217;s very similar to what I&#8217;ve talked about already. Rather I&#8217;ll talk about the changes I made. The first funny thing that you&#8217;ll notice is that we have to member functions which look like they deal with messages. One is MainWndProc, and it is static. The other is WndProc, and it is an instance member. You&#8217;ll see in Form.cpp that when we define our window, we pass a pointer to MainWndProc, instead of WndProc (like we did earlier). MainWndProc then handles the WM_CREATE message, gets a pointer to the class instance, and forever more delegates message handling to the instance member WndProc.</p>
<pre style="padding-left: 30px;">        wc.lpfnWndProc			= &amp;Form::MainWndProc;</pre>
<p>and the code for MainWndProc:</p>
<pre style="padding-left: 30px;">LRESULT CALLBACK Form::MainWndProc(HWND windowHandle, UINT message, WPARAM wParam, LPARAM lParam)
{
	static Form* me = 0;

	switch ( message )
	{
		case WM_CREATE:
		{
			CREATESTRUCT* createStruct = (CREATESTRUCT*)lParam;
			me = (Form*)createStruct-&gt;lpCreateParams;
			return 0;
		}
	}

	if ( me )
	{
		return me-&gt;WndProc(windowHandle, message, wParam, lParam);
	}
	else
	{
		return DefWindowProc(windowHandle, message, wParam, lParam);
	}
}</pre>
<p>I&#8217;ve also moved the CreateWindow call (as well as ShowWindow and UpdateWindow) to the start of the Run member function - meaning that the window doesn&#8217;t show until we actually want to start handling messages for it.</p>
<p>You&#8217;ll notice in Form.h that I&#8217;ve added some members for width, height and windowCaption so that we can customise these aspects of our window. There are setter functions for these:</p>
<pre style="padding-left: 30px;">void Form::SetCaption(std::wstring windowCaption)
{
	this-&gt;windowCaption = windowCaption;
}

void Form::SetWidth(int windowWidth)
{
	this-&gt;width = windowWidth;
}

void Form::SetHeight(int windowHeight)
{
	this-&gt;height = windowHeight;
}</pre>
<p>And you can work out how I&#8217;ve changed the call to CreateWindow.</p>
<p>That really just leaves our constructor, and empty destructor:</p>
<pre style="padding-left: 30px;">Form::Form(HINSTANCE appInstanceHandle)
{
	windowCaption = L"Abstracted Win32 Window";
	width = 800;
	height = 600;

	this-&gt;appInstanceHandle = appInstanceHandle;

	if ( !this-&gt;initialiseWindow(appInstanceHandle) )
		throw std::exception("Could not initialise window.");
}

Form::~Form(void)
{
}</pre>
<p>You&#8217;ll also find that stage2.cpp is far simpler because now all we have to do is create our Form, set its properties, and then run it.</p>
<h3>Conclusion</h3>
<p>We&#8217;ve learned how to create a Win32 window, and also how to wrap that up in a class. The implementation I&#8217;ve show here isn&#8217;t at all fancy, but it works and it illustrates the principal. I&#8217;ll be working on it in the future as I work my way through learning DirectX. That said, having written this article I&#8217;m not too sure whether I&#8217;ll keep up with writing detailed articles for the rest of my journey, probably just short notes on what I&#8217;ve learned - I really don&#8217;t have time for more.</p>
<p>Please leave any comments below :).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2009/12/22/learning-c-and-directx-step-one-create-a-window/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Learning DirectX and C++</title>
		<link>http://www.guysherman.com/2009/10/17/learning-directx-and-c/</link>
		<comments>http://www.guysherman.com/2009/10/17/learning-directx-and-c/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 23:26:47 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=137</guid>
		<description><![CDATA[After spending a bunch of time mucking around with XNA, I&#8217;ve decided to learn DirectX and C++. I&#8217;m going to write a series of short lessons as I do. Not from the perspective of an expert, but from the perspective of someone teaching themself, with a bit of good Software Engineering knowledge mixed in. Hopefully [...]]]></description>
			<content:encoded><![CDATA[<p>After spending a bunch of time mucking around with XNA, I&#8217;ve decided to learn DirectX and C++. I&#8217;m going to write a series of short lessons as I do. Not from the perspective of an expert, but from the perspective of someone teaching themself, with a bit of good Software Engineering knowledge mixed in. Hopefully I should have the first post out sometime today.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2009/10/17/learning-directx-and-c/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Lions and tigers and &#8230; Giant Robots, oh yeah!</title>
		<link>http://www.guysherman.com/2009/08/05/lions-and-tigers-and-giant-robots-oh-yeah/</link>
		<comments>http://www.guysherman.com/2009/08/05/lions-and-tigers-and-giant-robots-oh-yeah/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 02:31:53 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=133</guid>
		<description><![CDATA[Tokyo is now officially the most awesome city in the world.
http://quazen.com/arts/visual-arts/gundam-mecha-monument-towers-over-tokyo/
]]></description>
			<content:encoded><![CDATA[<p>Tokyo is now officially the most awesome city in the world.</p>
<p><a href="http://quazen.com/arts/visual-arts/gundam-mecha-monument-towers-over-tokyo/">http://quazen.com/arts/visual-arts/gundam-mecha-monument-towers-over-tokyo/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2009/08/05/lions-and-tigers-and-giant-robots-oh-yeah/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Three reasons I like iPhone OS 3</title>
		<link>http://www.guysherman.com/2009/07/24/three-reasons-i-like-iphone-os-3/</link>
		<comments>http://www.guysherman.com/2009/07/24/three-reasons-i-like-iphone-os-3/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 19:30:44 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[iPhone]]></category>

		<category><![CDATA[iPod]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=125</guid>
		<description><![CDATA[I recently updated my iPod Touch to the latest version of the OS and I&#8217;ve noticed some nice little touches that make the device even more excellent than it used to be.

Select / Cut / Copy / Paste - Tap and drag in notes and mail, and you immediately start selecting text, Tap and hold [...]]]></description>
			<content:encoded><![CDATA[<p>I recently updated my iPod Touch to the latest version of the OS and I&#8217;ve noticed some nice little touches that make the device even more excellent than it used to be.</p>
<ol>
<li>Select / Cut / Copy / Paste - Tap and drag in notes and mail, and you immediately start selecting text, Tap and hold in safari and it selects an entire block of text for you. When you have a selection, a little context ballon comes up to give you options like, Copy, Paste, etc.</li>
<li>Advanced audio controls - it used to be hard to scrub through a track, especially if it was long because the precision on the slider was not very good. Now, if you start scrubbing, but move your finger down (away from the slider itself) it makes your scrubbing more precise. Also, in audio books there is a little button which lets you back up by 30 seconds, and a speed control, so that you can slow the audio book down.</li>
<li>Landscape keyboard in notes - very nice for those of us with larger fingers / thumbs, who like a bit more spacing between our keys.</li>
</ol>
<p>Overall my impression of iPhone OS is that it is catching up quickly, in terms of general features that Windows Mobile has had for a while, but as it does, it revolutionises the usability of the feature - selecting text, and positioning the cursor are two such examples, where Apple have really thought about the issues inherent with controlling a small device with a blunt instrument like your thumb.</p>
<p>Here endeth the fanboyesque rhetoric.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2009/07/24/three-reasons-i-like-iphone-os-3/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Interesting Environmental Talk</title>
		<link>http://www.guysherman.com/2009/07/14/interesting-environmental-talk/</link>
		<comments>http://www.guysherman.com/2009/07/14/interesting-environmental-talk/#comments</comments>
		<pubDate>Tue, 14 Jul 2009 03:45:25 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[Cities]]></category>

		<category><![CDATA[Environment]]></category>

		<category><![CDATA[Genetic Modification]]></category>

		<category><![CDATA[Geoengineering]]></category>

		<category><![CDATA[Nuclear Power]]></category>

		<category><![CDATA[Stewart Brand]]></category>

		<category><![CDATA[TED]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=122</guid>
		<description><![CDATA[I just watched this on TED, its food for thought.

]]></description>
			<content:encoded><![CDATA[<p>I just watched this on <a href="http://www.ted.com">TED</a>, its food for thought.</p>
<p><object width="446" height="326"><param name="movie" value="http://video.ted.com/assets/player/swf/EmbedPlayer.swf"></param><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent"></param><param name="bgColor" value="#ffffff"></param><param name="flashvars" value="vu=http://video.ted.com/talks/embed/StewartBrand_2009S-embed_high.flv&#038;su=http://images.ted.com/images/ted/tedindex/embed-posters/StewartBrand-2009S.embed_thumbnail.jpg&#038;vw=432&#038;vh=240&#038;ap=0&#038;ti=598" /><embed src="http://video.ted.com/assets/player/swf/EmbedPlayer.swf" pluginspace="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent" bgColor="#ffffff" width="446" height="326" allowFullScreen="true" flashvars="vu=http://video.ted.com/talks/embed/StewartBrand_2009S-embed_high.flv&#038;su=http://images.ted.com/images/ted/tedindex/embed-posters/StewartBrand-2009S.embed_thumbnail.jpg&#038;vw=432&#038;vh=240&#038;ap=0&#038;ti=598"></embed></object></p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2009/07/14/interesting-environmental-talk/feed/</wfw:commentRss>
		</item>
		<item>
		<title>My re-vitalised Scooter</title>
		<link>http://www.guysherman.com/2009/05/09/my-re-vitalised-scooter/</link>
		<comments>http://www.guysherman.com/2009/05/09/my-re-vitalised-scooter/#comments</comments>
		<pubDate>Fri, 08 May 2009 23:37:43 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[Re-vitalise]]></category>

		<category><![CDATA[Scooter]]></category>

		<category><![CDATA[Service]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=119</guid>
		<description><![CDATA[Yesterday, whilst making my daily commute to work, my scooter (the one pictured in the theme of this blog) started making an aweful rattling sound, as if something was about to fall of. Something had, in fact, fallen off: the heat-guard from the muffler, and was now rattling around amongst the under-carriage. So, naturally I [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday, whilst making my daily commute to work, my scooter (the one pictured in the theme of this blog) started making an aweful rattling sound, as if something was about to fall of. Something had, in fact, fallen off: the heat-guard from the muffler, and was now rattling around amongst the under-carriage. So, naturally I took my scooter to my scooter people (<a href="http://www.scootling.co.nz">scootling</a>) and asked them to give it a thorough once over while they were at it. </p>
<p>As it turns out it needed a bit of work, but boy did they do a good job! The scooter used to struggle to hit 55km/h on the flat, now it exceeds 60km/h with ease; there is a lot more power up in the top end so that I can power up hills a lot faster, and down hill I can push the speedo as far round as it will go (~70km/h, but I can&#8217;t be sure because the numbers only go up to 60). The brakes have also been replaced and tightened, so they work a lot better, and don&#8217;t jam on any more, and with a new rear tyre I have more confidence in the wet and around corners. It is like riding a new scooter and it has definitely been a highlight of my week.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2009/05/09/my-re-vitalised-scooter/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Interesting article on Alpha Blending</title>
		<link>http://www.guysherman.com/2009/03/19/interesting-article-on-alpha-blending/</link>
		<comments>http://www.guysherman.com/2009/03/19/interesting-article-on-alpha-blending/#comments</comments>
		<pubDate>Thu, 19 Mar 2009 03:06:36 +0000</pubDate>
		<dc:creator>Guy</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.guysherman.com/?p=116</guid>
		<description><![CDATA[I just read this and it seems like Tom has a point. I still have to go over it a few times more and put it into practice before I make judgement.
]]></description>
			<content:encoded><![CDATA[<p>I just read <a href="http://home.comcast.net/~tom_forsyth/blog.wiki.html#%5B%5BPremultiplied%20alpha%5D%5D">this</a> and it seems like Tom has a point. I still have to go over it a few times more and put it into practice before I make judgement.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.guysherman.com/2009/03/19/interesting-article-on-alpha-blending/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
