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

<channel>
	<title>BreakTryCatch</title>
	<atom:link href="http://www.breaktrycatch.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.breaktrycatch.com</link>
	<description></description>
	<lastBuildDate>Sat, 29 Dec 2012 15:48:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Deeper into the Rabbit Hole: C++ Function Pointers and Callbacks</title>
		<link>http://www.breaktrycatch.com/deeper-into-the-rabbit-hole-c-function-pointers-and-callbacks/</link>
		<comments>http://www.breaktrycatch.com/deeper-into-the-rabbit-hole-c-function-pointers-and-callbacks/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 16:04:30 +0000</pubDate>
		<dc:creator>Jon Keon</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[templates]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=949</guid>
		<description><![CDATA[DISCLAIMER: The code shown in this post is not 100% my own original work. It is instead derivative of Elbert Mai&#8217;s post on a CodeProject submission on C++ Callbacks which I have used in a previous post for my Windows framework. Link. My changes are largely cosmetic in terms of formatting and naming in an...]]></description>
			<content:encoded><![CDATA[<h3>DISCLAIMER:</h3>
<p>The code shown in this post is not 100% my own original work. It is instead derivative of Elbert Mai&#8217;s post on a CodeProject submission on C++ Callbacks which I have used in a previous post for my Windows framework. <a title="Elbert Mai's Callbacks" href="http://www.codeproject.com/KB/cpp/CPPCallback.aspx" target="_blank">Link</a>.</p>
<p>My changes are largely cosmetic in terms of formatting and naming in an effort to fully understand what Elbert is doing. I have also fixed some of the code to allow for compiling on MacOS without compiler errors in GCC due to some template issues and I also added the ability to have equality checks between two Functions.</p>
<p>This post is not intended to show that I am the author or originator of the idea but rather to delve deeper into how it works and how it can be used in projects.</p>
<h2>Background:</h2>
<p>When I first started playing around with making my Windows framework I had a rough idea of how I wanted it to work and it involved the use of Function objects as they are implemented in ActionScript 3.0.</p>
<p>Essentially for any function anywhere (including anonymous ones) you can store these in an object called Function, pass them around and invoke them at a later time.</p>
<pre class="brush: as3; title: ; notranslate">
//Assigns the doWork function to the myFunction variable
var myFunction:Function = myClass.doWork;
//Calls myClass.doWork
myFunction();
</pre>
<p>This works extremely well if you want to place these Function objects inside a Dictionary and Key them off of an integer or string. Since the Windows Messaging Pump works by sending different Messages, it would be great to use the Windows Message as the Key and a Function object as the value which can be invoked once the corresponding message is received.</p>
<p>Sadly this isn&#8217;t a native feature of C++. In my research I came across using raw function pointers but the specificity and syntax is complex and confusing and not an ideal path for a generic solution.</p>
<p>Raw function pointers are perfectly fine when you know exactly what type of function is going to be registered all the time&#8230; in which case, why not pass in a reference to the containing class and just call the function directly?</p>
<p>A general solution requires a feature of C++ called templates and that is a whole other can of worms that can be quite complex at first glance.</p>
<p>Fortunately I found Elbert Mai&#8217;s <a title="Elbert Mai's Callbacks" href="http://www.codeproject.com/KB/cpp/CPPCallback.aspx" target="_blank">implementation</a> of Callbacks on CodeProject.com and was able to simply use them.</p>
<p>I had looked at the code but it was overwhelming and it satisfied my needs for the time being.</p>
<p>After working more with C++ I was determined to go back and deconstruct the library, fully understand it, and if possible, improve upon it.</p>
<p>The results are a marginal improvement in that Functions can be equated although I&#8217;m sure there will be those that say they are not actually equal. For the intended purposes that I am using the Function class for, they are indeed equal and it works in all of my test cases. But nothing groundbreaking here.</p>
<p>The real benefit was that I am very familiar and comfortable with all types of Function pointers and in using Template programming with Template Partial Specialization. Learning++;</p>
<h2>Function Pointers:</h2>
<p>There are essentially two types of Function Pointers in C++. (There are technically more if you want to get really in depth, but essentially there are two ways of accessing them).</p>
<p><em>There is a great article on Code Project by Don Clugston that goes very in depth as to how Function Pointers work across different environments and Compilers <a title="Fast Delegates by Don Clugston" href="http://www.codeproject.com/KB/cpp/FastDelegate.aspx">here</a>. He also gives an implementation of Callbacks like Elbert Mai as well.</em></p>
<p>The first type is a <strong>Free Function</strong> pointer which is any static or global function. (A function that does not require an <em>instance</em> of a class to be executed).</p>
<p>The syntax for a <strong>Free Function</strong> pointer is ugly though:</p>
<p><em>&lt;Return Type&gt;</em> (*<em>&lt;Variable Name&gt;</em>)(<em>&lt;Parameter Type&gt;</em> &lt;<em>Parameter Name</em>&gt;);</p>
<p>Where:</p>
<p><em>&lt;Return Type&gt;</em> is the type that the function returns. (void, int, etc)</p>
<p><em>&lt;Variable Name&gt;</em> is the name you want to give your function pointer so you can reference it after.</p>
<p><em>&lt;Parameter Type&gt;</em> is the type of parameter this function takes in.</p>
<p><em>&lt;Parameter Name&gt;</em> is the name of the parameter this function takes in.</p>
<p>This can still be confusing so lets look at an example:</p>
<pre class="brush: cpp; title: ; notranslate">
//Actual void Function that takes in an int
#include &lt;iostream&gt;
void TestFreeFunction(int p) {
	std::cout &lt;&lt; &quot;Value of P is &quot; &lt;&lt; p &lt;&lt; std::endl;
}

//Declares a Free Function Pointer called freeFunctionPointer
//with return type void, and takes in one parameter that is an int
//and maps it to the Global function TestFreeFunction.
void (*freeFunctionPointer)(int parameter) = &amp;TestFreeFunction;
</pre>
<p>Here we have a <strong>Global</strong> function called <strong>TestFreeFunction</strong> that takes in one parameter of type int and return nothing so it&#8217;s return type is void. We create a function pointer with return type of void, give it a name of <strong>freeFunctionPointer</strong> and then specify that it takes in one parameter of type int. We then assign the address of the Function to our Function Pointer variable.</p>
<p>To call the function we simply do the following:</p>
<pre class="brush: cpp; title: ; notranslate">
//To use it, simply place brackets and pass in an int
(*freeFunctionPointer)(7);
</pre>
<p>The second type of Function Pointer is called a <strong>Member Function</strong> pointer. This function pointer requires an instance of a class to be used and complicates things a bit.</p>
<p>The syntax for a Member Function pointer is:</p>
<p><em>&lt;Return Type&gt;</em> (<em>&lt;Class Type&gt;</em>::*<em>&lt;Variable Name&gt;</em>)(<em>&lt;Parameter Type&gt;</em> &lt;<em>Parameter Name</em>&gt;);</p>
<p>This is almost the same as the <strong>Free Function</strong> pointer but instead includes a <em>&lt;Class Type&gt;</em> which is the type of class the function pointer is a part of.</p>
<p>Again an example illustrates it best:</p>
<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;
//Class with Member Function
class TestMemberFunctionClass {

public:
	//Actual Member Function with return type void and takes in one parameter of type int
	void TestMemberFunction(int p) {
		std::cout &lt;&lt; &quot;Value of P is &quot; &lt;&lt; p &lt;&lt; std::endl;
	}
};

//Declares a Member Function Pointer called memberFunctionPointer
//with return type void, and takes in one parameter that is an int
//and with a ClassType of TestMemberFunctionClass
//and maps it to the Member Function in TestMemberClass
void (TestMemberFunctionClass::*memberFunctionPointer)(int parameter) = &amp;TestMemberFunctionClass::TestMemberFunction;
</pre>
<p>Notice that we must specify the class qualifier when taking the address of the Function as well.</p>
<p>In order to call the function:</p>
<pre class="brush: cpp; title: ; notranslate">
//We must have an instance of the class
TestMemberFunctionClass instance;
//To use it, invoke the function pointer on the instance
(instance.*memberFunctionPointer)(7);
</pre>
<p><strong>Member Function</strong> pointers must have an instance specified in order to work. <strong>Member Function</strong> pointers do not point to specific functions on objects. Instead they point to specific functions on a Class Type. The instance qualifies which actual function to invoke.</p>
<h2>The Problem:</h2>
<p>So we have our two Function pointers. What&#8217;s the problem?</p>
<p>Well the problem lies in how specific the Function Pointers are and the fact that the vast majority of them will be <strong>Member Functions</strong>. Looking at our example Member Function pointer that function pointer is only valid for functions that return void, take in one and only one parameter that is an int and are part of the TestMemberFunctionClass.</p>
<p>Obviously this severely limits the usefulness of this variable.</p>
<p>To use only raw Function Pointers we&#8217;d have to declare one for every &#8220;type&#8221; of Function we might want to point to and do a giant switch statement. Something that is neither developer friendly nor performant.</p>
<p>Fortunately we have a solution in the usage of templates.</p>
<h2>Templates:</h2>
<p>Templates in C++ aren&#8217;t always shown in the best light due to the perception that they are complicated and make it difficult to read code.</p>
<p>I would agree with both of those statements. However, if you take the time to really dig into templates and understand how they work, they can be very powerful and aren&#8217;t as complex as they initially appear to be.</p>
<p>Let&#8217;s start with a very simple example:</p>
<pre class="brush: cpp; title: ; notranslate">
//Templated Function that takes in some type and returns that same type.
template &lt;typename ParamType&gt;
ParamType TemplatedFunction(ParamType p) {
	return p;
}
</pre>
<p>This function uses the template keyword to specify that this function is a templated function and uses the typename <strong>ParamType</strong> to specify that <strong>ParamType</strong> could be anything. In short, it&#8217;s a definition or &#8220;template&#8221;.</p>
<p>This function will return something of type <strong>ParamType</strong> and takes in a variable of type <strong>ParamType</strong>.</p>
<p>Now initially we don&#8217;t know what this will be. But it could be anything.</p>
<p>As we write our code and use the function, the compiler will then properly build the real functions that we need.</p>
<p>For example:</p>
<pre class="brush: cpp; title: ; notranslate">
int myInt = TemplatedFunction(6);
float myFloat = TemplatedFunction(12.2);
</pre>
<p>Will actually generate the following two functions even though we never wrote them ourselves. Note: The compiler generates these functions behind the scenes and doesn&#8217;t actually write C++ code.</p>
<pre class="brush: cpp; title: ; notranslate">
//Compiler generated function for type int. (Not actually ever seen)
int TemplatedFunction(int p) {
	return p;
}
//Compiler generated function for type float. (Not actually ever seen)
float TemplatedFunction(float p) {
	return p;
}
</pre>
<p>As you can see, the type we needed to use in our code generated a function using that type. This example is very simple but if you can imagine taking this concept to that of Member Function pointers, you can see how it would be extremely useful. We can write our handlers just once and let the compiler create the proper actual functions to handle all the different possibilites we might pass into it.</p>
<p>This is in fact the basis of how many libraries for handling Callbacks or Delegates work.</p>
<h2>First Attempts:</h2>
<p>My first attempt was to just create a standalone Function object for each type of Function. (Free Function and Member Function) Both of these work and work quite well but I&#8217;ll get into the problems after when I revisit Elbert Mai&#8217;s solution and slightly modify it.</p>
<p><strong>Free Function:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
template &lt;typename ReturnType&gt;
class FreeFunction {

//PUBLIC FUNCTIONS
public:
	//Constructor - Set function pointer via initalizer list
	inline FreeFunction(ReturnType (*fp)()) : freeFunctionPointer(fp) {}

	//Copy Constructor - Set function pointer via initializer list
	inline FreeFunction(const FreeFunction&amp; other) : freeFunctionPointer(other.freeFunctionPointer) {}

	//Destructor - Simply set function pointer to 0
	inline ~FreeFunction() {
		freeFunctionPointer = 0;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() () {
		return (*freeFunctionPointer)();
	}

	//Overloading = operator to allow for assignment
	inline FreeFunction&lt;ReturnType&gt;&amp; operator= (const FreeFunction&lt;ReturnType&gt; &amp;other) {
		if (*this != &amp;other) {
			freeFunctionPointer = other.freeFunctionPointer;
		}
		return *this;
	}

	//Exposing private variables to global equality functions
	template &lt;typename EqualFuncReturnType&gt;
	friend inline bool operator== (const FreeFunction&lt;EqualFuncReturnType&gt; &amp;lhs, const FreeFunction&lt;EqualFuncReturnType&gt; &amp;rhs);
	template &lt;typename NotEqualReturnType&gt;
	friend inline bool operator!= (const FreeFunction&lt;NotEqualReturnType&gt; &amp;lhs, const FreeFunction&lt;NotEqualReturnType&gt; &amp;rhs);

//PRIVATE VARIABLES
private:
	//Stores a Free Function Pointer
	ReturnType (*freeFunctionPointer)();

};

//Global Equality Function
template &lt;typename EqualFuncReturnType&gt;
inline bool operator== (const FreeFunction&lt;EqualFuncReturnType&gt; &amp;lhs, const FreeFunction&lt;EqualFuncReturnType&gt; &amp;rhs) {
	return (lhs.freeFunctionPointer == rhs.freeFunctionPointer);
}

//Global InEquality Function
template &lt;typename NotEqualReturnType&gt;
inline bool operator!= (const FreeFunction&lt;NotEqualReturnType&gt; &amp;lhs, const FreeFunction&lt;NotEqualReturnType&gt; &amp;rhs) {
	return (lhs.freeFunctionPointer != rhs.freeFunctionPointer);
}
</pre>
<p>The FreeFunction class simply wraps a Free Function pointer and provides some convenient methods to invoke the function and check equality etc. In terms of templating, the only varying aspect is the return type as this version only supports functions that take in 0 parameters. (To handle multiple parameters we need to create multiple versions of the class as you will see later)</p>
<p>Equality functions are implemented as global functions that are friends of the class so they can inspect the private properties of the FreeFunction class.</p>
<p><strong>Member Function:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
template &lt;typename ReturnType, class ClassType&gt;
class MemberFunction {

//PUBLIC FUNCTIONS
public:
	//Constructor - Set function pointer via initalizer list
	inline MemberFunction(ReturnType (ClassType::*fp)(), ClassType *ip) : memberFunctionPointer(fp), instancePointer(ip) {}

	//Copy Constructor - Set function pointer via initializer list
	inline MemberFunction(const MemberFunction&amp;; other) : memberFunctionPointer(other.memberFunctionPointer), instancePointer(other.instancePointer) {}

	//Destructor - Simply set function pointer and instance pointer to 0
	inline ~MemberFunction() {
		memberFunctionPointer = 0;
		instancePointer = 0;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() () {
		return (instancePointer-&gt;*memberFunctionPointer)();
	}

	//Overloading = operator to allow for assignment
	inline MemberFunction&lt;ReturnType, ClassType&gt;&amp; operator= (const MemberFunction&lt;ReturnType, ClassType&gt; &amp;other) {
		if (*this != &amp;other) {
			memberFunctionPointer = other.memberFunctionPointer;
			instancePointer = other.instancePointer;
		}
		return *this;
	}

	//Exposing private variables to global equality functions
	template &lt;typename EqualFuncReturnType, class EqualFuncClassType&gt;
	friend inline bool operator== (const MemberFunction&lt;EqualFuncReturnType, EqualFuncClassType&gt; &amp;lhs, const MemberFunction&lt;EqualFuncReturnType, EqualFuncClassType&gt; &amp;rhs);
	template &lt;typename NotEqualFuncReturnType, class NotEqualFuncClassType&gt;
	friend inline bool operator!= (const MemberFunction&lt;NotEqualFuncReturnType, NotEqualFuncClassType&gt; &amp;lhs, const MemberFunction&lt;NotEqualFuncReturnType, NotEqualFuncClassType&gt; &amp;rhs);

//PRIVATE VARIABLES
private:
	//Stores a Member Function Pointer
	ReturnType (ClassType::*memberFunctionPointer)();
	//Stores an Instance Pointer
	ClassType *instancePointer;
};

//Global Equality Function
template &lt;typename EqualFuncReturnType, class EqualFuncClassType&gt;
inline bool operator== (const MemberFunction&lt;EqualFuncReturnType, EqualFuncClassType&gt; &amp;lhs, const MemberFunction&lt;EqualFuncReturnType, EqualFuncClassType&gt; &amp;rhs) {
	return ((lhs.instancePointer == rhs.instancePointer) &amp;&amp; (lhs.memberFunctionPointer == rhs.memberFunctionPointer));
}

//Global InEquality Function
template &lt;typename NotEqualFuncReturnType, class NotEqualFuncClassType&gt;
inline bool operator!= (const MemberFunction&lt;NotEqualFuncReturnType, NotEqualFuncClassType&gt; &amp;lhs, const MemberFunction&lt;NotEqualFuncReturnType, NotEqualFuncClassType&gt; &amp;rhs) {
	return ((lhs.instancePointer != rhs.instancePointer) || (lhs.memberFunctionPointer != rhs.memberFunctionPointer));
}
</pre>
<p>Same thing here with the MemberFunction class. We wrap the member function pointer and store the instance pointer as well. Templating needs to be updated to include a class type. (You&#8217;ll notice that I use typename and class, there is no difference in what these keywords do but I differentiate by using typename when it&#8217;s a type that gets returned or passed in, and class when it&#8217;s explicitly referring to qualifying something like &#8220;ClassType::something&#8221;).</p>
<p>In addition the equality checks also include checking the instance pointers.</p>
<p>So both of these classes work very well but there are two issues.</p>
<ol>
<li>Declaring a Member Function Pointer requires you to specify the ClassType in the declaration of your Function Pointer.</li>
<li>You can&#8217;t use both of them interchangeably. Ie. You can&#8217;t have a vector of FreeFunctions and MemberFunctions, only one or the other.</li>
</ol>
<div></div>
<div></div>
<h2>Elbert&#8217;s Solution:</h2>
<p>As pointed out <a title="Elbert Mai's Callbacks" href="http://www.codeproject.com/KB/cpp/CPPCallback.aspx">here</a>, Elbert Mai came up with a great way to have one Function object that handles both Member and Free Functions.</p>
<p>I won&#8217;t fully go into it right now but the basic premise is that he used Partial Template Specialization with  Global Function to extract the Type information. He then creates a temporary Builder class with that type information. Using that Builder class, he invokes two partial template specialized static functions which create the actual Function object.</p>
<p>This Function object receives a Free Function pointer to the templated static function. NOT the actual function. The actual function exists as the partial template specialized parameter and gets invoked when the static function is invoked.</p>
<p>If you scratched your head and said &#8220;HUH?&#8221; don&#8217;t worry, you&#8217;re not alone. It took me a while to fully grasp this and understand how cool it actually is.</p>
<p>I&#8217;ll use my version of Elbert&#8217;s Solution to walkthrough it as it&#8217;s more verbosely commented and the names are expanded out to make it easier to read for learning.</p>
<h2>My Take on Elbert&#8217;s Solution:</h2>
<p>So the first thing we need to take a look at is the following code:</p>
<pre class="brush: cpp; title: ; notranslate">
//Declaring a Class called Function which can be of any type. Naturally we want it to be the Function Signature.
//We're declaring this here so that the Type itself exists but does nothing and we can extend this with Partial Template Specialization later.
template &lt;typename FunctionSignature&gt;
class Function;
</pre>
<p>This simply declares the class called Function and that it can be templated with a Function Signature. We&#8217;re not going to implement the class in any way because we don&#8217;t actually want a generic version of the class. Instead we want partially specialized versions of the class to be generated only when needed and by the types of functions we&#8217;re going to use.</p>
<p>Next we&#8217;ll look at how it gets invoked from the member function perspective and follow the chain of execution.</p>
<p>It all starts with a helper Macro:</p>
<pre class="brush: cpp; title: ; notranslate">
/Creates and Returns a Member Function object. Functions inside a class.
#define MEMBER_FUNCTION(functionPointer, instancePointer) util::CreateFunctionBuilder(functionPointer).Wrap&lt;functionPointer&gt;(instancePointer)
</pre>
<p>This Macro simply makes it easier for end users to create Member Function pointers. It takes in the function pointer address and a pointer to the class instance.</p>
<p><em>Note: This will error in Eclipse Indigo as Symbol &#8216;Wrap&#8217; could not be resolved and Invalid arguments &#8216;Candidates are: util::Function&lt;classtype ()&gt;. These are known issues with Eclipse&#8217;s code analysis and can be ignored. GCC will compile it just fine. No issues on Visual Studio 2010</em></p>
<p>Usage is:</p>
<pre class="brush: cpp; title: ; notranslate">
//Declares a Function of signature int(int, float) called mTestOne and maps it to MemberClass::TestMember on instance mem
util::Function&lt;int (int, float)&gt; mTestOne = MEMBER_FUNCTION(&amp;MemberClass::TestMember, &amp;mem);
</pre>
<p>This is fairly nice syntax. You specify a function and it&#8217;s templated type is the signature of the function. Then all you have to do is pass in the Function pointer address and a pointer to the instance.</p>
<p>You can even typedef your function type if you will be using it a lot or for even better readability.</p>
<pre class="brush: cpp; title: ; notranslate">
typedef util::Function&lt;int (int, float)&gt; IntFunction;
IntFunction mTestOne = MEMBER_FUNCTION(&amp;MemberClass::TestMember, &amp;mem);
</pre>
<p>Let&#8217;s now look at the first part of the Macro, the CreateFunctionBuilder function.</p>
<pre class="brush: cpp; title: ; notranslate">
//////////////////////////////////////////////////////////////////////
// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 2 PARAMETER VERSION //////
//////////////////////////////////////////////////////////////////////

template &lt;typename ReturnType, class ClassType, typename Param0, typename Param1&gt;
inline MemberFunctionBuilder2&lt;ReturnType, ClassType, Param0, Param1&gt; CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0, Param1 p1)) {
	return MemberFunctionBuilder2&lt;ReturnType, ClassType, Param0, Param1&gt;();
}
</pre>
<p>Ok so now the eyes start to bleed a bit.<br />
First off this is a template function and it expects to receive four parameters. One for the Return Type of the Function, one for the Class Type and one for each of the Parameters to be passed in.</p>
<p>The function will construct an instance of MemberFunctionBuilder2 with those four types based on what gets passed in.</p>
<p>If we use our function from the macro, the compiler will create a function line this:</p>
<pre class="brush: cpp; title: ; notranslate">
//Not a real function, simply illustrating what the template expands too when compiled.
inline MemberFunctionBuilder2&lt;int, MemberClass, int, float&gt; CreateFunctionBuilder(int (MemberClass::*fp)(int p0, float p1)) {
	return MemberFunctionBuilder2&lt;int, MemberClass, int, float&gt;();
}
</pre>
<p>Ok this makes a bit more sense. There is now an actual function just for our specific Function pointer that returns an int and takes in an int and a float on an instance of a MemberClass.</p>
<p>Once this MemberFunctionBuilder2 instance is created we call the static method Wrap on it to create the actual Function object. To see how this works, let&#8217;s look at the MemberFunctionBuilder2 class.</p>
<pre class="brush: cpp; title: ; notranslate">
//////////////////////////////////////////////////////////////////////
// FUNCTION BUILDER: MEMBER FUNCTION 2 PARAMETER VERSION /////////////
//////////////////////////////////////////////////////////////////////

//Builds a Member Function
template &lt;typename ReturnType, class ClassType, typename Param0, typename Param1&gt;
class MemberFunctionBuilder2 {
public:
	//Empty Constructor/Destructor
	inline MemberFunctionBuilder2() {}
	inline ~MemberFunctionBuilder2() {}

	//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
	template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)&gt;
	inline static Function&lt;ReturnType (Param0, Param1)&gt; Wrap(ClassType* ip) {
		return Function&lt;ReturnType (Param0, Param1)&gt;(&amp;MemberFunctionBuilder2::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
	}

private:
	//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
	template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)&gt;
	inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
		ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
		return (instancePointer-&gt;*functionPointer)(p0, p1);
	}

};
</pre>
<p>Ok back to bleeding eyes, the class itself is meaningless and will in fact get destroyed once the function calls from the macro return due to them going out of scope; but we need it because of it&#8217;s template parameters. These template parameters allow for us to define static functions that use those template parameters.<br />
The Wrap function creates a new Function by combining the ReturnType and any ParamX template parameters into a Function Signature. This allows us to create a Function using our Function Signature as the specialization for that Function Class.</p>
<p>Essentially, we will have a Function class that specifically tuned to our specific type of Function Signature.</p>
<p>Let&#8217;s look at the Wrap function as it will be generated by the compiler:</p>
<pre class="brush: cpp; title: ; notranslate">
//Not an actual function, just to illustrate what it expands too when compiled
//functionPointer gets populated by &amp;amp;MemberClass::TestMember
inline static Function&lt;int (int, float)&gt; Wrap(MemberClass* ip) {
	return Function&lt;int (int, float)&gt;(&amp;amp;MemberFunctionBuilder2::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
}
</pre>
<p>Again we see our Function Signature of return type int with two params int and float and we see that it also takes in a pointer to an instance of a MemberClass. This is because it&#8217;s still a Member Function pointer and in order to invoke it we need an instance of the class.</p>
<p>The Wrap function constructs a Function object (which we will see in a moment) but it doesn&#8217;t give the Function object itself the Function Pointer or even the Instance pointer. Remember at the beginning there are two types of Function pointers. Free and Member. Those two aren&#8217;t compatible and we can&#8217;t store them in one catch all variable. So instead we have to lose some information in the interest of storage and a common interface.</p>
<p>Instead of passing in the actual Raw Member Function pointer, we pass in a Free Function Pointer which points to the private static function called Wrapper which has been template specialized by the actual Raw Member Function pointer.</p>
<p>This is the whole trick and it&#8217;s really quite brilliant.</p>
<p>At compile time, we have a Static function that is specialized to our Function pointer&#8217;s signature so it is unique. Inside that Static function we&#8217;ve basically hardcoded the address to the actual Member Function Pointer via template specialization. We only pass the function pointer to the static function into the Actual Function object which is a Free Function pointer. So regardless of whether we originally wanted to fire off a Free Function or a Member Function, only a Free Function pointer needs to be stored.</p>
<p>When we go to invoke the stored function pointer in the Function object itself, it invokes the Static Wrapper function which in turn invokes either the Member Function or the Free Function we originally wanted to store. It&#8217;s simply a layer of indirection.</p>
<p>You&#8217;ll also notice that we are casting the instance pointer to a void*. There&#8217;s a lot of information on the net about how this can be a bad thing but for our purposes it&#8217;s fine. We simply need to store the instance value in a generic way in the Function object.</p>
<p>Let&#8217;s look at the Wrapper function now:</p>
<pre class="brush: cpp; title: ; notranslate">
//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)&gt;
inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
	ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
	return (instancePointer-&gt;*functionPointer)(p0, p1);
}
</pre>
<p>This function is what gets sent to the Function object and later invoked when you want to call your function again. Again using template specialization it allows the original function to be called. Let&#8217;s take a look using our actual function parameters</p>
<pre class="brush: cpp; title: ; notranslate">
//Not an actual function. Just illustrating how it expands.
inline static int Wrapper(const void* ip, int p0, float p1) {
	MemberClass* instancePointer = const_cast&lt;MemberClass*&gt;(static_cast&lt;const MemberClass*&gt;(ip));
	return (instancePointer-&gt;*functionPointer)(p0, p1);
}
</pre>
<p>This should be feeling fairly familiar now, the Wrapper function takes in a void* pointer representing the instance which we can cast back to the actual Class type because the template already knows what Class it should be. As well due to template specialization the actual function pointer itself is stored in the definition of the function and so we can invoke it on our instance pointer and pass in the two parameters.</p>
<p>Finally we can look at the actual Function class which really is just a shell that we can use to pass around in a more generic way.</p>
<pre class="brush: cpp; title: ; notranslate">
//////////////////////////////////////////////////////////////////////
// FUNCTION: 2 PARAMETER VERSION /////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
template &lt;typename ReturnType, typename Param0, typename Param1&gt;
class Function&lt;ReturnType (Param0, Param1)&gt; {

//PUBLIC FUNCTIONS
public:
	//Default Constructor - To allow for creation with assigning
	inline Function() : functionPointer(0), instancePointer(0) {}

	//Constructor - Set function pointer via initalizer list
	inline Function(ReturnType (*fp)(const void*, Param0 p0, Param1 p1), const void *ip) : functionPointer(fp), instancePointer(ip) {}

	//Copy Constructor - Set function pointer via initializer list
	inline Function(const Function&amp; other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

	//Destructor - Simply set function and instance pointer to 0
	inline ~Function() {
		functionPointer = 0;
		instancePointer = 0;
	}

	//Overloading = operator to allow for assignment
	inline Function&lt;ReturnType&gt;&amp; operator= (const Function&lt;ReturnType&gt; &amp;other) {
		functionPointer = other.functionPointer;
		instancePointer = other.instancePointer;
		return *this;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() (Param0 p0, Param1 p1) const {
		return (*functionPointer)(instancePointer, p0, p1);
	}

	//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
	typedef const void* Function::*bool_type;
	inline operator bool_type() const {
		return (functionPointer != 0) ? &amp;Function::instancePointer : false;
	}

	template &lt;typename EqualFuncReturnType&gt;
	friend inline bool operator ==(const Function&lt;EqualFuncReturnType&gt; &amp; lhs, const Function&lt;EqualFuncReturnType&gt; &amp; rhs);
	template&lt;typename NotEqualFuncReturnType&gt;
	friend inline bool operator !=(const Function&lt;NotEqualFuncReturnType&gt; &amp; lhs, const Function&lt;NotEqualFuncReturnType&gt; &amp; rhs);

//PRIVATE VARIABLES
private:
	//Stores a Free Function Pointer to the static wrapper function
	ReturnType (*functionPointer)(const void*, Param0 p0, Param1 p1);
	//Stores an Instance Pointer
	const void *instancePointer;

};
</pre>
<p>And we should look at it as well with the params filled in.</p>
<pre class="brush: cpp; title: ; notranslate">
//Not an actual class, simply illustrating expansion when compiled
class Function&lt;int (int, float)&gt; {

//PUBLIC FUNCTIONS
public:
	//Default Constructor - To allow for creation with assigning
	inline Function() : functionPointer(0), instancePointer(0) {}

	//Constructor - Set function pointer via initalizer list
	inline Function(int (*fp)(const void*, int p0, float p1), const void *ip) : functionPointer(fp), instancePointer(ip) {}

	//Copy Constructor - Set function pointer via initializer list
	inline Function(const Function&amp; other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

	//Destructor - Simply set function and instance pointer to 0
	inline ~Function() {
		functionPointer = 0;
		instancePointer = 0;
	}

	//Overloading = operator to allow for assignment
	inline Function&lt;int (int, float)&gt;&amp; operator= (const Function&lt;int (int, float)&gt; &amp;other) {
		functionPointer = other.functionPointer;
		instancePointer = other.instancePointer;
		return *this;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() (int p0, float p1) const {
		return (*functionPointer)(instancePointer, p0, p1);
	}

	//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
	typedef const void* Function::*bool_type;
	inline operator bool_type() const {
		return (functionPointer != 0) ? &amp;Function::instancePointer : false;
	}

	friend inline bool operator ==(const Function&lt;int (int, float)&gt; &amp; lhs, const Function&lt;int (int, float)&gt; &amp; rhs);
	friend inline bool operator !=(const Function&lt;int (int, float)&gt; &amp; lhs, const Function&lt;int (int, float)&gt; &amp; rhs);

//PRIVATE VARIABLES
private:
	//Stores a Free Function Pointer to the static wrapper function
	int (*functionPointer)(const void*, int p0, float p1);
	//Stores an Instance Pointer
	const void *instancePointer;

};
</pre>
<p>The class itself is fairly basic and the comments should explain most of it. Elbert&#8217;s version has a few more extra features that I&#8217;m not sure if I&#8217;ll add in to my version or not. I want to try and wait and see if they are needed.</p>
<p>The first thing to notice are the two pieces of member data. A Function pointer to a static function that matches our function signature. This will hold the static Wrapper function. And a const void* which will hold our casted instance. In the case of actual Free Functions, this will always be 0.</p>
<p>In terms of functions we have a Default Constructor so we can simply declare an empty Function and populate it later. A Constructor which takes in the Function Pointer and instance pointer, a Copy constructor which simply copies the two pointers and a Destructor which sets both pointers to 0. The Destructor doesn&#8217;t really need to set them to 0 since Function objects are always created on the Stack but I put it in all the same in case it ever goes on the Heap and I change how it works.</p>
<p>In terms of operators, the assignment operator is overloaded so we can assign Functions to Functions.</p>
<p>The most important operator is the () operator which lets us use the Function as a Function. It simply calls the Static Wrapper function and passes along whatever variables we need to pass.</p>
<p>Finally we have what is known as the <a title="Safe Bool Idiom" href="http://www.artima.com/cppsource/safebool.html">Safe Bool Idiom</a> which let&#8217;s us do something like <em>if (myFunction) {</em> but safely. I won&#8217;t go into details but it&#8217;s a good article to read.</p>
<p>The last part of the class is two friend declarations for the equality and inequality operators. This is the one major change I made to Elbert&#8217;s version because I definitely needed to have the ability to check if two Function objects were the same.</p>
<p>And that sums up how Functions work from start to finish.</p>
<p>There are just two more quick topics to discuss and then the final full source.</p>
<h2>Parameter Versions:</h2>
<p>You might have noticed that the comments refer to the code as the &#8220;2 Parameter Version&#8221;. The one thing we can&#8217;t do is write code once and have it work for a variable length of arguments so we have to duplicate a lot of the code to account for the different parameters. This is annoying but not a bad thing since C++ supports overloading of functions. Depending on what you pass in it will resolve to the proper function to handle X amount of Parameters. The version I&#8217;ll paste at the end only supports up to two parameters because otherwise the file is super long but you can easily extend it to as many parameters as you need. Commonly this is anywhere from 6 to 8. If you&#8217;re passing in more&#8230; well maybe you might want to condense some of those into a Data class to more easily pass around.</p>
<h2>Equality:</h2>
<p>The equality subject is a bit sticky because we&#8217;re kind of breaking the rules here. You are allowed to compare two function pointers for equality provided they are the same type. (Free or Member). You&#8217;re also allowed to compare any two pointers together because they are just pointers so we&#8217;re allowed to compare our instance pointers.</p>
<p>The problem arises in that if we compare the two function pointers in the Function object, we&#8217;re not actually comparing the Function pointers but actually comparing the Static Wrapper Function pointers instead.</p>
<p>This should immediately set off alarm bells in your head as it&#8217;s a static function so it&#8217;s very easy to have a one to many relationship resulting in false positives.</p>
<p>However; we&#8217;re also using template specialization keyed to our exact function signature. So there isn&#8217;t one static function everything gets piped through, instead there are many static functions that are uniquely tied to our original function pointers.</p>
<p>Since we&#8217;re really just looking for a way to check if the same function will be called, the comparison is still valid at the static wrapper level. I have tested this with various free functions, member function, virtual functions etc and the tests all properly come back as true when they are in fact equal and false when they are not.</p>
<p>I will admit that there may be a corner case here, but I have no found it and I&#8217;ve stepped through the debugger looking at the addresses and even started digging in the dissassembly. (But that&#8217;s a future post).</p>
<p>The great thing about the equality functions is we only need one set and not multiple versions for each parameter since templating will just create the versions we need. This allows us to add functions to maps and check if a function already exists in a set or not.</p>
<h2>Conclusion:</h2>
<p>Well this has been yet another novel, but the subject is deep and complex and I spent a lot of time digging into it to really understand how it all works and how I can use it in my own projects. Once again I have to thank Elbert Mai and Don Clougston for making their own discoveries and code available so I could piece it all together. I touched on some very interesting and complex areas of C++ and came out with more tools for the toolbox.</p>
<p>One final note with the below source, you&#8217;ll notice it handles a third function type known as a const Member function. This is the exact same as the Member Function it&#8217;s just const and unfortunately requires duplication of the code to make the compiler enforce your code properly.</p>
<p>At the end of the day, these Functions have a ton of benefits as outlined in Elberts article but one of the best is that it&#8217;s all resolved at compile time. If there are going to be errors, you&#8217;re going to get them before you&#8217;re running your program. In addition the compiler will optimize a lot for you, inlining function calls and making things fast.</p>
<p><strong>Source:</strong></p>
<pre class="brush: cpp; title: ; notranslate">
/*********************************
*Class: Function
*Description: Based off of Elbert Mai's (http://www.codeproject.com/script/Membership/View.aspx?mid=2301380) implementation
*of Callbacks (http://www.codeproject.com/KB/cpp/CPPCallback.aspx).
*Modified to support equality and heavily commented to provide easier understanding of what's happening under the hood.
*Author: jkeon
**********************************/

#ifndef _FUNCTION_H_
#define _FUNCTION_H_

//////////////////////////////////////////////////////////////////////
// MACROS ////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Creates and Returns a Free Function object. Static functions etc.
#define FREE_FUNCTION(functionPointer) util::CreateFunctionBuilder(functionPointer).Wrap&lt;functionPointer&gt;()

//Creates and Returns a Member Function object. Functions inside a class.
#define MEMBER_FUNCTION(functionPointer, instancePointer) util::CreateFunctionBuilder(functionPointer).Wrap&lt;functionPointer&gt;(instancePointer)

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace util {

	//////////////////////////////////////////////////////////////////////
	// CLASS DECLARATION /////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Declaring a Class called Function which can be of any type. Naturally we want it to be the Function Signature.
	//We're declaring this here so that the Type itself exists but does nothing and we can extend this with Partial Template Specialization later.
	template &lt;typename FunctionSignature&gt;
	class Function;

	//////////////////////////////////////////////////////////////////////
	// GLOBAL EQUALITY CHECKS ////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename EqualFuncReturnType&gt;
	inline bool operator== (const Function&lt;EqualFuncReturnType&gt; &amp;lhs, const Function&lt;EqualFuncReturnType&gt; &amp;rhs) {
		return ((lhs.functionPointer == rhs.functionPointer) &amp;&amp; (lhs.instancePointer == rhs.instancePointer));
	}

	template &lt;typename NotEqualFuncReturnType&gt;
	inline bool operator!= (const Function&lt;NotEqualFuncReturnType&gt; &amp;lhs, const Function&lt;NotEqualFuncReturnType&gt; &amp;rhs) {
		return ((lhs.functionPointer != rhs.functionPointer) || (lhs.instancePointer != rhs.instancePointer));
	}

	//*********************************************************************************************************************************************************************
	//*********************************************************************************************************************************************************************

	//////////////////////////////////////////////////////////////////////
	// FUNCTION: 0 PARAMETER VERSION /////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
	template &lt;typename ReturnType&gt;
	class Function&lt;ReturnType ()&gt; {

	//PUBLIC FUNCTIONS
	public:
		//Default Constructor - To allow for creation with assigning
		inline Function() : functionPointer(0), instancePointer(0) {}

		//Constructor - Set function pointer via initalizer list
		inline Function(ReturnType (*fp)(const void*), const void *ip) : functionPointer(fp), instancePointer(ip) {}

		//Copy Constructor - Set function pointer via initializer list
		inline Function(const Function&amp; other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

		//Destructor - Simply set function and instance pointer to 0
		inline ~Function() {
			functionPointer = 0;
			instancePointer = 0;
		}

		//Overloading = operator to allow for assignment
		inline Function&lt;ReturnType&gt;&amp; operator= (const Function&lt;ReturnType&gt; &amp;other) {
			functionPointer = other.functionPointer;
			instancePointer = other.instancePointer;
			return *this;
		}

		//Overloading () operator so we can use this like a Function
		inline ReturnType operator() () const {
			return (*functionPointer)(instancePointer);
		}

		//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
		typedef const void* Function::*bool_type;
		inline operator bool_type() const {
			return (functionPointer != 0) ? &amp;Function::instancePointer : false;
		}

		//Allowing for Equality/InEquality Checks by granting the Global Equality/InEquality Check Functions access to this classes internals via the friend keyword.
		template &lt;typename EqualFuncReturnType&gt;
		friend inline bool operator ==(const Function&lt;EqualFuncReturnType&gt; &amp; lhs, const Function&lt;EqualFuncReturnType&gt; &amp; rhs);
		template&lt;typename NotEqualFuncReturnType&gt;
		friend inline bool operator !=(const Function&lt;NotEqualFuncReturnType&gt; &amp; lhs, const Function&lt;NotEqualFuncReturnType&gt; &amp; rhs);

	//PRIVATE VARIABLES
	private:
		//Stores a Free Function Pointer to the static wrapper function
		ReturnType (*functionPointer)(const void*);
		//Stores an Instance Pointer
		const void *instancePointer;

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: FREE FUNCTION 0 PARAMETER VERSION ///////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Free Function
	template &lt;typename ReturnType&gt;
	class FreeFunctionBuilder0 {
	public:
		//Empty Constructor/Destructor
		inline FreeFunctionBuilder0() {}
		inline ~FreeFunctionBuilder0() {}

		//Performs the wrapping from the actual Free Function to the static Free Function Wrapper in this class.
		template&lt;ReturnType (*functionPointer)()&gt;
		inline static Function&lt;ReturnType ()&gt; Wrap() {
			return Function&lt;ReturnType ()&gt;(&amp;FreeFunctionBuilder0::template Wrapper&lt;functionPointer&gt;, 0);
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params
		template&lt;ReturnType (*functionPointer)()&gt;
		inline static ReturnType Wrapper(const void*) {
			return (*functionPointer)();
		}
	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: MEMBER FUNCTION 0 PARAMETER VERSION /////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Member Function
	template &lt;typename ReturnType, class ClassType&gt;
	class MemberFunctionBuilder0 {
	public:
		//Empty Constructor/Destructor
		inline MemberFunctionBuilder0() {}
		inline ~MemberFunctionBuilder0() {}

		//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template&lt;ReturnType (ClassType::*functionPointer)()&gt;
		inline static Function&lt;ReturnType ()&gt; Wrap(ClassType* ip) {
			return Function&lt;ReturnType ()&gt;(&amp;MemberFunctionBuilder0::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template&lt;ReturnType (ClassType::*functionPointer)()&gt;
		inline static ReturnType Wrapper(const void* ip) {
			ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
			return (instancePointer-&gt;*functionPointer)();
		}

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: CONST MEMBER FUNCTION 0 PARAMETER VERSION ///////
	//////////////////////////////////////////////////////////////////////

	//Builds a Const Member Function
	template &lt;typename ReturnType, class ClassType&gt;
	class ConstMemberFunctionBuilder0 {
	public:
		//Empty Constructor/Destructor
		inline ConstMemberFunctionBuilder0() {}
		inline ~ConstMemberFunctionBuilder0() {}

		//Performs the wrapping from the actual Const Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template&lt;ReturnType (ClassType::*functionPointer)() const&gt;
		inline static Function&lt;ReturnType ()&gt; Wrap(ClassType* ip) {
			return Function&lt;ReturnType ()&gt;(&amp;ConstMemberFunctionBuilder0::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template&lt;ReturnType (ClassType::*functionPointer)() const&gt;
		inline static ReturnType Wrapper(const void* ip) {
			ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
			return (instancePointer-&gt;*functionPointer)();
		}

	};

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: FREE FUNCTION 0 PARAMETER VERSION ////////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType&gt;
	inline FreeFunctionBuilder0&lt;ReturnType&gt; CreateFunctionBuilder(ReturnType (*fp)()) {
		return FreeFunctionBuilder0&lt;ReturnType&gt;();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 0 PARAMETER VERSION //////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, class ClassType&gt;
	inline MemberFunctionBuilder0&lt;ReturnType, ClassType&gt; CreateFunctionBuilder(ReturnType (ClassType::*fp)()) {
		return MemberFunctionBuilder0&lt;ReturnType, ClassType&gt;();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: C MEMBER FUNCTION 0 PARAMETER VERSION ////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, class ClassType&gt;
	inline ConstMemberFunctionBuilder0&lt;ReturnType, ClassType&gt; CreateFunctionBuilder(ReturnType (ClassType::*fp)() const) {
		return ConstMemberFunctionBuilder0&lt;ReturnType, ClassType&gt;();
	}

	//*********************************************************************************************************************************************************************
	//*********************************************************************************************************************************************************************

	//////////////////////////////////////////////////////////////////////
	// FUNCTION: 1 PARAMETER VERSION /////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
	template &lt;typename ReturnType, typename Param0&gt;
	class Function&lt;ReturnType (Param0)&gt; {

	//PUBLIC FUNCTIONS
	public:
		//Default Constructor - To allow for creation with assigning
		inline Function() : functionPointer(0), instancePointer(0) {}

		//Constructor - Set function pointer via initalizer list
		inline Function(ReturnType (*fp)(const void*, Param0 p0), const void *ip) : functionPointer(fp), instancePointer(ip) {}

		//Copy Constructor - Set function pointer via initializer list
		inline Function(const Function&amp; other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

		//Destructor - Simply set function and instance pointer to 0
		inline ~Function() {
			functionPointer = 0;
			instancePointer = 0;
		}

		//Overloading = operator to allow for assignment
		inline Function&lt;ReturnType&gt;&amp; operator= (const Function&lt;ReturnType&gt; &amp;other) {
			functionPointer = other.functionPointer;
			instancePointer = other.instancePointer;
			return *this;
		}

		//Overloading () operator so we can use this like a Function
		inline ReturnType operator() (Param0 p0) const {
			return (*functionPointer)(instancePointer, p0);
		}

		//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
		typedef const void* Function::*bool_type;
		inline operator bool_type() const {
			return (functionPointer != 0) ? &amp;Function::instancePointer : false;
		}

		//Allowing for Equality/InEquality Checks by granting the Global Equality/InEquality Check Functions access to this classes internals via the friend keyword.
		template &lt;typename EqualFuncReturnType&gt;
		friend inline bool operator ==(const Function&lt;EqualFuncReturnType&gt; &amp; lhs, const Function&lt;EqualFuncReturnType&gt; &amp; rhs);
		template&lt;typename NotEqualFuncReturnType&gt;
		friend inline bool operator !=(const Function&lt;NotEqualFuncReturnType&gt; &amp; lhs, const Function&lt;NotEqualFuncReturnType&gt; &amp; rhs);

	//PRIVATE VARIABLES
	private:
		//Stores a Free Function Pointer to the static wrapper function
		ReturnType (*functionPointer)(const void*, Param0 p0);
		//Stores an Instance Pointer
		const void *instancePointer;

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: FREE FUNCTION 1 PARAMETER VERSION ///////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Free Function
	template &lt;typename ReturnType, typename Param0&gt;
	class FreeFunctionBuilder1 {
	public:
		//Empty Constructor/Destructor
		inline FreeFunctionBuilder1() {}
		inline ~FreeFunctionBuilder1() {}

		//Performs the wrapping from the actual Free Function to the static Free Function Wrapper in this class.
		template&lt;ReturnType (*functionPointer)(Param0 p0)&gt;
		inline static Function&lt;ReturnType (Param0)&gt; Wrap() {
			return Function&lt;ReturnType (Param0)&gt;(&amp;FreeFunctionBuilder1::template Wrapper&lt;functionPointer&gt;, 0);
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params
		template&lt;ReturnType (*functionPointer)(Param0 p0)&gt;
		inline static ReturnType Wrapper(const void*, Param0 p0) {
			return (*functionPointer)(p0);
		}
	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: MEMBER FUNCTION 1 PARAMETER VERSION /////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Member Function
	template &lt;typename ReturnType, class ClassType, typename Param0&gt;
	class MemberFunctionBuilder1 {
	public:
		//Empty Constructor/Destructor
		inline MemberFunctionBuilder1() {}
		inline ~MemberFunctionBuilder1() {}

		//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0)&gt;
		inline static Function&lt;ReturnType (Param0)&gt; Wrap(ClassType* ip) {
			return Function&lt;ReturnType (Param0)&gt;(&amp;MemberFunctionBuilder1::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0)&gt;
		inline static ReturnType Wrapper(const void* ip, Param0 p0) {
			ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
			return (instancePointer-&gt;*functionPointer)(p0);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: CONST MEMBER FUNCTION 1 PARAMETER VERSION ///////
	//////////////////////////////////////////////////////////////////////

	//Builds a Const Member Function
	template &lt;typename ReturnType, class ClassType, typename Param0&gt;
	class ConstMemberFunctionBuilder1 {
	public:
		//Empty Constructor/Destructor
		inline ConstMemberFunctionBuilder1() {}
		inline ~ConstMemberFunctionBuilder1() {}

		//Performs the wrapping from the actual Const Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0) const&gt;
		inline static Function&lt;ReturnType (Param0 p0)&gt; Wrap(ClassType* ip) {
			return Function&lt;ReturnType (Param0 p0)&gt;(&amp;ConstMemberFunctionBuilder1::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0) const&gt;
		inline static ReturnType Wrapper(const void* ip, Param0 p0) {
			ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
			return (instancePointer-&gt;*functionPointer)(p0);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: FREE FUNCTION 1 PARAMETER VERSION ////////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, typename Param0&gt;
	inline FreeFunctionBuilder1&lt;ReturnType, Param0&gt; CreateFunctionBuilder(ReturnType (*fp)(Param0 p0)) {
		return FreeFunctionBuilder1&lt;ReturnType, Param0&gt;();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 1 PARAMETER VERSION //////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, class ClassType, typename Param0&gt;
	inline MemberFunctionBuilder1&lt;ReturnType, ClassType, Param0&gt; CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0)) {
		return MemberFunctionBuilder1&lt;ReturnType, ClassType, Param0&gt;();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: C MEMBER FUNCTION 1 PARAMETER VERSION ////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, class ClassType, typename Param0&gt;
	inline ConstMemberFunctionBuilder1&lt;ReturnType, ClassType, Param0&gt; CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0) const) {
		return ConstMemberFunctionBuilder1&lt;ReturnType, ClassType, Param0&gt;();
	}

	//*********************************************************************************************************************************************************************
	//*********************************************************************************************************************************************************************

	//////////////////////////////////////////////////////////////////////
	// FUNCTION: 2 PARAMETER VERSION /////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
	template &lt;typename ReturnType, typename Param0, typename Param1&gt;
	class Function&lt;ReturnType (Param0, Param1)&gt; {

	//PUBLIC FUNCTIONS
	public:
		//Default Constructor - To allow for creation with assigning
		inline Function() : functionPointer(0), instancePointer(0) {}

		//Constructor - Set function pointer via initalizer list
		inline Function(ReturnType (*fp)(const void*, Param0 p0, Param1 p1), const void *ip) : functionPointer(fp), instancePointer(ip) {}

		//Copy Constructor - Set function pointer via initializer list
		inline Function(const Function&amp; other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

		//Destructor - Simply set function and instance pointer to 0
		inline ~Function() {
			functionPointer = 0;
			instancePointer = 0;
		}

		//Overloading = operator to allow for assignment
		inline Function&lt;ReturnType&gt;&amp; operator= (const Function&lt;ReturnType&gt; &amp;other) {
			functionPointer = other.functionPointer;
			instancePointer = other.instancePointer;
			return *this;
		}

		//Overloading () operator so we can use this like a Function
		inline ReturnType operator() (Param0 p0, Param1 p1) const {
			return (*functionPointer)(instancePointer, p0, p1);
		}

		//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
		typedef const void* Function::*bool_type;
		inline operator bool_type() const {
			return (functionPointer != 0) ? &amp;Function::instancePointer : false;
		}

		template &lt;typename EqualFuncReturnType&gt;
		friend inline bool operator ==(const Function&lt;EqualFuncReturnType&gt; &amp; lhs, const Function&lt;EqualFuncReturnType&gt; &amp; rhs);
		template&lt;typename NotEqualFuncReturnType&gt;
		friend inline bool operator !=(const Function&lt;NotEqualFuncReturnType&gt; &amp; lhs, const Function&lt;NotEqualFuncReturnType&gt; &amp; rhs);

	//PRIVATE VARIABLES
	private:
		//Stores a Free Function Pointer to the static wrapper function
		ReturnType (*functionPointer)(const void*, Param0 p0, Param1 p1);
		//Stores an Instance Pointer
		const void *instancePointer;

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: FREE FUNCTION 2 PARAMETER VERSION ///////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Free Function
	template &lt;typename ReturnType, typename Param0, typename Param1&gt;
	class FreeFunctionBuilder2 {
	public:
		//Empty Constructor/Destructor
		inline FreeFunctionBuilder2() {}
		inline ~FreeFunctionBuilder2() {}

		//Performs the wrapping from the actual Free Function to the static Free Function Wrapper in this class.
		template&lt;ReturnType (*functionPointer)(Param0 p0, Param1 p1)&gt;
		inline static Function&lt;ReturnType (Param0, Param1)&gt; Wrap() {
			return Function&lt;ReturnType (Param0, Param1)&gt;(&amp;FreeFunctionBuilder2::template Wrapper&lt;functionPointer&gt;, 0);
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params
		template&lt;ReturnType (*functionPointer)(Param0 p0, Param1 p1)&gt;
		inline static ReturnType Wrapper(const void*, Param0 p0, Param1 p1) {
			return (*functionPointer)(p0, p1);
		}
	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: MEMBER FUNCTION 2 PARAMETER VERSION /////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Member Function
	template &lt;typename ReturnType, class ClassType, typename Param0, typename Param1&gt;
	class MemberFunctionBuilder2 {
	public:
		//Empty Constructor/Destructor
		inline MemberFunctionBuilder2() {}
		inline ~MemberFunctionBuilder2() {}

		//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)&gt;
		inline static Function&lt;ReturnType (Param0, Param1)&gt; Wrap(ClassType* ip) {
			return Function&lt;ReturnType (Param0, Param1)&gt;(&amp;MemberFunctionBuilder2::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)&gt;
		inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
			ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
			return (instancePointer-&gt;*functionPointer)(p0, p1);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: CONST MEMBER FUNCTION 2 PARAMETER VERSION ///////
	//////////////////////////////////////////////////////////////////////

	//Builds a Const Member Function
	template &lt;typename ReturnType, class ClassType, typename Param0, typename Param1&gt;
	class ConstMemberFunctionBuilder2 {
	public:
		//Empty Constructor/Destructor
		inline ConstMemberFunctionBuilder2() {}
		inline ~ConstMemberFunctionBuilder2() {}

		//Performs the wrapping from the actual Const Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0, Param0 p1) const&gt;
		inline static Function&lt;ReturnType (Param0 p0, Param1 p1)&gt; Wrap(ClassType* ip) {
			return Function&lt;ReturnType (Param0 p0, Param1 p1)&gt;(&amp;ConstMemberFunctionBuilder2::template Wrapper&lt;functionPointer&gt;, static_cast&lt;const void*&gt;(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template&lt;ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1) const&gt;
		inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
			ClassType* instancePointer = const_cast&lt;ClassType*&gt;(static_cast&lt;const ClassType*&gt;(ip));
			return (instancePointer-&gt;*functionPointer)(p0, p1);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: FREE FUNCTION 2 PARAMETER VERSION ////////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, typename Param0, typename Param1&gt;
	inline FreeFunctionBuilder2&lt;ReturnType, Param0, Param1&gt; CreateFunctionBuilder(ReturnType (*fp)(Param0 p0, Param1 p1)) {
		return FreeFunctionBuilder2&lt;ReturnType, Param0, Param1&gt;();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 2 PARAMETER VERSION //////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, class ClassType, typename Param0, typename Param1&gt;
	inline MemberFunctionBuilder2&lt;ReturnType, ClassType, Param0, Param1&gt; CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0, Param1 p1)) {
		return MemberFunctionBuilder2&lt;ReturnType, ClassType, Param0, Param1&gt;();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: C MEMBER FUNCTION 2 PARAMETER VERSION ////
	//////////////////////////////////////////////////////////////////////

	template &lt;typename ReturnType, class ClassType, typename Param0, typename Param1&gt;
	inline ConstMemberFunctionBuilder2&lt;ReturnType, ClassType, Param0, Param1&gt; CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0, Param1 p1) const) {
		return ConstMemberFunctionBuilder2&lt;ReturnType, ClassType, Param0, Param1&gt;();
	}
}
#endif
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/deeper-into-the-rabbit-hole-c-function-pointers-and-callbacks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sketchy Sunday: Soundflow</title>
		<link>http://www.breaktrycatch.com/sketchy-sunday-soundflow/</link>
		<comments>http://www.breaktrycatch.com/sketchy-sunday-soundflow/#comments</comments>
		<pubDate>Sun, 20 Nov 2011 16:32:04 +0000</pubDate>
		<dc:creator>Paul</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[Sketches]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=931</guid>
		<description><![CDATA[Drawing smooth lines with the Flash drawing API and the haunting piano of Maxence Cyrin. ]]></description>
			<content:encoded><![CDATA[<p><script type="text/javascript">// <![CDATA[
	var flashvars = {
		asseturl: escape("http://breaktrycatch.com/labs/soundflow/assets/"),
		json_url: escape("http://breaktrycatch.com/labs/soundflow/assets/json/"),
		audio_url: escape("http://breaktrycatch.com/labs/soundflow/assets/audio/")
	}
	var id = "flashreplace";
	var params = { menu: "false", wmode: "opaque", allowFullScreen: "true", bgcolor: "#000000" };
	var attributes = { id: "theflash", name: "theflash" };
	window.onload = function() {
		document.getElementById("noflashwords").style.display = "none";
		setTimeout( "shownoflashwords()", 15000 );
		if (swfobject.hasFlashPlayerVersion("9")) {
			var att = { data:"http://breaktrycatch.com/labs/soundflow/assets/swf/musicvis_framework_lite.swf", width:"100%", height:"700" };
swfobject.embedSWF("http://breaktrycatch.com/labs/soundflow/assets/swf/musicvis_framework_lite.swf", id, "100%", "700", "10", "", flashvars, params, attributes);
		}
	};
	function shownoflashwords() {
		if (!swfobject.hasFlashPlayerVersion("9")) {
		document.getElementById("noflashwords").style.display = "block";
		}
	}
// ]]&gt;</script><br />
<a href="http://breaktrycatch.com/labs/soundflow/" target="_self"></p>
<div id="flash">
<div id="flashreplace">
<div id="noflashwords" style="display: none;">
<p>The best way to view this site is with the Adobe Flash Player.</p>
<p><a class="whiteLink" href="http://www.adobe.com/products/flashplayer/" target="_blank">Click here</a> to update your system with the latest Flash Player.</p>
</div>
</div>
</div>
<p></a><br />
Drawing smooth lines with the Flash drawing API and the haunting piano of Maxence Cyrin. </p>
<p><a href="http://breaktrycatch.com/labs/soundflow/" target="_self">View Fullscreen</a><br />
Music: <a href="http://www.amazon.com/L-F-O/dp/B000T345WW">L.F.O. &#8211; Maxence Cyrin</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/sketchy-sunday-soundflow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sketchy Sunday: Polygon Field</title>
		<link>http://www.breaktrycatch.com/sketchy-sunday-polygon-field/</link>
		<comments>http://www.breaktrycatch.com/sketchy-sunday-polygon-field/#comments</comments>
		<pubDate>Sun, 13 Nov 2011 15:51:06 +0000</pubDate>
		<dc:creator>Paul</dc:creator>
				<category><![CDATA[Processing]]></category>
		<category><![CDATA[Sketches]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=917</guid>
		<description><![CDATA[Its gotten pretty serious around here with pointers flying back and forth, buffers being created and recreated again, segfaults ruining afternoons, so I thought I'd start posting the little sketches I tinker with in my spare time. These things usually evolve organically, aren't optimized in the slightest and serve no purpose other than to look cool. But they do remind me to keep playing with code, and that's what I feel in love with back before I was relying on it to keep a roof over my head.]]></description>
			<content:encoded><![CDATA[<div class="processing_embed" id="PolygonField_container"><script type="text/javascript">
				/* <![CDATA[ */
				var attributes = { 
					code: 'PolygonField.class',
					archive: 'http://www.breaktrycatch.com/wp-content/uploads/2011/11/PolygonField.jar,http://www.breaktrycatch.com/wp-content/plugins/wordpress-processing-embed/data/core.jar',
					width: 600, 
					height: 600,
					image: 'http://www.breaktrycatch.com/wp-content/plugins/wordpress-processing-embed/data/loading.gif'
					};
				var parameters = { };
				var version = '1.5';
				deployJava.runApplet(attributes, parameters, version);
				/* ]]&gt; */
			</script>
			<noscript><div>
				<!--[if !IE]> -->
				<object classid="java:PolygonField.class" 
					type="application/x-java-applet"
					archive="http://www.breaktrycatch.com/wp-content/uploads/2011/11/PolygonField.jar,http://www.breaktrycatch.com/wp-content/plugins/wordpress-processing-embed/data/core.jar"
					width="600" height="600"
					standby="Loading Processing software..." >
				<param name="archive" value="http://www.breaktrycatch.com/wp-content/uploads/2011/11/PolygonField.jar,http://www.breaktrycatch.com/wp-content/plugins/wordpress-processing-embed/data/core.jar" />
				
				<param name="mayscript" value="true" />
				<param name="scriptable" value="true" />
				
				<param name="image" value="http://www.breaktrycatch.com/wp-content/plugins/wordpress-processing-embed/data/loading.gif" />
				<param name="boxmessage" value="Loading Processing software..." />
				<param name="boxbgcolor" value="#FFFFFF" />
				
				<param name="test_string" value="outer" />
				<!--<![endif]-->
				
				<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
					codebase="http://java.sun.com/update/1.6.0/jinstall-6u20-windows-i586.cab"
					width="600" height="{600}"
					standby="Loading Processing software..."  >
					
					<param name="code" value="PolygonField" />
					<param name="archive" value="http://www.breaktrycatch.com/wp-content/uploads/2011/11/PolygonField.jar,http://www.breaktrycatch.com/wp-content/plugins/wordpress-processing-embed/data/core.jar" />
					
					<param name="mayscript" value="true" />
					<param name="scriptable" value="true" />
					
					<param name="image" value="http://www.breaktrycatch.com/wp-content/plugins/wordpress-processing-embed/data/loading.gif" />
					<param name="boxmessage" value="Loading Processing software..." />
					<param name="boxbgcolor" value="#FFFFFF" />
					
					<param name="test_string" value="inner" />
					
					<p>
						
						<strong>This browser does not have a Java Plug-in.
						<br />
						<a href="http://www.java.com/getjava" title="Download Java Plug-in">Get the latest Java Plug-in here.</a>
						</strong>
					</p>
				
				</object>
				<!--[if !IE]> -->
				</object>
				<!--<![endif]-->
			</div></noscript></div>
<p><center><a href="http://breaktrycatch.com/labs/polygonfield/PolygonField.pde">Source Code</a></center>Its gotten pretty serious around here with pointers flying back and forth, buffers being created and recreated again, segfaults ruining afternoons, so I thought I&#8217;d start posting the little sketches I tinker with in my spare time. These things usually evolve organically, aren&#8217;t optimized in the slightest and serve no purpose other than to look cool. But they do remind me to keep playing with code, and that&#8217;s what I feel in love with back before I was relying on it to keep a roof over my head.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/sketchy-sunday-polygon-field/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating and Configuring a DirectX 11 Project in Visual Studio 2010</title>
		<link>http://www.breaktrycatch.com/creating-and-configuring-a-directx-11-project-in-visual-studio-2010/</link>
		<comments>http://www.breaktrycatch.com/creating-and-configuring-a-directx-11-project-in-visual-studio-2010/#comments</comments>
		<pubDate>Sat, 05 Nov 2011 22:34:54 +0000</pubDate>
		<dc:creator>Jon Keon</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[Visual Studio 2010]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=878</guid>
		<description><![CDATA[After working with Visual Studio 2010 for a while, there are quite a few settings and choices you can make that will enable your projects to be easier to work with and also allow others to work on your project with you with minimal hassle. This is how I&#8217;ve ended up configuring Visual Studio 2010...]]></description>
			<content:encoded><![CDATA[<p>After working with Visual Studio 2010 for a while, there are quite a few settings and choices you can make that will enable your projects to be easier to work with and also allow others to work on your project with you with minimal hassle. This is how I&#8217;ve ended up configuring Visual Studio 2010 to work with DirectX 11. I&#8217;d be curious as to what others in the industry currently do.</p>
<h2>Prereqs:</h2>
<p>First a couple prerequisites:</p>
<ul>
<li>Download and Install Visual Studio 2010</li>
<ul>
<li>There&#8217;s a 90 Trial for all versions or a Free Edition of Visual Studio C++ Express</li>
<li><a title="Visual Studio 2010 Download Links" href="http://www.microsoft.com/visualstudio/en-au/products">Download Links</a></li>
</ul>
<li>Download and Install the June 2010 DirectX SDK</li>
<ul>
<li><a title="June 2010 DirectX Download Link" href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=6812" target="_blank">Download Link</a></li>
</ul>
</ul>
<p>Once everything is installed you can start setting up your project.</p>
<h2>Creating a Project:</h2>
<p>The first thing to do is setup your project&#8217;s directory structure on your harddrive. It&#8217;s a good idea to prepare in advance for dealing with whatever source versioning system you&#8217;re going to use as well. I&#8217;ll be using SVN through <a title="Assembla" href="http://www.assembla.com/" target="_blank">Assembla</a>. It&#8217;s free until you start going over a 1 GB or getting into the advance features but if you&#8217;re looking for an easy private place to store your code I&#8217;d recommend it.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_001.png"><img class="aligncenter size-full wp-image-879" title="Directory Structure" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_001.png" alt="" width="329" height="194" /></a></p>
<p>Not too much to say here, just your standard versioning directory structure.</p>
<p>Now you can open Visual Studio and select <strong>File &gt; New &gt; Project&#8230;</strong></p>
<p>This will bring up the New Project Dialog and you can configure it to look like this:</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_002.png"><img class="aligncenter size-medium wp-image-880" title="New VS2010 Project" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_002-300x207.png" alt="" width="300" height="207" /></a></p>
<p>Essentially you&#8217;ll just want <strong>Visual C++ &gt; Empty Project </strong>with the <strong>.NET Framework 4</strong> selected at the top.</p>
<p>You can enter whatever name you want for the project/solution but the location is somewhat important. When Visual Studio creates a project and solution it uses that directory as the working directory for placing new files and running your builds. This leads to a lot of clutter if you aren&#8217;t customizing things and ideally you want to be able to log onto any computer and just pull down your SVN repo and have everything ready to go.</p>
<p>In my project, in my <strong>trunk</strong> directory on my harddrive, I&#8217;ve created the following directories:</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_003.png"><img class="aligncenter size-medium wp-image-881" title="Directory Structure" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_003-300x195.png" alt="" width="300" height="195" /></a></p>
<ul>
<li><strong>bin</strong></li>
<ul>
<li>This is where all the executables will be built and where all the runtime data will be stored. You could just send someone the bin folder and they could run the final version of your project (not compile it though!)</li>
</ul>
<li><strong>docs</strong></li>
<ul>
<li>All the supplemental material relating to the project. Blog posts, architecture diagrams etc.</li>
</ul>
<li><strong>obj</strong></li>
<ul>
<li>When Visual Studio compiles your projects it will create .obj files for debugging. These files are often pretty large and change all the time. We want to store them in a separate directory so we can ignore them in SVN and if for some reason we have some weirdness in compiling a build, we can just delete the directory to force a recompile of the whole project.</li>
</ul>
<li><strong>raw</strong></li>
<ul>
<li>The raw directory is where all the raw assets for your project would live. PSD&#8217;s, Maya files etc. Files in this directory are where your artists would work and the final work that gets used by your program (png sequences or model files) would get put in the <strong>bin/data/</strong> directory as you&#8217;ll want to use those final produced assets at runtime.</li>
</ul>
<li><strong>src</strong></li>
<ul>
<li>This is where all your source code will code and where your programmers will spend the majority of their time.</li>
</ul>
<li><strong>tools</strong></li>
<ul>
<li>This directory is for any special tools or scripts that might help your project along. Such as taking a generic OBJ 3D Model file and converting it to some proprietary format your program uses.</li>
</ul>
<li><strong>vs</strong></li>
<ul>
<li>This is where I&#8217;ve chosen to store all the Visual Studio specific files. It keeps them out of the way and allows for the possibility of members of a team using a different IDE if they so chose.</li>
</ul>
</ul>
<p>So naturally, when I&#8217;m creating a new project I want to choose the <strong>trunk/vs</strong> directory for where to store my project.</p>
<h2>Customizing Filters:</h2>
<p>Once you&#8217;ve created your project you&#8217;ll be greeted with a blank slate and a pre-populated Solution Explorer.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_004.png"><img class="aligncenter size-full wp-image-882" title="Default Solution Explorer" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_004.png" alt="" width="194" height="122" /></a>If you&#8217;ve come from a Java or ActionScript background this will be reminiscent of a Package Explorer. The <strong>MAJOR DIFFERENCE</strong> though is that with C++, these are just filters and are virtual. They have no reflection of the file structure on the hard drive where as in Java or ActionScript, classes must be placed in a folder tree that represents their package structure.</p>
<p>The default filters are one for Header files, Resource files and Source files. I&#8217;ve looked at quite a few Open Source C++ projects and they all seem to roll their own structure depending on their needs so personally I&#8217;m going to do the same.</p>
<p>I&#8217;ve deleted the three default filters for Header files, Resource files and Source files and added a new one by right-clicking on my solution name and selecting <strong>Add &gt; New Filter&#8230;</strong> and calling it <strong>src</strong></p>
<p>This will be the root directory for all source files and then I will create a new folder on the hard drive for every new filter I create in Visual Studio. In this manner we have the concept of &#8220;packages&#8221; as they exist in AS3 or Java which I find just makes things easier to read and understand what functionality a class may contain.</p>
<p>After a bit of development you&#8217;d have something similar to this:</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_005.png"><img class="aligncenter size-medium wp-image-883" title="Solution Explorer and File System Parity" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_005-300x233.png" alt="" width="300" height="233" /></a></p>
<p>As you can see, the filters match the folders on the harddrive making it easy to see what concepts classes belong to.</p>
<h2>Configuration:</h2>
<p>Now we&#8217;ll need to configure Visual Studio so it knows where to get the proper libraries and include files to build DirectX and to make sure it knows where to place all of our files in our custom directory structure.</p>
<p>Selecting your project name in the Solution Explorer go to the menu bar and select <strong>Project &gt; Properties</strong></p>
<p>This will bring up the Property Pages screen for your projects. At the top right there is a button called <strong>Configuration Manager&#8230;</strong> We&#8217;ll want to open that so we can customize our builds.</p>
<p>By default, Visual Studio will create two builds for you. A Debug one and a Release one. The Debug build will allow you to debug and step through your code but it will run slower. The Release build is the one you&#8217;ll want to ship to your customers or end users and will run at the proper speed but you can&#8217;t debug it to check for errors.</p>
<p>Ultimately in development you&#8217;ll want to test your program under various conditions. Sometimes in tracking down a bug you&#8217;ll want as much information as possible and you won&#8217;t care how slow everything is running. Other times you&#8217;ll want to test performance and you want everything running as fast as possible. You can create as many builds as you see fit but for now I&#8217;m going with just three of them.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_006.png"><img class="aligncenter size-medium wp-image-884" title="Creating a New Build" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_006-300x212.png" alt="" width="300" height="212" /></a></p>
<p>First I&#8217;ll need to create a new build by selecting <strong>&lt;New&#8230;&gt; </strong>from the drop down for Active Solution configuration.</p>
<p>I&#8217;ll give it the name <strong>Development</strong>. This will be the build that I&#8217;ll normally be using. I can still debug, but it should run at a decent speed. <strong>Debug</strong> I&#8217;ll reserve for heavy debugging where everything is checked and logged and <strong>Release </strong>will be the fast build I&#8217;ll send out to users etc. I&#8217;ll base this build off of the current Debug build to make it easier.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_007.png"><img class="aligncenter size-medium wp-image-885" title="New Build" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_007-300x158.png" alt="" width="300" height="158" /></a></p>
<p>Now we can start editing the properties of our Build Configurations. <strong>Note:</strong> Make sure you have <strong>All Configurations</strong> selected!</p>
<p>Below are the default properties:</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_008.png"><img class="aligncenter size-medium wp-image-886" title="Default Config Props" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_008-300x213.png" alt="" width="300" height="213" /></a></p>
<p>With <strong>All Configurations </strong>selected we&#8217;re going to change<strong> Output Directory, Intermediate Directory </strong>and<strong> Build Log File.</strong></p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_0091.png"><img class="aligncenter size-medium wp-image-899" title="General All Configurations" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_0091-300x212.png" alt="" width="300" height="212" /></a></p>
<p>The Output Directory is where your program will be compiled to and where the end .exe that you click on lives. The macro <strong>$(SolutionDir)</strong> refers to where your Solution file is stored. In our case it will be in <strong>trunk/vs/&lt;project_name&gt;/&lt;solution_name&gt;. </strong>We simply jump up two directories so we&#8217;re in trunk and then select <strong>bin</strong>.</p>
<p>Now we could put the absolute path instead and have something like <strong>C:\work\code\cpp\athena\trunk\bin</strong> but this assumes that everyone using the project will have placed the project in the exact same file path which is rarely the case so relative pathing is ideal.</p>
<p>The Intermediate Directory is where the debug obj files are created and stored. Again we just jump up two directories and choose the <strong>obj </strong>directory. This time we&#8217;re also going to append another macro called <strong>$(Configuration)</strong> which is the name of your Configuration (Debug, Deployment, or Release). This will keep the obj files separate from the different builds so we&#8217;re no overwriting files all the time.</p>
<p>Finally the build log file just gets chucked into the same folder as the Intermediate Directory.</p>
<p>You&#8217;ll notice that the <strong>Target Name</strong> is blank. This is because we want the Target to be different across the different configurations. So you&#8217;ll have to change from <strong>All Configurations</strong> to <strong>Debug, Deployment, </strong>and <strong>Release</strong> respectively and choose a name. I&#8217;ve chosen:</p>
<ul>
<li><strong>Debug: </strong>$(ProjectName)_Debug</li>
<li><strong>Deployment:</strong> $(ProjectName)_Deployment</li>
<li><strong>Release: </strong>$(ProjectName)</li>
</ul>
<p>This will allow for three separate exe&#8217;s to be created based on the configuration.<br />
Next we&#8217;ll want to select the <strong>VC++ Directories</strong> tab and make sure that <strong>All Configurations</strong> is selected again.<br />
<a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_010.png"><img class="aligncenter size-medium wp-image-889" title="VC++ Directories" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_010-300x213.png" alt="" width="300" height="213" /></a><br />
Select the <strong>Include Directories</strong> and click on <strong>Edit&#8230; </strong>Then add the DirectX include directory from <strong>C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Include</strong><br />
Also include your source directory! So add <strong>$(SolutionDir)..\..\src\</strong> as well.<br />
<a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_011.png"><img class="aligncenter size-medium wp-image-890" title="DX11 Include" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_011-300x262.png" alt="" width="300" height="262" /></a><br />
Then do the same thing for the <strong>Library Directories</strong> and add the DirectX lib directory from <strong>C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)\Lib\x86</strong><br />
<a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_012.png"><img class="aligncenter size-medium wp-image-891" title="DX11 Lib" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_012-300x260.png" alt="" width="300" height="260" /></a><br />
Now Visual Studio will know where to find the Header files it needs to compile and the Linker will know where to find the various libraries it needs.</p>
<h2>Debug Specific Configuration Settings:</h2>
<p>Now we&#8217;ll want to go through and set up the specific configuration settings for our various deployments. We&#8217;ll start with <strong>Debug.</strong></p>
<p>Choose the <strong>C/C++</strong> tab and choose <strong>General</strong>. Make sure you have <strong>Debug</strong> selected as your Configuration!</p>
<p>By default the <strong>Debug Information Format</strong> should be set to <strong>Program Database for Edit and Continue (/ZI)</strong> which will let us edit the code while debugging and have changes update in real time.</p>
<p>I&#8217;ve upped the <strong>Warning Level</strong> to <strong>Level3(/W3)</strong>. I tried to enable all Warnings or go to W4 but it found a ton of them in the Windows code and that was just annoying.</p>
<p>I also set the compiler to treat <strong>Warnings </strong>as errors. While a warning won&#8217;t break your program, it&#8217;s a good idea to fix any warnings immediately before they get out of hand.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_0131.png"><img class="aligncenter size-medium wp-image-901" title="Debug C++ General" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_0131-300x212.png" alt="" width="300" height="212" /></a></p>
<p>&nbsp;</p>
<p>Next select the <strong>Optimization </strong>tab. There shouldn&#8217;t be anything to modify as we don&#8217;t want any optimization while debugging. It should look like this:</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_014.png"><img class="aligncenter size-medium wp-image-893" title="Debug C++ Optimization" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_014-300x212.png" alt="" width="300" height="212" /></a></p>
<p>Next select the <strong>Preprocessor </strong>tab. We&#8217;re just going to add our own Preprocessor Definition so we know the difference between our <strong>Debug</strong> and <strong>Deployment</strong> builds.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_015.png"><img class="aligncenter size-medium wp-image-894" title="Debug C++ Preprocessor" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_015-300x212.png" alt="" width="300" height="212" /></a></p>
<p>Finally select the <strong>Code Generation</strong> tab. The defaults should be fine but for <strong>Edit and Continue</strong> to work properly, the setting <strong>Enable Function-Level Linking </strong>should be set to <strong>Yes</strong>.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_016.png"><img class="aligncenter size-medium wp-image-895" title="Debug C++ Code Generation" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_016-300x213.png" alt="" width="300" height="213" /></a>The rest of the settings should be fine as the defaults.</p>
<p>&nbsp;</p>
<h2>Development Specific Configuration Settings:</h2>
<p>The <strong>Development </strong>configuration settings are the exact same as the <strong>Debug </strong>ones except that the preprocessor definition is <strong>ATHENA_DEVELOPMENT </strong>instead of <strong>ATHENA_DEBUG.</strong></p>
<h2>Release Specific Configuration Settings:</h2>
<p>With <strong>Release</strong> mode, the settings are largely the same but we&#8217;ll make a few changes to a couple of the screens and turn on Optimizations.</p>
<p>In the <strong>General </strong>screen, we don&#8217;t need <strong>Edit and Continue</strong> functionality and we can also use <strong>Multi-Processor Compilation</strong> for faster compiling.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_0171.png"><img class="aligncenter size-medium wp-image-902" title="Release C++ General" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_0171-300x212.png" alt="" width="300" height="212" /></a></p>
<p>&nbsp;</p>
<p>In the <strong>Optimization </strong>screen, we want to enable as much as possible to make our program run as fast as possible. <strong>NOTE: </strong>When optimizations are enabled, even if you happen to be debugging, the information you&#8217;ll see on screen will not be accurate due to the changes the compiler makes to your code when compiling.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_018.png"><img class="aligncenter size-medium wp-image-897" title="Release C++ Optimization" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_018-300x212.png" alt="" width="300" height="212" /></a></p>
<p>The defaults for the rest of the screens are fine for Release mode.</p>
<p>&nbsp;</p>
<h2>Building:</h2>
<p>Now that everything is set up you should be able to build and run your program using the three configurations and all of the files will be created at the correct locations on the harddrive.</p>
<p>&nbsp;</p>
<h2>Additional Visual Studio 2010 Plugins:</h2>
<p>At this point there are a few Visual Studio 2010 Plugins that are great for helping you code.</p>
<ul>
<li><a title="Visual Assist X" href="http://www.wholetomato.com/downloads/downloadTrial.asp" target="_blank">Visual Assist X </a></li>
<ul>
<li>Great plugin for intellisense among other things. Has a 30 day trial and then a personal licence is only $90. Could be cheaper but it&#8217;s still pretty good.</li>
</ul>
<li><a title="Productivity Power Tools" href="http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef" target="_blank">Productivity Power Tools</a></li>
<ul>
<li>Getting this free plugin for the CTRL-Click ability alone is worth it. Also comes with some neat features like a scrollbar that is a smaller version of your code.</li>
</ul>
</ul>
<h2>Additional Visual Studio 2010 Configurations:</h2>
<p>Custom Tasks are sometimes something you&#8217;ll want to add to your comments to let you know why something was done a certain way and to come back to it.</p>
<p>To add your own custom tasks go to <strong>Tools &gt; Options. </strong>When the Options screen comes up select <strong>Environment &gt; Task List</strong>. Then to add a new one simply type in the name and choose a priority and then select <strong>Add.</strong></p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_019.png"><img class="aligncenter size-medium wp-image-903" title="Custom Tasks" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_019-300x174.png" alt="" width="300" height="174" /></a><br />
To actually enable these Tasks to be shown in your Task Window, you need to enable it by going to <strong>Text Editor &gt; C/C++ &gt; Formatting</strong> and then selecting <strong>Enumerate Comment Tasks</strong> to true.<br />
<a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_020.png"><img class="aligncenter size-medium wp-image-904" title="Enabling Comment Tasks" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_020-300x174.png" alt="" width="300" height="174" /></a></p>
<h2>Committing to Source Control:</h2>
<p>Now that everything is all setup, we&#8217;ll want to save this to our Source Control server so that no matter where we are, we can always pull the project down and build it.</p>
<p>Ideally you&#8217;ll want to version control everything that is necessary to build your program. This includes assets and the like but it depends on how much space you need. Version controlling 4GB+ raw video files may not be the wisest of solutions.</p>
<p>At the very least we need the source code and project settings.</p>
<p>I&#8217;ll go through the directories we created earlier for what should and should not be committed.</p>
<ul>
<li><strong>bin</strong></li>
<ul>
<li>We&#8217;ll want to commit anything in the <strong>data</strong> folder as those are final assets that the program needs at runtime. I&#8217;ve committed my <strong>logs</strong> folder so it exists, but everything inside that folder gets added to SVN Ignore.</li>
<li>All of the exe&#8217;s and their corresponding pdb and ilk files get added to SVN Ignore as well since we&#8217;ll be building those again and frequently.</li>
</ul>
</ul>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_021.png"><img class="aligncenter size-medium wp-image-905" title="Bin Folder SVN" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_021-300x209.png" alt="" width="300" height="209" /></a></p>
<ul>
<li><strong>docs</strong></li>
<ul>
<li>Everything in here gets committed.</li>
</ul>
<li><strong>obj</strong></li>
<ul>
<li>Everything inside the obj folder gets added to SVN Ignore. These files get recreated on every build and are not necessary to save.</li>
</ul>
<li><strong>raw</strong></li>
<ul>
<li>Judgement call based on your raw assets. Better to be safe than sorry.</li>
</ul>
<li><strong>src</strong></li>
<ul>
<li>Without a doubt yes! Everything gets committed.</li>
</ul>
<li><strong>tools</strong></li>
<ul>
<li>Same here, all the tools should get committed.</li>
</ul>
<li><strong>vs</strong></li>
<ul>
<li>We only want to commit the <strong>.sln</strong> file in the Solution Directory.</li>
<li>And only the <strong>.vcxproj</strong> and <strong>.vcxproj.filters</strong> files in the Project Directory.</li>
<li>This way only the settings that work across different computers get saved and all the user information and custom aspects are unique from user to user.</li>
</ul>
</ul>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_022.png"><img class="aligncenter size-medium wp-image-906" title="Solution Directory Ignores" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_022-300x175.png" alt="" width="300" height="175" /></a><br />
<a href="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_023.png"><img class="aligncenter size-medium wp-image-907" title="Project Directory Ignores" src="http://www.breaktrycatch.com/wp-content/uploads/2011/11/Post_023-300x106.png" alt="" width="300" height="106" /></a><br />
Now you can commit and update as much as you like. It&#8217;s a bit of a process but getting Visual Studio configured in this way makes development much easier across the board.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/creating-and-configuring-a-directx-11-project-in-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Getting Started With DirectX 11</title>
		<link>http://www.breaktrycatch.com/getting-started-with-directx-11/</link>
		<comments>http://www.breaktrycatch.com/getting-started-with-directx-11/#comments</comments>
		<pubDate>Sat, 29 Oct 2011 16:01:45 +0000</pubDate>
		<dc:creator>Jon Keon</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[DirectX11]]></category>
		<category><![CDATA[directx]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=861</guid>
		<description><![CDATA[Now that we have a bit of a basic framework going with the SystemWindow, we can start using that Window to actually display something. In this case, we&#8217;re going to get up and running with DirectX 11. While DirectX 9 is still somewhat relevant, it&#8217;s rapidly diminishing and with Microsoft announcing that they will be...]]></description>
			<content:encoded><![CDATA[<p>Now that we have a bit of a basic framework going with the <a title="Windows: Part 2" href="http://www.breaktrycatch.com/windows-part-2/">SystemWindow</a>, we can start using that Window to actually display something.</p>
<p>In this case, we&#8217;re going to get up and running with DirectX 11. While DirectX 9 is still somewhat relevant, it&#8217;s rapidly diminishing and with Microsoft announcing that they will be dropping support for Windows XP, everyone will be moving onward to a new OS (most likely Win7 or Win8). DirectX 10 (and 10.1) are somewhat of a black sheep in that it wasn&#8217;t around long enough before 11 came out to gain traction and personally feels a bit like a beta of DirectX 11. So in the interest of keeping relevant and modern, I&#8217;m only going to focus on and implement for DirectX 11.</p>
<p>There is DirectX 11.1 but that&#8217;s for the Win8 Developer preview build and mostly suited towards building Metro applications. Once Win8 is released and DX11.1 has noticeable improvements to vanilla DX11, I&#8217;ll make the jump and upgrade.</p>
<p><strong>Requirements:</strong></p>
<ul>
<li>DirectX 11 Compatible Video Card</li>
</ul>
<p>There&#8217;s really only one requirement and that&#8217;s to have a DirectX 11 Compatible Video Card. If you have a recent computer, most likely you&#8217;re good to go but just be aware.</p>
<p><strong>Architecture:</strong></p>
<p>I&#8217;ll be keeping with the idea behind the SystemWindow class and creating a SystemGraphics class. Any of the &#8220;System&#8221; classes will eventually be used for Platform Independence should I decide to support running on a Mac/Linux in addition to Windows or allowing for different Graphics API&#8217;s such as OpenGL or a Software Rasterizer. Most likely I&#8217;ll just be sticking with Windows and DirectX but it&#8217;s good to plan ahead.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/10/Image_007.png"><img class="aligncenter size-full wp-image-862" title="Very Basic Athena Architecture" src="http://www.breaktrycatch.com/wp-content/uploads/2011/10/Image_007.png" alt="" width="559" height="121" /></a><br />
We&#8217;ll start by taking a look at the SystemGraphics.h file.</p>
<h2>SystemGraphics.h</h2>
<pre class="brush: cpp; title: ; notranslate">
/*********************************
*Class: D3D11API
*Description:
*Author: jkeon
**********************************/

#ifndef _SYSTEMGRAPHICS_H_
#define _SYSTEMGRAPHICS_H_

//////////////////////////////////////////////////////////////////////
// LINKING ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#pragma comment(lib, &quot;dxgi.lib&quot;)
#pragma comment(lib, &quot;d3d11.lib&quot;)

//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &amp;lt;util/DebugUtil.h&amp;gt;
#include &amp;lt;util/Macros.h&amp;gt;
#include &amp;lt;engine/platform/window/SystemWindow.h&amp;gt;
#include &amp;lt;DXGI.h&amp;gt;
#include &amp;lt;D3D11.h&amp;gt;
#include &amp;lt;vector&amp;gt;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {

	//////////////////////////////////////////////////////////////////////
	// GLOBALS ///////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////
	// CLASS DECLARATION /////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	class SystemGraphics {

	//TYPEDEFS
		typedef std::vector&amp;lt;IDXGIAdapter1*&amp;gt; IDXGIAdapterVector;
		typedef std::vector&amp;lt;IDXGIOutput*&amp;gt; IDXGIOutputVector;

	//PUBLIC FUNCTIONS
	public:
		SystemGraphics();
		virtual ~SystemGraphics();

		bool Init(SystemWindow *window, int adapterIndex, int outputIndex, int numBackBuffers, bool vsync);
		void Destroy();

		void Begin();
		void End();

		bool ToggleFullScreen(bool fullScreen);

		void GetDXGIAdapters(IDXGIAdapterVector &amp;amp;adapterVector);
		void SetDXGIAdapter(UINT adapterIndex, IDXGIAdapter1 *adapter);

		void GetDXGIOutputs(IDXGIOutputVector &amp;amp;outputVector);
		void SetDXGIOutput(UINT outputIndex, IDXGIOutput *output);

		DXGI_MODE_DESC* GetDisplayModes();
		void SetDisplayMode(DXGI_MODE_DESC *displayMode);

		DXGI_ADAPTER_DESC1* GetAdapterDesc();

	//PUBLIC VARIABLES
	public:

	//PROTECTED FUNCTIONS
	protected:

	//PROTECTED VARIABLES
	protected:

	//PRIVATE FUNCTIONS
	private:
		SystemGraphics(const SystemGraphics&amp;amp; other);
		SystemGraphics&amp;amp; operator = (const SystemGraphics&amp;amp; other);

		bool InitDXGIFactory();
		bool InitDXGIAdapter();
		bool InitDXGIOutput();
		bool InitDisplayModes();
		bool InitSwapChainDesc();
		bool InitDeviceAndSwapChain();
		bool InitBackBuffer();
		bool InitViewport();

		void OnWindowResize(WPARAM wparam, LPARAM lparam);

	//PRIVATE VARIABLES
	private:

		HRESULT hr;

		bool m_fullScreen;
		bool m_vsync;

		SystemWindow* p_window;

		int m_numBackBuffers;
		int m_msaaLevel;
		int m_msaaQuality;

		UINT m_adapterIndex;
		UINT m_outputIndex;

		IDXGIFactory1* p_factory;
		IDXGIAdapter1* p_adapter;
		IDXGIOutput* p_output;

		DXGI_FORMAT m_desiredFormat;
		DXGI_MODE_DESC* p_displayModes;
		DXGI_MODE_DESC m_displayMode;

		DXGI_ADAPTER_DESC1 m_adapterDesc;

		DXGI_SWAP_CHAIN_DESC m_swapChainDesc;

		IDXGISwapChain* p_swapChain;
		ID3D11Device* p_device;
		ID3D11DeviceContext* p_deviceContext;

		ID3D11Texture2D* p_backbuffer;
		ID3D11RenderTargetView* p_backbufferRenderTarget;

		D3D11_VIEWPORT m_viewport;

		D3D_FEATURE_LEVEL m_targetFeatureLevel;
		D3D_FEATURE_LEVEL m_highestFeatureLevel;

	};

	//////////////////////////////////////////////////////////////////////
	// STATICS ///////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

}
#endif
</pre>
<p>Not too much to say here as it&#8217;s very basic. All we really do is initialize and destroy the various DirectX components and have a few helper methods. Obviously this class isn&#8217;t even close to complete as we  will need to add a lot more functionality to be able to actually render something. But again, it&#8217;s all about baby steps and making sure you have a solid understanding of the foundations you are building on top of.</p>
<p>It&#8217;s boring and unsatisfying to have to do some much grunt work just to get things going but it&#8217;s necessary. This also means that you&#8217;re going to be doing a lot of reading instead of coding at the beginning. I&#8217;d highly recommend the series by <strong>Fabian Giesen</strong> on the <a title="Through the Graphics Pipeline" href="http://fgiesen.wordpress.com/2011/07/01/a-trip-through-the-graphics-pipeline-2011-part-1/">Graphics Pipeline</a>. It&#8217;s a 13 part, heavy in the theory series but it gives you a great understanding of how everything works under the hood and makes the functions that the DX11 API exposes much more meaninful.</p>
<p>In addition, I&#8217;d also always have a window to <a title="MSDN" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff476147(v=VS.85).aspx">MSDN </a>open. It can be tricky to navigate the site but just copy pasting the function or flag into Google generates the first hit and you can see exactly what you need to pass in, what it returns and (hopefully) why.</p>
<p>&nbsp;</p>
<h2> Constructor:</h2>
<pre class="brush: cpp; title: ; notranslate">
SystemGraphics::SystemGraphics() {

		m_fullScreen = false;
		m_vsync = false;

		m_adapterIndex = 0;
		m_outputIndex = 0;

		m_numBackBuffers = 1;
		m_msaaLevel = 1;
		m_msaaQuality = 0;

		m_desiredFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
		m_targetFeatureLevel = D3D_FEATURE_LEVEL_11_0;

		p_window = NULL;

		p_factory = NULL;
		p_adapter = NULL;
		p_output = NULL;
		p_displayModes = NULL;

		p_swapChain = NULL;
		p_device = NULL;
		p_deviceContext = NULL;

		p_backbuffer = NULL;
		p_backbufferRenderTarget = NULL;
	}
</pre>
<p>Once again, the Constructor does nothing but initialize pointers to be NULL and set a few of the member variables to defaults.</p>
<h2>Init:</h2>
<pre class="brush: cpp; title: ; notranslate">
bool SystemGraphics::Init(SystemWindow *window, int adapterIndex, int outputIndex, int numBackBuffers, bool vsync) {

		p_window = window;
		m_fullScreen = p_window-&amp;gt;IsFullScreen();
		m_adapterIndex = adapterIndex;
		m_outputIndex = outputIndex;
		m_numBackBuffers = numBackBuffers;
		m_vsync = vsync;

		FAIL_ON_INIT(InitDXGIFactory());
		FAIL_ON_INIT(InitDXGIAdapter());
		FAIL_ON_INIT(InitDXGIOutput());
		FAIL_ON_INIT(InitDisplayModes());
		FAIL_ON_INIT(InitSwapChainDesc());
		FAIL_ON_INIT(InitDeviceAndSwapChain());
		FAIL_ON_INIT(InitBackBuffer());
		FAIL_ON_INIT(InitViewport());

		p_window-&amp;gt;AddMessageCallback(WM_SIZE, BIND_MEM_CB(&amp;amp;SystemGraphics::OnWindowResize, this));

		return true;
	}
</pre>
<p>The Init function is again where everything actually starts up. It takes in a pointer to a <strong>SystemWindow</strong> so that the <strong>SystemGraphics</strong> class knows what Window we are going to be rendering to. We also use the window to determine whether we are in FullScreen mode or not.</p>
<p>The adapter index and output index refer to the index of the video card and monitor attached to that video card respectively on your current system. This will seem a bit catch-22 at the moment but once we are saving/loading user configuration settings, these values will make sense.</p>
<p>By default, we&#8217;ll have them both set to 0, although in the future we&#8217;ll want to default to the user&#8217;s best video card and the primary monitor attached to that videocard.</p>
<p>The number of back buffers is a setting for whether we want to use <a title="Buffering" href="http://en.wikipedia.org/wiki/Multiple_buffering">Double Buffering or Triple Buffering</a>.</p>
<p>Vsync is whether we want to run as fast as possible at the expense of potentially wasted frames or limit ourselves to the monitor refresh rate at the potential drastic loss of framerate when one frame takes too long to render. There&#8217;s a great explanation of what Vsync is and how it affects your experience <a title="VSync" href="http://hardforum.com/showthread.php?t=928593">here</a>.</p>
<p>Next we initialize all of the sub components of the SystemGraphics class. The FAIL_ON_INIT macro is a very simple macro to make the code a bit more readable and clean that essentially says if any of these functions fail, don&#8217;t execute the next one and return false.</p>
<pre class="brush: cpp; title: ; notranslate">
//FAIL_ON_INIT - Returns false if the passed value equates to false. Used for exiting a chain of init statements
#define FAIL_ON_INIT(p) {if ((p) == false) { return false;}}
</pre>
<p>Finally we add a callback to the <strong>SystemWindow</strong> class for when the Window Resizes. This allows the Graphics components to resize themselves as well to keep in sync with any resizing that happens with our Window.</p>
<h2>InitDXGIFactory:</h2>
<pre class="brush: cpp; title: ; notranslate">
//TODO: If this fails, we should throw up a message box or something and tell the user it's all over.
	bool SystemGraphics::InitDXGIFactory() {
		//Create a DXGI Factory
		hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&amp;amp;p_factory);
		if (FAILED(hr)) {
			etrace(&quot;CreateDXGIFactory1 Failed!&quot;);
			return false;
		}
		return true;
	}
</pre>
<p>It all starts with creating an instance of a <a title="IDXGIFactory1" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff471335(v=vs.85).aspx">IDXGIFactory1</a>. Starting with DirectX 10, Microsoft introduced the concept of <a title="DXGI" href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb205075(v=VS.85).aspx">DXGI </a>or Direct X Graphics Infrastructure. You can read more at the link but essentially it serves to help handle some of the low level operations that need to happen so you can focus more on implementing graphics.</p>
<p>If for whatever reason (and I really mean whatever&#8230; I have no idea how or why this would fail) we can&#8217;t create a DXGIFactory then it&#8217;s really all over and we can&#8217;t continue. In the future I&#8217;ll add some way of letting the user know this.</p>
<h2>InitDXGIAdapter:</h2>
<pre class="brush: cpp; title: ; notranslate">
//TODO: If this fails, we should fallback to enumerating the Adapters and selecting the first one.
	bool SystemGraphics::InitDXGIAdapter() {
		//Get the Primary Adapter (Video Card)
		hr = p_factory-&amp;gt;EnumAdapters1(m_adapterIndex, &amp;amp;p_adapter);
		if (FAILED(hr)) {
			etrace(&quot;EnumAdapters1 Failed!&quot;);
			return false;
		}
		return true;
	}
</pre>
<p>Once we have a factory we can use that factory to get access to the video cards attached to your system. Now in most cases, the user will only have one video card. But if you&#8217;re on a laptop you might have an integrated graphics solution on your motherboard and a video card. If you&#8217;re on a dev machine or you&#8217;re a hardcore pc enthusiast, it&#8217;s possible that you might have more than one video card.</p>
<p>To get the Adapter we pass in the adapter index. This is the &#8220;slot&#8221; the video card occupies in your system. By default we set this to 0 since if you only have one video card this is the slot it will occupy. If for some reason there are no video cards in at the slot we&#8217;ve specified we should try and see all the video cards attached to the system and choose the best one (Highest memory/processor speed most likely). If there are no video cards then we can&#8217;t do any DirectX and we&#8217;ll have to let the user know and quite the program.</p>
<p>Again all future problems that we can deal with later when we&#8217;re polishing. For now the main thing is Adapter = Video Card, we want the one in Slot 0.</p>
<h2>InitDXGIOutput:</h2>
<pre class="brush: cpp; title: ; notranslate">
//TODO: If this fails, we should fallback to enumerating the Outputs and selecting the first one.
	bool SystemGraphics::InitDXGIOutput() {
		//Get the Primary Output (Monitor) using the Adapter
		hr = p_adapter-&amp;gt;EnumOutputs(m_outputIndex, &amp;amp;p_output);
		if (FAILED(hr)) {
			etrace(&quot;EnumOutputs Failed!&quot;);
			return false;
		}
		return true;
	}
</pre>
<p>Now that we have an Adapter we need to get the Output associated with it. An Output is usually a Monitor but could be a TV, Projector, Laptop screen etc. If you have the physical video card in front of you, whatever is plugged into the back of it via a VGA/DVI/HDMI is an Output.</p>
<p>Again we&#8217;re using the output index which we default to 0 and we want to use the primary monitor to display our graphics to. In the possibility that there is no Output at that slot, we&#8217;ll want to loop through all connected Outputs and choose the &#8220;best&#8221; one. If nothing is connected to the video card, then there&#8217;s nothing we can display and we&#8217;ll need to exit and let the user know. (Although without a monitor&#8230; this may be tricky. Morse code system beeps?)</p>
<h2>InitDisplayModes:</h2>
<pre class="brush: cpp; title: ; notranslate">
bool SystemGraphics::InitDisplayModes() {
		UINT numModes;
		//TODO: Pull these in from elsewhere
		int matchWidth = GetSystemMetrics(SM_CXSCREEN);
		int matchHeight = GetSystemMetrics(SM_CYSCREEN);
		//Get the Display Modes that fit the DXGI FORMAT
		//TODO: Which format should we use? Which Flags? Why?
		hr = p_output-&amp;gt;GetDisplayModeList(m_desiredFormat, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &amp;amp;numModes, NULL);
		if (FAILED(hr)) {
			etrace(&quot;GetDisplayModeList for Formats Failed!&quot;);
			return false;
		}

		//Create the DXGI Mode Description
		p_displayModes = new DXGI_MODE_DESC[numModes];
		if (p_displayModes == NULL) {
			etrace(&quot;Creation of DXGI_MODE_DESC Array with %i modes Failed!&quot;, numModes);
			return false;
		}

		//Populate the DXGI_MODE_DESC list with structures of supported Display Modes
		hr = p_output-&amp;gt;GetDisplayModeList(m_desiredFormat, DXGI_ENUM_MODES_INTERLACED, &amp;amp;numModes, p_displayModes);
		if (FAILED(hr)) {
			etrace(&quot;GetDisplayModeList for populating DXGI_MODE_DESC Array Failed!&quot;);
			return false;
		}

		//Choose the Display Mode that most closely matches our current screen resolution
		ZeroMemory(&amp;amp;m_displayMode, sizeof(m_displayMode));
		int i;
		int len = (int)numModes;
		for (i = 0; i &amp;lt; len; ++i) {
			if (p_displayModes[i].Width == matchWidth &amp;amp;&amp;amp; p_displayModes[i].Height == matchHeight) {
				m_displayMode = p_displayModes[i];
				return true;
			}
		}

		etrace(&quot;No suitable display mode was found for resolution of %i, %i!&quot;, matchWidth, matchHeight);
		return false;
	}
</pre>
<p>Great, so now we have a VideoCard and a Monitor from DXGI in the form of an Adapter and Output. We now need to know what Display Modes our Output supports so we can ensure that our rendering formats and timings are compatible.</p>
<p>The first thing we&#8217;ll want to do is determine what our current resolution of the screen is with the <a title="GetSystemMetrics" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx">GetSystemMetrics </a>function. This part is a bit of a catch-22 because in most games you can specify a resolution that is not the same as what your current screen resolution is. Ideally we want to use whatever the user has specified in their settings but if it&#8217;s the first time ever, we should default to the current screen size as most LCD monitors only operate really well at their native resolutions.</p>
<p>Next we call the <a title="GetDisplayModeList" href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb174549(v=vs.85).aspx" target="_blank">GetDisplayModeList </a>function on our Output. As weird as it is, this function is intended to be called twice. The first time we want to populate our <strong>numModes</strong> variable to see how many different modes our monitor supports. Then we can create an array of <a title="DXGI_MODE_DESC" href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb173064(v=vs.85).aspx" target="_blank">DXGI_MODE_DESC </a>that has that many elements in it and call the function again to populate that array.</p>
<p>You&#8217;ll notice that I still need to do some investigation on which format and which flags I should be using to get the modes. For now the desired format is <a title="Formats" href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb173059(v=vs.85).aspx" target="_blank">DXGI_FORMAT_R8G8B8A8_UNORM</a> because that is what most of the tutorials set it as. The flags for Interlaced and Scaling are there for the same reason. I don&#8217;t think we really care about Interlaced unless we&#8217;re outputting to a TV and ideally we want to stay away from scaled resolutions so we can avoid stretching but again, I still need to research this more in depth.</p>
<p>Once we have all the possible display modes that our Output can support, we need to choose one to use. We simply iterate through all of them until we find one that matches our desired screen resolution. If we can&#8217;t find one we&#8217;ll have to handle this error eventually and let the user choose a supported display mode.</p>
<h2>InitSwapChainDesc:</h2>
<pre class="brush: cpp; title: ; notranslate">
bool SystemGraphics::InitSwapChainDesc() {
		//Construct our SwapChainDesc
		ZeroMemory(&amp;amp;m_swapChainDesc, sizeof(m_swapChainDesc));

		//Double or Triple Buffering
		m_swapChainDesc.BufferCount = m_numBackBuffers;

		//BUFFER DESC
		m_swapChainDesc.BufferDesc.Format = m_desiredFormat;
		m_swapChainDesc.BufferDesc.Height = m_displayMode.Height;
		m_swapChainDesc.BufferDesc.RefreshRate.Numerator = (m_vsync) ? m_displayMode.RefreshRate.Numerator : 0;
		m_swapChainDesc.BufferDesc.RefreshRate.Denominator = (m_vsync) ? m_displayMode.RefreshRate.Denominator : 1;
		m_swapChainDesc.BufferDesc.Scaling = m_displayMode.Scaling;
		m_swapChainDesc.BufferDesc.ScanlineOrdering = m_displayMode.ScanlineOrdering;
		m_swapChainDesc.BufferDesc.Width = m_displayMode.Width;

		m_swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

		m_swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

		m_swapChainDesc.OutputWindow = *p_window-&amp;gt;GetHWND();

		//SAMPLE DESC
		m_swapChainDesc.SampleDesc.Count = m_msaaLevel;
		m_swapChainDesc.SampleDesc.Quality = m_msaaQuality;

		m_swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

		m_swapChainDesc.Windowed = TRUE;

		return true;
	}
</pre>
<p>Next up is creating a <a title="DXGI_SWAP_CHAIN_DESC" href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb173075(v=vs.85).aspx">DXGI_SWAP_CHAIN_DESC</a>. This is simply a structure to define what our SwapChain will do before we create it.</p>
<p>First this to do is initialize it by zeroing out the memory it occupies. We do this so that all the values are set to defaults in case we forget to set one and doesn&#8217;t contain any garbage values.</p>
<p>The <strong>BufferCount </strong>is where we tie in our desire for Double or Triple buffering.</p>
<p>The <strong>BufferDesc</strong> is a description structure for how each of those back buffers will behave. We set the format based on our desired format and fill in the rest of the parameters based on the chosen display mode. Note that if we have vsync enabled, we want to override the RefreshRate so that we can draw as a fast as our hardware will let us.</p>
<p>The <strong>BufferUsage</strong> is a flag to say we will be using these buffers to render to them from DirectX.</p>
<p>The <strong>Flags</strong> are option settings. We specify the <a title="SWAP CHAIN FLAGS" href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb173076(v=vs.85).aspx">DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH </a>because this will allow us to use Alt-Enter for toggling between Fullscreen and windowed mode and it will also ensure that we can hook into the Size messages from Windows to resize our buffers properly when that switch occurs.</p>
<p>The <strong>OutputWindow</strong> is simply the handle of our window instance from the <strong>SystemWindow</strong>.</p>
<p>The <strong>SampleDesc</strong> specifies what sort of <a title="MSAA" href="http://en.wikipedia.org/wiki/Multisample_anti-aliasing">MSAA </a>we want to use. For now we set it to nothing.</p>
<p>The <strong>SwapEffect</strong> specifies what we want to have happen to our front buffer after we switch to the next back buffer. Sometimes you want to keep that front buffer around in order to perform some sort of post processing on it. But for the most part, once it&#8217;s been shown, it&#8217;s old news and you&#8217;ll want to discard it, hence the flag <a title="SWAP EFFECTS" href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb173077(v=vs.85).aspx">DXGI_SWAP_EFFECT_DISCARD</a>.</p>
<h2>InitDeviceAndSwapChain:</h2>
<pre class="brush: cpp; title: ; notranslate">
bool SystemGraphics::InitDeviceAndSwapChain() {

		//TODO: Flags we might be concerned with are the Debug D3D11_CREATE_DEVICE_DEBUG

		//Create the Device and Swap Chain - If we specify the Adapter the type must be D3D_DRIVER_TYPE_UNKNOWN
		hr = D3D11CreateDeviceAndSwapChain(p_adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, &amp;amp;m_targetFeatureLevel, 1, D3D11_SDK_VERSION, &amp;amp;m_swapChainDesc, &amp;amp;p_swapChain, &amp;amp;p_device, &amp;amp;m_highestFeatureLevel, &amp;amp;p_deviceContext);
		if (FAILED(hr)) {
			etrace(&quot;D3D11CreateDeviceAndSwapChain Failed!&quot;);
			return false;
		}
		return true;
	}
</pre>
<p>Now we can actually create our SwapChain and in the process, create a Device and a DeviceContext. These three pieces are what you will interact with to make DirectX do what you want it to do.</p>
<p>Fortunately there&#8217;s a very simple and easy function to do this for us, <a title="D3D11CreateDeviceAndSwapChain" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff476083(v=vs.85).aspx">D3D11CreateDeviceAndSwapChain</a>.</p>
<p>The function takes in our Adapter that we acquired earlier. You can pass NULL in here and the function will take the primary Adapter it finds. I think it&#8217;s better to be explicit if we can.</p>
<p>Note that if we specify an Adapter we have to specify that the the <strong>DriverType</strong> is D3D_DRIVER_TYPE_UNKNOWN. Since we know that our Adapter is actually a video card this will resolve internally to D3D_DRIVER_TYPE_HARDWARE which is what we want anyway.</p>
<p>The next parameter is for if we wanted to use Software Rendering which we don&#8217;t so we can just set it to NULL.</p>
<p>Next are flags which i&#8217;ve set to 0 for now but will probably set the D3D11_CREATE_DEVICE_DEBUG flag when running in DebugMode. This will require changes to the pragma library links at the top of the header to link against the debug versions of those DLL&#8217;s too.</p>
<p>The target feature level is the Feature level that we want to try and get from the Device. Since we&#8217;re doing DirectX11 we want to use D3D_FEATURE_LEVEL_11_0.</p>
<p>Next is the number of feature levels in our target feature level array which is currently just 1.</p>
<p>Next you always specify D3D11_SDK_VERSION. Not sure why this isn&#8217;t just defaulted.</p>
<p>Then it&#8217;s just a pointer to our swap chain description, the pointer to where we want to store our swapchain and the pointer to where we want to store our device.</p>
<p>The next parameter will get written into with the highest feature level we can support. This should equal D3D_FEATURE_LEVEL_11_0 if you have a DirectX 11 compatible video card.</p>
<p>Finally, we pass the location for DirectX to populate our Device Context.</p>
<h2>InitBackBuffer:</h2>
<pre class="brush: cpp; title: ; notranslate">
bool SystemGraphics::InitBackBuffer() {
		hr = p_swapChain-&amp;gt;GetBuffer(0, __uuidof(p_backbuffer), reinterpret_cast&amp;lt;void**&amp;gt;(&amp;amp;p_backbuffer));
		if (FAILED(hr)) {
			etrace(&quot;Get Buffer Failed!&quot;);
			return false;
		}

		//TODO: D3D11_RENDER_TARGET_VIEW_DESC

		hr = p_device-&amp;gt;CreateRenderTargetView(p_backbuffer, NULL, &amp;amp;p_backbufferRenderTarget);
		if (FAILED(hr)) {
			etrace(&quot;Create Render Target View Failed!&quot;);
			return false;
		}

		//TODO: Handle DepthStencil
		p_deviceContext-&amp;gt;OMSetRenderTargets(1, &amp;amp;p_backbufferRenderTarget, NULL);

		return true;
	}
</pre>
<p>Ok, almost there. Next we need to get access to our backbuffer since that is what we will be drawing to. We simply get the first backbuffer and then create a RenderTargetView using that backbuffer.</p>
<p>There are still more things to configure but we can do that later.</p>
<p>Once we have a RenderTargetView we can tell our Device Context to use it to render to.</p>
<h2>InitViewport:</h2>
<pre class="brush: cpp; title: ; notranslate">
bool SystemGraphics::InitViewport() {
		ZeroMemory(&amp;amp;m_viewport, sizeof(m_viewport));

		m_viewport.Width = (float)m_displayMode.Width;
		m_viewport.Height = (float)m_displayMode.Height;
		m_viewport.TopLeftX = 0.0f;
		m_viewport.TopLeftY = 0.0f;
		m_viewport.MinDepth = 0.0f;
		m_viewport.MaxDepth = 1.0f;

		p_deviceContext-&amp;gt;RSSetViewports(1, &amp;amp;m_viewport);

		return true;
	}
</pre>
<p>&nbsp;</p>
<p>The last step is to create a Viewport. We simply initialize it with our screen size values and tell the device context to use this viewport when rendering to our previously set RenderTargetView.</p>
<h2>Begin and End:</h2>
<pre class="brush: cpp; title: ; notranslate">
void SystemGraphics::Begin() {

		float color[4];
		color[0] = 0.2f;
		color[1] = 0.2f;
		color[2] = 0.2f;
		color[3] = 1.0f;

		p_deviceContext-&amp;gt;ClearRenderTargetView(p_backbufferRenderTarget, color);
	}

	void SystemGraphics::End() {
		p_swapChain-&amp;gt;Present((m_vsync) ? 1 : 0, 0);
	}
</pre>
<p>Everything is finally initialized and good to go. Begin and End are two very simple functions that get called every frame. In Begin, we tell the Device Context to clear our RenderTargetView to the color we specified. In this case a dark grey.</p>
<p>In End, we simply present the backbuffer to the screen accounting for vsync.</p>
<p>You won&#8217;t get anything exciting but you&#8217;ll know it works if you get a dark grey screen.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/10/Image_008.png"><img class="aligncenter size-medium wp-image-871" title="Working DirectX11" src="http://www.breaktrycatch.com/wp-content/uploads/2011/10/Image_008-300x181.png" alt="" width="300" height="181" /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>That&#8217;s pretty much it. There is a destroy function to ensure that everything gets cleaned up properly but you can see that in the full source at the end of the article. One thing to note is that you MUST exist fullscreen mode before destroying everything otherwise you might be stuck in a bad state and have to restart your computer.</p>
<p>Before we get to that, there are two other useful functions to cover.</p>
<p>&nbsp;</p>
<h2>OnWindowResize:</h2>
<pre class="brush: cpp; title: ; notranslate">
void SystemGraphics::OnWindowResize(WPARAM wparam, LPARAM lparam) {
		//If we have a Swap Chain we need to resize it
		if (p_swapChain != NULL) {
			//Release Buffers
			p_deviceContext-&amp;gt;OMSetRenderTargets(0, NULL, NULL);

			p_backbufferRenderTarget-&amp;gt;Release();
			p_backbuffer-&amp;gt;Release();

			HRESULT hr;
			int horizontalResolution = LOWORD(lparam);
			int verticalResolution = HIWORD(lparam);

			dtrace(&quot;RESIZING SYSTEM GRAPHICS: Message says %i, %i&quot;, horizontalResolution, verticalResolution);

			hr = p_swapChain-&amp;gt;ResizeBuffers(0, horizontalResolution, verticalResolution, DXGI_FORMAT_UNKNOWN, 0);

			if (FAILED(hr)) {
				etrace(&quot;Resize Buffers Failed!&quot;);
				return;
			}

			InitBackBuffer();

			ZeroMemory(&amp;amp;m_viewport, sizeof(m_viewport));

			m_viewport.Width = (float)horizontalResolution;
			m_viewport.Height = (float)verticalResolution;
			m_viewport.TopLeftX = 0.0f;
			m_viewport.TopLeftY = 0.0f;
			m_viewport.MinDepth = 0.0f;
			m_viewport.MaxDepth = 1.0f;

			p_deviceContext-&amp;gt;RSSetViewports(1, &amp;amp;m_viewport);
		}
	}
</pre>
<p>OnWindowResize gets called every time we get a WM_SIZE message from the SystemWindow. In the <a title="DXGI Best Practices" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ee417025(v=vs.85).aspx" target="_blank">DXGI Best Practices</a> we will want to respond to these events to resize our buffers to the new size of our window. This will also happen when we go between full screen and windowed mode.</p>
<p>We simply have to make sure to clean everything up, resize our buffers and then recreate them.</p>
<p>&nbsp;</p>
<h2>ToggleFullScreen:</h2>
<pre class="brush: cpp; title: ; notranslate">
bool SystemGraphics::ToggleFullScreen(bool fullScreen) {
		//Only if there's a change and we have a valid swapchain and monitor
		if (m_fullScreen != fullScreen &amp;amp;&amp;amp; p_swapChain != NULL &amp;amp;&amp;amp; p_output != NULL) {
			m_fullScreen = fullScreen;

			/*hr = p_swapChain-&amp;gt;ResizeTarget(&amp;amp;m_displayMode);
			if (FAILED(hr)) {
				m_fullScreen = !m_fullScreen;
				etrace(&quot;Unable to ResizeTarget!&quot;);
				return false;
			}*/

			//Try and set the Fullscreen state
			hr = p_swapChain-&amp;gt;SetFullscreenState((m_fullScreen) ? TRUE : FALSE, (m_fullScreen) ? p_output : NULL);
			//If we fail, reset our internal state
			if (FAILED(hr)) {
				m_fullScreen = !m_fullScreen;
				etrace(&quot;Unable to SetFullScreen State!&quot;);
				return false;
			}
			else {

				/*DXGI_MODE_DESC tempMode;
				ZeroMemory(&amp;amp;tempMode, sizeof(tempMode));
				tempMode.Format = (m_fullScreen) ? DXGI_FORMAT_UNKNOWN : m_displayMode.Format;
				tempMode.Height = m_displayMode.Height;
				tempMode.Scaling = m_displayMode.Scaling;
				tempMode.ScanlineOrdering = m_displayMode.ScanlineOrdering;
				tempMode.Width = m_displayMode.Width;

				hr = p_swapChain-&amp;gt;ResizeTarget(&amp;amp;tempMode);
				if (FAILED(hr)) {
					m_fullScreen = !m_fullScreen;
					etrace(&quot;Unable to ResizeTarget!&quot;);
					return false;
				}
				else {
					return true;
				}*/
				return true;
			}
		}
		else {
			return false;
		}
	}
</pre>
<p>This one is much more complicated and as you can see by the commented code, I still need to investigate this further.</p>
<p>The main thing we want to ensure when using DXGI is that when we are in fullscreen mode, we want to be using a &#8220;Flip&#8221; operation on the buffers instead of a &#8220;Blit&#8221; operation. (See <a title="DXGI Best Practices" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ee417025(v=vs.85).aspx" target="_blank">DXGI Best Practices</a> again).</p>
<p>The docs say to resize your targets first, then set the fullscreen state and then call resize targets again with a zeroed out RefreshRate.</p>
<p>When I do that though I get some funky sizing behaviors when switching back and forth.</p>
<p>So for now I simply set the fullscreen state which DXGI takes and handles the setting of the Fullscreen state on our SystemWindow for us. Notice that we never tell the Window to switch fullscreen states even though SystemWindow exposes that functionality. The rule of thumb here is that if you&#8217;re using SystemGraphics with a SystemWindow, SystemGraphics gets to control the SystemWindow state.</p>
<p>I will probably modify the code to make this more safe in the future, but for now just be aware of it.</p>
<p>When switching state, the WM_SIZE message is dispatched which handles our resizing methods as listed before.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>There you have it, DirectX11 Initialization. Still pretty boring in terms of visuals but again it&#8217;s all about the foundations. Visuals will come afterwards.</p>
<p>&nbsp;</p>
<p>As promised, the full source for SystemGraphics.cpp</p>
<h2>SystemGraphics.cpp</h2>
<pre class="brush: cpp; title: ; notranslate">
//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &quot;SystemGraphics.h&quot;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {

	//////////////////////////////////////////////////////////////////////
	// STATICS ///////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//////////////////////////////////////////////////////////////////////
	// CONSTRUCTORS //////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	SystemGraphics::SystemGraphics() {

		m_fullScreen = false;
		m_vsync = false;

		m_adapterIndex = 0;
		m_outputIndex = 0;

		m_numBackBuffers = 1;
		m_msaaLevel = 1;
		m_msaaQuality = 0;

		m_desiredFormat = DXGI_FORMAT_R8G8B8A8_UNORM;
		m_targetFeatureLevel = D3D_FEATURE_LEVEL_11_0;

		p_window = NULL;

		p_factory = NULL;
		p_adapter = NULL;
		p_output = NULL;
		p_displayModes = NULL;

		p_swapChain = NULL;
		p_device = NULL;
		p_deviceContext = NULL;

		p_backbuffer = NULL;
		p_backbufferRenderTarget = NULL;
	}

	//////////////////////////////////////////////////////////////////////
	// DESTRUCTOR ////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	SystemGraphics::~SystemGraphics() {

	}

	//////////////////////////////////////////////////////////////////////
	// INITIALIZE ////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	bool SystemGraphics::Init(SystemWindow *window, int adapterIndex, int outputIndex, int numBackBuffers, bool vsync) {

		p_window = window;
		m_fullScreen = p_window-&amp;gt;IsFullScreen();
		m_adapterIndex = adapterIndex;
		m_outputIndex = outputIndex;
		m_numBackBuffers = numBackBuffers;
		m_vsync = vsync;

		FAIL_ON_INIT(InitDXGIFactory());
		FAIL_ON_INIT(InitDXGIAdapter());
		FAIL_ON_INIT(InitDXGIOutput());
		FAIL_ON_INIT(InitDisplayModes());
		FAIL_ON_INIT(InitSwapChainDesc());
		FAIL_ON_INIT(InitDeviceAndSwapChain());
		FAIL_ON_INIT(InitBackBuffer());
		FAIL_ON_INIT(InitViewport());

		p_window-&amp;gt;AddMessageCallback(WM_SIZE, BIND_MEM_CB(&amp;amp;SystemGraphics::OnWindowResize, this));

		return true;
	}

	//TODO: If this fails, we should throw up a message box or something and tell the user it's all over.
	bool SystemGraphics::InitDXGIFactory() {
		//Create a DXGI Factory
		hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&amp;amp;p_factory);
		if (FAILED(hr)) {
			etrace(&quot;CreateDXGIFactory1 Failed!&quot;);
			return false;
		}
		return true;
	}

	//TODO: If this fails, we should fallback to enumerating the Adapters and selecting the first one.
	bool SystemGraphics::InitDXGIAdapter() {
		//Get the Primary Adapter (Video Card)
		hr = p_factory-&amp;gt;EnumAdapters1(m_adapterIndex, &amp;amp;p_adapter);
		if (FAILED(hr)) {
			etrace(&quot;EnumAdapters1 Failed!&quot;);
			return false;
		}
		return true;
	}

	//TODO: If this fails, we should fallback to enumerating the Outputs and selecting the first one.
	bool SystemGraphics::InitDXGIOutput() {
		//Get the Primary Output (Monitor) using the Adapter
		hr = p_adapter-&amp;gt;EnumOutputs(m_outputIndex, &amp;amp;p_output);
		if (FAILED(hr)) {
			etrace(&quot;EnumOutputs Failed!&quot;);
			return false;
		}
		return true;
	}

	bool SystemGraphics::InitDisplayModes() {
		UINT numModes;
		//TODO: Pull these in from elsewhere
		int matchWidth = GetSystemMetrics(SM_CXSCREEN);
		int matchHeight = GetSystemMetrics(SM_CYSCREEN);
		//Get the Display Modes that fit the DXGI FORMAT
		//TODO: Which format should we use? Which Flags? Why?
		hr = p_output-&amp;gt;GetDisplayModeList(m_desiredFormat, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &amp;amp;numModes, NULL);
		if (FAILED(hr)) {
			etrace(&quot;GetDisplayModeList for Formats Failed!&quot;);
			return false;
		}

		//Create the DXGI Mode Description
		p_displayModes = new DXGI_MODE_DESC[numModes];
		if (p_displayModes == NULL) {
			etrace(&quot;Creation of DXGI_MODE_DESC Array with %i modes Failed!&quot;, numModes);
			return false;
		}

		//Populate the DXGI_MODE_DESC list with structures of supported Display Modes
		hr = p_output-&amp;gt;GetDisplayModeList(m_desiredFormat, DXGI_ENUM_MODES_INTERLACED, &amp;amp;numModes, p_displayModes);
		if (FAILED(hr)) {
			etrace(&quot;GetDisplayModeList for populating DXGI_MODE_DESC Array Failed!&quot;);
			return false;
		}

		//Choose the Display Mode that most closely matches our current screen resolution
		ZeroMemory(&amp;amp;m_displayMode, sizeof(m_displayMode));
		int i;
		int len = (int)numModes;
		for (i = 0; i &amp;lt; len; ++i) {
			if (p_displayModes[i].Width == matchWidth &amp;amp;&amp;amp; p_displayModes[i].Height == matchHeight) {
				m_displayMode = p_displayModes[i];
				return true;
			}
		}

		etrace(&quot;No suitable display mode was found for resolution of %i, %i!&quot;, matchWidth, matchHeight);
		return false;
	}

	bool SystemGraphics::InitSwapChainDesc() {
		//Construct our SwapChainDesc
		ZeroMemory(&amp;amp;m_swapChainDesc, sizeof(m_swapChainDesc));

		//Double or Triple Buffering
		m_swapChainDesc.BufferCount = m_numBackBuffers;

		//BUFFER DESC
		m_swapChainDesc.BufferDesc.Format = m_desiredFormat;
		m_swapChainDesc.BufferDesc.Height = m_displayMode.Height;
		m_swapChainDesc.BufferDesc.RefreshRate.Numerator = (m_vsync) ? m_displayMode.RefreshRate.Numerator : 0;
		m_swapChainDesc.BufferDesc.RefreshRate.Denominator = (m_vsync) ? m_displayMode.RefreshRate.Denominator : 1;
		m_swapChainDesc.BufferDesc.Scaling = m_displayMode.Scaling;
		m_swapChainDesc.BufferDesc.ScanlineOrdering = m_displayMode.ScanlineOrdering;
		m_swapChainDesc.BufferDesc.Width = m_displayMode.Width;

		m_swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;

		m_swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;

		m_swapChainDesc.OutputWindow = *p_window-&amp;gt;GetHWND();

		//SAMPLE DESC
		m_swapChainDesc.SampleDesc.Count = m_msaaLevel;
		m_swapChainDesc.SampleDesc.Quality = m_msaaQuality;

		m_swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

		m_swapChainDesc.Windowed = TRUE;

		return true;
	}

	bool SystemGraphics::InitDeviceAndSwapChain() {

		//TODO: Flags we might be concerned with are the Debug D3D11_CREATE_DEVICE_DEBUG

		//Create the Device and Swap Chain - If we specify the Adapter the type must be D3D_DRIVER_TYPE_UNKNOWN
		hr = D3D11CreateDeviceAndSwapChain(p_adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, &amp;amp;m_targetFeatureLevel, 1, D3D11_SDK_VERSION, &amp;amp;m_swapChainDesc, &amp;amp;p_swapChain, &amp;amp;p_device, &amp;amp;m_highestFeatureLevel, &amp;amp;p_deviceContext);
		if (FAILED(hr)) {
			etrace(&quot;D3D11CreateDeviceAndSwapChain Failed!&quot;);
			return false;
		}
		return true;
	}

	bool SystemGraphics::InitBackBuffer() {
		hr = p_swapChain-&amp;gt;GetBuffer(0, __uuidof(p_backbuffer), reinterpret_cast&amp;lt;void**&amp;gt;(&amp;amp;p_backbuffer));
		if (FAILED(hr)) {
			etrace(&quot;Get Buffer Failed!&quot;);
			return false;
		}

		//TODO: D3D11_RENDER_TARGET_VIEW_DESC

		hr = p_device-&amp;gt;CreateRenderTargetView(p_backbuffer, NULL, &amp;amp;p_backbufferRenderTarget);
		if (FAILED(hr)) {
			etrace(&quot;Create Render Target View Failed!&quot;);
			return false;
		}

		//TODO: Handle DepthStencil
		p_deviceContext-&amp;gt;OMSetRenderTargets(1, &amp;amp;p_backbufferRenderTarget, NULL);

		return true;
	}

	bool SystemGraphics::InitViewport() {
		ZeroMemory(&amp;amp;m_viewport, sizeof(m_viewport));

		m_viewport.Width = (float)m_displayMode.Width;
		m_viewport.Height = (float)m_displayMode.Height;
		m_viewport.TopLeftX = 0.0f;
		m_viewport.TopLeftY = 0.0f;
		m_viewport.MinDepth = 0.0f;
		m_viewport.MaxDepth = 1.0f;

		p_deviceContext-&amp;gt;RSSetViewports(1, &amp;amp;m_viewport);

		return true;
	}

	//////////////////////////////////////////////////////////////////////
	// DESTROY ///////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	void SystemGraphics::Destroy() {
		//It's important to switch back to window mode before closing the application
		if (p_swapChain) {
			p_swapChain-&amp;gt;SetFullscreenState(FALSE, NULL);
		}

		SAFE_RELEASE(p_backbufferRenderTarget);
		SAFE_RELEASE(p_backbuffer);
		SAFE_RELEASE(p_deviceContext);
		SAFE_RELEASE(p_device);
		SAFE_RELEASE(p_swapChain);
		p_window = NULL;
		SAFE_DELETE_ARRAY(p_displayModes);
		SAFE_RELEASE(p_output);
		SAFE_RELEASE(p_adapter);
		SAFE_RELEASE(p_factory);
	}

	//////////////////////////////////////////////////////////////////////
	// BODY //////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	void SystemGraphics::Begin() {

		float color[4];
		color[0] = 0.2f;
		color[1] = 0.2f;
		color[2] = 0.2f;
		color[3] = 1.0f;

		p_deviceContext-&amp;gt;ClearRenderTargetView(p_backbufferRenderTarget, color);
	}

	void SystemGraphics::End() {
		p_swapChain-&amp;gt;Present((m_vsync) ? 1 : 0, 0);
	}

	void SystemGraphics::OnWindowResize(WPARAM wparam, LPARAM lparam) {
		//If we have a Swap Chain we need to resize it
		if (p_swapChain != NULL) {
			//Release Buffers
			p_deviceContext-&amp;gt;OMSetRenderTargets(0, NULL, NULL);

			p_backbufferRenderTarget-&amp;gt;Release();
			p_backbuffer-&amp;gt;Release();

			HRESULT hr;
			int horizontalResolution = LOWORD(lparam);
			int verticalResolution = HIWORD(lparam);

			dtrace(&quot;RESIZING SYSTEM GRAPHICS: Message says %i, %i&quot;, horizontalResolution, verticalResolution);

			hr = p_swapChain-&amp;gt;ResizeBuffers(0, horizontalResolution, verticalResolution, DXGI_FORMAT_UNKNOWN, 0);

			if (FAILED(hr)) {
				etrace(&quot;Resize Buffers Failed!&quot;);
				return;
			}

			InitBackBuffer();

			ZeroMemory(&amp;amp;m_viewport, sizeof(m_viewport));

			m_viewport.Width = (float)horizontalResolution;
			m_viewport.Height = (float)verticalResolution;
			m_viewport.TopLeftX = 0.0f;
			m_viewport.TopLeftY = 0.0f;
			m_viewport.MinDepth = 0.0f;
			m_viewport.MaxDepth = 1.0f;

			p_deviceContext-&amp;gt;RSSetViewports(1, &amp;amp;m_viewport);
		}
	}

	bool SystemGraphics::ToggleFullScreen(bool fullScreen) {
		//Only if there's a change and we have a valid swapchain and monitor
		if (m_fullScreen != fullScreen &amp;amp;&amp;amp; p_swapChain != NULL &amp;amp;&amp;amp; p_output != NULL) {
			m_fullScreen = fullScreen;

			/*hr = p_swapChain-&amp;gt;ResizeTarget(&amp;amp;m_displayMode);
			if (FAILED(hr)) {
				m_fullScreen = !m_fullScreen;
				etrace(&quot;Unable to ResizeTarget!&quot;);
				return false;
			}*/

			//Try and set the Fullscreen state
			hr = p_swapChain-&amp;gt;SetFullscreenState((m_fullScreen) ? TRUE : FALSE, (m_fullScreen) ? p_output : NULL);
			//If we fail, reset our internal state
			if (FAILED(hr)) {
				m_fullScreen = !m_fullScreen;
				etrace(&quot;Unable to SetFullScreen State!&quot;);
				return false;
			}
			else {

				/*DXGI_MODE_DESC tempMode;
				ZeroMemory(&amp;amp;tempMode, sizeof(tempMode));
				tempMode.Format = (m_fullScreen) ? DXGI_FORMAT_UNKNOWN : m_displayMode.Format;
				tempMode.Height = m_displayMode.Height;
				tempMode.Scaling = m_displayMode.Scaling;
				tempMode.ScanlineOrdering = m_displayMode.ScanlineOrdering;
				tempMode.Width = m_displayMode.Width;

				hr = p_swapChain-&amp;gt;ResizeTarget(&amp;amp;tempMode);
				if (FAILED(hr)) {
					m_fullScreen = !m_fullScreen;
					etrace(&quot;Unable to ResizeTarget!&quot;);
					return false;
				}
				else {
					return true;
				}*/
				return true;
			}
		}
		else {
			return false;
		}
	}

	//////////////////////////////////////////////////////////////////////
	// ADAPTERS //////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	void SystemGraphics::GetDXGIAdapters(IDXGIAdapterVector &amp;amp;adapterVector) {
		//TODO: Should we remove and release all the adapters inside?
		UINT i = 0; 
		IDXGIAdapter1* adapter; 
		while(p_factory-&amp;gt;EnumAdapters1(i, &amp;amp;adapter) != DXGI_ERROR_NOT_FOUND) { 
			adapterVector.push_back(adapter); 
			++i; 
		} 
	}

	void SystemGraphics::SetDXGIAdapter(UINT adapterIndex, IDXGIAdapter1* adapter) {
		//If we're setting the same adapter, return
		if (adapterIndex == m_adapterIndex) {
			return;
		}
		//Check to see if we already have an adapter and clean it up nicely
		SAFE_RELEASE(p_adapter);

		m_adapterIndex = adapterIndex;
		p_adapter = adapter;
		//TODO: Invalidate all dependent setup etc
	}

	DXGI_ADAPTER_DESC1* SystemGraphics::GetAdapterDesc() {
		ZeroMemory(&amp;amp;m_adapterDesc, sizeof(m_adapterDesc));
		//Get the DXGI_ADAPTER_DESC of the Adapter
		hr = p_adapter-&amp;gt;GetDesc1(&amp;amp;m_adapterDesc);
		if (FAILED(hr)) {
			etrace(&quot;GetDesc1 Failed!&quot;);
			return NULL;
		}
		return &amp;amp;m_adapterDesc;
	}

	//////////////////////////////////////////////////////////////////////
	// OUTPUTS ///////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	void SystemGraphics::GetDXGIOutputs(IDXGIOutputVector &amp;amp;outputVector) {
		//TODO: Should we remove and release all the outputs inside?
		UINT i = 0;
		IDXGIOutput* output;
		while(p_adapter-&amp;gt;EnumOutputs(i, &amp;amp;output) != DXGI_ERROR_NOT_FOUND){
			outputVector.push_back(output);
			++i;
		}
	}

	void SystemGraphics::SetDXGIOutput(UINT outputIndex, IDXGIOutput* output) {
		//If we're setting the same output, return
		if (outputIndex == m_outputIndex) {
			return;
		}
		//Check to see if we already have an output and clean it up nicely
		SAFE_RELEASE(p_output);

		m_outputIndex = outputIndex;
		p_output = output;
		//TODO: Invalidate all dependent setup etc
	}

	//////////////////////////////////////////////////////////////////////
	// DISPLAY MODES /////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	DXGI_MODE_DESC* SystemGraphics::GetDisplayModes() {
		return p_displayModes;
	}

	void SystemGraphics::SetDisplayMode(DXGI_MODE_DESC* displayMode) {
		m_displayMode = *displayMode;
		//TODO: Invalidate all dependent setup etc
	}

	//////////////////////////////////////////////////////////////////////
	// GETTERS/SETTERS ///////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/getting-started-with-directx-11/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Windows: Part 2</title>
		<link>http://www.breaktrycatch.com/windows-part-2/</link>
		<comments>http://www.breaktrycatch.com/windows-part-2/#comments</comments>
		<pubDate>Sat, 22 Oct 2011 19:56:31 +0000</pubDate>
		<dc:creator>Jon Keon</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=846</guid>
		<description><![CDATA[Last time I was just starting to build a Window wrapper class to use in C++ projects. As I started digging deeper though and implementing more features I was greeted with this: Yep, good old Windows Blue Screen of Death. Fortunately I only managed to make it happen four times although once it was enough...]]></description>
			<content:encoded><![CDATA[<p><a title="Windows: Part 1" href="http://www.breaktrycatch.com/windows-part-1/" target="_blank">Last time</a> I was just starting to build a Window wrapper class to use in C++ projects.</p>
<p>As I started digging deeper though and implementing more features I was greeted with this:</p>
<p style="text-align: center;"><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/10/bdo69870.jpeg"><img class="aligncenter size-full wp-image-847" title="BSOD" src="http://www.breaktrycatch.com/wp-content/uploads/2011/10/bdo69870.jpeg" alt="" width="480" height="360" /></a></p>
<p>Yep, good old Windows Blue Screen of Death. Fortunately I only managed to make it happen four times although once it was enough to completely corrupt my SystemWindow.cpp file. SVN showed it as having no changes but when I opened it it was just a bunch of garbage null characters.</p>
<ul>
<li><strong>Important Lesson Of The Day:<br />
</strong>Always make sure you back up your work using some sort of Source Control. You never know when your own faulty code will erase it for you.<br />
I use <a title="Assembla" href="http://www.assembla.com/" target="_blank">Assembla </a>because it is awesome.</li>
</ul>
<p>Harrowing excitement aside, I was able to figure out why these crashes were happening and more importantly fix my code to prevent them, build a nice encapsulated Window wrapper class, and meet all of my objectives from the previous post.</p>
<p>&nbsp;</p>
<p>Let&#8217;s recap those objectives quickly:</p>
<ul>
<li>Class that encapsulates Microsoft Windows functionality.</li>
<li>Allow for Message Based or Real Time interactivity with the Window.</li>
<li>Toggle between Full Screen and Windowed Mode</li>
<li>Allow for dynamic re-sizing and re- positioning of the window.</li>
<li>Allow for Multiple Windows and Proper message dispatching to the right window instance.</li>
<li>Map dynamic functionality in response to a Windows Message.</li>
</ul>
<div>For readability I&#8217;ll start by posting the Header file so you can see the overall structure of the class and then I&#8217;ll post snippets of the source to explain. I&#8217;ll post the full source file at the end of the post though for a simple copy/paste.</div>
<h2>SystemWindow.h</h2>
<pre>
<pre class="brush: cpp; title: ; notranslate">
//////////////////////////////////////////////////////////////////////
// Window //
// //
// Description: //
// Author: jkeon //
//////////////////////////////////////////////////////////////////////

#ifndef _SYSTEMWINDOW_H_
#define _SYSTEMWINDOW_H_

//FUTURE: In the future we may make this multi-platform
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#endif

//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//FUTURE: In the future we may make this multi-platform
#ifdef _WIN32
#include &amp;lt;Windows.h&amp;gt;
#endif

#include &amp;lt;unordered_map&amp;gt;
#include &amp;lt;string/TString.h&amp;gt;
#include &amp;lt;util/DebugUtil.h&amp;gt;
#include &amp;lt;util/Callback.h&amp;gt;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {
//////////////////////////////////////////////////////////////////////
// GLOBALS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// CLASS DECLARATION /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

class SystemWindow {

//TYPEDEFS
typedef util::Callback&amp;lt;void (WPARAM wparam, LPARAM lparam)&amp;gt; MessageCallback;
typedef std::unordered_multimap&amp;lt;UINT, MessageCallback&amp;gt; MessageMap;

//PUBLIC FUNCTIONS
public:
SystemWindow();
virtual ~SystemWindow();

bool Init(HINSTANCE* hInstance, tstring windowClassName, tstring windowTitleBarName, bool fullScreen, bool realTime);
void Show(int nCmdShow);
void Destroy();
MSG HandleWindowsMessage();

void SetWindowedProperties(int x, int y, int width, int height);
void SetFullScreenProperties(DWORD horizontalResolution, DWORD verticalResolution, DWORD bitsPerPixel, DWORD refreshRate);

void ToggleFullScreen(bool fullScreen);

void AddMessageCallback(UINT msg, MessageCallback messageHandler);
void RemoveMessageCallback(UINT msg, MessageCallback messageHandler);
void RemoveAllMessageCallbacks();

HWND* GetHWND();

bool IsFullScreen();
bool IsMinimized();

LRESULT CALLBACK LocalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);

//PUBLIC VARIABLES
public:

//PROTECTED FUNCTIONS
protected:

//PROTECTED VARIABLES
protected:

//PRIVATE FUNCTIONS
private:
SystemWindow(const SystemWindow&amp;amp; other);
SystemWindow&amp;amp; operator = (const SystemWindow&amp;amp; other);

void DefaultCloseMessageCallback(WPARAM wparam, LPARAM lparam);
void DefaultDestroyMessageCallback(WPARAM wparam, LPARAM lparam);
void DefaultSizeMessageCallback(WPARAM wparam, LPARAM lparam);
void DefaultMoveMessageCallback(WPARAM wparam, LPARAM lparam);

//PRIVATE VARIABLES
private:
HINSTANCE* p_hInstance;
WNDCLASSEX m_definition;
HWND m_hwnd;

int m_windowed_x;
int m_windowed_y;
int m_windowed_width;
int m_windowed_height;

int m_fullscreen_width;
int m_fullscreen_height;

tstring m_windowClassName;
tstring m_windowTitleBarName;
bool m_realTime;
bool m_fullScreen;
bool m_hasMenu;
bool m_minimized;
bool m_manageFullScreen;
LONG_PTR m_gwl_style;
LONG_PTR m_gwl_exstyle;
DEVMODE m_originalSettings;
DEVMODE m_fullScreenSettings;

MessageMap m_messageMap;

static const LONG_PTR GWL_STYLE_WINDOWED = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
static const LONG_PTR GWL_STYLE_FULLSCREEN = WS_POPUP | WS_SYSMENU | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;

static const LONG_PTR GWL_EXSTYLE_WINDOWED = WS_EX_OVERLAPPEDWINDOW;
static const LONG_PTR GWL_EXSTYLE_FULLSCREEN = WS_EX_TOPMOST;
};

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

static LRESULT CALLBACK GlobalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);

}
#endif
</pre>
</pre>
<p>&nbsp;</p>
<h2>Constructor:</h2>
<pre>
<pre class="brush: cpp; title: ; notranslate">
SystemWindow::SystemWindow() {
p_hInstance = NULL;

m_fullscreen_width = GetSystemMetrics(SM_CXSCREEN);
m_fullscreen_height = GetSystemMetrics(SM_CYSCREEN);

m_windowed_x = 100;
m_windowed_y = 100;
m_windowed_width = 960;
m_windowed_height = 540;

m_minimized = false;
m_fullScreen = false;
m_realTime = false;
m_hasMenu = false;
m_gwl_style = GWL_STYLE_WINDOWED;
m_gwl_exstyle = GWL_EXSTYLE_WINDOWED;
}
</pre>
</pre>
<p>The Constructor does nothing but initialize variables. By default, I assume the window is a window (and not a fullscreen app) and I give it a position of 100, 100 and width/height of 960/540 which is exactly half of 1080p resolution and not a standard display format. This just makes sure that my future code for switching between fullscreen and windowed mode works correctly.</p>
<p>The fullscreen width and height are defined by the resolution you have your monitor set to. You can override this later but we need something there in case you want to start in fullscreen mode.</p>
<p>The rest is pretty self explanatory. <strong>m_realTime</strong> is just a flag for whether I use <strong>PeekMessage</strong> or <strong>GetMessage</strong> which you will see later and the style variables are for setting the Window Style and Extended Style through the windows API.</p>
<p>&nbsp;</p>
<h2>Init:</h2>
<pre>
<pre class="brush: cpp; title: ; notranslate">
bool SystemWindow::Init(HINSTANCE* hInstance, tstring windowClassName, tstring windowTitleBarName, bool fullScreen, bool realTime) {

//Store Instance Variables
m_windowClassName = windowClassName;
m_windowTitleBarName = windowTitleBarName;
p_hInstance = hInstance;
m_fullScreen = fullScreen;
m_realTime = realTime;
m_gwl_style = (m_fullScreen) ? GWL_STYLE_FULLSCREEN : GWL_STYLE_WINDOWED;

//Default Message Mapping
AddMessageCallback(WM_SIZE, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultSizeMessageCallback, this));
AddMessageCallback(WM_MOVE, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultMoveMessageCallback, this));
AddMessageCallback(WM_CLOSE, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultCloseMessageCallback, this));
AddMessageCallback(WM_DESTROY, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultDestroyMessageCallback, this));

//TODO: Pull in some of this from Config file
ZeroMemory(&amp;amp;m_definition, sizeof(m_definition));
m_definition.cbSize = sizeof(WNDCLASSEX);
m_definition.cbClsExtra = 0;
m_definition.cbWndExtra = 0;
m_definition.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
m_definition.hCursor = LoadCursor(NULL, IDC_ARROW);
m_definition.hIcon = LoadIcon(NULL, IDI_WINLOGO);
m_definition.hIconSm = m_definition.hIcon;
m_definition.hInstance = *p_hInstance;
m_definition.lpfnWndProc = GlobalWndProc;
m_definition.lpszClassName = m_windowClassName.c_str();
m_definition.lpszMenuName = NULL;
m_definition.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

//Register the Class
if (!RegisterClassEx(&amp;amp;m_definition)) {
//If a failure, let us know about it
etrace(&quot;Register Class Failed on %s&quot;, m_windowClassName.c_str());
return false;
}

//Set the initial window size and position
RECT rect;
rect.left = (m_fullScreen) ? 0 : m_windowed_x;
rect.top = (m_fullScreen) ? 0 : m_windowed_y;
rect.right = (m_fullScreen) ? m_fullscreen_width : m_windowed_x + m_windowed_width;
rect.bottom = (m_fullScreen) ? m_fullscreen_height : m_windowed_y + m_windowed_height;
AdjustWindowRectEx(&amp;amp;rect, m_gwl_style, m_hasMenu, m_gwl_exstyle);

//Create the window and store the handle. Passing &quot;this&quot; pointer as the lparam so we can make the mappings in our GlobalWndProc
m_hwnd = CreateWindowEx(m_gwl_exstyle, m_windowClassName.c_str(), m_windowTitleBarName.c_str(), m_gwl_style, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, *p_hInstance, this);
if (!m_hwnd) {
//If a failure, let us know about it
etrace(&quot;Create Window Failed on %s&quot;, m_windowClassName.c_str());
return false;
}

//Get and Store the current System Display Settings
HDC hdc = GetDC(m_hwnd);

//These are the current settings of the users computer
m_originalSettings.dmSize = sizeof(DEVMODE);
m_originalSettings.dmPelsWidth = GetDeviceCaps(hdc, HORZRES);
m_originalSettings.dmPelsHeight = GetDeviceCaps(hdc, VERTRES);
m_originalSettings.dmBitsPerPel = GetDeviceCaps(hdc, BITSPIXEL);
m_originalSettings.dmDisplayFrequency = GetDeviceCaps(hdc, VREFRESH);
m_originalSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;

//Fullscreen settings SHOULD mimic the current settings but we do want to be able to override them in the future potentially.
m_fullScreenSettings.dmSize = sizeof(DEVMODE);
m_fullScreenSettings.dmPelsWidth = m_fullscreen_width = GetDeviceCaps(hdc, HORZRES);
m_fullScreenSettings.dmPelsHeight = m_fullscreen_height = GetDeviceCaps(hdc, VERTRES);
m_fullScreenSettings.dmBitsPerPel = GetDeviceCaps(hdc, BITSPIXEL);
m_fullScreenSettings.dmDisplayFrequency = GetDeviceCaps(hdc, VREFRESH);
m_fullScreenSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;

//For every GetDC we should ReleaseDC
ReleaseDC(m_hwnd, hdc);

//If we're starting in Fullscreen Mode, ensure the Display Settings have switched as well
if (m_fullScreen) {
ChangeDisplaySettings(&amp;amp;m_fullScreenSettings, CDS_FULLSCREEN);
}

return true;
}
</pre>
</pre>
<p>The Init method is where all the initial setup and actual creation of the window happens. At first I&#8217;m simply storing the variables passed in and modifying some flags based on whether we&#8217;re starting in fullscreen mode or not.</p>
<p>The next section requires a bit of an aside and I&#8217;ll talk more about it when dealing with Message Callbacks. Essentially I&#8217;m just saying that when we get a message of a certain type from the Windows Message Pump, then call this specific function.</p>
<p>Ex.</p>
<pre>
<pre class="brush: cpp; title: ; notranslate">
AddMessageCallback(WM_SIZE, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultSizeMessageCallback, this));
</pre>
</pre>
<p>Whenever I get a <strong>WM_SIZE</strong> message, I&#8217;ll call the <strong>DefaultSizeMessageCallback</strong> function on this instance of <strong>SystemWindow</strong>.</p>
<p>Next I fill out the Window classex definition. This is pretty standard but note that the <strong>lpfnWndProc</strong> is pointing to the <strong>GlobalWndProc</strong> function which is a static function and that the style has <strong>CS_OWNDC</strong> for performance.</p>
<p>Then the class definition is registered and the initial rectangle of the window is sized and adjusted based on the flags.</p>
<p>Now the window can actually be created, again ensuring that the flags are properly passed in to allow for starting in fullscreen mode or windowed mode. Take note that the last parameter is a <strong>this</strong> pointer which I will be using in the <strong>GlobalWndProc</strong> function later.</p>
<p>Since the window is created, I can get the device context and get some of the settings for your monitor. I get these twice, once for the original settings that the user&#8217;s computer was using before they started the application and then a duplicate version for the fullscreen settings.</p>
<p>In most cases, when you go full screen, you&#8217;re simply going to make your window take up the entire resolution of the monitor. However, you may allow the user to configure the resolution to be a lower or higher resolution than what their monitor is currently set at and so we need a way to store the desired settings to change to. The settings are pretty easy to understand, it&#8217;s just the Horizontal/Vertical resolution, the number of bits per pixel (usually 32) and the display frequency or monitor refresh rate (usually 60hz). The dmFields simply specifies that we want to use those four properties.</p>
<p>Finally if I&#8217;m starting in fullscreen mode, I&#8217;ll want to force a change in the display settings of your monitor. This will work the same as when you go into control panel and change the resolution. If there is a change, your monitor should flicker. In most cases, there won&#8217;t be a flicker since the resolution, bits per pixel and frequency haven&#8217;t changed. The <strong>CDS_FULLSCREEN</strong> flag makes it so it hides the Start menu.</p>
<h2>ToggleFullScreen:</h2>
<pre>
<pre class="brush: cpp; title: ; notranslate">
void SystemWindow::ToggleFullScreen(bool fullScreen) {
//Only if we're actually changing
if (m_fullScreen != fullScreen) {

m_fullScreen = fullScreen;

//Adjust the location and size of the window
RECT rect;
rect.left = (m_fullScreen) ? 0 : m_windowed_x;
rect.top = (m_fullScreen) ? 0 : m_windowed_y;
rect.right = (m_fullScreen) ? m_fullscreen_width : m_windowed_x + m_windowed_width;
rect.bottom = (m_fullScreen) ? m_fullscreen_height : m_windowed_y + m_windowed_height;

//Set all the styles and booleans based on Fullscreen or not
m_gwl_exstyle = (m_fullScreen) ? GWL_EXSTYLE_FULLSCREEN : GWL_EXSTYLE_WINDOWED;
m_gwl_style = (m_fullScreen) ? GWL_STYLE_FULLSCREEN : GWL_STYLE_WINDOWED;
SetWindowLongPtr(m_hwnd, GWL_EXSTYLE, m_gwl_exstyle);
SetWindowLongPtr(m_hwnd, GWL_STYLE, m_gwl_style);

AdjustWindowRectEx(&amp;amp;rect, m_gwl_style, m_hasMenu, m_gwl_exstyle);

SetWindowPos(m_hwnd, (m_fullScreen) ? HWND_TOPMOST : HWND_NOTOPMOST, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_SHOWWINDOW);

//Change the Display Settings
ChangeDisplaySettings((m_fullScreen) ? &amp;amp;m_fullScreenSettings : &amp;amp;m_originalSettings, (m_fullScreen) ? CDS_FULLSCREEN : CDS_RESET);
}
}
</pre>
</pre>
<p>Toggling between fullscreen and back was actually somewhat difficult. This is one of the areas that caused the Blue Screens of Death but it was due to my own fault of not properly setting the fullscreen width and height so they were set to 0 which causes a fatal crash.</p>
<p>However the actual function logic is pretty simple. So long as we&#8217;re actually changing from fullscreen to windowed mode or vice versa, we update a rect with the stored windowed dimensions or the stored fullscreen dimensions.</p>
<p>The flags are set for the window styles but to actually change them on the window itself we need to use the <strong>SetWindowLongPtr</strong> function.</p>
<p><strong>AdjustWindowRectEx</strong> just modifies the window size to account for things like borders and menus and whatever styles you had set. I had mistakenly been using <strong>AdjustWindowRect</strong> with an Ex style window and everytime I would switch between fullscreen or windowed the size would slowly shrink by about 10 pixels in the width and height. Just make sure if you&#8217;re using the Ex style window, you use all the Ex style functions!</p>
<p>Next we set the window&#8217;s position using that Rect and toggle a few flags based on fullscreen or not.</p>
<p>Finally we change the monitor display settings to account for fullscreen or not. If we&#8217;re going from Fullscreen to windowed there will always be the flicker because we&#8217;re using <strong>CDS_RESET</strong>. That flag simply means that no matter what, force the change.</p>
<p>Now to make the fullscreen/windowed toggle actually work, we need to be able to intercept and update our sizes properly. You&#8217;ll see in the full source code below there are two functions for setting the windowed properties and the fullscreen properties. This allows your application to explicitly specify the size and location in both modes.</p>
<p>When in windowed mode though, the user could drag the window around or resize it by dragging on the edges of the window. This is where those Default callbacks come in. We have two specifically for this responding to the <strong>WM_SIZE</strong> and <strong>WM_MOVE</strong> windows messages. They simply update the internal properties of the x, y, width and height of the window so that when you toggle between fullscreen and windowed mode everything behaves as expected.</p>
<p>&nbsp;</p>
<h2>Messages:</h2>
<p>Messages are a big part of Windows programming and probably could warrant their own post.</p>
<p>Essentially this is the basic flow.</p>
<ol>
<li>Windows (The Operating System) will queue up messages to give to your application.</li>
<li>You need to explicitly check these messages and do something with them. See <strong>SystemWindow::HandleWindowsMessage</strong>.</li>
<ol>
<li>This requires either <strong>PeekMessage</strong> or <strong>GetMessage</strong>.</li>
<li>Once you&#8217;ve gotten the message you need to <strong>TranslateMessage</strong> and then <strong>DispatchMessage</strong>.</li>
</ol>
<li>When a message is dispatched, it will hit your <strong>lpfnWndProc</strong> static function that you defined in your Window ClassEx definition. See <strong>SystemWindow:::GlobalWndProc</strong></li>
</ol>
<div>Now if you&#8217;re making a very simple app with only ever one window, you can follow the Microsoft documentation and have a while loop that does the GetMessage or PeekMessage and then have a giant case statement in your version of a GlobalWndProc for handling the various messages.</div>
<div>But what if you want to have more than one window? And you want to customize the functionality per message? Now you need to have some more advanced functionality to deal with that.</div>
<div>Let&#8217;s start with HandleWindowsMessage.</div>
<h2>HandleWindowsMessage:</h2>
<pre>
<pre class="brush: cpp; title: ; notranslate">
MSG SystemWindow::HandleWindowsMessage() {
MSG msg;
ZeroMemory(&amp;amp;msg, sizeof(MSG));
if (m_realTime) {
PeekMessage(&amp;amp;msg, m_hwnd, 0, 0, PM_REMOVE);
}
else {
GetMessage(&amp;amp;msg, m_hwnd, 0, 0);
}

if (msg.message != WM_NULL) {
TranslateMessage(&amp;amp;msg);
DispatchMessage(&amp;amp;msg);
}

return msg;
}
</pre>
</pre>
<pre>You'll notice that I don't have a Message Loop in the window class. This is because that loop would restrict execution of the program to this instance of the Window class. Again what if i had multiple windows? We'd just be stuck inside the first window's message loop until that window was destroyed. Instead I opted to let the user define their own program loop and explicitly call to check what messages are waiting for a certain window.

Here's an example:</pre>
<pre>
<pre class="brush: cpp; title: ; notranslate">
bool running = true;
MSG windowMessage;

while(running) {
windowMessage = m_window.HandleWindowsMessage();
if (windowMessage.message != WM_QUIT) {
//TODO: Execute app code
}
else {
running = false;
break;
}
}
</pre>
</pre>
<p>The loop runs at the application level and each iteration we check to see if there is a windows message waiting. So long as the message isn&#8217;t <strong>WM_QUIT</strong>, we can execute our application code. Otherwise we will want to exit the loop and start cleaning up. This approach allows us to extend this loop for multiple windows.</p>
<p>In the <strong>HandleWindowsMessage</strong> function itself, we use <strong>PeekMessage</strong> or <strong>GetMessage</strong> based on whether we want to run in real time or not. It really depends on what your application will do but know that <strong>PeekMessage</strong> returns immediately while <strong>GetMessage</strong> is a blocking call and your program will wait there forever until a message comes into play. If you&#8217;re making a 3D game or something that requires constant updates to visuals etc, you don&#8217;t want to get stuck waiting for a message.</p>
<p>So long as there is a message, we translate and then dispatch it to our <strong>GlobalWndProc</strong>.</p>
<p>&nbsp;</p>
<h2>GlobalWndProc:</h2>
<pre>
<pre class="brush: cpp; title: ; notranslate">
//Every Windows Message will hit this function.
LRESULT CALLBACK GlobalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {

//Hold our target window instance
SystemWindow *targetWindow = NULL;

//If it's the WM_NCCREATE message (which should be the first message we get...)
if(msg == WM_NCCREATE) {
//Pull the target window out of the lpCreateParams which is the this pointer we pass into CreateWindowEx
targetWindow = reinterpret_cast&amp;lt;SystemWindow*&amp;gt;((LONG)((LPCREATESTRUCT)lparam)-&amp;gt;lpCreateParams);
//Set the pointer to this instance in the GWLP_USERDATA so we can pull it out reliably in the future
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)targetWindow);
}
else {
//Pull the window instance out of the GWLP_USERDATA
targetWindow = reinterpret_cast&amp;lt;SystemWindow*&amp;gt;(GetWindowLongPtr(hwnd, GWLP_USERDATA));
}

//If we still don't have a window we can't respond to any events so kick it to the default.
if(targetWindow == NULL) {
return DefWindowProc(hwnd, msg, wparam, lparam);
}

//Otherwise we're all good and we can pipe it to the instances version of the WndProc
return targetWindow-&amp;gt;LocalWndProc(hwnd, msg, wparam, lparam);
}
</pre>
</pre>
<p>Remember when we defined our Windows ClassEx definition in the Init function we set the property <strong>lpfnWndProc</strong> to <strong>GlobalWndProc</strong>? This is because Windows needs to know where to pipe messages so you can handle them. For whatever reason it needs to be a static function too. This presents a bit of a problem because we might want to have multiple windows and have each of those windows respond to messages differently. Just one WndProc function won&#8217;t cut it.</p>
<p>So what we do instead is a bit of trickery courtesy of the following links:</p>
<p><a title="Window Class" href="http://members.gamedev.net/sicrane/articles/WindowClass.html" target="_blank">http://members.gamedev.net/sicrane/articles/WindowClass.html</a></p>
<p>&nbsp;</p>
<p><a title="LPFNWNDPROC" href="http://www.gamedev.net/topic/387255-wndclassexlpfnwndproc--member-function/" target="_blank">http://www.gamedev.net/topic/387255-wndclassexlpfnwndproc&#8211;member-function/</a></p>
<p><a title="More WndProc" href="http://stackoverflow.com/questions/7759874/weird-bug-with-wndproc-and-dispatchmessage-member-functions-dont-exist" target="_blank">http://stackoverflow.com/questions/7759874/weird-bug-with-wndproc-and-dispatchmessage-member-functions-dont-exist</a></p>
<p><a title="Window Wrapper Class" href="http://www.gamedev.net/page/resources/_/technical/game-programming/creating-a-win32-window-wrapper-class-r1810" target="_blank">http://www.gamedev.net/page/resources/_/technical/game-programming/creating-a-win32-window-wrapper-class-r1810</a></p>
<p>When we created our window with the <strong>CreateWindowEx</strong> function in our <strong>Init</strong> method, we passed a this pointer as the last parameter. Well it just so happens that the first message you receive when creating a window is the <strong>WM_NCCREATE</strong> message. This message comes along with a pointer to the handle to the window (<strong>hwnd</strong>) and some information in the <strong>lparam</strong>.</p>
<p>In the case of <strong>WM_NCCREATE</strong>, the <strong>lparam</strong> is whatever you passed in as the last parameter in the <strong>CreateWindowEx</strong> function. So as you can see in the code, we pull the instance of the window out of the lparam and by using SetWindowLongPtr, we store the pointer to the instance of the window in the special <strong>GWLP_USERDATA</strong> space on the handle to the window.</p>
<p><strong>NOTE:</strong> The Handle to the window and the instance of the Window are NOT the same thing. The Handle is a Windows API thing that allows limited access to the actual Window you see on screen. The pointer we got out of the lparam is a pointer to our instance of the SystemWindow class that we created.</p>
<p>By storing the pointer to our instance of our SystemWindow class on the Handle the next time we get a message we can simply pull it out again. If we still don&#8217;t have a valid window, we&#8217;ll just let the default occur which happens by calling <strong>DefWindowProc</strong>.</p>
<p>Otherwise we have a pointer to our instance so we can pipe the message down into our window&#8217;s <strong>LocalWndProc</strong> function.</p>
<p>This allows us to have custom functionality per window should we so choose.</p>
<h2>LocalWndProc:</h2>
<pre>
<pre class="brush: cpp; title: ; notranslate">
LRESULT CALLBACK SystemWindow::LocalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
//Check to make sure the map isn't empty
if (!m_messageMap.empty()) {

//Finds the first and last instance that matches the key
std::pair&amp;lt;MessageMap::const_iterator, MessageMap::const_iterator&amp;gt; range = m_messageMap.equal_range(msg);

//Exit condition
MessageMap::const_iterator end = m_messageMap.end();

//There were no matches found
if (range.first == end &amp;amp;&amp;amp; range.second == end) {
//We should default
return DefWindowProc(hwnd, msg, wparam, lparam);
}
else {
MessageMap::const_iterator start = range.first;
end = range.second;

MessageCallback messageCallback;

//Loop through all the callbacks
for (; start != end; ++start) {
//Get the Callback and Call it
messageCallback = start-&amp;gt;second;
messageCallback(wparam, lparam);
}
return 0;
}
}
else {
return DefWindowProc(hwnd, msg, wparam, lparam);
}
}
</pre>
</pre>
<p>Now since we want our Window instances to be able to have custom functionality per message we&#8217;ll introduce the concept of a <strong>MessageMap</strong>. A <strong>MessageMap</strong> is just a typedef for an <strong>unordered_multimap</strong> with a <strong>UINT</strong> for a key and a <strong>MessageCallback</strong> for the value.</p>
<p>This allows us to register MessageCallbacks to respond to certain Windows Messages which come in as UINT&#8217;s.</p>
<p>In the <strong>LocalWndProc</strong>, we check if the message map is empty which if it is, we don&#8217;t need to do anything and can just default the message handling to the Windows <strong>DefWindowProc</strong>.</p>
<p>If it&#8217;s not empty, we want to get all the items that have that specific Message as their key. (Since it&#8217;s a multimap, there can be more than one). If we don&#8217;t find any, we&#8217;ll let Windows handle it again. If we do find some, we simply iterate through the list and trigger each <strong>MessageCallback</strong> and pass the <strong>wparam</strong> and <strong>lparam</strong> in case those functions want to use them.</p>
<h2>Callbacks:</h2>
<p>Now is a good time for an aside on callbacks. Unfortunately in C++ there isn&#8217;t a nice way to just pass functions around and store them for later. You can use a void pointer and do some trickery with casting but its generally regarded as messy and potentially unsafe. There are solutions where you wrap the functions in objects that you can use later but they have some issues as well when dealing with ease of use and/or performance.</p>
<p>Fortunately I was able to find a great little <a title="Callback Library" href="http://www.codeproject.com/KB/cpp/CPPCallback.aspx" target="_blank">callback library</a> by Elbert Mai on The Code Project. It&#8217;s easy to use, has good performance and is published under a very permissive licence.</p>
<p>The only thing it doesn&#8217;t have is the ability to check for equality between Callback objects, but as I&#8217;ve posted in the comments of Elbert&#8217;s article I think I found a way to do it. At least it works as expected for me.</p>
<p>The <strong>AddMessageCallback</strong> and <strong>RemoveMessageCallback</strong> make use of adding and removing callbacks respectively from the message map and handle the checks for equality so that we remove the correct callback and never add a duplicate message. Because these are public, you can have any part of your application pipe into the message notifications from Windows without having to customize the SystemWindow class or extend off of it.</p>
<p>This is a great library and I&#8217;m very thankful to Mr. Mai for posting it.</p>
<h2>Cleaning Up:</h2>
<p>The last part of dealing with the SystemWindow is properly cleaning it up.</p>
<p>There is a default message callback for handling the <strong>WM_CLOSE</strong> message. This message occurs when you press Alt-F4 or click on the X or right click on the task bar and select close. In here it&#8217;s a good opportunity for you to prompt the user an &#8220;Are you sure?&#8221; dialog and handle any saving of state to a file etc.</p>
<pre>
<pre class="brush: cpp; title: ; notranslate">
void SystemWindow::DefaultCloseMessageCallback(WPARAM wparam, LPARAM lparam) {
		dtrace(&quot;CLOSING&quot;);
		//TODO: Allow for hook to save state
		//Destroy the Window
		DestroyWindow(m_hwnd);
		//Very important to set this to NULL so the WM_QUIT is picked up
		m_hwnd = NULL;
	}
</pre>
</pre>
<p>In my case, I&#8217;m not ready to save anything so I just call <strong>DestroyWindow</strong> which is a Windows API function to trigger the <strong>WM_DESTROY</strong> message. I also make sure I set my <strong>m_hwnd</strong> to <strong>NULL</strong>. This is because the final <strong>WM_QUIT</strong> message isn&#8217;t associated with any window handle in particular. If I didn&#8217;t set the <strong>m_hwnd</strong> to <strong>NULL</strong>, <strong>PeekMessage</strong> and <strong>GetMessage</strong> would never get the <strong>WM_QUIT</strong> because they would be looking only for messages on that window handle. Since <strong>WM_QUIT</strong> only comes in on <strong>NULL</strong> and now <strong>m_hwnd</strong> is <strong>NULL</strong>, we can get that message, pass it back up to our application loop through <strong>HandleWindowsMessage</strong> and our program can exit properly.</p>
<p>That took quite some time to figure out&#8230;</p>
<p>Finally, the default message callback for <strong>WM_DESTROY</strong> just posts the quit message via <strong>PostQuitMessage</strong>. This simply inserts a <strong>WM_QUIT</strong> into the queue so we can get it next time around.</p>
<pre>
<pre class="brush: cpp; title: ; notranslate">
void SystemWindow::DefaultDestroyMessageCallback(WPARAM wparam, LPARAM lparam) {
dtrace(&quot;DESTROYING&quot;);
PostQuitMessage(0);
}
</pre>
</pre>
<p>Lastly, you&#8217;ll notice that there is an explicit <strong>Destroy</strong> function in <strong>SystemWindow</strong>.</p>
<pre>
<pre class="brush: cpp; title: ; notranslate">
void SystemWindow::Destroy() {
//Unregister the Class
UnregisterClass(m_windowClassName.c_str(), *p_hInstance);

//Unregister the Message Mappings
RemoveAllMessageCallbacks();

//NULL out pointers
p_hInstance = NULL;
}
</pre>
</pre>
<p>Since the <strong>SystemWindow</strong> is explicitly instantiated via <strong>Init</strong>, it is expected to be explicitly destroyed via <strong>Destroy</strong>. You&#8217;d call this in your application once you&#8217;ve broken out of your application loop and are cleaning up after yourself.</p>
<p>The bits of destruction we did in the Close and Destroy MessageCallbacks are only for the Window itself, not the SystemWindow class. Still it&#8217;s pretty simple. We just unregister the class, remove all the message callback in the message map and then null out any pointers we had.</p>
<p>&nbsp;</p>
<h2>Recap:</h2>
<p>That&#8217;s it! It&#8217;s a long post with a fair amount of code but most of it is really understanding how Windows work under the hood. The actual logic is pretty simple once you&#8217;ve wrapped your head around it. Let&#8217;s look at the objectives:</p>
<ul>
<li>Class that encapsulates Microsoft Windows functionality. <em>- Done by the very nature of SystemWindow.</em></li>
<li>Allow for Message Based or Real Time interactivity with the Window. <em>- Done by setting the m_realTime flag and using PeekMessage or GetMessage.</em></li>
<li>Toggle between Full Screen and Windowed Mode<em> &#8211; Done by using ToggleFullScreen.</em></li>
<li>Allow for dynamic re-sizing and re- positioning of the window.<em> &#8211; Done by using the SetWindowProperties and SetWindowFullscreenProperties.</em></li>
<li>Allow for Multiple Windows and Proper message dispatching to the right window instance.<em> &#8211; Done by our GlobalWndProc/LocalWndProc mappings.</em></li>
<li>Map dynamic functionality in response to a Windows Message.<em> &#8211; Done by the MessageMap and MessageCallbacks.</em></li>
</ul>
<div>Looks like we hit all the objectives. Now we can start using the window to host content!</div>
<div>I don&#8217;t believe this class is fully complete by any means. I&#8217;m sure there will be other bits of functionality to add as I use the SystemWindow more and more but for now it handles all the major points I need.</div>
<h2>SystemWindow.cpp</h2>
<p>As promised, the full SystemWindow.cpp source.</p>
<pre>
<pre class="brush: cpp; title: ; notranslate">
//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &quot;SystemWindow.h&quot;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Every Windows Message will hit this function.
LRESULT CALLBACK GlobalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {

//Hold our target window instance
SystemWindow *targetWindow = NULL;

//If it's the WM_NCCREATE message (which should be the first message we get...)
if(msg == WM_NCCREATE) {
//Pull the target window out of the lpCreateParams which is the this pointer we pass into CreateWindowEx
targetWindow = reinterpret_cast&amp;lt;SystemWindow*&amp;gt;((LONG)((LPCREATESTRUCT)lparam)-&amp;gt;lpCreateParams);
//Set the pointer to this instance in the GWLP_USERDATA so we can pull it out reliably in the future
SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)targetWindow);
}
else {
//Pull the window instance out of the GWLP_USERDATA
targetWindow = reinterpret_cast&amp;lt;SystemWindow*&amp;gt;(GetWindowLongPtr(hwnd, GWLP_USERDATA));
}

//If we still don't have a window we can't respond to any events so kick it to the default.
if(targetWindow == NULL) {
return DefWindowProc(hwnd, msg, wparam, lparam);
}

//Otherwise we're all good and we can pipe it to the instances version of the WndProc
return targetWindow-&amp;gt;LocalWndProc(hwnd, msg, wparam, lparam);
}

//////////////////////////////////////////////////////////////////////
// CONSTRUCTORS //////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

SystemWindow::SystemWindow() {
p_hInstance = NULL;

m_fullscreen_width = GetSystemMetrics(SM_CXSCREEN);
m_fullscreen_height = GetSystemMetrics(SM_CYSCREEN);

m_windowed_x = 100;
m_windowed_y = 100;
m_windowed_width = 960;
m_windowed_height = 540;

m_minimized = false;
m_fullScreen = false;
m_realTime = false;
m_hasMenu = false;
m_gwl_style = GWL_STYLE_WINDOWED;
m_gwl_exstyle = GWL_EXSTYLE_WINDOWED;
}

//////////////////////////////////////////////////////////////////////
// DESTRUCTOR ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

SystemWindow::~SystemWindow() {

}

//////////////////////////////////////////////////////////////////////
// INITIALIZE ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

bool SystemWindow::Init(HINSTANCE* hInstance, tstring windowClassName, tstring windowTitleBarName, bool fullScreen, bool realTime) {

//Store Instance Variables
m_windowClassName = windowClassName;
m_windowTitleBarName = windowTitleBarName;
p_hInstance = hInstance;
m_fullScreen = fullScreen;
m_realTime = realTime;
m_gwl_style = (m_fullScreen) ? GWL_STYLE_FULLSCREEN : GWL_STYLE_WINDOWED;

//Default Message Mapping
AddMessageCallback(WM_SIZE, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultSizeMessageCallback, this));
AddMessageCallback(WM_MOVE, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultMoveMessageCallback, this));
AddMessageCallback(WM_CLOSE, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultCloseMessageCallback, this));
AddMessageCallback(WM_DESTROY, BIND_MEM_CB(&amp;amp;SystemWindow::DefaultDestroyMessageCallback, this));

//TODO: Pull in some of this from Config file
ZeroMemory(&amp;amp;m_definition, sizeof(m_definition));
m_definition.cbSize = sizeof(WNDCLASSEX);
m_definition.cbClsExtra = 0;
m_definition.cbWndExtra = 0;
m_definition.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
m_definition.hCursor = LoadCursor(NULL, IDC_ARROW);
m_definition.hIcon = LoadIcon(NULL, IDI_WINLOGO);
m_definition.hIconSm = m_definition.hIcon;
m_definition.hInstance = *p_hInstance;
m_definition.lpfnWndProc = GlobalWndProc;
m_definition.lpszClassName = m_windowClassName.c_str();
m_definition.lpszMenuName = NULL;
m_definition.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

//Register the Class
if (!RegisterClassEx(&amp;amp;m_definition)) {
//If a failure, let us know about it
etrace(&quot;Register Class Failed on %s&quot;, m_windowClassName.c_str());
return false;
}

//Set the initial window size and position
RECT rect;
rect.left = (m_fullScreen) ? 0 : m_windowed_x;
rect.top = (m_fullScreen) ? 0 : m_windowed_y;
rect.right = (m_fullScreen) ? m_fullscreen_width : m_windowed_x + m_windowed_width;
rect.bottom = (m_fullScreen) ? m_fullscreen_height : m_windowed_y + m_windowed_height;
AdjustWindowRectEx(&amp;amp;rect, m_gwl_style, m_hasMenu, m_gwl_exstyle);

//Create the window and store the handle. Passing &quot;this&quot; pointer as the lparam so we can make the mappings in our GlobalWndProc
m_hwnd = CreateWindowEx(m_gwl_exstyle, m_windowClassName.c_str(), m_windowTitleBarName.c_str(), m_gwl_style, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, *p_hInstance, this);
if (!m_hwnd) {
//If a failure, let us know about it
etrace(&quot;Create Window Failed on %s&quot;, m_windowClassName.c_str());
return false;
}

//Get and Store the current System Display Settings
HDC hdc = GetDC(m_hwnd);

//These are the current settings of the users computer
m_originalSettings.dmSize = sizeof(DEVMODE);
m_originalSettings.dmPelsWidth = GetDeviceCaps(hdc, HORZRES);
m_originalSettings.dmPelsHeight = GetDeviceCaps(hdc, VERTRES);
m_originalSettings.dmBitsPerPel = GetDeviceCaps(hdc, BITSPIXEL);
m_originalSettings.dmDisplayFrequency = GetDeviceCaps(hdc, VREFRESH);
m_originalSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;

//Fullscreen settings SHOULD mimic the current settings but we do want to be able to override them in the future potentially.
m_fullScreenSettings.dmSize = sizeof(DEVMODE);
m_fullScreenSettings.dmPelsWidth = m_fullscreen_width = GetDeviceCaps(hdc, HORZRES);
m_fullScreenSettings.dmPelsHeight = m_fullscreen_height = GetDeviceCaps(hdc, VERTRES);
m_fullScreenSettings.dmBitsPerPel = GetDeviceCaps(hdc, BITSPIXEL);
m_fullScreenSettings.dmDisplayFrequency = GetDeviceCaps(hdc, VREFRESH);
m_fullScreenSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL | DM_DISPLAYFREQUENCY;

//For every GetDC we should ReleaseDC
ReleaseDC(m_hwnd, hdc);

//If we're starting in Fullscreen Mode, ensure the Display Settings have switched as well
if (m_fullScreen) {
ChangeDisplaySettings(&amp;amp;m_fullScreenSettings, CDS_FULLSCREEN);
}

return true;
}

//////////////////////////////////////////////////////////////////////
// DESTROY ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

void SystemWindow::Destroy() {
//Unregister the Class
UnregisterClass(m_windowClassName.c_str(), *p_hInstance);

//Unregister the Message Mappings
RemoveAllMessageCallbacks();

//NULL out pointers
p_hInstance = NULL;
}

//////////////////////////////////////////////////////////////////////
// BODY //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

void SystemWindow::Show(int nCmdShow) {
//So long as we have the handle to the window, show it
if (m_hwnd != NULL) {
ShowWindow(m_hwnd, nCmdShow);
}
}

void SystemWindow::SetWindowedProperties(int x, int y, int width, int height) {
m_windowed_x = x;
m_windowed_y = y;
m_windowed_width = width;
m_windowed_height = height;
}

void SystemWindow::SetFullScreenProperties(DWORD horizontalResolution, DWORD verticalResolution, DWORD bitsPerPixel, DWORD refreshRate) {
//Allow for fullscreen settings to be overridden
m_fullScreenSettings.dmPelsWidth = m_fullscreen_width = horizontalResolution;
m_fullScreenSettings.dmPelsHeight = m_fullscreen_height = verticalResolution;
m_fullScreenSettings.dmBitsPerPel = bitsPerPixel;
m_fullScreenSettings.dmDisplayFrequency = refreshRate;

//If we're already in Fullscreen mode, reset to the new properties. Otherwise we'll wait till the next time ToggleFullScreen is called
if (m_fullScreen) {
ChangeDisplaySettings(&amp;amp;m_fullScreenSettings, CDS_FULLSCREEN);
}
}

void SystemWindow::ToggleFullScreen(bool fullScreen) {
//Only if we're actually changing
if (m_fullScreen != fullScreen) {

m_fullScreen = fullScreen;

//Adjust the location and size of the window
RECT rect;
rect.left = (m_fullScreen) ? 0 : m_windowed_x;
rect.top = (m_fullScreen) ? 0 : m_windowed_y;
rect.right = (m_fullScreen) ? m_fullscreen_width : m_windowed_x + m_windowed_width;
rect.bottom = (m_fullScreen) ? m_fullscreen_height : m_windowed_y + m_windowed_height;

//Set all the styles and booleans based on Fullscreen or not
m_gwl_exstyle = (m_fullScreen) ? GWL_EXSTYLE_FULLSCREEN : GWL_EXSTYLE_WINDOWED;
m_gwl_style = (m_fullScreen) ? GWL_STYLE_FULLSCREEN : GWL_STYLE_WINDOWED;
SetWindowLongPtr(m_hwnd, GWL_EXSTYLE, m_gwl_exstyle);
SetWindowLongPtr(m_hwnd, GWL_STYLE, m_gwl_style);

AdjustWindowRectEx(&amp;amp;rect, m_gwl_style, m_hasMenu, m_gwl_exstyle);

SetWindowPos(m_hwnd, (m_fullScreen) ? HWND_TOPMOST : HWND_NOTOPMOST, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_SHOWWINDOW);

//Change the Display Settings
ChangeDisplaySettings((m_fullScreen) ? &amp;amp;m_fullScreenSettings : &amp;amp;m_originalSettings, (m_fullScreen) ? CDS_FULLSCREEN : CDS_RESET);
}
}

//////////////////////////////////////////////////////////////////////
// MESSAGE MAPPING ///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

void SystemWindow::AddMessageCallback(UINT msg, MessageCallback messageHandler) {

//Finds the first and last instance that matches the key
std::pair&amp;lt;MessageMap::const_iterator, MessageMap::const_iterator&amp;gt; range = m_messageMap.equal_range(msg);

//Exit condition
MessageMap::const_iterator end = m_messageMap.end();

bool found = false;

//If there are matches
if (range.first != end &amp;amp;&amp;amp; range.second != end) {

MessageMap::const_iterator start = range.first;
end = range.second;
//Look for an existing messageHandler already mapped to the same msg
MessageCallback existing;

//Loop through all the callbacks
for (; start != end; ++start) {
//Get the Callback and see if we've already got it
existing = start-&amp;gt;second;
if (existing == messageHandler) {
found = true;
return;
}
}
}

if (!found) {
//Insert the new messageHandler at key msg
m_messageMap.insert(MessageMap::value_type(msg, messageHandler));
}

}

void SystemWindow::RemoveMessageCallback(UINT msg, MessageCallback messageHandler) {

//Finds the first and last instance that matches the key
std::pair&amp;lt;MessageMap::const_iterator, MessageMap::const_iterator&amp;gt; range = m_messageMap.equal_range(msg);

//Exit condition
MessageMap::const_iterator end = m_messageMap.end();

//If there are matches
if (range.first != end &amp;amp;&amp;amp; range.second != end) {
MessageMap::const_iterator start = range.first;
end = range.second;
//Look for an existing messageHandler already mapped to the same msg
MessageCallback existing;

//Loop through all the callbacks
for (; start != end; ++start) {
//Get the Callback and see if we've already got it
existing = start-&amp;gt;second;
if (existing == messageHandler) {
existing = util::NullCallback();
m_messageMap.erase(start);
return;
}
}
}
}

void SystemWindow::RemoveAllMessageCallbacks() {
//Delete all entries in the list
m_messageMap.clear();
}

//////////////////////////////////////////////////////////////////////
// MESSAGE HANDLING //////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

MSG SystemWindow::HandleWindowsMessage() {
MSG msg;
ZeroMemory(&amp;amp;msg, sizeof(MSG));
if (m_realTime) {
PeekMessage(&amp;amp;msg, m_hwnd, 0, 0, PM_REMOVE);
}
else {
GetMessage(&amp;amp;msg, m_hwnd, 0, 0);
}

if (msg.message != WM_NULL) {
TranslateMessage(&amp;amp;msg);
DispatchMessage(&amp;amp;msg);
}

return msg;
}

void SystemWindow::DefaultSizeMessageCallback(WPARAM wparam, LPARAM lparam) {
dtrace(&quot;SIZING&quot;);

m_minimized = (wparam == SIZE_MINIMIZED);
(m_fullScreen) ? (m_fullScreenSettings.dmPelsWidth = m_fullscreen_width = LOWORD(lparam)) : (m_windowed_width = LOWORD(lparam));
(m_fullScreen) ? (m_fullScreenSettings.dmPelsHeight = m_fullscreen_height = HIWORD(lparam)) : (m_windowed_height = HIWORD(lparam));
}

void SystemWindow::DefaultMoveMessageCallback(WPARAM wparam, LPARAM lparam) {
dtrace(&quot;MOVING&quot;);
if (m_fullScreen == false) {
m_windowed_x = LOWORD(lparam);
m_windowed_y = HIWORD(lparam);
}
}

void SystemWindow::DefaultCloseMessageCallback(WPARAM wparam, LPARAM lparam) {
dtrace(&quot;CLOSING&quot;);
//TODO: Allow for hook to save state
//Destroy the Window
DestroyWindow(m_hwnd);
//Very important to set this to NULL so the WM_QUIT is picked up
m_hwnd = NULL;
}

void SystemWindow::DefaultDestroyMessageCallback(WPARAM wparam, LPARAM lparam) {
dtrace(&quot;DESTROYING&quot;);
PostQuitMessage(0);
}

//////////////////////////////////////////////////////////////////////
// LOCAL WND PROC ////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

LRESULT CALLBACK SystemWindow::LocalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
//Check to make sure the map isn't empty
if (!m_messageMap.empty()) {

//Finds the first and last instance that matches the key
std::pair&amp;lt;MessageMap::const_iterator, MessageMap::const_iterator&amp;gt; range = m_messageMap.equal_range(msg);

//Exit condition
MessageMap::const_iterator end = m_messageMap.end();

//There were no matches found
if (range.first == end &amp;amp;&amp;amp; range.second == end) {
//We should default
return DefWindowProc(hwnd, msg, wparam, lparam);
}
else {
MessageMap::const_iterator start = range.first;
end = range.second;

MessageCallback messageCallback;

//Loop through all the callbacks
for (; start != end; ++start) {
//Get the Callback and Call it
messageCallback = start-&amp;gt;second;
messageCallback(wparam, lparam);
}
return 0;
}
}
else {
return DefWindowProc(hwnd, msg, wparam, lparam);
}
}

//////////////////////////////////////////////////////////////////////
// GETTERS/SETTERS ///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

HWND* SystemWindow::GetHWND() {
return &amp;amp;m_hwnd;
}

bool SystemWindow::IsFullScreen() {
return m_fullScreen;
}

bool SystemWindow::IsMinimized() {
return m_minimized;
}

}
</pre>
</pre>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/windows-part-2/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Windows: Part 1</title>
		<link>http://www.breaktrycatch.com/windows-part-1/</link>
		<comments>http://www.breaktrycatch.com/windows-part-1/#comments</comments>
		<pubDate>Sun, 02 Oct 2011 23:53:27 +0000</pubDate>
		<dc:creator>Jon Keon</dc:creator>
				<category><![CDATA[C++]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=831</guid>
		<description><![CDATA[After getting my system all setup and ready for C++ programming, it was time to start actually having something being displayed to the screen. In order to do that on a Windows Box, you&#8217;re going to need a window. There are a variety of sites out there that will get you up and running pretty...]]></description>
			<content:encoded><![CDATA[<p>After getting my system all setup and ready for C++ programming, it was time to start actually having something being displayed to the screen.</p>
<p>In order to do that on a Windows Box, you&#8217;re going to need a window.</p>
<p>There are a variety of sites out there that will get you up and running pretty quick with a simple window but eventually you&#8217;re going to want to have a robust class that accomplishes all the functionality you need so you never have to write the boiler plate windows code again for your project.</p>
<h3>Window Class Goals:</h3>
<ul>
<li>Class that encapsulates Microsoft Windows functionality.</li>
<li>Allow for Message Based or Real Time interactivity with the Window.</li>
<li>Toggle between Full Screen and Windowed Mode</li>
<li>Allow for dynamic re-sizing and re- positioning of the window.</li>
<li>Allow for Multiple Windows and Proper message dispatching to the right window instance.</li>
<li>Map dynamic functionality in response to a Windows Message.</li>
</ul>
<div>There&#8217;s a lot of functionality there and some of it is a bit complex. So in Part 1, I&#8217;ll only be addressing (and basically at that) a few of those goals.</div>
<div>I struggled with this quite a bit. In my mind, I know what I want to build and roughly how to build it. But often the all-encompassing solution requires a bit of growth throughout the development. Requirements change and new caveats pop up depending of what features you are implementing. As much as it pains me (for some reason), this is only the first and rather incomplete version of the Window class. As I actually start using it to <strong>build things</strong> I will add/remove/refactor and hopefully by the end of my project, I&#8217;ll have a class that is a robust and complete as I had originally wanted to design.</div>
<div>I find that if you don&#8217;t take that hard stance in moving on with something that is less than ideal but works, you&#8217;ll be stuck in a endless state of paralysis thinking about all the what-if&#8217;s. A great majority of those what-if&#8217;s may never come up, and if they do, then you can address it and rethink the design.</div>
<div>That being said let&#8217;s take a look at the class:</div>
<h3>Window.h</h3>
<div>
<pre class="brush: cpp; title: ; notranslate">//////////////////////////////////////////////////////////////////////
// Window //
// //
// Description: //
// Author: jkeon //
//////////////////////////////////////////////////////////////////////
#ifndef _WINDOW_H_
#define _WINDOW_H_#define WIN32_LEAN_AND_MEAN//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &amp;lt;Windows.h&amp;gt;
#include &amp;lt;string/TString.h&amp;gt;
#include &amp;lt;util/DebugUtil.h&amp;gt;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {
//////////////////////////////////////////////////////////////////////
// GLOBALS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// CLASS DECLARATION /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

class Window {

//PUBLIC FUNCTIONS
public:
Window();
Window(const Window&amp;amp; other);
virtual ~Window();

bool Init(HINSTANCE* hInstance, tstring* windowClassName, tstring* windowTitleBarName, int x, int y, int width, int height);
void Show(int nCmdShow);
void Run();
void Destroy();

LRESULT CALLBACK LocalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);

//PUBLIC VARIABLES
public:

//PROTECTED FUNCTIONS
protected:

//PROTECTED VARIABLES
protected:

//PRIVATE FUNCTIONS
private:

//PRIVATE VARIABLES
private:
HINSTANCE* __hInstance;
WNDCLASSEX __definition;
HWND __hwnd;
int __x;
int __y;
int __width;
int __height;
tstring* __windowClassName;
bool __realTime;
bool __messagePumpActive;

};

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

static LRESULT CALLBACK GlobalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
static Window* globalWindow = 0;

}
#endif</pre>
<h3>Window.cpp</h3>
<pre class="brush: cpp; title: ; notranslate">//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &quot;Window.h&quot;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Every Windows Message will hit this function.
LRESULT CALLBACK GlobalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
if (globalWindow != NULL) {
return globalWindow-&amp;gt;LocalWndProc(hwnd, msg, wparam, lparam);
}
else {
return DefWindowProc(hwnd, msg, wparam, lparam);
}
}

//////////////////////////////////////////////////////////////////////
// CONSTRUCTORS //////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

Window::Window() {
__hInstance = NULL;
__windowClassName = NULL;
__x = 0;
__y = 0;
__width = 800;
__height = 600;
__realTime = false;
__messagePumpActive = false;
}

Window::Window(const Window&amp;amp; other) {

}

//////////////////////////////////////////////////////////////////////
// DESTRUCTOR ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

Window::~Window() {

}

//////////////////////////////////////////////////////////////////////
// INITIALIZE ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

bool Window::Init(HINSTANCE* hInstance, tstring* windowClassName, tstring* windowTitleBarName, int x, int y, int width, int height) {

//Store Instance Variables
__x = x;
__y = y;
__width = width;
__height = height;
__windowClassName = windowClassName;
__hInstance = hInstance;

//TODO: Pull in some of this from Config file
__definition.cbSize = sizeof(WNDCLASSEX);
__definition.cbClsExtra = 0;
__definition.cbWndExtra = 0;
__definition.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
__definition.hCursor = LoadCursor(NULL, IDC_ARROW);
__definition.hIcon = LoadIcon(NULL, IDI_WINLOGO);
__definition.hIconSm = __definition.hIcon;
__definition.hInstance = *__hInstance;
__definition.lpfnWndProc = GlobalWndProc;
__definition.lpszClassName = __windowClassName-&amp;gt;c_str();
__definition.lpszMenuName = NULL;
__definition.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;

//Register the Class
if (!RegisterClassEx(&amp;amp;__definition)) {
//If a failure, let us know about it
etrace(&quot;Register Class Failed on %s&quot;, __windowClassName-&amp;gt;c_str());
return false;
}

//Create the window and store the handle
__hwnd = CreateWindow(__windowClassName-&amp;gt;c_str(), windowTitleBarName-&amp;gt;c_str(), WS_OVERLAPPEDWINDOW, __x, __y, __width, __height, NULL, NULL, *__hInstance, NULL);
if (!__hwnd) {
//If a failure, let us know about it
etrace(&quot;Create Window Failed on %s&quot;, __windowClassName-&amp;gt;c_str());
return false;
}

//Set the static reference
globalWindow = this;

//Simple trace to let us know it's working
itrace(&quot;Window Init Properly for %s&quot;, __windowClassName-&amp;gt;c_str());

return true;
}

//////////////////////////////////////////////////////////////////////
// DESTROY ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

void Window::Destroy() {
//Destroy the Window
DestroyWindow(__hwnd);
__hwnd = NULL;

//Unregister the Class
UnregisterClass(__windowClassName-&amp;gt;c_str(), *__hInstance);

//NULL out pointers
__hInstance = NULL;
__windowClassName = NULL;
}

//////////////////////////////////////////////////////////////////////
// BODY //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

void Window::Show(int nCmdShow) {
//So long as we have the handle to the window, show it
if (__hwnd != NULL) {
ShowWindow(__hwnd, nCmdShow);
}
}

void Window::Run() {

MSG msg;
ZeroMemory(&amp;amp;msg, sizeof(MSG));
__messagePumpActive = true;

//If we're running this as a Real Time Window, use PeekMessage so it's non-blocking
if (__realTime) {
while(__messagePumpActive) {
if (PeekMessage(&amp;amp;msg, __hwnd, 0, 0, PM_REMOVE)) {
TranslateMessage(&amp;amp;msg);
DispatchMessage(&amp;amp;msg);
if (msg.message == WM_QUIT) {
__messagePumpActive = false;
}
}
}
}
//Otherwise use GetMessage which is blocking and will free up CPU cycles for other apps
else {
while(__messagePumpActive) {
GetMessage(&amp;amp;msg, __hwnd, 0, 0);
TranslateMessage(&amp;amp;msg);
DispatchMessage(&amp;amp;msg);
if (msg.message == WM_QUIT) {
__messagePumpActive = false;
}
}
}
}

LRESULT CALLBACK Window::LocalWndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
switch (msg) {

case WM_DESTROY:
PostQuitMessage(0);
return 0;
break;

case WM_CLOSE:
PostQuitMessage(0);
return 0;
break;

default:
return DefWindowProc(hwnd, msg, wparam, lparam);
}
}

//////////////////////////////////////////////////////////////////////
// GETTERS/SETTERS ///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

}
</pre>
<p>Fairly basic but it get&#8217;s the job done.</p>
<p>Some good references where I pulled bits and pieces from are:</p>
<ul>
<li><a href="http://bobobobo.wordpress.com/2008/02/03/skeleton-of-a-fast-c-windows-program-for-games-using-peekmessage/">http://bobobobo.wordpress.com/2008/02/03/skeleton-of-a-fast-c-windows-program-for-games-using-peekmessage/</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb384843.aspx">http://msdn.microsoft.com/en-us/library/bb384843.aspx</a></li>
<li><a href="http://www.rastertek.com/dx11tut02.html">http://www.rastertek.com/dx11tut02.html</a></li>
</ul>
<h4>Window::Window</h4>
<div>When we create a new Window, the first thing it does is just set some defaults for the private variables. Nothing special here.</div>
<h4><strong>Window::Init</strong></h4>
<div>The next function to call is Init which will initialize the window and actually create a Microsoft Window internally and give us the Handle to that Window.</div>
<div>We pass in the Application Instance as well as a class name for our window and the title in the menu bar and the initial position and size of the window. I feel like the API here is a bit too long so I might take the positioning and sizing part out in the future.</div>
<div>Windows need to be created via a definition, so we need to populate ours. Most of this is pretty straightforward if you follow along with <a title="MSDN WNDCLASSEX" href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633577(v=vs.85).aspx">MSDN</a>.</div>
<div>The property <strong>lpfnWndProc</strong> however is pretty important. This function is where Windows Messages will get piped too and it needs to be a static function.</div>
<div>But one of our goals was to be able to have multiple windows and have messages mapped to the correct instance of the window. If we pipe out messages to this static function, all messages will hit all of our windows and we won&#8217;t be able to have specific functionality for them. Fortunately there are ways around this as outlined <a title="GameDev: Windows Class" href="http://www.gamedev.net/page/resources/_/technical/game-programming/creating-a-win32-window-wrapper-class-r1810">here</a> but it&#8217;s a bit complex and I really need to sit down and fully understand it before I implement it.</div>
<div>After that we register  and then create the window, storing the handle to the actual window in our class.</div>
<div>The final step is registering this window as a static window so our GlobalWndProc function can access this window&#8217;s LocalWndProc function. This effectively limits us to one Window though which is definitely not what we want but at this point it will do since we&#8217;re only going to have one Window. We will be changing this for sure in the future.</div>
<h4>Window::Destroy</h4>
<p>The Destroy function is also pretty standard, just tearing things down and cleaning up.</p>
<h4>Window::Show</h4>
<p>Another standard function, simply lets the outside world show the window. I&#8217;m unsure if I&#8217;ll keep this. I don&#8217;t really want to wrap every little bit of Windows functionality but until I actually start<strong> building things</strong> with Windows in them, I don&#8217;t really know what&#8217;s useful or not.</p>
<h4><strong>Window::Run</strong></h4>
<p>The Run function is the infinite loop which keeps our program running and the window displayed. There are two code paths here (which can be cleaned up)  but they basically serve for whether what&#8217;s going on in the Window needs to use the CPU all the time (like a game etc) or whether it&#8217;s an application that only needs to respond to specific user interaction.</p>
<p>In Real Time mode, so long as the message pump is active we want to Peek at the Windows Message Stack and see if there are any messages. If there are, we want to Translate that Message and then Dispatch it. The Dispatch Function will send that message to our <strong>GlobalWndProc</strong> handler and then through the static instance of our window, send it back to our <strong>LocalWndProc</strong> where we actually handle the message.</p>
<p>When not in Real Time mode, we use <strong>GetMessage</strong> instead of <strong>PeekMessage</strong>. GetMessage is a blocking call. So until there is a message in the queue to process, the program will effectively halt at this location, freeing up resources for other programs that are running on your system. If you start interacting with your program, messages will get generated and you can respond to them.</p>
<p>In both cases, we need a way out of the loop so we check if the message is a <strong>WM_QUIT</strong> message. This means we&#8217;re trying to close the application and so we should exit and allow the program to terminate.</p>
<p>This function works just great for a Window but if we ever want our program to <em>Do Something</em>, we need to modify this function so that our custom logic exists inside this while loop or is in direct response to Windows Message. Just another piece we&#8217;ll have to modify as we go along.</p>
<h4>Window::LocalWndProc</h4>
<p>This function is purely for Message Management. Based on the Message that comes through we want to do different things. For now, we&#8217;ll only care about a <strong>WM_DESTROY</strong> or <strong>WM_CLOSE</strong>. When either of those happen we want to Post  a Quit Message which is what breaks us out of the while loop in <strong>Window::Run</strong>.</p>
<div>If it&#8217;s anything else, we just let the default happen whatever that may be.</div>
<div>There are quite a few messages that can come though and we may not need or want to define behaviours for all of them. Plus, if we want to have two Window classes which do different things on the same message, we&#8217;re pretty stuck right now. The plan is to use some sort of mapping to functions so that when a message comes in, we&#8217;ll check the instance&#8217;s message map to see if there is a function that corresponds to this message. If there is, we&#8217;ll call that function. If there isn&#8217;t then we&#8217;ll just let the default happen.</div>
<div>This will give us the flexibility to define outside the Window class what that window should do in the event of a certain message.</div>
<h4>GlobalWndProc</h4>
<p>The last function to touch on is pretty simple. We just pipe the function along to our global instances LocalWndProc function. This function will need to change to resolve <strong>which</strong> instance we want to pipe the function along to since in the future we probably will want multiple windows at a time.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<div>So there we have it, a basic Window class we can use to display the following on the screen:</div>
<div><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/10/Image_006.png"><img class="aligncenter size-full wp-image-840" title="Basic Window" src="http://www.breaktrycatch.com/wp-content/uploads/2011/10/Image_006.png" alt="" width="574" height="315" /></a></div>
<div>Super exciting eh?</div>
<div>Eventually I promise I&#8217;ll put something inside the window and actually getting to some interesting topics. For now though, it&#8217;s all about the foundations.</div>
<div>Finally for completeness this is my main.cpp to show how to invoke the Window class. Note that the Run() function is blocking because it has the infinite while loop inside it. Until the WM_QUIT message is dispatched we&#8217;ll stay in the Run() function and not start destroying or cleaning up our window.</div>
<h4>main.cpp</h4>
<div>
<pre class="brush: cpp; title: ; notranslate">//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////#include &amp;lt;util/DebugUtil.h&amp;gt;
#include &amp;lt;window/Window.h&amp;gt;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// MAIN //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Main Entry point to windows application
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {

//Create the Main Window
Athena::Window* mainWindow = new Athena::Window();
tstring mainWindowClassName = TEXT(&quot;AthenaMainWindowClass&quot;);
tstring mainWindowMenuTitle = TEXT(&quot;Athena Engine&quot;);

//Check that it was created properly. If not we should exit
if(mainWindow == NULL) {
return 0;
}

//Initialize the Main Window
bool success = mainWindow-&amp;gt;Init(&amp;amp;hInstance, &amp;amp;mainWindowClassName, &amp;amp;mainWindowMenuTitle, 100, 100, 1920, 1080);
if (success) {
mainWindow-&amp;gt;Show(nCmdShow);
mainWindow-&amp;gt;Run();
}

//Properly Destroy and cleanup the main window
mainWindow-&amp;gt;Destroy();
delete mainWindow;
mainWindow = 0;

//Making it this far means we are finished the program and we should exit normally.
return 0;
}</pre>
</div>
</div>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/windows-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Into the Abyss: Getting Started with C++</title>
		<link>http://www.breaktrycatch.com/into-the-abyss-getting-started-with-c/</link>
		<comments>http://www.breaktrycatch.com/into-the-abyss-getting-started-with-c/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 02:13:36 +0000</pubDate>
		<dc:creator>Jon Keon</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=810</guid>
		<description><![CDATA[Background: Feel free to skip this part if you aren&#8217;t interested in why I&#8217;m blogging about this and just want the info. &#160; First a little bit of background. I learned Visual Basic, Java and C in Highschool. Those were my first forays into the world of programming and sparked my interest for making things...]]></description>
			<content:encoded><![CDATA[<h2>Background:</h2>
<p><em>Feel free to skip this part if you aren&#8217;t interested in why I&#8217;m blogging about this and just want the info.</em></p>
<p>&nbsp;</p>
<p>First a little bit of background.</p>
<p>I learned Visual Basic, Java and C in Highschool. Those were my first forays into the world of programming and sparked my interest for making things happen on the screen. I did some more Java, C++, OpenGL and finally ActionScript in University. Not to knock the school&#8217;s but what I learned was introductory at best. I really became a programmer at my first actual programming job. I was an Actionscript Developer/Designer working on internal tools to help the Support Department more easily get access to information when trying to solve a client&#8217;s issue. Not exactly glamorous but it was a great gig while finishing up my degree. That was really where I learned how to program.</p>
<p>Two years later, I had graduated and it was off to an Ad Agency to develop ActionScript based promotional websites and games for pretty much all the big names in advertising. We did the Facebook game thing, we did the Online MMO thing, and even a little game you played via your cellphone up on the Times Square billboards. There it was trial by fire with tight deadlines and radically different challenges for each project. It was there I learned how to architect.</p>
<p>Three years of working my way up through development and then management and I was ready for another change. It&#8217;s been just over 4 months now that I&#8217;ve been working back as an Actionscript Developer in the tablet and phone space. New challenges and opportunities to be sure but I&#8217;ve found myself having less and less unknowns and less challenges to really stimulate that part of the brain that gets excited when you finally figure out just that perfect way to solve the problem at hand.</p>
<p>Don&#8217;t get me wrong, I&#8217;m not professing to have &#8220;Mastered&#8221; Actionscript and all there is to learn about Flash Development in the slightest. But I do want to branch out on my own time and start exploring something completely new.</p>
<p>I&#8217;ve always been really interested in 3D graphics programming and have been very invested in the new Stage3D technology with Flash Player 11. But if you want the culmination in 3D Graphics, you need to be working with DirectX or OpenGL to get the maximum result.</p>
<p>And so enters C++.</p>
<p>And I mean real C++. I&#8217;ve done it before in school, I&#8217;ve done some tutorials on the web, even gone through some of the exercises in the <a title="Sam's Teach Yourself C++" href="http://www.amazon.com/Sams-Teach-Yourself-One-Hour/dp/0672329417/ref=sr_1_1?ie=UTF8&amp;qid=1317001970&amp;sr=8-1" target="_blank">Sam&#8217;s Teach Yourself C++ in 21 Days</a>. While those were beneficial I found that they don&#8217;t convey nearly enough information on actually starting up a project and organizing it in a way to let you build something that&#8217;s more than just a quick demo or tutorial. Everything is either in main.cpp or has one or two classes.</p>
<p>What I want is best practices and real-world examples to learn off of. There are a few out there, but mostly it&#8217;s a lot of scouring the internet on sites like <a title="StackOverflow" href="http://stackoverflow.com/" target="_blank">StackOverflow </a>and the <a title="MSDN Library" href="http://msdn.microsoft.com/en-us/library/ms123401.aspx" target="_blank">MSDN </a>docs and cross referencing what people are saying with how my gut feels. I feel I&#8217;m finally at a point where I can really take off now and start building an application with which to learn from.</p>
<p>I plan on chronicling my journey as it were on this blog so that hopefully others can learn from it, or more likely, those that know better can post in the comments and correct me!</p>
<p>So we&#8217;ll see it goes but ultimately I hope to explore as much as I can in the world of C++ and DirectX 11.</p>
<h2>Getting Started:</h2>
<p>Coming from an ActionScript background, C++ is going to seem complicated and daunting. You get a lot more control, but there&#8217;s also quite a few more headaches that you have to deal with.</p>
<p>I&#8217;m developing on a Windows 7 x64 using Microsoft Visual Studio 2010 so file paths etc will reflect that.</p>
<p>The first tidbit I learned in wanting to have nice clean organized code was to modify the default templates for new .h and .cpp files.</p>
<p>If you navigate to C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcprojectitems you will find two files.</p>
<ul>
<li>hfile.h</li>
<li>newc++file.cpp</li>
</ul>
<div>These are the files Visual Studio uses when you try and add a new item to your project. By default, these are just empty files but I found myself always copy pasting the same thing, so I modified them to look like this:</div>
<p>&nbsp;</p>
<h3>hfile.h</h3>
<pre class="brush: cpp; title: ; notranslate">/*********************************
*Class: CLASSNAME
*Description:
*Author: jkeon
**********************************/

#ifndef _CLASSNAME_H_
#define _CLASSNAME_H_

//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace NAMESPACE {

//////////////////////////////////////////////////////////////////////
// GLOBALS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// CLASS DECLARATION /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

class CLASSNAME {

//PUBLIC FUNCTIONS
public:
CLASSNAME();
CLASSNAME(const CLASSNAME&amp;amp; other);
~CLASSNAME();

//PUBLIC VARIABLES
public:

//PROTECTED FUNCTIONS
protected:

//PROTECTED VARIABLES
protected:

//PRIVATE FUNCTIONS
private:

//PRIVATE VARIABLES
private:

};

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

}
#endif</pre>
<p>&nbsp;</p>
<h3> newc++file.cpp</h3>
<pre class="brush: cpp; title: ; notranslate">//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace NAMESPACE {

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// CONSTRUCTORS //////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

CLASSNAME::CLASSNAME() {

}

CLASSNAME::CLASSNAME(const CLASSNAME&amp;amp; other) {

}

//////////////////////////////////////////////////////////////////////
// DESTRUCTOR ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

CLASSNAME::~CLASSNAME() {

}

//////////////////////////////////////////////////////////////////////
// INITIALIZE ////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// DESTROY ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// BODY //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// GETTERS/SETTERS ///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

}</pre>
<div>Simple, and easy. Takes care of my header blockers, Constructor, Copy Constructor, Destructor and nice neat subsections for organizing my code. Of course most of the time a class won&#8217;t use all of it, but it&#8217;s way easier to delete than copy paste everytime I want  to use it.</div>
<p>&nbsp;</p>
<div>The one thing to note is that this is just straight text, there&#8217;s no automatic replacement happening based on class name or anything like that. You still have to manually replace those with the class and namespace names you chose.</div>
<h2>Organization:</h2>
<div>The next bit to tackle was class organization. Being from an Actionscript background, my classes have always been organized into packages which are reflected on the file system and broken down into sub sections denoting functionality. In C++ this doesn&#8217;t have to be the case. The majority of the tutorials out there just put every single file into the same directory because it&#8217;s easy to do include statements.</div>
<p>&nbsp;</p>
<div>In my research I haven&#8217;t found a consistent best practice for this, even looking at some prominent 3D engines out there like <a title="Wild Magic 5 Engine" href="http://www.geometrictools.com/" target="_blank">Wild Magic 5</a> and <a title="OGRE3D Engine" href="http://www.ogre3d.org/" target="_blank">Ogre3D </a>they vary pretty significantly. WildMagic has a few main folders and some sub folders but the .cpp and .h files are kept together. Ogre3D has a src and include directory and keeps all the cpp files in the src directory and all the h files in the include directory.</div>
<p>&nbsp;</p>
<div>The lack of enforcement really means you can do anything that works for your workflow and team unlike languages like ActionScript or Java where classes must be named as they are on the file system and located in nested folder structures that reflect their package location.</div>
<p>&nbsp;</p>
<div>In Visual Studio there is the concept of filters in the solution explorer. These filters would allow you to organize your files nicely regardless of what the representation is on the file system.</div>
<p>&nbsp;</p>
<div>Personally, the rules I&#8217;m going to use are that classes must be named as they are defined. If the class is called DebugUtil.h, the classname is DebugUtil. As well the organization of the Solution Explorer filters will mimic the file system exactly. It&#8217;s close to the packages I&#8217;m used to and I think it makes thing readable.</div>
<p>&nbsp;</p>
<div>Here&#8217;s my current Solution Explorer:</div>
<p>&nbsp;</p>
<div><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/09/Image_003.png"><img class="size-full wp-image-816 aligncenter" title="Solution Explorer" src="http://www.breaktrycatch.com/wp-content/uploads/2011/09/Image_003.png" alt="" width="267" height="333" /></a></div>
<p>&nbsp;</p>
<div>I&#8217;m keeping my headers and cpp files together as well.</div>
<p>&nbsp;</p>
<div>Now the only issue this brings up is the include statements so you just need to edit your include directories to include the root of your project&#8217;s source tree.</div>
<p>&nbsp;</p>
<div><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/09/Image_004.png"><img class="size-full wp-image-817 aligncenter" title="Editing Include Paths" src="http://www.breaktrycatch.com/wp-content/uploads/2011/09/Image_004.png" alt="" width="849" height="291" /></a></div>
<p>&nbsp;</p>
<div>Right where it says &#8220;Additional Include Directories&#8221; I&#8217;ve added &#8220;..\&#8221; and the path to my src directory in my project. &#8220;C:\__WORK\DX11\Athena\trunk\Athena\Athena\src&#8221;</div>
<p>&nbsp;</p>
<div>Now when I do Include statements they&#8217;re simply the fully qualified path on the file system relative to my src directory.</div>
<p>&nbsp;</p>
<div>ex. #include &lt;util/DebugUtil.h&gt;</div>
<p>&nbsp;</p>
<div>I&#8217;ll confess that I&#8217;m not 100% sure what&#8217;s going on here. Before doing this step, I would simply do #include &#8220;DebugUtil.h&#8221; because that was what intellisense was giving me. However when I would come back the next day, it would error and be unable to find the file. The intellisense and error checking seems flaky at best though with Visual Studio which is surprising. But I guess that I&#8217;m just used to the awesomeness that is <a title="FDT" href="http://www.fdt.powerflasher.com/" target="_blank">FDT</a>.</div>
<p>&nbsp;</p>
<h2>Strings:</h2>
<div>Strings are annoying in C++. Really annoying. It&#8217;s not a native type, and any string classes that exist essentially just wrap an array of characters. Which is fine, except that there are different Type&#8217;s of characters depending on your encoding. I&#8217;m not going to get into it, a quick google search will show you what I mean. Ultimately though it seems as though you want to use TCHAR which automatically decides to use char or wchar_t depending if you&#8217;re using ANSI or UNICODE character encoding.</div>
<p>&nbsp;</p>
<div>Problem is there&#8217;s no TSTRING, just std::string and std::wstring.</div>
<p>&nbsp;</p>
<div>So I&#8217;ve just created a class called TString.h which uses the magic of typedefs to declare my own type called tstring which is a basic_string vector of TCHARS. If you look at the definition of string and wstring you&#8217;ll find they are just basic_string vectors of chars and wchar_t&#8217;s respectively.</div>
<p>&nbsp;</p>
<div>C++ and the Windows library especially is littered with these typedefs so it&#8217;s imperative to look these up so you can see what you are really dealing with and how to cast between them.</div>
<p>&nbsp;</p>
<div>The good thing about using tstring everywhere is that in the event I change over to some other kind of string, I can simply update the typedef and barring and API changes, the rest of my code still works.</div>
<p>&nbsp;</p>
<h3>TString.h</h3>
<pre class="brush: cpp; title: ; notranslate">/*********************************
*Class: TSTRING
*Description:
*Author: jkeon
**********************************/

#ifndef _TSTRING_H_
#define _TSTRING_H_

//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &amp;lt;string&amp;gt;
#include &amp;lt;tchar.h&amp;gt;

//////////////////////////////////////////////////////////////////////
// TYPEDEF ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

typedef std::basic_string&amp;lt;TCHAR&amp;gt; tstring;

#endif</pre>
<h2>Debugging in a Windows Application:</h2>
<p>&nbsp;</p>
<div>The final part of this Getting Started in outputting Debug Statements to the console when running a Windows application.</div>
<p>&nbsp;</p>
<div>The famous printf or cout will output to the console if you&#8217;re writing a Console application (window with the black DOS like background and white text) but if you&#8217;re writing a Windows application, you don&#8217;t get a black console window by default. You can enable it if you like but there is also a handy function called <strong>OutputDebugString</strong> which will write out to the console in Visual Studio.</div>
<p>&nbsp;</p>
<div>Only problem is that it doesn&#8217;t take in variable arguments so you can print values of ints or strings etc. You&#8217;d have to process that, put it in a compatible string with a LPCWSTR which is a Long Pointer to a Wide Character String and then send it to the OutputDebugString function.</div>
<p>&nbsp;</p>
<div>If you&#8217;re doing serious debugging you should be using the debugger and stepping through, but sometimes you just want quick easy traces that you can monitor the console window more without halting execution of your program. Doing all those steps would make it tedious and annoying.</div>
<p>&nbsp;</p>
<div>So I created a class called DebugUtil which will handle those things for me.</div>
<p>&nbsp;</p>
<h3>DebugUtil.h</h3>
<pre class="brush: cpp; title: ; notranslate">/*********************************
*Class: DebugUtil
*Description:
*Author: jkeon
**********************************/

#ifndef _DEBUGUTIL_H_
#define _DEBUGUTIL_H_

#ifdef NDEBUG
#define dtrace(message, ...)
#define etrace(message, ...)
#define itrace(message, ...)
#else
#define __FILE_W__ TEXT(__FILE__)
#define __FUNCTION_W__ TEXT(__FUNCTION__)
#define dtrace(message, ...) \
DebugUtil::outputDebugTrace(TEXT(&quot;DEBUG&quot;), __FILE_W__, __FUNCTION_W__, __LINE__, TEXT(message), ##__VA_ARGS__)
#define etrace(message, ...) \
DebugUtil::outputDebugTrace(TEXT(&quot;ERROR&quot;), __FILE_W__, __FUNCTION_W__, __LINE__, TEXT(message), ##__VA_ARGS__)
#define itrace(message, ...) \
DebugUtil::outputDebugTrace(TEXT(&quot;INFO&quot;), __FILE_W__, __FUNCTION_W__, __LINE__, TEXT(message), ##__VA_ARGS__)
#endif

//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &amp;lt;Windows.h&amp;gt;
#include &amp;lt;string/TString.h&amp;gt;
#include &amp;lt;sstream&amp;gt;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {

//////////////////////////////////////////////////////////////////////
// CLASS DECLARATION /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

class DebugUtil {

//PUBLIC FUNCTIONS
public:
static void outputDebugTrace(const TCHAR* type, const TCHAR* file, const TCHAR* function, const unsigned long line, const TCHAR* message, ...);

//PUBLIC VARIABLES
public:

//PROTECTED FUNCTIONS
protected:

//PROTECTED VARIABLES
protected:

//PRIVATE FUNCTIONS
private:

//PRIVATE VARIABLES
private:

};

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

}
#endif</pre>
<div>The main purpose of this Header is to allow you to do a one line call via a macro.</div>
<p>&nbsp;</p>
<div>I have three defined if and only if we are in Debug mode. In Release mode these macros won&#8217;t do anything because the macro NDEBUG only exists in Release mode.</div>
<p>&nbsp;</p>
<div>There there are the macro&#8217;s __FILE__ and __FUNCTION__ which return the file name and path and the function name respectively. I should probably update this to handle it in TCHAR way but for now I&#8217;m forcing them to be Wide Characters since I know I&#8217;m working in UNICODE mode.</div>
<p>&nbsp;</p>
<div>dtrace, etrace and itrace stand for debug trace, error trace and info trace respectively and they simply take in a message as and a variable amount of arguments as if it were a printf statement.</div>
<p>&nbsp;</p>
<div>Which means you&#8217;ll need to know the codes for the different variables you pass in. You can find a good listing of them <a title="Printf Variable Codes" href="http://en.cppreference.com/w/cpp/io/c/fprintf" target="_blank">here</a>.</div>
<p>&nbsp;</p>
<div>This macro simply calls the Static function defined in DebugUtil.h and handles passing in the type, filename, function and line number for you.</div>
<p>&nbsp;</p>
<div>DebugUtil.cpp is where the function gets implemented.</div>
<p>&nbsp;</p>
<h3>DebugUtil.cpp</h3>
<pre class="brush: cpp; title: ; notranslate">//////////////////////////////////////////////////////////////////////
// INCLUDES //////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

#include &quot;DebugUtil.h&quot;

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace Athena {

//////////////////////////////////////////////////////////////////////
// STATICS ///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

void DebugUtil::outputDebugTrace(const TCHAR* type, const TCHAR* file, const TCHAR* function, const unsigned long line, const TCHAR* message, ...) {

tstring formattedFile;
formattedFile.append(file);

size_t index;
index = formattedFile.find_last_of('\\');

tstring output;
output.append(type);
output.append(TEXT(&quot; [&quot;));
output.append(formattedFile.substr(index+1));
output.append(TEXT(&quot; :: &quot;));
output.append(function);
output.append(TEXT(&quot; : &quot;));

std::wostringstream oss;
oss &amp;lt;&amp;lt; line;
output.append(oss.str());

output.append(TEXT(&quot;] - &quot;));

va_list argptr;
int len;
va_start(argptr, message);
len = _vsctprintf(message, argptr) + 1;
TCHAR* userOutput = new TCHAR[len];
_vstprintf(userOutput, message, argptr);
output.append(userOutput);
delete userOutput;

output.append(TEXT(&quot;\n&quot;));

OutputDebugString(output.c_str());

}

}</pre>
<div>The first thing to notice is that although the Header file has static void as the declaration, the cpp file does not. Confused me for quite some time as I was getting errors until I dropped the static in the cpp file. I can only guess that the declaration says it&#8217;s static and the implementation is just a method on the Class DebugUtil and doesn&#8217;t need another static keyword.</div>
<p>&nbsp;</p>
<div>Inside I do some String formatting on the file since I just want the name and not the whole path. Then I construct the output string into a temp tstring. For the line number I have to use the stringstream in order to convert from int to String. finally there are the arguments. Since it&#8217;s a variable number of arguments and I don&#8217;t know how many there are or what types there are, (And there is very little support for Run Time Type Checking) we use some interesting functions.</div>
<p>&nbsp;</p>
<div>First is va_list which declared that we need a pointer to a list of arguments. We use va_start to point to the last known argument that came in from a function which in our case is message. Then the function _vsctprintf looks at the message and the variables passed in and returns the length of how long a string would need to be to hold all the information we passed in plus the expanded variables.</div>
<p>&nbsp;</p>
<div>Next we create a new TCHAR array of that same length and use the _vstprintf function to essentially do a printf into that TCHAR array. It handles all the variable substitution so we don&#8217;t have to.</div>
<p>&nbsp;</p>
<div>We can then append it to our output string and delete that temporary TCHAR array. This is very important so we don&#8217;t have memory leaks.</div>
<p>&nbsp;</p>
<div>Finally we can send the whole thing to OutputDebugString and get a nicely formatted message in return.</div>
<p>&nbsp;</p>
<div>So when we call:</div>
<p>&nbsp;</p>
<div>
<pre class="brush: cpp; title: ; notranslate">dtrace(&quot;This is a Debug Trace with string %s and int %d and character %c!&quot;, TEXT(&quot;Test&quot;), 48, 'y');</pre>
</div>
<p>&nbsp;</p>
<div>We get:</div>
<p>&nbsp;</p>
<div><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/09/Image_005.png"><img class="aligncenter size-full wp-image-829" title="TraceExamples" src="http://www.breaktrycatch.com/wp-content/uploads/2011/09/Image_005.png" alt="" width="732" height="167" /></a></div>
<p>&nbsp;</p>
<div>This gives me a nice way to easily see that I wanted to debug some values in main.cpp in the WinMain function at line 29.</div>
<p>&nbsp;</p>
<div>Now we&#8217;re ready to actual start making something appear on the screen!</div>
<p>&nbsp;</p>
<div>But that&#8217;s for next time.</div>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/into-the-abyss-getting-started-with-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Error Embedding Fonts Across ApplicationDomains</title>
		<link>http://www.breaktrycatch.com/error-embedding-fonts-across-applicationdomains/</link>
		<comments>http://www.breaktrycatch.com/error-embedding-fonts-across-applicationdomains/#comments</comments>
		<pubDate>Sun, 15 May 2011 17:21:28 +0000</pubDate>
		<dc:creator>Mike Baker</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[ApplicationDomain]]></category>
		<category><![CDATA[as3]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=704</guid>
		<description><![CDATA[I ran into a frustrating problem the other day while working on some client work. While attempting to register a font with Flash at runtime I was getting the following error: Error #1508: The value specified for argument font is invalid. Let me describe the situation. With the sites I&#8217;ve been working on recently we...]]></description>
			<content:encoded><![CDATA[<p>I ran into a frustrating problem the other day while working on some client work. While attempting to register a font with Flash at runtime I was getting the following error:</p>
<pre>
Error #1508: The value specified for argument font is invalid.
</pre>
<p>Let me describe the situation. With the sites I&#8217;ve been working on recently we deploy the sites to 40+ different languages. Since embedding the entire UTF-8 character set results in users downloading multiple megs per font we use dynamic font embedding to embed specific ranges. One added advantage is that we can substitute fonts at run time in situations where the font we are using doesn&#8217;t support a specific character set. Our designers enjoy that they can use their fancy fonts and aren&#8217;t restricted to the handful of fonts which support the Georgian character set. In addition to dynamically embedding the fonts I was loading content into separate Application Domains with each of those applications attempting to register fonts.</p>
<p>Normally a font would be registered by:</p>
<pre lang="actionscript">var fontClass:Class = getDefinitionByName(FONT_LINKAGE) as Class;
Font.registerFont(fontClass);</pre>
<p>The error was throwing when the loaded content went to register fonts in its own Application Domain. I&#8217;ve been using runtime font embedding for some time now so the cause of the error above wasn&#8217;t immediately obvious. After a great deal of tweak and testing I&#8217;ve come to the conclusion that somewhere behind the scenes, Flash doesn&#8217;t like having fonts registered across multiple application domains when running locally. Oddly enough when deployed online everything works as expected.</p>
<p>My workaround, albeit a bit gross, is to pass the host application domain into the loaded content and use the host application domain&#8217;s Font class to register the font. The code to do this looks something like:</p>
<pre lang="actionscript">var fontClass:Class = getDefinitionByName(FONT_LINKAGE) as Class;
hostApplicatonDomain.getDefinition('flash.text.Font').registerFont(fontClass);</pre>
<p>Where hostApplicationDomain is the main applications Application Domain which I&#8217;ve passed in before hand.</p>
<p>I assume you could pass font instances you want to register back to the host application in an event instead of the approach I used. I opted to pass the host ApplicationDomain into the loaded content since I&#8217;m not sure what else might break internally in Flash as we continue to integrate applications into the framework. If this is the only problem I may change this in the future so I don&#8217;t have to make sure developers are dropping any reference to the passed in ApplicationDomain.</p>
<p>Check out the example application I threw together which demonstrates this bug in Flash. Keep in mind this bug only comes up when compiling locally so you&#8217;ll only see the error if you download the swf and run it on your machine. I&#8217;ve provided a link to the source code below as well. I&#8217;d love to hear feedback on the workaround.</p>
<p><a href="http://www.breaktrycatch.com/wp-content/uploads/2011/04/main1.swf"></a><object style="width: 550px; height: 400px;" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://www.breaktrycatch.com/wp-content/uploads/2011/04/loadedFontRegister_main.swf" /><embed style="width: 550px; height: 400px;" type="application/x-shockwave-flash" width="550" height="400" src="http://www.breaktrycatch.com/wp-content/uploads/2011/04/loadedFontRegister_main.swf"></embed></object></p>
<p><strong>Source: </strong></p>
<pre>https://breaktrycatchrepo.googlecode.com/svn/trunk/developers/mikebaker/flash/loadedFontRegister/trunk</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/error-embedding-fonts-across-applicationdomains/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Function Memoization in Actionscript</title>
		<link>http://www.breaktrycatch.com/function-memoization-in-actionscript/</link>
		<comments>http://www.breaktrycatch.com/function-memoization-in-actionscript/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 16:40:20 +0000</pubDate>
		<dc:creator>Paul</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[memoization]]></category>

		<guid isPermaLink="false">http://www.breaktrycatch.com/?p=700</guid>
		<description><![CDATA[Lets say you&#8217;ve got a grid based game and you&#8217;re using a path finding algorithm to get from cell A to B. You&#8217;re making path finding calculations several times per frame, and its starting to become a burden on your processor. You know your path finding algorithm is reasonably optimized and you won&#8217;t get huge...]]></description>
			<content:encoded><![CDATA[<p>Lets say you&#8217;ve got a grid based game and you&#8217;re using a path finding algorithm to get from cell A to B. You&#8217;re making path finding calculations several times per frame, and its starting to become a burden on your processor. You know your path finding algorithm is reasonably optimized and you won&#8217;t get huge performance boosts from tinkering with its internals, so what can you do to speed up your game? Well, if the conditions are right, we can use memoization and get a dramatic performance boost that should save the day.</p>
<h2>What is memoization?</h2>
<p>As always, Wikipedia offers a great overview:</p>
<blockquote><p>In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.</p></blockquote>
<p>Basically, you have a function that takes inputs and produces an output. If those inputs have been used before, we can look up the cached result instead of re-computing the costly function.</p>
<h2>When should I use it?</h2>
<p>Whenever you have a function that is expensive to run you should consider using memoization. However, you can&#8217;t memoize every function. First, a memoizable function must be pure. This means that it shouldn&#8217;t cause <i>side-effects</i>, which happen when a function changes data outside of its scope. For instance, a function is un-memoizable if it changes class level variables or dispatches an event. Here are some examples of what I&#8217;m talking about:</p>
<p><strong>Memoizable:</strong></p>
<pre lang="actionscript">
function(a:int, b:int):int {
	return a + b;
}
</pre>
<p>The function above will do the exact same thing every time we call it with the same inputs.</p>
<p><strong>Un-Memoizable:</strong></p>
<pre lang="actionscript">
var counter : int = 0;
function(a:int, b:int):int {
	counter++;
	return a+b;
}
</pre>
<p>This function will do something just a little bit different each time we call it with the same inputs, making it un-memoizable.</p>
<h2>An AS3 Implementation</h2>
<p>Now that you&#8217;re familiar with the basics, lets go about implementing a somewhat generic implementation in as3. </p>
<pre lang="actionscript">
/**
 * Takes a function defined with only primitive arguments and returns
 * a new memoized version that avoids repeating the calculation of
 * results for previously-processed input
 */
function memoize(fn:Function):Function {
	// lookup dictionary for our cached results.
	var cache : Object = {};

	// creates the memoized function that is returned. It will check for
	// cached results and if one doesn't exist it will call the original function.
	return function(...args):* {
		var memoized : Function = function(...args):* {
			// generates a quick and dirty hash
			// from our arguments that we can use to look up results
			// Because of this hash, arguments of memoized functions
			// can only be primitives!
			var key : String = "";
			for(var i : int = 0; i < args.length; i++) {
				if(typeof args[i] == "object" ) {
					throw new ArgumentError("This version of memoize() " +
						"only works on functions with primitive arguments.");
				}
				key += args[i].toString();
			}

			// we've been down this road before. Quick, return our cached result!
			if(cache[key]) {
				return cache[key];
			} else {
				// Well, these inputs are new. Compute the result for the first time
				// and store it in our lookup. Then we pass back the result.
				var result : * = fn.apply(null, args);
				cache[key] = result;
				return result;
			}
		}

		return memoized.apply(null, args);
	};
}
</pre>
<p>While this may look complicated (doubly nested anonymous functions always raise a few eyebrows) not a whole lot is going on here. First, we create a cache object we can store our computed results on. Then, we build our memoized version of the function that was passed in. </p>
<p>In order to determine if the function has been called once with the same inputs we build a hash of our arguments by just toStringing them together. This is the key mechanic of memoization, and it is what lets us do fast lookups on pre-computed values. For instance, if we pass in (1,2,3) as arguments the generated hash will be "123" and the next time (1,2,3) is used the same hash is built and we can fetch the result from our cache instead of computing it.</p>
<p>It is important to note that the method above only works for pure functions that have primitive arguments. This is because the hash function uses toString() on the arguments which always returns the same thing for types that extend Object even if they are two different objects of the same type. For instance, if you were to pass in a MovieClip, toString() would yeild "[object MovieClip]", and passing in a second, different MovieClip you'd get the same thing on toString() producing the same key for two different inputs. </p>
<p>You can get around this limitation by overriding toString on your custom objects, or by changing the hash function to serialize arguments that are object to strings. While this is a bit outside the scope of this article I'll be addressing it in an upcoming one.</p>
<p>Anyway, lets see our memoization method in action using the highly contrived but standard example of the Fibonacci sequence. First, we define our fibonacci function that has no side effects: </p>
<pre lang="actionscript">
function fib(x:Number):Number {
	return (x < 2) ? (1) : (fib(x-1) + fib(x-2))
}
</pre>
<p>Now we can memoize it and test its execution time. Our test calls memoizedFib 5000 times with a random number up to 20:</p>
<pre lang="actionscript">
var memoizedFib : Function = memoize(fib);

var startTime : int = getTimer();
for(var i:int = 0; i < 5000; i++)
{
	memoizedFib( Math.round( Math.random() * 20 ) );
}
trace("Memoized Fibonacci Sequence: " + (getTimer() - startTime));
</pre>
<p>And here are the results:<br />
Memoized Fibonacci Sequence: <strong>39ms</strong><br />
Unmemoized Fibonacci Sequence: <strong>1,542ms</strong></p>
<p>Ok, so this example may have been a bit contrived but you can see that for functions with finite input sets that are expensive to run, memoization can dramatically improve performance. Don't feel limited to crunching numbers either, I often implement a variation of memoization on service calls that fetch data from the server, saving you the time of a round trip over the net!</p>
<p>The above solution isn't a one-size-fits all answer, but its a good place to start. It's important to evaluate how a function will be used and how best to cache its results in order to get the best performance improvements while still striking a balance between execution time and memory consumption.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.breaktrycatch.com/function-memoization-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
