<?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>Roy Triesscheijn’s Weblog &#187; C#</title>
	<atom:link href="http://roy-t.nl/index.php/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://roy-t.nl</link>
	<description>My programming world</description>
	<lastBuildDate>Wed, 07 Dec 2011 23:19:38 +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>Another faster version of A* (2D+3D) in C#</title>
		<link>http://roy-t.nl/index.php/2011/09/24/another-faster-version-of-a-2d3d-in-c/</link>
		<comments>http://roy-t.nl/index.php/2011/09/24/another-faster-version-of-a-2d3d-in-c/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 20:08:51 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[General Gamedesign]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[A*]]></category>
		<category><![CDATA[A* 3D]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CoWorkerAwesomeNess]]></category>
		<category><![CDATA[Faster]]></category>
		<category><![CDATA[Heap]]></category>
		<category><![CDATA[MinHeap]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=514</guid>
		<description><![CDATA[As you might know I once wrote an A* sample for C# more than 2 years ago. The first version worked but was very slow because of a bug. The second version was faster, and a third version (made by one of the readers of this blog) was even faster. Btw did you know that [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/09/24/another-faster-version-of-a-2d3d-in-c/' addthis:title='Another faster version of A* (2D+3D) in C#' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>As you might know I once wrote an A* sample for C# more than 2 years ago. The first version worked but was very slow because of a bug. The second version was faster, and a third version (made by one of the readers of this blog) was even faster.</p>
<p>Btw did you know that the excellent game <a href="http://www.garethpw.co.uk/2009/06/dysnomia.html">Dysomnia</a> shipped with (a modified) version of my C#/A* code? Ok it&#8217;s just a few lines to get people started but it&#8217;s really cool to see how people use this little start for their cool projects!</p>
<p>Anyway, back on topic: during my internship at Nixxes an interested co-worker (thanks Marcel!) tweaked the heuristic, removed some unnecessary checks, and added a faster way to check if a tile was processed yet.</p>
<p>There is not much else to say, it&#8217;s still A*, it supports 2D and 3D, it uses a MinHeap and is faster than ever! (Note: this is a pure C# solution, so it doesn&#8217;t require XNA, but it will work nicely with XNA even on WP7 and the Xbox360).</p>
<p><a title="Version 2011-09-24" href="http://roy-t.nl/files/AStar3D-2011-09-24.zip">Download the latest version here</a></p>
<p>Older relevant blog posts about A*  (from older to newer)<br />
<a href="http://roy-t.nl/index.php/2009/02/24/implementing-a-path-finding-in-c-and-xna-source-code-can-we-cut-the-corner/">http://roy-t.nl/index.php/2009/02/24/implementing-a-path-finding-in-c-and-xna-source-code-can-we-cut-the-corner/</a><br />
<a href="http://roy-t.nl/index.php/2009/07/07/new-version-a-pathfinding-in-3d/">http://roy-t.nl/index.php/2009/07/07/new-version-a-pathfinding-in-3d/</a><br />
<a href="http://roy-t.nl/index.php/2010/06/27/more-a-improvements/">http://roy-t.nl/index.php/2010/06/27/more-a-improvements/</a></p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/09/24/another-faster-version-of-a-2d3d-in-c/' addthis:title='Another faster version of A* (2D+3D) in C#' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2011/09/24/another-faster-version-of-a-2d3d-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Nixxes internship post-mortem</title>
		<link>http://roy-t.nl/index.php/2011/09/05/nixxes-internship-post-mortem/</link>
		<comments>http://roy-t.nl/index.php/2011/09/05/nixxes-internship-post-mortem/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 07:56:42 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[General Gamedesign]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++/CLI]]></category>
		<category><![CDATA[Deus Ex]]></category>
		<category><![CDATA[Human Revolution]]></category>
		<category><![CDATA[internship]]></category>
		<category><![CDATA[Nixxes]]></category>
		<category><![CDATA[Tomb Raider]]></category>
		<category><![CDATA[Ubisoft Montreal]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=510</guid>
		<description><![CDATA[I tried to do a weekly update during my internship at Nixxes, but I never got around to finish a single post. However since Post-Mortems are hip these days I decided to write a simple post-mortem about my internship. Let&#8217;s start with the beginning. In the first week my mentor at Nixxes was still on [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/09/05/nixxes-internship-post-mortem/' addthis:title='Nixxes internship post-mortem' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>I tried to do a weekly update during my internship at Nixxes, but I never got around to finish a single post. However since Post-Mortems are hip these days I decided to write a simple post-mortem about my internship.</p>
<p>Let&#8217;s start with the beginning. In the first week my mentor at Nixxes was still on vacation so a co-worker set me up with a new computer (a shiny i7) and helped me set-up the development environment. I was handed a few drafts from another co-worker who a few years back wrote a proposal for the tool I was to build. So I tried to arm myself with knowledge and put my education to the task by writing things like inception documents and prototype proposals. Although this was a bit formal for the team (they only do a light scrum + two person commits) it helped me get a good overview of what I had to do. I also played a lot with their technology (trying to give good old Lara Croft green hair in a test-level of TR:Legend).</p>
<p>The tool I was to build had a simple enough goal and had to do with their automatic shader generation. I had to make a tool that gave artists insight in how different settings on materials would create different shader configurations. It was not to give technical insight inside the shaders (you wouldn&#8217;t want to bore artists with that) . But to let them reduce the number of actual shaders by simplifying material.</p>
<p>In the next few weeks I started searching for existing tech, testing and prototyping. I needed tools to show large complex graphs with a lot of cross-nodes. So I started searching for layout algorithms (In the end I combined two layout techniques and wrote code myself, but it&#8217;s always good to check if you&#8217;re not reinventing the wheel, and it gave me some great insights).</p>
<p>I also had to familiarize myself with WPF, which I really enjoyed (the learning curve for WPF is much shorter than for WinForms and the performance and &#8216;nice-ity&#8217;  of WPF greatly outclasses WinForms).</p>
<p>After a few prototypes we decided on a work-flow for the program and refined the core questions the program had to solve.  It&#8217;s really helpful to write those down because a goal might be too abstract/far away so these core questions help you refine your way to do the goal and give you some work flow hints. (It&#8217;s also good to have these in your help file).</p>
<p>Because of the limited time there was only one week of feedback from real artists but of course I was surrounded by techies  to help fill this void.</p>
<p>In the end we refined the work flow once more and tied in the program with existing tools. (Up until now I was just parsing raw data). I hooked into a content-service using C++/CLI. This C++/CLI program also hosted my C#/WPF frontend, and to my surprise this worked really well and was easy to do!</p>
<p>In the end I left behind a well document and finished product and because we had a week to spare there was even quite some polish (the last week was used to add in some background workers and  nicer progress bar, I also added cancellation support to the layout algorithm).</p>
<p>During my internship I also experienced the release of Deus Ex: Human Revolution, of which the tech and pc-port was done by Nixxes, so it was really great to see the game get an 8,9 on meta-critic!</p>
<p><img class="aligncenter" title="Deus Ex: Human Revolution" src="http://brutalgamer.com/wp-content/uploads/2011/08/DeusExTitle.jpg" alt="" width="570" height="300" /></p>
<p>The end-talk with my mentor was relaxed and pleasant. I knew I had done pretty well but I was quite surprised when he gave me a final grade of 9 out of 10! Yay!</p>
<p>All in all I had a great time, and I&#8217;ve learned a lot of new techniques (C++/CLI, WPF, Graph Layout Algorithms, Data Binding). I also finally got to experience a real hands-on approach where everything gets prioritized because resources are finite. On the university  it&#8217;s really a rare thing to experience this, so this was really an eye opener. I feel like I learned more valuable skills in these two months than I would have doing 3 more courses (Thanks to a helpful dean I could replace 3 courses with this intern shop)</p>
<p>I would like to thank everyone at Nixxes for a great time!</p>
<p>PS.</p>
<p>One of my co-workers again sped up my A* code after peeking at my blog. I have his code and am trying to add a nice visualizer to it this time before posting it, so expect it up soon.</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/09/05/nixxes-internship-post-mortem/' addthis:title='Nixxes internship post-mortem' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2011/09/05/nixxes-internship-post-mortem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Internship at Nixxes (cooperating with Ubisoft Montreal)</title>
		<link>http://roy-t.nl/index.php/2011/07/03/internship-at-nixxes-cooperating-with-ubisoft-montreal/</link>
		<comments>http://roy-t.nl/index.php/2011/07/03/internship-at-nixxes-cooperating-with-ubisoft-montreal/#comments</comments>
		<pubDate>Sun, 03 Jul 2011 11:57:22 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CLI]]></category>
		<category><![CDATA[intern]]></category>
		<category><![CDATA[internship]]></category>
		<category><![CDATA[Lara Croft]]></category>
		<category><![CDATA[Nixxes]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=506</guid>
		<description><![CDATA[&#160; This summer I&#8217;ll be doing an internship at Nixxes Software in Utrecht, the Netherlands.  They are a group of highly experienced game technology programmers who are independent but work mostly for Ubisoft Montreal. Their latest projects includes work on &#8220;Lara Croft and the guardian of light&#8221;, &#8220;Deus Ex: Human Revolution&#8221;, and &#8220;Kane &#38; Lynch [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/07/03/internship-at-nixxes-cooperating-with-ubisoft-montreal/' addthis:title='Internship at Nixxes (cooperating with Ubisoft Montreal)' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.nixxes.com"><img class="aligncenter size-full wp-image-507" title="Nixxes Logo" src="http://roy-t.nl/wp-content/uploads/2011/07/Nixxes_Logo.png" alt="" width="178" height="170" /></a></p>
<p>&nbsp;</p>
<p>This summer I&#8217;ll be doing an internship at <a title="Nixxes Homepage" href="http://www.nixxes.com/nixxes/" target="_blank">Nixxes</a> Software in Utrecht, the Netherlands.  They are a group of highly experienced game technology programmers who are independent but work mostly for Ubisoft Montreal. Their latest projects includes work on &#8220;Lara Croft and the guardian of light&#8221;, &#8220;Deus Ex: Human Revolution&#8221;, and &#8220;Kane &amp; Lynch 2&#8243;. They mostly develop on the engine used for these games, and tooling. It&#8217;s not yet sure what I&#8217;ll be doing but it will probably be a tool that too measure where performance can be increased, it will probably written in C# with interop-ed with C++/CLI.</p>
<p>I&#8217;m not yet sure if I&#8217;ll be working under an NDA (probably) and how much info I can release on what I&#8217;ve been doing, but I&#8217;d like to write a sort of development diary here. I&#8217;ll probably not be writing tutorials for the coming 2 months because I won&#8217;t have much free time.</p>
<p>Anyway I&#8217;ll be back after 2 months, so stay tuned and enjoy your summer vacation (I hope it will be more of an actual vacation for most people <img src='http://roy-t.nl/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  ).</p>
<div class="wp-caption aligncenter" style="width: 639px"><img title="Lara Croft" src="http://cdn0.spong.com/artwork/l/a/laracrofta331650l/_-Lara-Croft-and-the-Guardian-of-Light-Xbox-360-_.jpg" alt="" width="629" height="800" /><p class="wp-caption-text">Lare Croft and the Guardian of Light</p></div>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/07/03/internship-at-nixxes-cooperating-with-ubisoft-montreal/' addthis:title='Internship at Nixxes (cooperating with Ubisoft Montreal)' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2011/07/03/internship-at-nixxes-cooperating-with-ubisoft-montreal/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Traversal algorithms using yield</title>
		<link>http://roy-t.nl/index.php/2011/02/12/traversal-algorithms-using-yield/</link>
		<comments>http://roy-t.nl/index.php/2011/02/12/traversal-algorithms-using-yield/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 14:04:31 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[traversal]]></category>
		<category><![CDATA[yield]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=452</guid>
		<description><![CDATA[So two days ago I wrote a an article on traversal algorithms using delegates. One of the commenters (I&#8217;m looking at you Mart) mentioned a different approach using the yield keyword, which generates a state machine underneath. I had heard of the yield keyword before, but I&#8217;ve never used it so far. I was thrilled [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/02/12/traversal-algorithms-using-yield/' addthis:title='Traversal algorithms using yield' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>So two days ago I wrote a <a href="http://roy-t.nl/index.php/2011/02/10/traversal-algorithms-using-generics-generic-constraints-where-and-action-delegates/">an article on traversal algorithms</a> using delegates. One of the commenters (I&#8217;m looking at you Mart) mentioned a different approach using the <a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx">yield</a> keyword, which generates a state machine underneath.</p>
<p>I had heard of the yield keyword before, but I&#8217;ve never used it so far. I was thrilled to work out his comment, to find out how it works, et voila ,this blog-post was written.</p>
<p>I first wrote this generic Node class which allowed me to build a tree like structure.</p>
<pre class="brush: csharp; title: ; notranslate">
    public class Node&lt;T&gt;
    {
        public Node(T self, List&lt;Node&lt;T&gt;&gt; children)
        {
            this.self = self;
            this.children = children;
        }
        public T self;
        public List&lt;Node&lt;T&gt;&gt; children;
    }
</pre>
<p>Depth first traversal of this tree is easily done using yield.</p>
<pre class="brush: csharp; title: ; notranslate">
        public static IEnumerable&lt;T&gt; Traverse&lt;T&gt;(Node&lt;T&gt; root)
        {
            Stack&lt;Node&lt;T&gt;&gt; stack = new Stack&lt;Node&lt;T&gt;&gt;();
            stack.Push(root);
            while (stack.Count &gt; 0)
            {
                Node&lt;T&gt; n = stack.Pop();
                yield return n.self;
                foreach (Node&lt;T&gt; child in n.children)
                {
                    stack.Push(child);
                }
            }
        }
</pre>
<p>When compiled, this piece of code generates a thread-safe state machine (very nifty) but thanks to the abstraction that yield gives us we don&#8217;t have to worry about. We can just interact with this method as if the result is an IEnumerable<T> (as indicated/expected), so we can use this method like this:</p>
<pre class="brush: csharp; title: ; notranslate">
                foreach (int i in DepthFirstTraversal.Traverse&lt;int&gt;(rootNode))
                {
                     //DoSomethingWith(i);
                }
</pre>
<p>But what are the performance implications of this hidden state machine? To test this I&#8217;ve adapted the previous post&#8217;s traversal algorithm to be as similar as possible:</p>
<pre class="brush: csharp; title: ; notranslate">
        public static void Traverse&lt;T&gt;(Node&lt;T&gt; root, Action&lt;T&gt; action)
        {
            Stack&lt;Node&lt;T&gt;&gt; stack = new Stack&lt;Node&lt;T&gt;&gt;();
            stack.Push(root);

            while (stack.Count &gt; 0)
            {
                Node&lt;T&gt; n = stack.Pop();
                action(n.self);
                foreach (Node&lt;T&gt; child in n.children)
                {
                    stack.Push(child);
                }
            }
        }
</pre>
<p>Performing a given action for each item in our tree (depth first) is done like this:</p>
<pre class="brush: csharp; title: ; notranslate">
DepthFirstTraversal.Traverse&lt;int&gt;(rootNode, (i) =&gt; DoSomethingWith(i));
</pre>
<p>Using a recursive algorithm I constructed a tree (of ints) with a depth of 10, where each node has 2 child nodes. I then benchmarked how long it took to add each item in the tree to a list like this:</p>
<pre class="brush: csharp; title: ; notranslate">
List&lt;int&gt; results = new List&lt;int&gt;(41);
//Yield approach
                foreach (int i in DepthFirstTraversal.Traverse&lt;int&gt;(rootNode))
                {
                    results.Add(i);
                }
//Action approach
                DepthFirstTraversal.Traverse&lt;int&gt;(rootNode, (i) =&gt; results.Add(i));
</pre>
<p>After 100.000 iterations the result was the following:</p>
<pre class="brush: plain; title: ; notranslate">
Average milliseconds for yield approach:            0.01265
Average milliseconds for delegate/Action&lt;&gt; approach 0.00578
</pre>
<p>So the yield approach is more then two times as slow as the delegate approach to a depth first traversal, which isn&#8217;t surprising since we&#8217;re talking state machine vs method+virtual lookup. Still it was interesting to see how yield works. For more in depth info about yield see <a href="http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx">this article</a> by Jon Skeet.</p>
<p>See the code for this benchmark <a href="http://pastebin.com/wRZCRY8s">here</a></p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/02/12/traversal-algorithms-using-yield/' addthis:title='Traversal algorithms using yield' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2011/02/12/traversal-algorithms-using-yield/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Traversal algorithms using generics, generic constraints (where), and Action delegates</title>
		<link>http://roy-t.nl/index.php/2011/02/10/traversal-algorithms-using-generics-generic-constraints-where-and-action-delegates/</link>
		<comments>http://roy-t.nl/index.php/2011/02/10/traversal-algorithms-using-generics-generic-constraints-where-and-action-delegates/#comments</comments>
		<pubDate>Thu, 10 Feb 2011 17:14:08 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# generics]]></category>
		<category><![CDATA[codesnippet]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=449</guid>
		<description><![CDATA[As many of you I enjoy solving a very complex problem, however sometimes it&#8217;s finding new ways todo simple things that really excites me! This happened again today, I was working on a simple Depth-First-Search traversal algorithm when it suddenly doomed to me that I was duplicating a lot of code because I had to [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/02/10/traversal-algorithms-using-generics-generic-constraints-where-and-action-delegates/' addthis:title='Traversal algorithms using generics, generic constraints (where), and Action<T> delegates' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>As many of you I enjoy solving a very complex problem, however sometimes it&#8217;s finding new ways todo simple things that really excites me! This happened again today, I was working on a simple Depth-First-Search traversal algorithm when it suddenly doomed to me that I was duplicating a lot of code because I had to do DFS multiple times, with the only difference the action to take at each node.</p>
<p>Pondering about this for a few minutes and I thought about using a delegate as a sort of method pointer to tell the DFS algorithm what action to take for each node. I wrote a quick delegate and named it Action, but then I remembered that C# has the built in Action<T> delegate.</p>
<p>With these techniques in mind I quickly wrote the following code:</p>
<pre class="brush: csharp; title: ; notranslate">
public void DFS&lt;T&gt;(T node, Action&lt;T&gt; action) where T : IHasChildren&lt;T&gt;
{
    Stack&lt;T&gt; stack = new Stack&lt;T&gt;();
    action(node);
    stack.PushMany&lt;T&gt;(node.Children);
    while (stack.Count &gt; 0)
    {
        T n = stack.Pop();
        action(n);
        stack.PushMany&lt;T&gt;(n.Children);
    }
}

public interface IHasChildren&lt;T&gt;
{
    List&lt;T&gt; Children;
}
</pre>
<p>This way you can use DFS on any type of node as long as it implements IHasChildren, and you can use any Action<T> too, saves a lot of duplicate code !</p>
<p>Edit:</p>
<p>Stack.PushMany is my own extension method that allows a list to be put on a stack (just a simple for each).</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/02/10/traversal-algorithms-using-generics-generic-constraints-where-and-action-delegates/' addthis:title='Traversal algorithms using generics, generic constraints (where), and Action<T> delegates' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2011/02/10/traversal-algorithms-using-generics-generic-constraints-where-and-action-delegates/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Wrapping effect files into proper classes</title>
		<link>http://roy-t.nl/index.php/2011/02/06/wrappingeffect-files-into-proper-classes/</link>
		<comments>http://roy-t.nl/index.php/2011/02/06/wrappingeffect-files-into-proper-classes/#comments</comments>
		<pubDate>Sun, 06 Feb 2011 14:52:21 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Effect]]></category>
		<category><![CDATA[Properties]]></category>
		<category><![CDATA[Shader]]></category>
		<category><![CDATA[Technique]]></category>
		<category><![CDATA[Wrapper]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=444</guid>
		<description><![CDATA[In XNA shaders are processed into Effect objects by the content pipeline. These effect objects are not really &#8216;first class citizens&#8217; because, contrarily to most C# classes, these classes have a lot of loosely-typed features. To remedy this I&#8217;m going to show you how I wrap these effect objects into their own wrapper, when we [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/02/06/wrappingeffect-files-into-proper-classes/' addthis:title='Wrapping effect files into proper classes' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>In XNA shaders are processed into Effect objects by the content pipeline. These effect objects are not really &#8216;first class citizens&#8217; because, contrarily to most C# classes, these classes have a lot of loosely-typed features. To remedy this I&#8217;m going to show you how I wrap these effect objects into their own wrapper, when we see the differences I&#8217;ll explain the pros and cons of my approach.</p>
<p>For this tutorial we&#8217;re going to use a part of a shader I use for deferred rendering:</p>
<p>float4x4 World : WORLD;<br />
float specularIntensity = 0.8f;<br />
texture Texture : TEXTURE;</p>
<p>As said, the content processor wraps this nicely into an Effect object. Now if we&#8217;d like to draw something with this effect it would probably be done something like this:</p>
<pre class="brush: csharp; title: ; notranslate">
Effect effect = Content.Load&lt;Effect&gt;(&quot;myEffect&quot;);
//Draw:
effect.Parameters.GetParameterBySemantic(&quot;World&quot;) = Matrix.Identity;
effect.Parameters[&quot;specularIntensity&quot;] = 0.5f;
effect.Parameters[&quot;texture&quot;] = 56;
effect.Techniques[&quot;technique1&quot;].Passes[0].Apply();
</pre>
<p>Given the rest of the code is correct this will compile nicely, however during runtime we will receive an exception. Because we set the effect parameter &#8220;texture&#8221; to 56, which is not a proper texture value. Due to the loose typing this error could not be detected by the compiler, so it could sneak up on us. Also it&#8217;s a bit hard to remember all the parameters an effect has, because we cant see that without opening the .fx file, I&#8217;d argue that the effect class is not a proper class as we know other classes to be in C#. And it can&#8217;t be, because it has to be compatible with so many different shaders. Therefor I push forward my approach.</p>
<p>For the above shader I would write the following class:</p>
<pre class="brush: csharp; title: ; notranslate">
    public class MyEffect
    {
        public MyEffect(Effect effect)
        {
            worldMatrix = effect.Parameters.GetParameterBySemantic(&quot;World&quot;);
            texture = effect.Parameters.GetParameterBySemantic(&quot;Texture&quot;);
            specularIntensity = effect.Parameters[&quot;specularIntensity&quot;];

            technique1 = effect.Techniques[&quot;Technique1&quot;];
        }

        public void Apply()
        {
            technique1.passes[0].Apply();
        }

        #region FieldsAndProperties
        private EffectTechnique technique1;        

        private EffectParameter worldMatrix;
        public Matrix WorldMatrix { set { worldMatrix.SetValue(value); } }

        private EffectParameter texture;
        public Texture2D Texture { set { texture.SetValue(value); } }

        private EffectParameter specularIntensity;
        public Texture2D SpecularIntensity { set { specularIntensity.SetValue(value); } }
        #endregion

    }
</pre>
<p>Using this code drawing an object would look like this:</p>
<pre class="brush: csharp; title: ; notranslate">
MyEffect effect = new MyEffect(Content.Load&lt;Effect&gt;(&quot;myEffect&quot;));
//Draw:
effect.World = Matrix.Identity;
effect.SpecularIntensity = 0.5f;
effect.Texture = 56;
effect.Apply();
</pre>
<p>In my opinion this is a lot more readable and we now get an error while compiling that 56 does not match the type &#8220;Texture&#8221; also the new wrapper is more of an interface for the effect file. If we change one of the variable names in the effect file, we now only have to make a change at one place in our code base, even if we change the type of a parameter using some logic in the property we might still not have to change all the code. And if we really have to we will get a lot of helpful compiler warnings. We can now also find all references to a specific parameter. However the big downside is that Effect works for all effects (well you still have to remember the parameters and techniques which differ per shader), and this approach requires you to write a class per shader.</p>
<p>Anyway this is my approach, I&#8217;d love to know how other people handle this problem, and if you have any comments.</p>
<p>Update 7-2-2011:<br />
After discussing alternative approaches (thanks Flashed!) I would like to give everybody a tip to try an extend this system. How about have a content pipeline project that automatically matches an effect file with an effect wrapper? You can use metadata in the .fx files todo this!</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/02/06/wrappingeffect-files-into-proper-classes/' addthis:title='Wrapping effect files into proper classes' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2011/02/06/wrappingeffect-files-into-proper-classes/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>An example of the ref keyword in C# (for structs and classes)</title>
		<link>http://roy-t.nl/index.php/2011/01/22/an-example-of-the-ref-keyword-in-c-for-structs-and-classes/</link>
		<comments>http://roy-t.nl/index.php/2011/01/22/an-example-of-the-ref-keyword-in-c-for-structs-and-classes/#comments</comments>
		<pubDate>Sat, 22 Jan 2011 11:10:16 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[keyword]]></category>
		<category><![CDATA[pointers]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ref]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=441</guid>
		<description><![CDATA[There is a lot of confusion about the ref keyword in C#. Many claim that it shouldn&#8217;t be used for classes, only for the very different structs. But the reference keyword can actually be very handy for both classes and structs! The reference keyword signals .NET to pass the address of the reference to the [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/01/22/an-example-of-the-ref-keyword-in-c-for-structs-and-classes/' addthis:title='An example of the ref keyword in C# (for structs and classes)' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>There is a lot of confusion about the <strong>ref</strong> keyword in C#. Many claim that it shouldn&#8217;t be used for classes, only for the very different <a href="http://www.jaggersoft.com/pubs/StructsVsClasses.htm">structs</a>. But the reference keyword can actually be very handy for both classes and structs!</p>
<p>The reference keyword signals .NET to pass the address of the reference to the correct memory instead of the reference itself. Now that is a bit vague, so let&#8217;s take a look at the following diagram:<br />
<a href="http://roy-t.nl/wp-content/uploads/2011/01/Ref.png"><img class="aligncenter size-full wp-image-442" title="References explained" src="http://roy-t.nl/wp-content/uploads/2011/01/Ref.png" alt="" width="293" height="282" /></a></p>
<p>I&#8217;ll first explain the scenario without using the <strong>ref</strong> keyword:</p>
<pre class="brush: csharp; title: ; notranslate">
Object obj = new Object();
Change(obj);

public void Change(Object o)
{
    o = new Object();
}
</pre>
<p>First we create a new object. In our diagram this first creates the data &#8220;Reference1&#8243; in a fresh piece of memory. This reference is like an address book and points toward a location in memory (for C people, points as in pointer). In the fresh piece of memory where &#8220;Reference1&#8243; points we place the data for our new object. Now we pass our object to the method change. On a low level this means that a fresh piece of memory is found, the data in &#8220;Reference1&#8243; is  copied there (For the well computer versed, when a method is called, all the arguments for that method are copied and put on the stack). Let&#8217;s call this new pointer &#8220;Reference2&#8243;. This &#8220;Reference2&#8243; at first still points at &#8220;MemoryLocation1&#8243;. However in the Change method we now create a new Object using the <strong>new</strong> keyword. This creates a new object in a fresh location in our memory. Let&#8217;s call this &#8220;MemoryLocation2&#8243;. To reflect these changes the address where &#8220;Reference2&#8243; is pointing at is also changed, this way we keep referencing the correct object. As you can see the address in &#8220;Reference1&#8243; is not changed, so &#8220;Reference1&#8243; still points at &#8220;MemoryLocation1&#8243; and &#8220;Reference2&#8243; points at &#8220;MemoryLocation2&#8243;.</p>
<p>Now let&#8217;s consider what happens when we do use the reference keyword.</p>
<pre class="brush: csharp; title: ; notranslate">
Object obj = new Object();
Change(ref obj);

public void Change(ref Object o)
{
    o = new Object();
}
</pre>
<p>At first we again have &#8220;Reference1&#8243; pointing at &#8220;MemoryLocation1&#8243;. But when we pass our new object to the Change method something different happens. Instead of copying &#8220;Reference1&#8243; the memory location of &#8220;Reference1&#8243; is copied and put on the stack, in our diagram this is &#8220;ReferenceAddress&#8221;. When new object is created it&#8217;s again put in a fresh memory location (say &#8220;MemoryLocation3&#8243;). However since we are working with the address of &#8220;Reference1&#8243;, instead of a new reference, &#8220;Reference1&#8243; is updated to point to &#8220;MemoryLocation3&#8243;.  So the instance <strong>o</strong> inside the method change and the instance <strong>obj</strong> are now the same.</p>
<p>If this is still a bit fuzzy to you, here is a piece of code that should make it totally clear <img src='http://roy-t.nl/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . Note that structs and classes act in the same fashion this way:</p>
<pre class="brush: csharp; title: ; notranslate">

public class MyClass //public struct MyStruct looks exactly the same, but is a struct
{
    public int MyData;
    public MyClass(int data)
    {
        this.MyData = data;
    }
}
class Program
    {
        static void Main(string[] args)
        {
            MyStruct struct1 = new MyStruct(1);
            Modify(struct1);

            MyStruct struct2 = new MyStruct(2);
            ModifyRef(ref struct2);
            Console.Out.WriteLine(String.Format(&quot;struct1: {0}, struct2: {1}&quot;, struct1.MyData, struct2.MyData));
//outputs &quot;struct1: 1, struct2: 21&quot;

            MyClass class1 = new MyClass(1);
            Modify(class1);

            MyClass class2 = new MyClass(2);
            ModifyRef(ref class2);

            Console.Out.WriteLine(String.Format(&quot;class1: {0}, class2: {1}&quot;, class1.MyData, class2.MyData));
//outputs &quot;class1: 1, class2: 21&quot;
            Console.ReadLine();
        }

        static void Modify(MyStruct s)
        {
            s = new MyStruct(11);
        }
        static void Modify(MyClass c)
        {
            c = new MyClass(11);
        }
        static void ModifyRef(ref MyStruct s)
        {
            s = new MyStruct(21);
        }
        static void ModifyRef(ref MyClass c)
        {
            c = new MyClass(21);
        }
    }
</pre>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2011/01/22/an-example-of-the-ref-keyword-in-c-for-structs-and-classes/' addthis:title='An example of the ref keyword in C# (for structs and classes)' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2011/01/22/an-example-of-the-ref-keyword-in-c-for-structs-and-classes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Code snippet: EventLog wrapper</title>
		<link>http://roy-t.nl/index.php/2010/11/21/code-snippet-eventlog-wrapper/</link>
		<comments>http://roy-t.nl/index.php/2010/11/21/code-snippet-eventlog-wrapper/#comments</comments>
		<pubDate>Sun, 21 Nov 2010 11:19:58 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[code snippet]]></category>
		<category><![CDATA[eventlog]]></category>
		<category><![CDATA[events]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=414</guid>
		<description><![CDATA[This is a small code snippet that allows your application to write log message to the event log. It will also allow you to capture events of these log messages so that your GUI can show pop-ups or other information messages. (Added a small update a few hours after this was posted for Vista/W7 when [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2010/11/21/code-snippet-eventlog-wrapper/' addthis:title='Code snippet: EventLog wrapper' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>This is a small code snippet that allows your application to write log message to the event log. It will also allow you to capture events of these log messages so that your GUI can show pop-ups or other information messages.</p>
<p>(Added a small update a few hours after this was posted for Vista/W7 when not running the application as admin)</p>
<p>Anyway here&#8217;s the code:</p>
<pre class="brush: csharp; title: ; notranslate">
     public class Logger
    {
        private static Logger instance;
        public static Logger Instance
        {
            get { if (instance == null) { instance = new Logger(); } return instance; }
        }

        private Logger(){}

        private string eventSource = &quot;MyApplicationName&quot;;   //TODO: change this into the name of your application

        public delegate void logMessage(string message);
        public event logMessage Logged = delegate(string message) { };
        public event logMessage LoggedCritical = delegate(string message) { };
        public event logMessage LoggedWarning = delegate(string message) { };
        public event logMessage LoggedInfo = delegate(string message) { };

        public void Log(string message, EventLogEntryType severity)
        {
            try
            {
                if (!EventLog.SourceExists(eventSource))
                {
                    EventLog.CreateEventSource(eventSource, &quot;Application&quot;);
                }
                EventLog.WriteEntry(eventSource, message, severity);
            }
            catch (SecurityException noRightsException)
            {
                //User has no rights to write logs.
            }
            Logged(message);

            switch (severity)
            {
                case EventLogEntryType.Error:
                    LoggedCritical(message);
                    break;
                case EventLogEntryType.Information:
                    LoggedInfo(message);
                    break;
                case EventLogEntryType.Warning:
                    LoggedWarning(message);
                    break;
            }
        }
    }
</pre>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2010/11/21/code-snippet-eventlog-wrapper/' addthis:title='Code snippet: EventLog wrapper' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2010/11/21/code-snippet-eventlog-wrapper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom XML Serialization in C#</title>
		<link>http://roy-t.nl/index.php/2010/10/24/custom-xml-serialization-in-c/</link>
		<comments>http://roy-t.nl/index.php/2010/10/24/custom-xml-serialization-in-c/#comments</comments>
		<pubDate>Sun, 24 Oct 2010 09:00:21 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[General Gamedesign]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[by hand]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Custom]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=399</guid>
		<description><![CDATA[As people who follow me on twitter might know, I was working on a reflection tutorial for C#/XNA. However I got a bit carried away with the XML Serialization. So here&#8217;s first an XML Serialization tutorial. In previous tutorials/code-snippets I showed how to use the intermediate serializer. But for the tutorial I wanted to serialize [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2010/10/24/custom-xml-serialization-in-c/' addthis:title='Custom XML Serialization in C#' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>As people who follow me on twitter might know, I was working on a reflection tutorial for C#/XNA. However I got a bit carried away with the XML Serialization.</p>
<p>So here&#8217;s first an XML Serialization tutorial.</p>
<p>In previous tutorials/code-snippets I showed how to use the <a href="http://roy-t.nl/index.php/2010/09/28/xna-proxyclasses-to-serialize-assets-using-the-intermediateserializer/" target="_self"> intermediate serializer</a>. But for the tutorial I wanted to serialize all the XML by hand so that it would be crystal clear for anyone following the tutorial what was going on.</p>
<p>Quickly I coded up the following interface:</p>
<pre class="brush: csharp; title: ; notranslate">
    public interface ISerializable
    {
        /// &lt;summary&gt;
        /// Allows the object to serialize itself into the current xml node
        /// &lt;/summary&gt;
        void Serialize(XmlDocument document, XmlNode parent);

        /// &lt;summary&gt;
        /// Allows the object to reconstruct itself from the current xml node
        /// &lt;/summary&gt;
        void Deserialize(XmlDocument document, XmlNode self);
    }
</pre>
<p>This code should be pretty self explanatory. Remember that an XmlDocument object is also an XmlNode. So for the root object you can pass your newly constructed XmlDocument as parent node.</p>
<p>I quickly created 3 classes: </p>
<p>-Block, a simple class with texture, position scale and tinting with the ability to draw itself.<br />
-RotatbleBlock, child class of block, with the ability to rotate itself.<br />
-Scene, a class containing a Block[] that draws all the blocks.</p>
<p>Both Scene and Block, and thus RotatableBlock, implement ISerializable.</p>
<p>Serializing is now easy (only relevant bits here):<br />
In our static Serializer class we do this:</p>
<pre class="brush: csharp; title: ; notranslate">
        public static void Save(ISerializable root, string fileName)
        {
            //Set the culture of the saving thread to InvariantCulture so that
            //we do not get problems with different decimal seperators and the likes
            //when trying to save and load in different countries
            CultureInfo userCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            XmlDocument document = new XmlDocument();
            root.Serialize(document, document);
            document.Save(fileName);

            //Restore the thread culture
            Thread.CurrentThread.CurrentCulture = userCulture;
        }
</pre>
<p>Take extra care to set the culture to invariant temporarily so that we don&#8217;t get different results depending on our computer&#8217;s localization settings.</p>
<p>Scene is serialized this way:</p>
<pre class="brush: csharp; title: ; notranslate">
        public virtual void Serialize(XmlDocument document, XmlNode parent)
        {
            XmlElement me = document.CreateElement(&quot;ReflectionTutorialEngine.Scene&quot;);
            parent.AppendChild(me);

            XmlElement blocksElement = document.CreateElement(&quot;Blocks&quot;);
            me.AppendChild(blocksElement);

            foreach (Block b in blocks)
            {
                b.Serialize(document, blocksElement);
            }
        }
</pre>
<p>As you can see the object serialized just creates a new child node in the parent node. It&#8217;s name is it&#8217;s exact full namespace name (this will be important later).</p>
<p>The serialization code for Block is pretty straightforward too.</p>
<pre class="brush: csharp; title: ; notranslate">
        public virtual void Serialize(XmlDocument document, XmlNode parent)
        {
            XmlElement me = document.CreateElement(&quot;ReflectionTutorialEngine.Block&quot;);
            parent.AppendChild(me);

            XmlElement textureNode = document.CreateElement(&quot;Texture&quot;);
            textureNode.InnerText = texture.Tag.ToString(); //the full asset name is saved in the tag elsewhere

            XmlElement positionNode = document.CreateElement(&quot;Position&quot;);
            positionNode.InnerText = position.X + &quot;;&quot; + position.Y;

            XmlElement scaleNode = document.CreateElement(&quot;Scale&quot;);
            scaleNode.InnerText = scale.ToString();

            XmlElement tintingNode = document.CreateElement(&quot;Tinting&quot;);
            tintingNode.InnerText = tinting.R.ToString() + ';' + tinting.G.ToString() + ';' + tinting.B.ToString() + ';' + tinting.A.ToString();            

            me.AppendChild(textureNode);
            me.AppendChild(positionNode);
            me.AppendChild(scaleNode);
            me.AppendChild(tintingNode);
        }
</pre>
<p>Where it get&#8217;s interesting is in the serialization code of RotatableBlock:</p>
<pre class="brush: csharp; title: ; notranslate">
        public override void Serialize(XmlDocument document, XmlNode parent)
        {
            XmlElement me = document.CreateElement(&quot;ReflectionTutorialEngine.RotatableBlock&quot;);
            parent.AppendChild(me);

            XmlElement rotationElement = document.CreateElement(&quot;Rotation&quot;);
            rotationElement.InnerText = rotation.ToString();

            me.AppendChild(rotationElement);
            base.Serialize(document, me);
        }
</pre>
<p>As you can see we create an element for our object as normal. We also append anything we want to remember in child nodes in the XML. The interesting part is that we pass the newly created node as a root node for the Serialize method of the base class.</p>
<p>This approach generates the following XML:<br />
(We saved a Scene which had an array of blocks, which contained one normal Block and one RotatableBlock using our Serializer&#8217;s Save method).</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ReflectionTutorialEngine.Scene&gt;
  &lt;Blocks&gt;
    &lt;ReflectionTutorialEngine.Block&gt;
      &lt;Texture&gt;test&lt;/Texture&gt;
      &lt;Position&gt;32;32&lt;/Position&gt;
      &lt;Scale&gt;1&lt;/Scale&gt;
      &lt;Tinting&gt;255;255;255;255&lt;/Tinting&gt;
    &lt;/ReflectionTutorialEngine.Block&gt;
    &lt;ReflectionTutorialEngine.RotatableBlock&gt;
      &lt;Rotation&gt;0.7853982&lt;/Rotation&gt;
      &lt;ReflectionTutorialEngine.Block&gt;
        &lt;Texture&gt;test&lt;/Texture&gt;
        &lt;Position&gt;64;64&lt;/Position&gt;
        &lt;Scale&gt;0.5&lt;/Scale&gt;
        &lt;Tinting&gt;245;245;220;255&lt;/Tinting&gt;
      &lt;/ReflectionTutorialEngine.Block&gt;
    &lt;/ReflectionTutorialEngine.RotatableBlock&gt;
  &lt;/Blocks&gt;
&lt;/ReflectionTutorialEngine.Scene&gt;
</pre>
<p>Recreating the Scene, Block and RotatableBlock from this XML file is fairly easy. Let&#8217;s first declare a Load method in our Serializer.</p>
<pre class="brush: csharp; title: ; notranslate">
        public static ISerializable Load(string fileName)
        {
            CultureInfo userCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            XmlDocument document = new XmlDocument();
            document.Load(fileName);

            XmlNode rootNode = document.FirstChild;
            ISerializable rootObject = GetObjectFromNode(rootNode);
            rootObject.Deserialize(document, rootNode);

            Thread.CurrentThread.CurrentCulture = userCulture;

            return rootObject;
        }

        //Small helper method that creates an instance of ISerializable from a node
        public static ISerializable GetObjectFromNode(XmlNode node)
        {
            return (ISerializable)Assembly.GetExecutingAssembly().CreateInstance(node.Name);
        }
</pre>
<p>As you can see we load an XMLDocument normally. And start deserializing the first child of the document (the <TutorialEngine.Scene> element in our case). I&#8217;ve added a little helper method (GetObjectFromNode) that actually does a lot of work. Via reflection it looks up the class stored in the name of the node. At first it will find &#8220;TutorialEngine.Scene&#8221; and it will thus create an instance of our Scene class.</p>
<p>After this we simply call Deserialize on our newly instantiated Scene object, giving it the XMlDocument and the node that represents the Scene itself.</p>
<p>Deserializing a Scene is now easy:</p>
<pre class="brush: csharp; title: ; notranslate">
        public virtual void Deserialize(XmlDocument document, XmlNode self)
        {
            XmlElement blocksElement = self[&quot;Blocks&quot;];

            blocks = new Block[blocksElement.ChildNodes.Count];
            for (int i = 0; i &lt; blocks.Length; i++)
            {
                blocks[i] = (Block)Serializer.GetObjectFromNode(blocksElement.ChildNodes[i]);
                blocks[i].Deserialize(document, blocksElement.ChildNodes[i]);
            }
        }
</pre>
<p>See that we keep using the Serializer.GetObjectFromNode helper method to instantiate a block. Note that a RotatableBlock can be casted to a Block (we are using polymorphism here again). But that when deserialzing the overriden method in RotatableBlock will be used.</p>
<p>The deserialization code for a block is easy (and a bit dull)</p>
<pre class="brush: csharp; title: ; notranslate">
        public virtual void Deserialize(XmlDocument document, XmlNode self)
        {
            try
            {
                texture = GameServices.GetService&lt;ContentManager&gt;().Load&lt;Texture2D&gt;(self[&quot;Texture&quot;].InnerText);
                position.X = Single.Parse(self[&quot;Position&quot;].InnerText.Split(';')[0]);
                position.Y = Single.Parse(self[&quot;Position&quot;].InnerText.Split(';')[1]);
                scale = Single.Parse(self[&quot;Scale&quot;].InnerText);
                tinting.R = Byte.Parse(self[&quot;Tinting&quot;].InnerText.Split(';')[0]);
                tinting.G = Byte.Parse(self[&quot;Tinting&quot;].InnerText.Split(';')[1]);
                tinting.B = Byte.Parse(self[&quot;Tinting&quot;].InnerText.Split(';')[2]);
                tinting.A = Byte.Parse(self[&quot;Tinting&quot;].InnerText.Split(';')[3]);
            }
            catch(Exception e)
            {
                throw new XmlException(&quot;Error deserializing from XML, see inner exception for details&quot;, e);
            }
        }
</pre>
<p>Note that we are using the <a href="http://roy-t.nl/index.php/2010/08/25/xna-accessing-contentmanager-and-graphicsdevice-anywhere-anytime-the-gameservicecontainer/">GameServices class</a> from a previous tutorial to get easy access to the ContentManager.</p>
<p>Now the interesting part is again in how we handled Inheritance in RotatableBlock, so let&#8217;s take a look at that code:</p>
<pre class="brush: csharp; title: ; notranslate">
        public override void Deserialize(XmlDocument document, XmlNode self)
        {
            try
            {
                rotation = Single.Parse(self[&quot;Rotation&quot;].InnerText);
                base.Deserialize(document, self[&quot;ReflectionTutorialEngine.Block&quot;]);
            }
            catch (Exception e)
            {
                throw new XmlException(&quot;Error deserializing from XML, see inner exception for details&quot;, e);
            }
        }
</pre>
<p>As you can see we first set the rotation variable with the data saved in our XMLNode. However the special thing is that we now just deserialize the rest of our RotatableBlock data by calling the base.Deserialize method on the <Block> element inside our <RotatableBlock> element. This way we don&#8217;t have to duplicate any code.</p>
<p>As you can see this is a pretty neat and clean way of writing your own XML Serialization code. It will save you a lot of work, and a lot of errors compared to writing the same boring serialization code for each object. If you have problems understanding inheritance and polymorphism I suggest that you quickly brush up on those techniques as they are crazy powerful and a must for every developer that works with an object oriented language as C#.</p>
<p>Be aware that there are multiple ways to automatically serialize your data, like the previously mentioned IntermediateSerializer, or using Xna.BinaryWriter.</p>
<p>I believe that the above code is as Xbox360 compatible as the other ways, and the nice thing is, is that it will also work when not using XNA at all <img src='http://roy-t.nl/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>Anyway, I hope you liked this. Stay tuned for the reflection tutorial for which I wrote this (yeah I did get carried away).</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2010/10/24/custom-xml-serialization-in-c/' addthis:title='Custom XML Serialization in C#' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2010/10/24/custom-xml-serialization-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>XNA: Proxyclasses to &#8216;Serialize&#8217; assets using the IntermediateSerializer</title>
		<link>http://roy-t.nl/index.php/2010/09/28/xna-proxyclasses-to-serialize-assets-using-the-intermediateserializer/</link>
		<comments>http://roy-t.nl/index.php/2010/09/28/xna-proxyclasses-to-serialize-assets-using-the-intermediateserializer/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 18:50:17 +0000</pubDate>
		<dc:creator>Roy Triesscheijn</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[General Gamedesign]]></category>
		<category><![CDATA[Hollandia]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Content]]></category>
		<category><![CDATA[Deserialize]]></category>
		<category><![CDATA[IntermediateSerializer]]></category>
		<category><![CDATA[Serialization]]></category>

		<guid isPermaLink="false">http://roy-t.nl/?p=386</guid>
		<description><![CDATA[As some of you&#8217;ve might seen, I&#8217;ve been breaking my head over the following problem for the past few days: How do I serialize the class like the following without creating a special &#8216;intermediate&#8217; struct for each and ever classes Even though I&#8217;ve marked the Texture2D as a shared resource, I still can&#8217;t serialize it [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2010/09/28/xna-proxyclasses-to-serialize-assets-using-the-intermediateserializer/' addthis:title='XNA: Proxyclasses to &#8216;Serialize&#8217; assets using the IntermediateSerializer' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>As some of you&#8217;ve might seen, I&#8217;ve been breaking my head over the following problem for the past few days:</p>
<p>How do I serialize the class like the following without creating a special &#8216;intermediate&#8217; struct for each and ever classes</p>
<pre class="brush: csharp; title: ; notranslate">
public class MyData
    {
        [ContentSerializer(SharedResource = true)]
        public Texture2D myTexture;
        public int myInt;
        public string[] myLines;
        public MyData() { } // for deserialization
        public MyData(int myInt, Texture2DProxy myTexture, string[] myLines)
        {
            this.myInt = myInt;
            this.myTexture = myTexture;
            this.myLines = myLines;
        }
    }
</pre>
<p>Even though I&#8217;ve marked the Texture2D as a shared resource, I still can&#8217;t serialize it using the IntermediateSerializer because a Texture2D always has a reference to a GraphicsDevice object, and the IS can&#8217;t serialize that.</p>
<p>Fortunately some helpfull people in #XNA on Efnet (ecosky and flashed, that&#8217;s you guys!) told me about proxyclasses, first I was confused and thought they wanted me to write a proxy for every class in my project, but soon they helped me understand that I should write a proxy class for Texture2D. I just had to write a proxy class that can be serialized and that will store the path to texture, so that it can reload itself when deserialized. </p>
<p>I quickly came up with the following class, very simple but it will suffice for now:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Texture2DProxy
    {
        public Texture2DProxy(string path)
        {
            LoadTexture(path);
        }

        public Texture2DProxy() { }

        private void LoadTexture(string path)
        {
            ContentManager content = GameServices.GetService&lt;ContentManager&gt;(); //My own class, see my code snippet, you can also reference a static CM here.
            texture = content.Load&lt;Texture2D&gt;(path);
            this.path = path;
        }

        [ContentSerializerIgnore()] //make this is not serialized
        private Texture2D texture;

        [ContentSerializerIgnore()]
        public Texture2D Texture
        {
            get
            {
                if (texture == null)
                {
                    LoadTexture(path);
                }
                return texture;
            }
        }

        [ContentSerializer()] //make sure this is, even-though it's a private field.
        private string path;
    }
</pre>
<p>Now we just need to replace Texture2D with Texture2DProxy everywhere, and update some code. In the end we can now serialize and deserialize the MyData class like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public void DoSerialize(MyData myData)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            using (XmlWriter writer = XmlWriter.Create(&quot;example.xml&quot;, settings))
            {
                IntermediateSerializer.Serialize(writer, myData, null);
            }
        }

        public MyData DoLoad()
        {
            MyData tmp;
            XmlReaderSettings settings = new XmlReaderSettings();
            using(XmlReader reader = XmlReader.Create(&quot;example.xml&quot;, settings))
            {
                tmp = IntermediateSerializer.Deserialize&lt;MyData&gt;(reader, null);
            }

            return tmp;
        }
</pre>
<p>Btw, serializing like this will generate the following XML file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;XnaContent&gt;
  &lt;Asset Type=&quot;XNASerialization.MyData&quot;&gt;
    &lt;myTexture&gt;#Resource1&lt;/myTexture&gt;
    &lt;myInt&gt;42&lt;/myInt&gt;
    &lt;myLines&gt;
      &lt;Item&gt;Two households, both alike in dignity,&lt;/Item&gt;
      &lt;Item&gt;In fair Verona, where we lay our scene,&lt;/Item&gt;
      &lt;Item&gt;From ancient grudge break to new mutiny,&lt;/Item&gt;
      &lt;Item&gt;Where civil blood makes civil hands unclean.&lt;/Item&gt;
    &lt;/myLines&gt;
  &lt;/Asset&gt;
  &lt;Resources&gt;
    &lt;Resource ID=&quot;#Resource1&quot; Type=&quot;XNASerialization.Texture2DProxy&quot;&gt;
      &lt;path&gt;latern&lt;/path&gt;
    &lt;/Resource&gt;
  &lt;/Resources&gt;
&lt;/XnaContent&gt;
</pre>
<p>With this problem out of the way, I can now finally start working on a way to save and restore levels in Hollandia. Oh btw, you can ofcourse do the same trick with SoundEffects and Models or anything else for that matter.</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://roy-t.nl/index.php/2010/09/28/xna-proxyclasses-to-serialize-assets-using-the-intermediateserializer/' addthis:title='XNA: Proxyclasses to &#8216;Serialize&#8217; assets using the IntermediateSerializer' ><a class="addthis_button_twitter"></a><a class="addthis_button_stumbleupon"></a><a class="addthis_button_reddit"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://roy-t.nl/index.php/2010/09/28/xna-proxyclasses-to-serialize-assets-using-the-intermediateserializer/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

